ESPHome 2025.10.3
Loading...
Searching...
No Matches
helpers.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <cmath>
5#include <cstdint>
6#include <cstring>
7#include <functional>
8#include <iterator>
9#include <limits>
10#include <memory>
11#include <string>
12#include <type_traits>
13#include <vector>
14
16
17#ifdef USE_ESP8266
18#include <Esp.h>
19#endif
20
21#ifdef USE_RP2040
22#include <Arduino.h>
23#endif
24
25#ifdef USE_ESP32
26#include <esp_heap_caps.h>
27#endif
28
29#if defined(USE_ESP32)
30#include <freertos/FreeRTOS.h>
31#include <freertos/semphr.h>
32#elif defined(USE_LIBRETINY)
33#include <FreeRTOS.h>
34#include <semphr.h>
35#endif
36
37#ifdef USE_HOST
38#include <mutex>
39#endif
40
41#define HOT __attribute__((hot))
42#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
43#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
44#define PACKED __attribute__((packed))
45
46namespace esphome {
47
48// Forward declaration to avoid circular dependency with string_ref.h
49class StringRef;
50
53
54// Keep "using" even after the removal of our backports, to avoid breaking existing code.
55using std::to_string;
56using std::is_trivially_copyable;
57using std::make_unique;
58using std::enable_if_t;
59using std::clamp;
60using std::is_invocable;
61#if __cpp_lib_bit_cast >= 201806
62using std::bit_cast;
63#else
65template<
66 typename To, typename From,
67 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
68 int> = 0>
69To bit_cast(const From &src) {
70 To dst;
71 memcpy(&dst, &src, sizeof(To));
72 return dst;
73}
74#endif
75
76// clang-format off
77inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
78// clang-format on
79
80// std::byteswap from C++23
81template<typename T> constexpr T byteswap(T n) {
82 T m;
83 for (size_t i = 0; i < sizeof(T); i++)
84 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
85 return m;
86}
87template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
88#ifdef USE_LIBRETINY
89// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
90template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
91template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
92template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
93template<> inline int8_t byteswap(int8_t n) { return n; }
94template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
95template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
96template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
97#else
98template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
99template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
100template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
101template<> constexpr int8_t byteswap(int8_t n) { return n; }
102template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
103template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
104template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
105#endif
106
108
111
113template<typename T, size_t N> class StaticVector {
114 public:
115 using value_type = T;
116 using iterator = typename std::array<T, N>::iterator;
117 using const_iterator = typename std::array<T, N>::const_iterator;
118 using reverse_iterator = std::reverse_iterator<iterator>;
119 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
120
121 private:
122 std::array<T, N> data_{};
123 size_t count_{0};
124
125 public:
126 // Minimal vector-compatible interface - only what we actually use
127 void push_back(const T &value) {
128 if (count_ < N) {
129 data_[count_++] = value;
130 }
131 }
132
133 // Return reference to next element and increment count (with bounds checking)
135 if (count_ >= N) {
136 // Should never happen with proper size calculation
137 // Return reference to last element to avoid crash
138 return data_[N - 1];
139 }
140 return data_[count_++];
141 }
142
143 size_t size() const { return count_; }
144 bool empty() const { return count_ == 0; }
145
146 T &operator[](size_t i) { return data_[i]; }
147 const T &operator[](size_t i) const { return data_[i]; }
148
149 // For range-based for loops
150 iterator begin() { return data_.begin(); }
151 iterator end() { return data_.begin() + count_; }
152 const_iterator begin() const { return data_.begin(); }
153 const_iterator end() const { return data_.begin() + count_; }
154
155 // Reverse iterators
160};
161
163
166
168template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
169 return (value - min) * (max_out - min_out) / (max - min) + min_out;
170}
171
173uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
174
176uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
177 bool refin = false, bool refout = false);
178uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
179 bool refout = false);
180
182uint32_t fnv1_hash(const char *str);
183inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
184
186uint32_t random_uint32();
188float random_float();
190bool random_bytes(uint8_t *data, size_t len);
191
193
196
198constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
199 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
200}
202constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
203 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
204}
206constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
207 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
208 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
209}
210
212template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
213 T val = 0;
214 for (size_t i = 0; i < sizeof(T); i++) {
215 val <<= 8;
216 val |= bytes[i];
217 }
218 return val;
219}
221template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
222constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
223 return encode_value<T>(bytes.data());
224}
226template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
227constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
228 std::array<uint8_t, sizeof(T)> ret{};
229 for (size_t i = sizeof(T); i > 0; i--) {
230 ret[i - 1] = val & 0xFF;
231 val >>= 8;
232 }
233 return ret;
234}
235
237inline uint8_t reverse_bits(uint8_t x) {
238 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
239 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
240 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
241 return x;
242}
244inline uint16_t reverse_bits(uint16_t x) {
245 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
246}
248inline uint32_t reverse_bits(uint32_t x) {
249 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
250 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
251}
252
254template<typename T> constexpr T convert_big_endian(T val) {
255#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
256 return byteswap(val);
257#else
258 return val;
259#endif
260}
261
263template<typename T> constexpr T convert_little_endian(T val) {
264#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
265 return val;
266#else
267 return byteswap(val);
268#endif
269}
270
272
275
277bool str_equals_case_insensitive(const std::string &a, const std::string &b);
278
280bool str_startswith(const std::string &str, const std::string &start);
282bool str_endswith(const std::string &str, const std::string &end);
283
285std::string str_truncate(const std::string &str, size_t length);
286
289std::string str_until(const char *str, char ch);
291std::string str_until(const std::string &str, char ch);
292
294std::string str_lower_case(const std::string &str);
296std::string str_upper_case(const std::string &str);
298std::string str_snake_case(const std::string &str);
299
301std::string str_sanitize(const std::string &str);
302
304std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
305
307std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
308
310
313
315template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
316optional<T> parse_number(const char *str) {
317 char *end = nullptr;
318 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
319 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
320 return {};
321 return value;
322}
324template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
325optional<T> parse_number(const std::string &str) {
326 return parse_number<T>(str.c_str());
327}
329template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
330optional<T> parse_number(const char *str) {
331 char *end = nullptr;
332 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
333 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
334 return {};
335 return value;
336}
338template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
339optional<T> parse_number(const std::string &str) {
340 return parse_number<T>(str.c_str());
341}
343template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
344 char *end = nullptr;
345 float value = ::strtof(str, &end);
346 if (end == str || *end != '\0' || value == HUGE_VALF)
347 return {};
348 return value;
349}
351template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
352optional<T> parse_number(const std::string &str) {
353 return parse_number<T>(str.c_str());
354}
355
367size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
369inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
370 return parse_hex(str, strlen(str), data, count) == 2 * count;
371}
373inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
374 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
375}
377inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
378 data.resize(count);
379 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
380}
382inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
383 data.resize(count);
384 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
385}
391template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
392optional<T> parse_hex(const char *str, size_t len) {
393 T val = 0;
394 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
395 return {};
396 return convert_big_endian(val);
397}
399template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
400 return parse_hex<T>(str, strlen(str));
401}
403template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
404 return parse_hex<T>(str.c_str(), str.length());
405}
406
408inline char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
409
412inline char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
413
415inline void format_mac_addr_upper(const uint8_t *mac, char *output) {
416 for (size_t i = 0; i < 6; i++) {
417 uint8_t byte = mac[i];
418 output[i * 3] = format_hex_pretty_char(byte >> 4);
419 output[i * 3 + 1] = format_hex_pretty_char(byte & 0x0F);
420 if (i < 5)
421 output[i * 3 + 2] = ':';
422 }
423 output[17] = '\0';
424}
425
427inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
428 for (size_t i = 0; i < 6; i++) {
429 uint8_t byte = mac[i];
430 output[i * 2] = format_hex_char(byte >> 4);
431 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
432 }
433 output[12] = '\0';
434}
435
437std::string format_mac_address_pretty(const uint8_t mac[6]);
439std::string format_hex(const uint8_t *data, size_t length);
441std::string format_hex(const std::vector<uint8_t> &data);
443template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
445 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
446}
447template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
448 return format_hex(data.data(), data.size());
449}
450
476std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
477
498std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
499
521std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
522
543std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
544
565std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
566
590template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
591std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
593 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
594}
595
597std::string format_bin(const uint8_t *data, size_t length);
599template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
601 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
602}
603
612ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
613
615std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
617std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement);
618
620int8_t step_to_accuracy_decimals(float step);
621
622std::string base64_encode(const uint8_t *buf, size_t buf_len);
623std::string base64_encode(const std::vector<uint8_t> &buf);
624
625std::vector<uint8_t> base64_decode(const std::string &encoded_string);
626size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
627
629
632
634float gamma_correct(float value, float gamma);
636float gamma_uncorrect(float value, float gamma);
637
639void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
641void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
642
644
647
649constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
651constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
652
654
657
658template<typename... X> class CallbackManager;
659
664template<typename... Ts> class CallbackManager<void(Ts...)> {
665 public:
667 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
668
670 void call(Ts... args) {
671 for (auto &cb : this->callbacks_)
672 cb(args...);
673 }
674 size_t size() const { return this->callbacks_.size(); }
675
677 void operator()(Ts... args) { call(args...); }
678
679 protected:
680 std::vector<std::function<void(Ts...)>> callbacks_;
681};
682
684template<typename T> class Deduplicator {
685 public:
687 bool next(T value) {
688 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
689 return false;
690 }
691 this->has_value_ = true;
692 this->value_unknown_ = false;
693 this->last_value_ = value;
694 return true;
695 }
698 bool ret = !this->value_unknown_;
699 this->value_unknown_ = true;
700 return ret;
701 }
703 bool has_value() const { return this->has_value_; }
704
705 protected:
706 bool has_value_{false};
707 bool value_unknown_{false};
709};
710
712template<typename T> class Parented {
713 public:
715 Parented(T *parent) : parent_(parent) {}
716
718 T *get_parent() const { return parent_; }
720 void set_parent(T *parent) { parent_ = parent; }
721
722 protected:
723 T *parent_{nullptr};
724};
725
727
730
735class Mutex {
736 public:
737 Mutex();
738 Mutex(const Mutex &) = delete;
739 ~Mutex();
740 void lock();
741 bool try_lock();
742 void unlock();
743
744 Mutex &operator=(const Mutex &) = delete;
745
746 private:
747#if defined(USE_ESP32) || defined(USE_LIBRETINY)
748 SemaphoreHandle_t handle_;
749#else
750 // d-pointer to store private data on new platforms
751 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
752#endif
753};
754
760 public:
761 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
762 ~LockGuard() { mutex_.unlock(); }
763
764 private:
765 Mutex &mutex_;
766};
767
789 public:
792
793 protected:
794#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
795 uint32_t state_;
796#endif
797};
798
806class LwIPLock {
807 public:
808 LwIPLock();
809 ~LwIPLock();
810
811 // Delete copy constructor and copy assignment operator to prevent accidental copying
812 LwIPLock(const LwIPLock &) = delete;
813 LwIPLock &operator=(const LwIPLock &) = delete;
814};
815
822 public:
824 void start();
826 void stop();
827
829 static bool is_high_frequency();
830
831 protected:
832 bool started_{false};
833 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
834};
835
837void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
838
840std::string get_mac_address();
841
843std::string get_mac_address_pretty();
844
845#ifdef USE_ESP32
847void set_mac_address(uint8_t *mac);
848#endif
849
853
856bool mac_address_is_valid(const uint8_t *mac);
857
859void delay_microseconds_safe(uint32_t us);
860
862
865
874template<class T> class RAMAllocator {
875 public:
876 using value_type = T;
877
878 enum Flags {
879 NONE = 0, // Perform external allocation and fall back to internal memory
880 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
881 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
882 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
883 };
884
885 RAMAllocator() = default;
887 // default is both external and internal
889 if (flags != 0)
890 this->flags_ = flags;
891 }
892 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
893
894 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
895
896 T *allocate(size_t n, size_t manual_size) {
897 size_t size = n * manual_size;
898 T *ptr = nullptr;
899#ifdef USE_ESP32
900 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
901 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
902 }
903 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
904 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
905 }
906#else
907 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
908 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
909#endif
910 return ptr;
911 }
912
913 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
914
915 T *reallocate(T *p, size_t n, size_t manual_size) {
916 size_t size = n * manual_size;
917 T *ptr = nullptr;
918#ifdef USE_ESP32
919 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
920 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
921 }
922 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
923 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
924 }
925#else
926 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
927 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
928#endif
929 return ptr;
930 }
931
932 void deallocate(T *p, size_t n) {
933 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
934 }
935
939 size_t get_free_heap_size() const {
940#ifdef USE_ESP8266
941 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
942#elif defined(USE_ESP32)
943 auto max_internal =
944 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
945 auto max_external =
946 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
947 return max_internal + max_external;
948#elif defined(USE_RP2040)
949 return ::rp2040.getFreeHeap();
950#elif defined(USE_LIBRETINY)
951 return lt_heap_get_free();
952#else
953 return 100000;
954#endif
955 }
956
960 size_t get_max_free_block_size() const {
961#ifdef USE_ESP8266
962 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
963#elif defined(USE_ESP32)
964 auto max_internal =
965 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
966 auto max_external =
967 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
968 return std::max(max_internal, max_external);
969#else
970 return this->get_free_heap_size();
971#endif
972 }
973
974 private:
975 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
976};
977
978template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
979
981
984
989template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
994template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
995
997
1000
1001ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
1002inline std::string hexencode(const uint8_t *data, uint32_t len) { return format_hex_pretty(data, len); }
1003
1004template<typename T>
1005ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
1006std::string hexencode(const T &data) {
1007 return hexencode(data.data(), data.size());
1008}
1009
1011
1012} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:677
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:680
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:670
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:667
Helper class to deduplicate items in a series of values.
Definition helpers.h:684
bool next(T value)
Feeds the next item in the series to the deduplicator and returns false if this is a duplicate.
Definition helpers.h:687
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:703
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:697
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:821
void stop()
Stop running the loop continuously.
Definition helpers.cpp:600
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:606
void start()
Start running the loop continuously.
Definition helpers.cpp:594
Helper class to disable interrupts.
Definition helpers.h:788
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:759
LockGuard(Mutex &mutex)
Definition helpers.h:761
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:806
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:735
void unlock()
Definition helpers.cpp:27
bool try_lock()
Definition helpers.cpp:26
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:712
T * get_parent() const
Get the parent of this object.
Definition helpers.h:718
Parented(T *parent)
Definition helpers.h:715
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:720
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:874
RAMAllocator(uint8_t flags)
Definition helpers.h:886
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:915
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:939
T * reallocate(T *p, size_t n)
Definition helpers.h:913
void deallocate(T *p, size_t n)
Definition helpers.h:932
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:960
T * allocate(size_t n)
Definition helpers.h:894
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:892
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:896
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:113
const_reverse_iterator rend() const
Definition helpers.h:159
size_t size() const
Definition helpers.h:143
reverse_iterator rbegin()
Definition helpers.h:156
const T & operator[](size_t i) const
Definition helpers.h:147
reverse_iterator rend()
Definition helpers.h:157
void push_back(const T &value)
Definition helpers.h:127
bool empty() const
Definition helpers.h:144
const_reverse_iterator rbegin() const
Definition helpers.h:158
T & operator[](size_t i)
Definition helpers.h:146
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:119
typename std::array< T, N >::iterator iterator
Definition helpers.h:116
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:117
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:118
const_iterator end() const
Definition helpers.h:153
const_iterator begin() const
Definition helpers.h:152
struct @63::@64 __attribute__
uint16_t flags
uint16_t id
mopeka_std_values val[4]
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1") inline std
Definition helpers.h:1001
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:157
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:520
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:72
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Create a string from a value and an accuracy in decimals.
Definition helpers.cpp:360
constexpr T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order.
Definition helpers.h:254
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing) This always uses uppercase (...
Definition helpers.h:412
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:512
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:415
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:626
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:427
void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value)
Convert red, green and blue (all 0-1) values to hue (0-360), saturation (0-1) and value (0-1).
Definition helpers.cpp:529
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
Definition helpers.cpp:264
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:189
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:337
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:325
constexpr T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order.
Definition helpers.h:263
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:198
std::string size_t len
Definition helpers.h:304
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:202
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:93
std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Create a string from a value, an accuracy in decimals, and a unit of measurement.
Definition helpers.cpp:367
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:240
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:146
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:316
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:616
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:208
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:91
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:380
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:641
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:190
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:293
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:161
std::string str_until(const char *str, char ch)
Extract the part of the string until either the first occurrence of the specified character,...
Definition helpers.cpp:176
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:258
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:412
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:212
void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue)
Convert hue (0-360), saturation (0-1) and value (0-1) to red, green and blue (all 0-1).
Definition helpers.cpp:552
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:112
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:206
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
Definition helpers.cpp:45
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:649
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:222
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:198
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:73
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:165
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
Definition helpers.h:408
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:227
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:608
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:69
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:651
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:237
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:191
float lerp(float completion, float start, float end)=delete
T remap(U value, U min, U max, T min_out, T max_out)
Remap value from the range (min, max) to (min_out, max_out).
Definition helpers.h:168
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:166
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:454
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:605
@ PARSE_ON
Definition helpers.h:607
@ PARSE_TOGGLE
Definition helpers.h:609
@ PARSE_OFF
Definition helpers.h:608
@ PARSE_NONE
Definition helpers.h:606
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:173
uint8_t end[39]
Definition sun_gtil2.cpp:17
void byteswap()
uint16_t length
Definition tt21100.cpp:0
uint16_t x
Definition tt21100.cpp:5