ESPHome 2025.12.0-dev
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 FixedVector &operator=(FixedVector &&other) noexcept {
229 if (this != &other) {
230 // Delete our current data
231 cleanup_();
232 // Take ownership of other's data
233 data_ = other.data_;
234 size_ = other.size_;
235 capacity_ = other.capacity_;
236 // Leave other in valid empty state
237 other.reset_();
238 }
239 return *this;
240 }
241
244 FixedVector &operator=(std::initializer_list<T> init_list) {
245 cleanup_();
246 reset_();
247 assign_from_initializer_list_(init_list);
248 return *this;
249 }
250
251 // Allocate capacity - can be called multiple times to reinit
252 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
253 // Direct assignment via operator[] does NOT update the size counter.
254 void init(size_t n) {
255 cleanup_();
256 reset_();
257 if (n > 0) {
258 // Allocate raw memory without calling constructors
259 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
260 // NOLINTNEXTLINE(bugprone-sizeof-expression)
261 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
262 capacity_ = n;
263 }
264 }
265
266 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
267 void clear() {
268 destroy_elements_();
269 size_ = 0;
270 }
271
272 // Shrink capacity to fit current size (frees all memory)
274 cleanup_();
275 reset_();
276 }
277
281 void push_back(const T &value) {
282 if (size_ < capacity_) {
283 // Use placement new to construct the object in pre-allocated memory
284 new (&data_[size_]) T(value);
285 size_++;
286 }
287 }
288
292 void push_back(T &&value) {
293 if (size_ < capacity_) {
294 // Use placement new to move-construct the object in pre-allocated memory
295 new (&data_[size_]) T(std::move(value));
296 size_++;
297 }
298 }
299
304 template<typename... Args> T &emplace_back(Args &&...args) {
305 // Use placement new to construct the object in pre-allocated memory
306 new (&data_[size_]) T(std::forward<Args>(args)...);
307 size_++;
308 return data_[size_ - 1];
309 }
310
313 T &front() { return data_[0]; }
314 const T &front() const { return data_[0]; }
315
318 T &back() { return data_[size_ - 1]; }
319 const T &back() const { return data_[size_ - 1]; }
320
321 size_t size() const { return size_; }
322 bool empty() const { return size_ == 0; }
323
326 T &operator[](size_t i) { return data_[i]; }
327 const T &operator[](size_t i) const { return data_[i]; }
328
331 T &at(size_t i) { return data_[i]; }
332 const T &at(size_t i) const { return data_[i]; }
333
334 // Iterator support for range-based for loops
335 T *begin() { return data_; }
336 T *end() { return data_ + size_; }
337 const T *begin() const { return data_; }
338 const T *end() const { return data_ + size_; }
339};
340
342
345
347template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
348 return (value - min) * (max_out - min_out) / (max - min) + min_out;
349}
350
352uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
353
355uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
356 bool refin = false, bool refout = false);
357uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
358 bool refout = false);
359
361uint32_t fnv1_hash(const char *str);
362inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
363
365uint32_t random_uint32();
367float random_float();
369bool random_bytes(uint8_t *data, size_t len);
370
372
375
377constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
378 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
379}
381constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
382 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
383}
385constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
386 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
387 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
388}
389
391template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
392 T val = 0;
393 for (size_t i = 0; i < sizeof(T); i++) {
394 val <<= 8;
395 val |= bytes[i];
396 }
397 return val;
398}
400template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
401constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
402 return encode_value<T>(bytes.data());
403}
405template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
406constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
407 std::array<uint8_t, sizeof(T)> ret{};
408 for (size_t i = sizeof(T); i > 0; i--) {
409 ret[i - 1] = val & 0xFF;
410 val >>= 8;
411 }
412 return ret;
413}
414
416inline uint8_t reverse_bits(uint8_t x) {
417 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
418 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
419 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
420 return x;
421}
423inline uint16_t reverse_bits(uint16_t x) {
424 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
425}
427inline uint32_t reverse_bits(uint32_t x) {
428 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
429 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
430}
431
433template<typename T> constexpr T convert_big_endian(T val) {
434#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
435 return byteswap(val);
436#else
437 return val;
438#endif
439}
440
442template<typename T> constexpr T convert_little_endian(T val) {
443#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
444 return val;
445#else
446 return byteswap(val);
447#endif
448}
449
451
454
456bool str_equals_case_insensitive(const std::string &a, const std::string &b);
457
459bool str_startswith(const std::string &str, const std::string &start);
461bool str_endswith(const std::string &str, const std::string &end);
462
464std::string str_truncate(const std::string &str, size_t length);
465
468std::string str_until(const char *str, char ch);
470std::string str_until(const std::string &str, char ch);
471
473std::string str_lower_case(const std::string &str);
475std::string str_upper_case(const std::string &str);
477std::string str_snake_case(const std::string &str);
478
480std::string str_sanitize(const std::string &str);
481
483std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
484
486std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
487
496std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len);
497
499
502
504template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
505optional<T> parse_number(const char *str) {
506 char *end = nullptr;
507 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
508 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
509 return {};
510 return value;
511}
513template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
514optional<T> parse_number(const std::string &str) {
515 return parse_number<T>(str.c_str());
516}
518template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
519optional<T> parse_number(const char *str) {
520 char *end = nullptr;
521 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
522 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
523 return {};
524 return value;
525}
527template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
528optional<T> parse_number(const std::string &str) {
529 return parse_number<T>(str.c_str());
530}
532template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
533 char *end = nullptr;
534 float value = ::strtof(str, &end);
535 if (end == str || *end != '\0' || value == HUGE_VALF)
536 return {};
537 return value;
538}
540template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
541optional<T> parse_number(const std::string &str) {
542 return parse_number<T>(str.c_str());
543}
544
556size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
558inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
559 return parse_hex(str, strlen(str), data, count) == 2 * count;
560}
562inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
563 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
564}
566inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
567 data.resize(count);
568 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
569}
571inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
572 data.resize(count);
573 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
574}
580template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
581optional<T> parse_hex(const char *str, size_t len) {
582 T val = 0;
583 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
584 return {};
585 return convert_big_endian(val);
586}
588template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
589 return parse_hex<T>(str, strlen(str));
590}
592template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
593 return parse_hex<T>(str.c_str(), str.length());
594}
595
597inline char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
598
601inline char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
602
604inline void format_mac_addr_upper(const uint8_t *mac, char *output) {
605 for (size_t i = 0; i < 6; i++) {
606 uint8_t byte = mac[i];
607 output[i * 3] = format_hex_pretty_char(byte >> 4);
608 output[i * 3 + 1] = format_hex_pretty_char(byte & 0x0F);
609 if (i < 5)
610 output[i * 3 + 2] = ':';
611 }
612 output[17] = '\0';
613}
614
616inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
617 for (size_t i = 0; i < 6; i++) {
618 uint8_t byte = mac[i];
619 output[i * 2] = format_hex_char(byte >> 4);
620 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
621 }
622 output[12] = '\0';
623}
624
626std::string format_mac_address_pretty(const uint8_t mac[6]);
628std::string format_hex(const uint8_t *data, size_t length);
630std::string format_hex(const std::vector<uint8_t> &data);
632template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
634 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
635}
636template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
637 return format_hex(data.data(), data.size());
638}
639
665std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
666
687std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
688
710std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
711
732std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
733
754std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
755
779template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
780std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
782 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
783}
784
786std::string format_bin(const uint8_t *data, size_t length);
788template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
790 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
791}
792
801ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
802
804std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
806std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement);
807
809int8_t step_to_accuracy_decimals(float step);
810
811std::string base64_encode(const uint8_t *buf, size_t buf_len);
812std::string base64_encode(const std::vector<uint8_t> &buf);
813
814std::vector<uint8_t> base64_decode(const std::string &encoded_string);
815size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
816
818
821
823float gamma_correct(float value, float gamma);
825float gamma_uncorrect(float value, float gamma);
826
828void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
830void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
831
833
836
838constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
840constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
841
843
846
847template<typename... X> class CallbackManager;
848
853template<typename... Ts> class CallbackManager<void(Ts...)> {
854 public:
856 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
857
859 void call(Ts... args) {
860 for (auto &cb : this->callbacks_)
861 cb(args...);
862 }
863 size_t size() const { return this->callbacks_.size(); }
864
866 void operator()(Ts... args) { call(args...); }
867
868 protected:
869 std::vector<std::function<void(Ts...)>> callbacks_;
870};
871
873template<typename T> class Deduplicator {
874 public:
876 bool next(T value) {
877 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
878 return false;
879 }
880 this->has_value_ = true;
881 this->value_unknown_ = false;
882 this->last_value_ = value;
883 return true;
884 }
887 bool ret = !this->value_unknown_;
888 this->value_unknown_ = true;
889 return ret;
890 }
892 bool has_value() const { return this->has_value_; }
893
894 protected:
895 bool has_value_{false};
896 bool value_unknown_{false};
898};
899
901template<typename T> class Parented {
902 public:
904 Parented(T *parent) : parent_(parent) {}
905
907 T *get_parent() const { return parent_; }
909 void set_parent(T *parent) { parent_ = parent; }
910
911 protected:
912 T *parent_{nullptr};
913};
914
916
919
924class Mutex {
925 public:
926 Mutex();
927 Mutex(const Mutex &) = delete;
928 ~Mutex();
929 void lock();
930 bool try_lock();
931 void unlock();
932
933 Mutex &operator=(const Mutex &) = delete;
934
935 private:
936#if defined(USE_ESP32) || defined(USE_LIBRETINY)
937 SemaphoreHandle_t handle_;
938#else
939 // d-pointer to store private data on new platforms
940 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
941#endif
942};
943
949 public:
950 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
951 ~LockGuard() { mutex_.unlock(); }
952
953 private:
954 Mutex &mutex_;
955};
956
978 public:
981
982 protected:
983#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
984 uint32_t state_;
985#endif
986};
987
995class LwIPLock {
996 public:
997 LwIPLock();
998 ~LwIPLock();
999
1000 // Delete copy constructor and copy assignment operator to prevent accidental copying
1001 LwIPLock(const LwIPLock &) = delete;
1002 LwIPLock &operator=(const LwIPLock &) = delete;
1003};
1004
1011 public:
1013 void start();
1015 void stop();
1016
1018 static bool is_high_frequency();
1019
1020 protected:
1021 bool started_{false};
1022 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1023};
1024
1026void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
1027
1029std::string get_mac_address();
1030
1032std::string get_mac_address_pretty();
1033
1036void get_mac_address_into_buffer(std::span<char, 13> buf);
1037
1038#ifdef USE_ESP32
1040void set_mac_address(uint8_t *mac);
1041#endif
1042
1046
1049bool mac_address_is_valid(const uint8_t *mac);
1050
1052void delay_microseconds_safe(uint32_t us);
1053
1055
1058
1067template<class T> class RAMAllocator {
1068 public:
1069 using value_type = T;
1070
1071 enum Flags {
1072 NONE = 0, // Perform external allocation and fall back to internal memory
1073 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
1074 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
1075 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
1076 };
1077
1078 RAMAllocator() = default;
1080 // default is both external and internal
1082 if (flags != 0)
1083 this->flags_ = flags;
1084 }
1085 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
1086
1087 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
1088
1089 T *allocate(size_t n, size_t manual_size) {
1090 size_t size = n * manual_size;
1091 T *ptr = nullptr;
1092#ifdef USE_ESP32
1093 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1094 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1095 }
1096 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1097 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1098 }
1099#else
1100 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1101 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1102#endif
1103 return ptr;
1104 }
1105
1106 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
1107
1108 T *reallocate(T *p, size_t n, size_t manual_size) {
1109 size_t size = n * manual_size;
1110 T *ptr = nullptr;
1111#ifdef USE_ESP32
1112 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1113 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1114 }
1115 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1116 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1117 }
1118#else
1119 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1120 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1121#endif
1122 return ptr;
1123 }
1124
1125 void deallocate(T *p, size_t n) {
1126 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1127 }
1128
1132 size_t get_free_heap_size() const {
1133#ifdef USE_ESP8266
1134 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
1135#elif defined(USE_ESP32)
1136 auto max_internal =
1137 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1138 auto max_external =
1139 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1140 return max_internal + max_external;
1141#elif defined(USE_RP2040)
1142 return ::rp2040.getFreeHeap();
1143#elif defined(USE_LIBRETINY)
1144 return lt_heap_get_free();
1145#else
1146 return 100000;
1147#endif
1148 }
1149
1154#ifdef USE_ESP8266
1155 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
1156#elif defined(USE_ESP32)
1157 auto max_internal =
1158 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1159 auto max_external =
1160 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1161 return std::max(max_internal, max_external);
1162#else
1163 return this->get_free_heap_size();
1164#endif
1165 }
1166
1167 private:
1168 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
1169};
1170
1171template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
1172
1177template<typename T, typename U>
1178concept comparable_with = requires(T a, U b) {
1179 { a > b } -> std::convertible_to<bool>;
1180 { a < b } -> std::convertible_to<bool>;
1181};
1182
1183template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
1184 if (value < min)
1185 return min;
1186 return value;
1187}
1188template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
1189 if (value > max)
1190 return max;
1191 return value;
1192}
1193
1196
1201template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
1206template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
1207
1209
1210} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:866
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:869
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:859
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:856
Helper class to deduplicate items in a series of values.
Definition helpers.h:873
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:876
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:892
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:886
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:332
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:337
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:244
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:313
const T & operator[](size_t i) const
Definition helpers.h:327
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:326
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:318
bool empty() const
Definition helpers.h:322
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:292
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:304
size_t size() const
Definition helpers.h:321
const T & front() const
Definition helpers.h:314
const T & back() const
Definition helpers.h:319
const T * end() const
Definition helpers.h:338
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:228
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:331
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:281
void init(size_t n)
Definition helpers.h:254
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:1010
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:977
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:948
LockGuard(Mutex &mutex)
Definition helpers.h:950
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:995
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:924
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:901
T * get_parent() const
Get the parent of this object.
Definition helpers.h:907
Parented(T *parent)
Definition helpers.h:904
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:909
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1067
RAMAllocator(uint8_t flags)
Definition helpers.h:1079
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:1108
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:1132
T * reallocate(T *p, size_t n)
Definition helpers.h:1106
void deallocate(T *p, size_t n)
Definition helpers.h:1125
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:1153
T * allocate(size_t n)
Definition helpers.h:1087
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:1085
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:1089
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:1178
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:1188
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:433
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:601
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:604
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:616
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:442
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:483
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:381
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:1183
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:505
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:391
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:385
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:838
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:377
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:597
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:406
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:840
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:416
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:347
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:794
@ PARSE_ON
Definition helpers.h:796
@ PARSE_TOGGLE
Definition helpers.h:798
@ PARSE_OFF
Definition helpers.h:797
@ PARSE_NONE
Definition helpers.h:795
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