ESPHome 2026.2.2
Loading...
Searching...
No Matches
helpers.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <cstdarg>
7#include <cstdint>
8#include <cstdio>
9#include <cstring>
10#include <functional>
11#include <iterator>
12#include <limits>
13#include <memory>
14#include <span>
15#include <string>
16#include <type_traits>
17#include <vector>
18#include <concepts>
19#include <strings.h>
20
22
23#ifdef USE_ESP8266
24#include <Esp.h>
25#include <pgmspace.h>
26#endif
27
28#ifdef USE_RP2040
29#include <Arduino.h>
30#endif
31
32#ifdef USE_ESP32
33#include <esp_heap_caps.h>
34#endif
35
36#if defined(USE_ESP32)
37#include <freertos/FreeRTOS.h>
38#include <freertos/semphr.h>
39#elif defined(USE_LIBRETINY)
40#include <FreeRTOS.h>
41#include <semphr.h>
42#endif
43
44#ifdef USE_HOST
45#include <mutex>
46#endif
47
48#define HOT __attribute__((hot))
49#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
50#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
51#define PACKED __attribute__((packed))
52
53namespace esphome {
54
55// Forward declaration to avoid circular dependency with string_ref.h
56class StringRef;
57
60
61// Keep "using" even after the removal of our backports, to avoid breaking existing code.
62using std::to_string;
63using std::is_trivially_copyable;
64using std::make_unique;
65using std::enable_if_t;
66using std::clamp;
67using std::is_invocable;
68#if __cpp_lib_bit_cast >= 201806
69using std::bit_cast;
70#else
72template<
73 typename To, typename From,
74 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
75 int> = 0>
76To bit_cast(const From &src) {
77 To dst;
78 memcpy(&dst, &src, sizeof(To));
79 return dst;
80}
81#endif
82
83// clang-format off
84inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
85// clang-format on
86
87// std::byteswap from C++23
88template<typename T> constexpr T byteswap(T n) {
89 T m;
90 for (size_t i = 0; i < sizeof(T); i++)
91 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
92 return m;
93}
94template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
95#ifdef USE_LIBRETINY
96// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
97template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
98template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
99template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
100template<> inline int8_t byteswap(int8_t n) { return n; }
101template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
102template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
103template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
104#else
105template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
106template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
107template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
108template<> constexpr int8_t byteswap(int8_t n) { return n; }
109template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
110template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
111template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
112#endif
113
115
118
122
123template<typename T> class ConstVector {
124 public:
125 constexpr ConstVector(const T *data, size_t size) : data_(data), size_(size) {}
126
127 const constexpr T &operator[](size_t i) const { return data_[i]; }
128 constexpr size_t size() const { return size_; }
129 constexpr bool empty() const { return size_ == 0; }
130
131 protected:
132 const T *data_;
133 size_t size_;
134};
135
137template<typename T, size_t N> class StaticVector {
138 public:
139 using value_type = T;
140 using iterator = typename std::array<T, N>::iterator;
141 using const_iterator = typename std::array<T, N>::const_iterator;
142 using reverse_iterator = std::reverse_iterator<iterator>;
143 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
144
145 private:
146 std::array<T, N> data_{};
147 size_t count_{0};
148
149 public:
150 // Default constructor
151 StaticVector() = default;
152
153 // Iterator range constructor
154 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
155 while (first != last && count_ < N) {
156 data_[count_++] = *first++;
157 }
158 }
159
160 // Initializer list constructor
161 StaticVector(std::initializer_list<T> init) {
162 for (const auto &val : init) {
163 if (count_ >= N)
164 break;
165 data_[count_++] = val;
166 }
167 }
168
169 // Minimal vector-compatible interface - only what we actually use
170 void push_back(const T &value) {
171 if (count_ < N) {
172 data_[count_++] = value;
173 }
174 }
175
176 // Clear all elements
177 void clear() { count_ = 0; }
178
179 // Assign from iterator range
180 template<typename InputIt> void assign(InputIt first, InputIt last) {
181 count_ = 0;
182 while (first != last && count_ < N) {
183 data_[count_++] = *first++;
184 }
185 }
186
187 // Return reference to next element and increment count (with bounds checking)
189 if (count_ >= N) {
190 // Should never happen with proper size calculation
191 // Return reference to last element to avoid crash
192 return data_[N - 1];
193 }
194 return data_[count_++];
195 }
196
197 size_t size() const { return count_; }
198 bool empty() const { return count_ == 0; }
199
200 // Direct access to underlying data
201 T *data() { return data_.data(); }
202 const T *data() const { return data_.data(); }
203
204 T &operator[](size_t i) { return data_[i]; }
205 const T &operator[](size_t i) const { return data_[i]; }
206
207 // For range-based for loops
208 iterator begin() { return data_.begin(); }
209 iterator end() { return data_.begin() + count_; }
210 const_iterator begin() const { return data_.begin(); }
211 const_iterator end() const { return data_.begin() + count_; }
212
213 // Reverse iterators
218
219 // Conversion to std::span for compatibility with span-based APIs
220 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
221 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
222};
223
227template<typename T> class FixedVector {
228 private:
229 T *data_{nullptr};
230 size_t size_{0};
231 size_t capacity_{0};
232
233 // Helper to destroy all elements without freeing memory
234 void destroy_elements_() {
235 // Only call destructors for non-trivially destructible types
236 if constexpr (!std::is_trivially_destructible<T>::value) {
237 for (size_t i = 0; i < size_; i++) {
238 data_[i].~T();
239 }
240 }
241 }
242
243 // Helper to destroy elements and free memory
244 void cleanup_() {
245 if (data_ != nullptr) {
246 destroy_elements_();
247 // Free raw memory
248 ::operator delete(data_);
249 }
250 }
251
252 // Helper to reset pointers after cleanup
253 void reset_() {
254 data_ = nullptr;
255 capacity_ = 0;
256 size_ = 0;
257 }
258
259 // Helper to assign from initializer list (shared by constructor and assignment operator)
260 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
261 init(init_list.size());
262 size_t idx = 0;
263 for (const auto &item : init_list) {
264 new (data_ + idx) T(item);
265 ++idx;
266 }
267 size_ = init_list.size();
268 }
269
270 public:
271 FixedVector() = default;
272
275 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
276
277 ~FixedVector() { cleanup_(); }
278
279 // Disable copy operations (avoid accidental expensive copies)
280 FixedVector(const FixedVector &) = delete;
282
283 // Enable move semantics (allows use in move-only containers like std::vector)
284 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
285 other.reset_();
286 }
287
288 // Allow conversion to std::vector
289 operator std::vector<T>() const { return {data_, data_ + size_}; }
290
291 FixedVector &operator=(FixedVector &&other) noexcept {
292 if (this != &other) {
293 // Delete our current data
294 cleanup_();
295 // Take ownership of other's data
296 data_ = other.data_;
297 size_ = other.size_;
298 capacity_ = other.capacity_;
299 // Leave other in valid empty state
300 other.reset_();
301 }
302 return *this;
303 }
304
307 FixedVector &operator=(std::initializer_list<T> init_list) {
308 cleanup_();
309 reset_();
310 assign_from_initializer_list_(init_list);
311 return *this;
312 }
313
314 // Allocate capacity - can be called multiple times to reinit
315 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
316 // Direct assignment via operator[] does NOT update the size counter.
317 void init(size_t n) {
318 cleanup_();
319 reset_();
320 if (n > 0) {
321 // Allocate raw memory without calling constructors
322 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
323 // NOLINTNEXTLINE(bugprone-sizeof-expression)
324 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
325 capacity_ = n;
326 }
327 }
328
329 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
330 void clear() {
331 destroy_elements_();
332 size_ = 0;
333 }
334
335 // Release all memory (destroys elements and frees memory)
336 void release() {
337 cleanup_();
338 reset_();
339 }
340
344 void push_back(const T &value) {
345 if (size_ < capacity_) {
346 // Use placement new to construct the object in pre-allocated memory
347 new (&data_[size_]) T(value);
348 size_++;
349 }
350 }
351
355 void push_back(T &&value) {
356 if (size_ < capacity_) {
357 // Use placement new to move-construct the object in pre-allocated memory
358 new (&data_[size_]) T(std::move(value));
359 size_++;
360 }
361 }
362
367 template<typename... Args> T &emplace_back(Args &&...args) {
368 // Use placement new to construct the object in pre-allocated memory
369 new (&data_[size_]) T(std::forward<Args>(args)...);
370 size_++;
371 return data_[size_ - 1];
372 }
373
376 T &front() { return data_[0]; }
377 const T &front() const { return data_[0]; }
378
381 T &back() { return data_[size_ - 1]; }
382 const T &back() const { return data_[size_ - 1]; }
383
384 size_t size() const { return size_; }
385 bool empty() const { return size_ == 0; }
386 size_t capacity() const { return capacity_; }
387 bool full() const { return size_ == capacity_; }
388
391 T &operator[](size_t i) { return data_[i]; }
392 const T &operator[](size_t i) const { return data_[i]; }
393
396 T &at(size_t i) { return data_[i]; }
397 const T &at(size_t i) const { return data_[i]; }
398
399 // Iterator support for range-based for loops
400 T *begin() { return data_; }
401 T *end() { return data_ + size_; }
402 const T *begin() const { return data_; }
403 const T *end() const { return data_ + size_; }
404};
405
411template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
412 public:
414 if (size <= STACK_SIZE) {
415 this->buffer_ = this->stack_buffer_;
416 } else {
417 this->heap_buffer_ = new T[size];
418 this->buffer_ = this->heap_buffer_;
419 }
420 }
421 ~SmallBufferWithHeapFallback() { delete[] this->heap_buffer_; }
422
423 // Delete copy and move operations to prevent double-delete
428
429 T *get() { return this->buffer_; }
430
431 private:
432 T stack_buffer_[STACK_SIZE];
433 T *heap_buffer_{nullptr};
434 T *buffer_;
435};
436
438
441
443template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
444 return (value - min) * (max_out - min_out) / (max - min) + min_out;
445}
446
448uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
449
451uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
452 bool refin = false, bool refout = false);
453uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
454 bool refout = false);
455
458uint32_t fnv1_hash(const char *str);
459inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
460
462constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
464constexpr uint32_t FNV1_PRIME = 16777619UL;
465
467template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
468 using UnsignedT = std::make_unsigned_t<T>;
469 UnsignedT uvalue = static_cast<UnsignedT>(value);
470 for (size_t i = 0; i < sizeof(T); i++) {
471 hash *= FNV1_PRIME;
472 hash ^= (uvalue >> (i * 8)) & 0xFF;
473 }
474 return hash;
475}
477constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
478 if (str) {
479 while (*str) {
480 hash *= FNV1_PRIME;
481 hash ^= *str++;
482 }
483 }
484 return hash;
485}
486inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
487
489constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
490 if (str) {
491 while (*str) {
492 hash ^= *str++;
493 hash *= FNV1_PRIME;
494 }
495 }
496 return hash;
497}
498inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
499 return fnv1a_hash_extend(hash, str.c_str());
500}
502template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
503 using UnsignedT = std::make_unsigned_t<T>;
504 UnsignedT uvalue = static_cast<UnsignedT>(value);
505 for (size_t i = 0; i < sizeof(T); i++) {
506 hash ^= (uvalue >> (i * 8)) & 0xFF;
507 hash *= FNV1_PRIME;
508 }
509 return hash;
510}
512constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
513inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
514
516uint32_t random_uint32();
518float random_float();
520bool random_bytes(uint8_t *data, size_t len);
521
523
526
528constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
529 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
530}
532constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
533 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
534}
536constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
537 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
538 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
539}
540
542template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
543 T val = 0;
544 for (size_t i = 0; i < sizeof(T); i++) {
545 val <<= 8;
546 val |= bytes[i];
547 }
548 return val;
549}
551template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
552constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
553 return encode_value<T>(bytes.data());
554}
556template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
557constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
558 std::array<uint8_t, sizeof(T)> ret{};
559 for (size_t i = sizeof(T); i > 0; i--) {
560 ret[i - 1] = val & 0xFF;
561 val >>= 8;
562 }
563 return ret;
564}
565
567inline uint8_t reverse_bits(uint8_t x) {
568 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
569 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
570 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
571 return x;
572}
574inline uint16_t reverse_bits(uint16_t x) {
575 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
576}
578inline uint32_t reverse_bits(uint32_t x) {
579 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
580 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
581}
582
584template<typename T> constexpr T convert_big_endian(T val) {
585#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
586 return byteswap(val);
587#else
588 return val;
589#endif
590}
591
593template<typename T> constexpr T convert_little_endian(T val) {
594#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
595 return val;
596#else
597 return byteswap(val);
598#endif
599}
600
602
605
607bool str_equals_case_insensitive(const std::string &a, const std::string &b);
609bool str_equals_case_insensitive(StringRef a, StringRef b);
611inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
612inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
613inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
614
616bool str_startswith(const std::string &str, const std::string &start);
618bool str_endswith(const std::string &str, const std::string &end);
619
621bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
622inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
623 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
624}
625inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
626 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
627}
628
631std::string str_truncate(const std::string &str, size_t length);
632
635std::string str_until(const char *str, char ch);
637std::string str_until(const std::string &str, char ch);
638
640std::string str_lower_case(const std::string &str);
643std::string str_upper_case(const std::string &str);
644
646constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
649std::string str_snake_case(const std::string &str);
650
652constexpr char to_sanitized_char(char c) {
653 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
654}
655
665char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
666
668template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
669 return str_sanitize_to(buffer, N, str);
670}
671
674std::string str_sanitize(const std::string &str);
675
680inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
681 uint32_t hash = FNV1_OFFSET_BASIS;
682 for (size_t i = 0; i < len; i++) {
683 hash *= FNV1_PRIME;
684 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
685 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(str[i])));
686 }
687 return hash;
688}
689
692std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
693
696std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
697
698#ifdef USE_ESP8266
699// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
700// Format strings must be wrapped with PSTR() macro
707inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
708 if (pos >= size) {
709 return size;
710 }
711 va_list args;
712 va_start(args, fmt);
713 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
714 va_end(args);
715 if (written < 0) {
716 return pos; // encoding error
717 }
718 return std::min(pos + static_cast<size_t>(written), size);
719}
720#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
721#else
729__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
730 const char *fmt, ...) {
731 if (pos >= size) {
732 return size;
733 }
734 va_list args;
735 va_start(args, fmt);
736 int written = vsnprintf(buf + pos, size - pos, fmt, args);
737 va_end(args);
738 if (written < 0) {
739 return pos; // encoding error
740 }
741 return std::min(pos + static_cast<size_t>(written), size);
742}
743#endif
744
753std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len);
754
763std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
764 size_t suffix_len);
765
775size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
776 const char *suffix_ptr, size_t suffix_len);
777
779
782
784template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
785optional<T> parse_number(const char *str) {
786 char *end = nullptr;
787 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
788 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
789 return {};
790 return value;
791}
793template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
794optional<T> parse_number(const std::string &str) {
795 return parse_number<T>(str.c_str());
796}
798template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
799optional<T> parse_number(const char *str) {
800 char *end = nullptr;
801 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
802 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
803 return {};
804 return value;
805}
807template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
808optional<T> parse_number(const std::string &str) {
809 return parse_number<T>(str.c_str());
810}
812template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
813 char *end = nullptr;
814 float value = ::strtof(str, &end);
815 if (end == str || *end != '\0' || value == HUGE_VALF)
816 return {};
817 return value;
818}
820template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
821optional<T> parse_number(const std::string &str) {
822 return parse_number<T>(str.c_str());
823}
824
836size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
838inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
839 return parse_hex(str, strlen(str), data, count) == 2 * count;
840}
842inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
843 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
844}
846inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
847 data.resize(count);
848 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
849}
851inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
852 data.resize(count);
853 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
854}
860template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
861optional<T> parse_hex(const char *str, size_t len) {
862 T val = 0;
863 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
864 return {};
865 return convert_big_endian(val);
866}
868template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
869 return parse_hex<T>(str, strlen(str));
870}
872template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
873 return parse_hex<T>(str.c_str(), str.length());
874}
875
878static constexpr uint8_t INVALID_HEX_CHAR = 255;
879
880constexpr uint8_t parse_hex_char(char c) {
881 if (c >= '0' && c <= '9')
882 return c - '0';
883 if (c >= 'A' && c <= 'F')
884 return c - 'A' + 10;
885 if (c >= 'a' && c <= 'f')
886 return c - 'a' + 10;
887 return INVALID_HEX_CHAR;
888}
889
891inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
892
894inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
895
897inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
898
901inline char *int8_to_str(char *buf, int8_t val) {
902 int32_t v = val;
903 if (v < 0) {
904 *buf++ = '-';
905 v = -v;
906 }
907 if (v >= 100) {
908 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
909 v -= 100;
910 // Must write tens digit (even if 0) after hundreds
911 int32_t tens = v / 10;
912 *buf++ = '0' + tens;
913 v -= tens * 10;
914 } else if (v >= 10) {
915 int32_t tens = v / 10;
916 *buf++ = '0' + tens;
917 v -= tens * 10;
918 }
919 *buf++ = '0' + v;
920 return buf;
921}
922
924char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
925
928template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
929 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
930 return format_hex_to(buffer, N, data, length);
931}
932
934template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
935inline char *format_hex_to(char (&buffer)[N], T val) {
936 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
938 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
939}
940
942template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
943 return format_hex_to(buffer, data.data(), data.size());
944}
945
947template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
948 return format_hex_to(buffer, data.data(), data.size());
949}
950
952constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
953
955constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
956
958template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
959inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
960 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
961 buffer[0] = '0';
962 buffer[1] = 'x';
964 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
965 return buffer;
966}
967
969template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
970 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
971 buffer[0] = '0';
972 buffer[1] = 'x';
973 format_hex_to(buffer + 2, N - 2, data, length);
974 return buffer;
975}
976
978constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
979
991char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
992
994template<size_t N>
995inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
996 static_assert(N >= 3, "Buffer must hold at least one hex byte");
997 return format_hex_pretty_to(buffer, N, data, length, separator);
998}
999
1001template<size_t N>
1002inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1003 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1004}
1005
1007template<size_t N, size_t M>
1008inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1009 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1010}
1011
1013constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1014
1028char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1029
1031template<size_t N>
1032inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1033 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1034 return format_hex_pretty_to(buffer, N, data, length, separator);
1035}
1036
1038static constexpr size_t MAC_ADDRESS_SIZE = 6;
1040static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1042static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1043
1045inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1046 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1047}
1048
1050inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1051 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1052}
1053
1057std::string format_mac_address_pretty(const uint8_t mac[6]);
1061std::string format_hex(const uint8_t *data, size_t length);
1065std::string format_hex(const std::vector<uint8_t> &data);
1069template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
1071 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1072}
1076template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
1077 return format_hex(data.data(), data.size());
1078}
1079
1105std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
1106
1127std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
1128
1150std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
1151
1172std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
1173
1194std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
1195
1219template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1220std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
1222 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
1223}
1224
1226constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1227
1247char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1248
1250template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1251 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1252 return format_bin_to(buffer, N, data, length);
1253}
1254
1271template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1272inline char *format_bin_to(char (&buffer)[N], T val) {
1273 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1275 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1276}
1277
1281std::string format_bin(const uint8_t *data, size_t length);
1285template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
1287 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1288}
1289
1298ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1299
1301ESPDEPRECATED("Allocates heap memory. Use value_accuracy_to_buf() instead. Removed in 2026.7.0.", "2026.1.0")
1302std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
1303
1305static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1306
1308size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1310size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1311 int8_t accuracy_decimals, StringRef unit_of_measurement);
1312
1314int8_t step_to_accuracy_decimals(float step);
1315
1316std::string base64_encode(const uint8_t *buf, size_t buf_len);
1317std::string base64_encode(const std::vector<uint8_t> &buf);
1318
1319std::vector<uint8_t> base64_decode(const std::string &encoded_string);
1320size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1321size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1322
1327bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1328
1330
1333
1335float gamma_correct(float value, float gamma);
1337float gamma_uncorrect(float value, float gamma);
1338
1340void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1342void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1343
1345
1348
1350constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1352constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1353
1355
1358
1359template<typename... X> class CallbackManager;
1360
1365template<typename... Ts> class CallbackManager<void(Ts...)> {
1366 public:
1368 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
1369
1371 void call(Ts... args) {
1372 for (auto &cb : this->callbacks_)
1373 cb(args...);
1374 }
1375 size_t size() const { return this->callbacks_.size(); }
1376
1378 void operator()(Ts... args) { call(args...); }
1379
1380 protected:
1381 std::vector<std::function<void(Ts...)>> callbacks_;
1382};
1383
1384template<typename... X> class LazyCallbackManager;
1385
1401template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
1402 public:
1406 ~LazyCallbackManager() { delete this->callbacks_; }
1407
1408 // Non-copyable and non-movable (entities are never copied or moved)
1413
1415 void add(std::function<void(Ts...)> &&callback) {
1416 if (!this->callbacks_) {
1417 this->callbacks_ = new CallbackManager<void(Ts...)>();
1418 }
1419 this->callbacks_->add(std::move(callback));
1420 }
1421
1423 void call(Ts... args) {
1424 if (this->callbacks_) {
1425 this->callbacks_->call(args...);
1426 }
1427 }
1428
1430 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
1431
1433 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
1434
1436 void operator()(Ts... args) { this->call(args...); }
1437
1438 protected:
1439 CallbackManager<void(Ts...)> *callbacks_{nullptr};
1440};
1441
1443template<typename T> class Deduplicator {
1444 public:
1446 bool next(T value) {
1447 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
1448 return false;
1449 }
1450 this->has_value_ = true;
1451 this->value_unknown_ = false;
1452 this->last_value_ = value;
1453 return true;
1454 }
1457 bool ret = !this->value_unknown_;
1458 this->value_unknown_ = true;
1459 return ret;
1460 }
1462 bool has_value() const { return this->has_value_; }
1463
1464 protected:
1465 bool has_value_{false};
1466 bool value_unknown_{false};
1468};
1469
1471template<typename T> class Parented {
1472 public:
1474 Parented(T *parent) : parent_(parent) {}
1475
1477 T *get_parent() const { return parent_; }
1479 void set_parent(T *parent) { parent_ = parent; }
1480
1481 protected:
1482 T *parent_{nullptr};
1483};
1484
1486
1489
1494class Mutex {
1495 public:
1496 Mutex();
1497 Mutex(const Mutex &) = delete;
1498 ~Mutex();
1499 void lock();
1500 bool try_lock();
1501 void unlock();
1502
1503 Mutex &operator=(const Mutex &) = delete;
1504
1505 private:
1506#if defined(USE_ESP32) || defined(USE_LIBRETINY)
1507 SemaphoreHandle_t handle_;
1508#else
1509 // d-pointer to store private data on new platforms
1510 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
1511#endif
1512};
1513
1519 public:
1520 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
1521 ~LockGuard() { mutex_.unlock(); }
1522
1523 private:
1524 Mutex &mutex_;
1525};
1526
1548 public:
1549 InterruptLock();
1551
1552 protected:
1553#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
1554 uint32_t state_;
1555#endif
1556};
1557
1566 public:
1567 LwIPLock();
1568 ~LwIPLock();
1569
1570 // Delete copy constructor and copy assignment operator to prevent accidental copying
1571 LwIPLock(const LwIPLock &) = delete;
1572 LwIPLock &operator=(const LwIPLock &) = delete;
1573};
1574
1581 public:
1583 void start();
1585 void stop();
1586
1588 static bool is_high_frequency();
1589
1590 protected:
1591 bool started_{false};
1592 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1593};
1594
1596void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
1597
1601std::string get_mac_address();
1602
1606std::string get_mac_address_pretty();
1607
1611void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
1612
1616const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
1617
1618#ifdef USE_ESP32
1620void set_mac_address(uint8_t *mac);
1621#endif
1622
1626
1629bool mac_address_is_valid(const uint8_t *mac);
1630
1632void delay_microseconds_safe(uint32_t us);
1633
1635
1638
1647template<class T> class RAMAllocator {
1648 public:
1649 using value_type = T;
1650
1651 enum Flags {
1652 NONE = 0, // Perform external allocation and fall back to internal memory
1653 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
1654 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
1655 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
1656 };
1657
1658 RAMAllocator() = default;
1660 // default is both external and internal
1662 if (flags != 0)
1663 this->flags_ = flags;
1664 }
1665 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
1666
1667 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
1668
1669 T *allocate(size_t n, size_t manual_size) {
1670 size_t size = n * manual_size;
1671 T *ptr = nullptr;
1672#ifdef USE_ESP32
1673 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1674 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1675 }
1676 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1677 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1678 }
1679#else
1680 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1681 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1682#endif
1683 return ptr;
1684 }
1685
1686 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
1687
1688 T *reallocate(T *p, size_t n, size_t manual_size) {
1689 size_t size = n * manual_size;
1690 T *ptr = nullptr;
1691#ifdef USE_ESP32
1692 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1693 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1694 }
1695 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1696 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1697 }
1698#else
1699 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1700 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1701#endif
1702 return ptr;
1703 }
1704
1705 void deallocate(T *p, size_t n) {
1706 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1707 }
1708
1712 size_t get_free_heap_size() const {
1713#ifdef USE_ESP8266
1714 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
1715#elif defined(USE_ESP32)
1716 auto max_internal =
1717 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1718 auto max_external =
1719 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1720 return max_internal + max_external;
1721#elif defined(USE_RP2040)
1722 return ::rp2040.getFreeHeap();
1723#elif defined(USE_LIBRETINY)
1724 return lt_heap_get_free();
1725#else
1726 return 100000;
1727#endif
1728 }
1729
1734#ifdef USE_ESP8266
1735 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
1736#elif defined(USE_ESP32)
1737 auto max_internal =
1738 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1739 auto max_external =
1740 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1741 return std::max(max_internal, max_external);
1742#else
1743 return this->get_free_heap_size();
1744#endif
1745 }
1746
1747 private:
1748 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
1749};
1750
1751template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
1752
1757template<typename T, typename U>
1758concept comparable_with = requires(T a, U b) {
1759 { a > b } -> std::convertible_to<bool>;
1760 { a < b } -> std::convertible_to<bool>;
1761};
1762
1763template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
1764 if (value < min)
1765 return min;
1766 return value;
1767}
1768template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
1769 if (value > max)
1770 return max;
1771 return value;
1772}
1773
1776
1781template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
1786template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
1787
1789
1790} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1378
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:1381
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1371
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:1368
Lightweight read-only view over a const array stored in RODATA (will typically be in flash memory) Av...
Definition helpers.h:123
const constexpr T & operator[](size_t i) const
Definition helpers.h:127
constexpr bool empty() const
Definition helpers.h:129
constexpr ConstVector(const T *data, size_t size)
Definition helpers.h:125
constexpr size_t size() const
Definition helpers.h:128
Helper class to deduplicate items in a series of values.
Definition helpers.h:1443
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:1446
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:1462
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:1456
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:227
const T & at(size_t i) const
Definition helpers.h:397
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:284
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:275
const T * begin() const
Definition helpers.h:402
bool full() const
Definition helpers.h:387
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:307
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:376
const T & operator[](size_t i) const
Definition helpers.h:392
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:391
size_t capacity() const
Definition helpers.h:386
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:381
bool empty() const
Definition helpers.h:385
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:355
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:367
size_t size() const
Definition helpers.h:384
const T & front() const
Definition helpers.h:377
const T & back() const
Definition helpers.h:382
const T * end() const
Definition helpers.h:403
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:291
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:396
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:344
void init(size_t n)
Definition helpers.h:317
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:1580
void stop()
Stop running the loop continuously.
Definition helpers.cpp:792
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:798
void start()
Start running the loop continuously.
Definition helpers.cpp:786
Helper class to disable interrupts.
Definition helpers.h:1547
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:1430
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1436
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list. Allocates the underlying CallbackManager on first use.
Definition helpers.h:1415
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:1406
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:1423
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:1433
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1518
LockGuard(Mutex &mutex)
Definition helpers.h:1520
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:1565
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1494
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:1471
T * get_parent() const
Get the parent of this object.
Definition helpers.h:1477
Parented(T *parent)
Definition helpers.h:1474
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:1479
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1647
RAMAllocator(uint8_t flags)
Definition helpers.h:1659
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:1688
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:1712
T * reallocate(T *p, size_t n)
Definition helpers.h:1686
void deallocate(T *p, size_t n)
Definition helpers.h:1705
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:1733
T * allocate(size_t n)
Definition helpers.h:1667
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:1665
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:1669
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:411
SmallBufferWithHeapFallback(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback & operator=(SmallBufferWithHeapFallback &&)=delete
SmallBufferWithHeapFallback & operator=(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback(SmallBufferWithHeapFallback &&)=delete
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:137
const_reverse_iterator rend() const
Definition helpers.h:217
size_t size() const
Definition helpers.h:197
reverse_iterator rbegin()
Definition helpers.h:214
const T & operator[](size_t i) const
Definition helpers.h:205
reverse_iterator rend()
Definition helpers.h:215
void push_back(const T &value)
Definition helpers.h:170
bool empty() const
Definition helpers.h:198
void assign(InputIt first, InputIt last)
Definition helpers.h:180
const_reverse_iterator rbegin() const
Definition helpers.h:216
T & operator[](size_t i)
Definition helpers.h:204
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:143
typename std::array< T, N >::iterator iterator
Definition helpers.h:140
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:141
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:142
const T * data() const
Definition helpers.h:202
const_iterator end() const
Definition helpers.h:211
StaticVector(InputIt first, InputIt last)
Definition helpers.h:154
StaticVector(std::initializer_list< T > init)
Definition helpers.h:161
const_iterator begin() const
Definition helpers.h:210
struct @65::@66 __attribute__
Functions to constrain the range of arithmetic values.
Definition helpers.h:1758
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:1768
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:489
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:159
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:712
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:73
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Zero-allocation version: format name + separator + suffix directly into buffer.
Definition helpers.cpp:261
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Definition helpers.cpp:477
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:584
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:897
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:704
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:652
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:830
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1050
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:462
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:721
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:345
char format_hex_char(uint8_t v, char base)
Convert a nibble (0-15) to hex char with specified base ('a' for lowercase, 'A' for uppercase)
Definition helpers.h:891
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:483
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:201
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:454
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:447
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:593
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:222
constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value)
Extend a FNV-1 hash with an integer (hashes each byte).
Definition helpers.h:467
bool base64_decode_int32_vector(const std::string &base64, std::vector< int32_t > &out)
Decode base64/base64url string directly into vector of little-endian int32 values.
Definition helpers.cpp:666
va_end(args)
std::string size_t len
Definition helpers.h:692
constexpr size_t format_hex_prefixed_size(size_t byte_count)
Calculate buffer size needed for format_hex_prefixed_to: "0xXXXXXXXX...\0" = bytes * 2 + 3.
Definition helpers.h:955
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:532
char * format_hex_prefixed_to(char(&buffer)[N], T val)
Format an unsigned integer as "0x" prefixed lowercase hex to buffer.
Definition helpers.h:959
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:93
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:294
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:353
size_t size
Definition helpers.h:729
uint32_t fnv1_hash_object_id(const char *str, size_t len)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
Definition helpers.h:680
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:148
T clamp_at_least(T value, U min)
Definition helpers.h:1763
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:785
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:808
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:228
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:507
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
size_t size_t pos
Definition helpers.h:729
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:819
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:845
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:202
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:401
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:952
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:163
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:188
bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len)
Case-insensitive check if string ends with suffix (no heap allocation).
Definition helpers.cpp:179
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
Definition helpers.cpp:210
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
Definition helpers.h:901
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:305
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:493
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:978
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:546
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:464
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:542
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:744
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:813
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:113
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:536
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:46
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:1350
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:242
size_t size_t const char va_start(args, fmt)
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:528
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
size_t size_t const char * fmt
Definition helpers.h:730
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:880
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:170
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:557
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:800
constexpr size_t format_bin_size(size_t byte_count)
Calculate buffer size needed for format_bin_to: "01234567...\0" = bytes * 8 + 1.
Definition helpers.h:1226
int written
Definition helpers.h:736
struct ESPDEPRECATED("Use std::index_sequence instead. Removed in 2026.6.0", "2025.12.0") seq
Definition automation.h:25
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:76
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:646
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1352
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:567
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:341
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:203
float lerp(float completion, float start, float end)=delete
constexpr size_t format_hex_pretty_uint16_size(size_t count)
Calculate buffer size needed for format_hex_pretty_to with uint16_t data: "XXXX:XXXX:....
Definition helpers.h:1013
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:443
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:171
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:512
std::string size_t std::string size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt,...)
Safely append formatted string to buffer, returning new position (capped at size).
Definition helpers.h:707
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:588
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1291
@ PARSE_ON
Definition helpers.h:1293
@ PARSE_TOGGLE
Definition helpers.h:1295
@ PARSE_OFF
Definition helpers.h:1294
@ PARSE_NONE
Definition helpers.h:1292
std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Optimized string concatenation: name + separator + suffix (const char* overload) Uses a fixed stack b...
Definition helpers.cpp:281
char * format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as binary string to buffer.
Definition helpers.cpp:426
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1045
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:185
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