ESPHome 2025.11.4
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 <span>
12#include <string>
13#include <type_traits>
14#include <vector>
15#include <concepts>
16
18
19#ifdef USE_ESP8266
20#include <Esp.h>
21#endif
22
23#ifdef USE_RP2040
24#include <Arduino.h>
25#endif
26
27#ifdef USE_ESP32
28#include <esp_heap_caps.h>
29#endif
30
31#if defined(USE_ESP32)
32#include <freertos/FreeRTOS.h>
33#include <freertos/semphr.h>
34#elif defined(USE_LIBRETINY)
35#include <FreeRTOS.h>
36#include <semphr.h>
37#endif
38
39#ifdef USE_HOST
40#include <mutex>
41#endif
42
43#define HOT __attribute__((hot))
44#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
45#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
46#define PACKED __attribute__((packed))
47
48namespace esphome {
49
50// Forward declaration to avoid circular dependency with string_ref.h
51class StringRef;
52
55
56// Keep "using" even after the removal of our backports, to avoid breaking existing code.
57using std::to_string;
58using std::is_trivially_copyable;
59using std::make_unique;
60using std::enable_if_t;
61using std::clamp;
62using std::is_invocable;
63#if __cpp_lib_bit_cast >= 201806
64using std::bit_cast;
65#else
67template<
68 typename To, typename From,
69 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
70 int> = 0>
71To bit_cast(const From &src) {
72 To dst;
73 memcpy(&dst, &src, sizeof(To));
74 return dst;
75}
76#endif
77
78// clang-format off
79inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
80// clang-format on
81
82// std::byteswap from C++23
83template<typename T> constexpr T byteswap(T n) {
84 T m;
85 for (size_t i = 0; i < sizeof(T); i++)
86 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
87 return m;
88}
89template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
90#ifdef USE_LIBRETINY
91// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
92template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
93template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
94template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
95template<> inline int8_t byteswap(int8_t n) { return n; }
96template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
97template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
98template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
99#else
100template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
101template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
102template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
103template<> constexpr int8_t byteswap(int8_t n) { return n; }
104template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
105template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
106template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
107#endif
108
110
113
115template<typename T, size_t N> class StaticVector {
116 public:
117 using value_type = T;
118 using iterator = typename std::array<T, N>::iterator;
119 using const_iterator = typename std::array<T, N>::const_iterator;
120 using reverse_iterator = std::reverse_iterator<iterator>;
121 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
122
123 private:
124 std::array<T, N> data_{};
125 size_t count_{0};
126
127 public:
128 // Minimal vector-compatible interface - only what we actually use
129 void push_back(const T &value) {
130 if (count_ < N) {
131 data_[count_++] = value;
132 }
133 }
134
135 // Return reference to next element and increment count (with bounds checking)
137 if (count_ >= N) {
138 // Should never happen with proper size calculation
139 // Return reference to last element to avoid crash
140 return data_[N - 1];
141 }
142 return data_[count_++];
143 }
144
145 size_t size() const { return count_; }
146 bool empty() const { return count_ == 0; }
147
148 T &operator[](size_t i) { return data_[i]; }
149 const T &operator[](size_t i) const { return data_[i]; }
150
151 // For range-based for loops
152 iterator begin() { return data_.begin(); }
153 iterator end() { return data_.begin() + count_; }
154 const_iterator begin() const { return data_.begin(); }
155 const_iterator end() const { return data_.begin() + count_; }
156
157 // Reverse iterators
162};
163
167template<typename T> class FixedVector {
168 private:
169 T *data_{nullptr};
170 size_t size_{0};
171 size_t capacity_{0};
172
173 // Helper to destroy all elements without freeing memory
174 void destroy_elements_() {
175 // Only call destructors for non-trivially destructible types
176 if constexpr (!std::is_trivially_destructible<T>::value) {
177 for (size_t i = 0; i < size_; i++) {
178 data_[i].~T();
179 }
180 }
181 }
182
183 // Helper to destroy elements and free memory
184 void cleanup_() {
185 if (data_ != nullptr) {
186 destroy_elements_();
187 // Free raw memory
188 ::operator delete(data_);
189 }
190 }
191
192 // Helper to reset pointers after cleanup
193 void reset_() {
194 data_ = nullptr;
195 capacity_ = 0;
196 size_ = 0;
197 }
198
199 // Helper to assign from initializer list (shared by constructor and assignment operator)
200 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
201 init(init_list.size());
202 size_t idx = 0;
203 for (const auto &item : init_list) {
204 new (data_ + idx) T(item);
205 ++idx;
206 }
207 size_ = init_list.size();
208 }
209
210 public:
211 FixedVector() = default;
212
215 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
216
217 ~FixedVector() { cleanup_(); }
218
219 // Disable copy operations (avoid accidental expensive copies)
220 FixedVector(const FixedVector &) = delete;
222
223 // Enable move semantics (allows use in move-only containers like std::vector)
224 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
225 other.reset_();
226 }
227
228 // Allow conversion to std::vector
229 operator std::vector<T>() const { return {data_, data_ + size_}; }
230
231 FixedVector &operator=(FixedVector &&other) noexcept {
232 if (this != &other) {
233 // Delete our current data
234 cleanup_();
235 // Take ownership of other's data
236 data_ = other.data_;
237 size_ = other.size_;
238 capacity_ = other.capacity_;
239 // Leave other in valid empty state
240 other.reset_();
241 }
242 return *this;
243 }
244
247 FixedVector &operator=(std::initializer_list<T> init_list) {
248 cleanup_();
249 reset_();
250 assign_from_initializer_list_(init_list);
251 return *this;
252 }
253
254 // Allocate capacity - can be called multiple times to reinit
255 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
256 // Direct assignment via operator[] does NOT update the size counter.
257 void init(size_t n) {
258 cleanup_();
259 reset_();
260 if (n > 0) {
261 // Allocate raw memory without calling constructors
262 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
263 // NOLINTNEXTLINE(bugprone-sizeof-expression)
264 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
265 capacity_ = n;
266 }
267 }
268
269 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
270 void clear() {
271 destroy_elements_();
272 size_ = 0;
273 }
274
275 // Shrink capacity to fit current size (frees all memory)
277 cleanup_();
278 reset_();
279 }
280
284 void push_back(const T &value) {
285 if (size_ < capacity_) {
286 // Use placement new to construct the object in pre-allocated memory
287 new (&data_[size_]) T(value);
288 size_++;
289 }
290 }
291
295 void push_back(T &&value) {
296 if (size_ < capacity_) {
297 // Use placement new to move-construct the object in pre-allocated memory
298 new (&data_[size_]) T(std::move(value));
299 size_++;
300 }
301 }
302
307 template<typename... Args> T &emplace_back(Args &&...args) {
308 // Use placement new to construct the object in pre-allocated memory
309 new (&data_[size_]) T(std::forward<Args>(args)...);
310 size_++;
311 return data_[size_ - 1];
312 }
313
316 T &front() { return data_[0]; }
317 const T &front() const { return data_[0]; }
318
321 T &back() { return data_[size_ - 1]; }
322 const T &back() const { return data_[size_ - 1]; }
323
324 size_t size() const { return size_; }
325 bool empty() const { return size_ == 0; }
326
329 T &operator[](size_t i) { return data_[i]; }
330 const T &operator[](size_t i) const { return data_[i]; }
331
334 T &at(size_t i) { return data_[i]; }
335 const T &at(size_t i) const { return data_[i]; }
336
337 // Iterator support for range-based for loops
338 T *begin() { return data_; }
339 T *end() { return data_ + size_; }
340 const T *begin() const { return data_; }
341 const T *end() const { return data_ + size_; }
342};
343
345
348
350template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
351 return (value - min) * (max_out - min_out) / (max - min) + min_out;
352}
353
355uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
356
358uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
359 bool refin = false, bool refout = false);
360uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
361 bool refout = false);
362
364uint32_t fnv1_hash(const char *str);
365inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
366
368uint32_t random_uint32();
370float random_float();
372bool random_bytes(uint8_t *data, size_t len);
373
375
378
380constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
381 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
382}
384constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
385 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
386}
388constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
389 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
390 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
391}
392
394template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
395 T val = 0;
396 for (size_t i = 0; i < sizeof(T); i++) {
397 val <<= 8;
398 val |= bytes[i];
399 }
400 return val;
401}
403template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
404constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
405 return encode_value<T>(bytes.data());
406}
408template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
409constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
410 std::array<uint8_t, sizeof(T)> ret{};
411 for (size_t i = sizeof(T); i > 0; i--) {
412 ret[i - 1] = val & 0xFF;
413 val >>= 8;
414 }
415 return ret;
416}
417
419inline uint8_t reverse_bits(uint8_t x) {
420 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
421 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
422 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
423 return x;
424}
426inline uint16_t reverse_bits(uint16_t x) {
427 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
428}
430inline uint32_t reverse_bits(uint32_t x) {
431 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
432 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
433}
434
436template<typename T> constexpr T convert_big_endian(T val) {
437#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
438 return byteswap(val);
439#else
440 return val;
441#endif
442}
443
445template<typename T> constexpr T convert_little_endian(T val) {
446#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
447 return val;
448#else
449 return byteswap(val);
450#endif
451}
452
454
457
459bool str_equals_case_insensitive(const std::string &a, const std::string &b);
460
462bool str_startswith(const std::string &str, const std::string &start);
464bool str_endswith(const std::string &str, const std::string &end);
465
467std::string str_truncate(const std::string &str, size_t length);
468
471std::string str_until(const char *str, char ch);
473std::string str_until(const std::string &str, char ch);
474
476std::string str_lower_case(const std::string &str);
478std::string str_upper_case(const std::string &str);
480std::string str_snake_case(const std::string &str);
481
483std::string str_sanitize(const std::string &str);
484
486std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
487
489std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
490
499std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len);
500
502
505
507template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
508optional<T> parse_number(const char *str) {
509 char *end = nullptr;
510 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
511 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
512 return {};
513 return value;
514}
516template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
517optional<T> parse_number(const std::string &str) {
518 return parse_number<T>(str.c_str());
519}
521template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
522optional<T> parse_number(const char *str) {
523 char *end = nullptr;
524 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
525 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
526 return {};
527 return value;
528}
530template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
531optional<T> parse_number(const std::string &str) {
532 return parse_number<T>(str.c_str());
533}
535template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
536 char *end = nullptr;
537 float value = ::strtof(str, &end);
538 if (end == str || *end != '\0' || value == HUGE_VALF)
539 return {};
540 return value;
541}
543template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
544optional<T> parse_number(const std::string &str) {
545 return parse_number<T>(str.c_str());
546}
547
559size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
561inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
562 return parse_hex(str, strlen(str), data, count) == 2 * count;
563}
565inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
566 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
567}
569inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
570 data.resize(count);
571 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
572}
574inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
575 data.resize(count);
576 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
577}
583template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
584optional<T> parse_hex(const char *str, size_t len) {
585 T val = 0;
586 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
587 return {};
588 return convert_big_endian(val);
589}
591template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
592 return parse_hex<T>(str, strlen(str));
593}
595template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
596 return parse_hex<T>(str.c_str(), str.length());
597}
598
600inline char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
601
604inline char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
605
607inline void format_mac_addr_upper(const uint8_t *mac, char *output) {
608 for (size_t i = 0; i < 6; i++) {
609 uint8_t byte = mac[i];
610 output[i * 3] = format_hex_pretty_char(byte >> 4);
611 output[i * 3 + 1] = format_hex_pretty_char(byte & 0x0F);
612 if (i < 5)
613 output[i * 3 + 2] = ':';
614 }
615 output[17] = '\0';
616}
617
619inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
620 for (size_t i = 0; i < 6; i++) {
621 uint8_t byte = mac[i];
622 output[i * 2] = format_hex_char(byte >> 4);
623 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
624 }
625 output[12] = '\0';
626}
627
629std::string format_mac_address_pretty(const uint8_t mac[6]);
631std::string format_hex(const uint8_t *data, size_t length);
633std::string format_hex(const std::vector<uint8_t> &data);
635template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
637 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
638}
639template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
640 return format_hex(data.data(), data.size());
641}
642
668std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
669
690std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
691
713std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
714
735std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
736
757std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
758
782template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
783std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
785 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
786}
787
789std::string format_bin(const uint8_t *data, size_t length);
791template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
793 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
794}
795
804ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
805
807std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
809std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement);
810
812int8_t step_to_accuracy_decimals(float step);
813
814std::string base64_encode(const uint8_t *buf, size_t buf_len);
815std::string base64_encode(const std::vector<uint8_t> &buf);
816
817std::vector<uint8_t> base64_decode(const std::string &encoded_string);
818size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
819
821
824
826float gamma_correct(float value, float gamma);
828float gamma_uncorrect(float value, float gamma);
829
831void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
833void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
834
836
839
841constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
843constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
844
846
849
850template<typename... X> class CallbackManager;
851
856template<typename... Ts> class CallbackManager<void(Ts...)> {
857 public:
859 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
860
862 void call(Ts... args) {
863 for (auto &cb : this->callbacks_)
864 cb(args...);
865 }
866 size_t size() const { return this->callbacks_.size(); }
867
869 void operator()(Ts... args) { call(args...); }
870
871 protected:
872 std::vector<std::function<void(Ts...)>> callbacks_;
873};
874
876template<typename T> class Deduplicator {
877 public:
879 bool next(T value) {
880 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
881 return false;
882 }
883 this->has_value_ = true;
884 this->value_unknown_ = false;
885 this->last_value_ = value;
886 return true;
887 }
890 bool ret = !this->value_unknown_;
891 this->value_unknown_ = true;
892 return ret;
893 }
895 bool has_value() const { return this->has_value_; }
896
897 protected:
898 bool has_value_{false};
899 bool value_unknown_{false};
901};
902
904template<typename T> class Parented {
905 public:
907 Parented(T *parent) : parent_(parent) {}
908
910 T *get_parent() const { return parent_; }
912 void set_parent(T *parent) { parent_ = parent; }
913
914 protected:
915 T *parent_{nullptr};
916};
917
919
922
927class Mutex {
928 public:
929 Mutex();
930 Mutex(const Mutex &) = delete;
931 ~Mutex();
932 void lock();
933 bool try_lock();
934 void unlock();
935
936 Mutex &operator=(const Mutex &) = delete;
937
938 private:
939#if defined(USE_ESP32) || defined(USE_LIBRETINY)
940 SemaphoreHandle_t handle_;
941#else
942 // d-pointer to store private data on new platforms
943 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
944#endif
945};
946
952 public:
953 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
954 ~LockGuard() { mutex_.unlock(); }
955
956 private:
957 Mutex &mutex_;
958};
959
981 public:
984
985 protected:
986#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
987 uint32_t state_;
988#endif
989};
990
998class LwIPLock {
999 public:
1000 LwIPLock();
1001 ~LwIPLock();
1002
1003 // Delete copy constructor and copy assignment operator to prevent accidental copying
1004 LwIPLock(const LwIPLock &) = delete;
1005 LwIPLock &operator=(const LwIPLock &) = delete;
1006};
1007
1014 public:
1016 void start();
1018 void stop();
1019
1021 static bool is_high_frequency();
1022
1023 protected:
1024 bool started_{false};
1025 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1026};
1027
1029void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
1030
1032std::string get_mac_address();
1033
1035std::string get_mac_address_pretty();
1036
1039void get_mac_address_into_buffer(std::span<char, 13> buf);
1040
1041#ifdef USE_ESP32
1043void set_mac_address(uint8_t *mac);
1044#endif
1045
1049
1052bool mac_address_is_valid(const uint8_t *mac);
1053
1055void delay_microseconds_safe(uint32_t us);
1056
1058
1061
1070template<class T> class RAMAllocator {
1071 public:
1072 using value_type = T;
1073
1074 enum Flags {
1075 NONE = 0, // Perform external allocation and fall back to internal memory
1076 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
1077 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
1078 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
1079 };
1080
1081 RAMAllocator() = default;
1083 // default is both external and internal
1085 if (flags != 0)
1086 this->flags_ = flags;
1087 }
1088 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
1089
1090 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
1091
1092 T *allocate(size_t n, size_t manual_size) {
1093 size_t size = n * manual_size;
1094 T *ptr = nullptr;
1095#ifdef USE_ESP32
1096 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1097 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1098 }
1099 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1100 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1101 }
1102#else
1103 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1104 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1105#endif
1106 return ptr;
1107 }
1108
1109 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
1110
1111 T *reallocate(T *p, size_t n, size_t manual_size) {
1112 size_t size = n * manual_size;
1113 T *ptr = nullptr;
1114#ifdef USE_ESP32
1115 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1116 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1117 }
1118 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1119 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1120 }
1121#else
1122 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1123 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1124#endif
1125 return ptr;
1126 }
1127
1128 void deallocate(T *p, size_t n) {
1129 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1130 }
1131
1135 size_t get_free_heap_size() const {
1136#ifdef USE_ESP8266
1137 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
1138#elif defined(USE_ESP32)
1139 auto max_internal =
1140 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1141 auto max_external =
1142 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1143 return max_internal + max_external;
1144#elif defined(USE_RP2040)
1145 return ::rp2040.getFreeHeap();
1146#elif defined(USE_LIBRETINY)
1147 return lt_heap_get_free();
1148#else
1149 return 100000;
1150#endif
1151 }
1152
1157#ifdef USE_ESP8266
1158 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
1159#elif defined(USE_ESP32)
1160 auto max_internal =
1161 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1162 auto max_external =
1163 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1164 return std::max(max_internal, max_external);
1165#else
1166 return this->get_free_heap_size();
1167#endif
1168 }
1169
1170 private:
1171 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
1172};
1173
1174template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
1175
1180template<typename T, typename U>
1181concept comparable_with = requires(T a, U b) {
1182 { a > b } -> std::convertible_to<bool>;
1183 { a < b } -> std::convertible_to<bool>;
1184};
1185
1186template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
1187 if (value < min)
1188 return min;
1189 return value;
1190}
1191template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
1192 if (value > max)
1193 return max;
1194 return value;
1195}
1196
1199
1204template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
1209template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
1210
1212
1213} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:869
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:872
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:862
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:859
Helper class to deduplicate items in a series of values.
Definition helpers.h:876
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:879
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:895
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:889
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:167
const T & at(size_t i) const
Definition helpers.h:335
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:224
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:215
const T * begin() const
Definition helpers.h:340
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:247
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:316
const T & operator[](size_t i) const
Definition helpers.h:330
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:329
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:321
bool empty() const
Definition helpers.h:325
FixedVector & operator=(const FixedVector &)=delete
FixedVector(const FixedVector &)=delete
void push_back(T &&value)
Add element by move without bounds checking Caller must ensure sufficient capacity was allocated via ...
Definition helpers.h:295
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:307
size_t size() const
Definition helpers.h:324
const T & front() const
Definition helpers.h:317
const T & back() const
Definition helpers.h:322
const T * end() const
Definition helpers.h:341
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:231
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:334
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:284
void init(size_t n)
Definition helpers.h:257
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:1013
void stop()
Stop running the loop continuously.
Definition helpers.cpp:624
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:630
void start()
Start running the loop continuously.
Definition helpers.cpp:618
Helper class to disable interrupts.
Definition helpers.h:980
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:951
LockGuard(Mutex &mutex)
Definition helpers.h:953
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:998
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:927
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:904
T * get_parent() const
Get the parent of this object.
Definition helpers.h:910
Parented(T *parent)
Definition helpers.h:907
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:912
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1070
RAMAllocator(uint8_t flags)
Definition helpers.h:1082
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:1111
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:1135
T * reallocate(T *p, size_t n)
Definition helpers.h:1109
void deallocate(T *p, size_t n)
Definition helpers.h:1128
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:1156
T * allocate(size_t n)
Definition helpers.h:1090
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:1088
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:1092
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:115
const_reverse_iterator rend() const
Definition helpers.h:161
size_t size() const
Definition helpers.h:145
reverse_iterator rbegin()
Definition helpers.h:158
const T & operator[](size_t i) const
Definition helpers.h:149
reverse_iterator rend()
Definition helpers.h:159
void push_back(const T &value)
Definition helpers.h:129
bool empty() const
Definition helpers.h:146
const_reverse_iterator rbegin() const
Definition helpers.h:160
T & operator[](size_t i)
Definition helpers.h:148
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:121
typename std::array< T, N >::iterator iterator
Definition helpers.h:118
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:119
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:120
const_iterator end() const
Definition helpers.h:155
const_iterator begin() const
Definition helpers.h:154
struct @65::@66 __attribute__
Functions to constrain the range of arithmetic values.
Definition helpers.h:1181
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
T clamp_at_most(T value, U max)
Definition helpers.h:1191
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
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:544
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:384
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:436
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:604
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:536
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:607
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:656
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:619
std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len)
Concatenate a name with a separator and suffix using an efficient stack-based approach.
Definition helpers.cpp:241
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:553
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:288
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:361
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:349
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:445
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:486
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:384
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:391
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:264
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:146
T clamp_at_least(T value, U min)
Definition helpers.h:1186
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:508
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:640
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:404
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:671
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:317
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:282
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:436
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:394
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:576
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:388
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:841
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:380
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:600
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:409
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:632
void get_mac_address_into_buffer(std::span< char, 13 > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:646
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:71
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:843
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:419
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:350
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:478
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:797
@ PARSE_ON
Definition helpers.h:799
@ PARSE_TOGGLE
Definition helpers.h:801
@ PARSE_OFF
Definition helpers.h:800
@ PARSE_NONE
Definition helpers.h:798
void init()
Definition core.cpp:109
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