ESPHome 2026.3.0-dev
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
139template<size_t InlineSize = 8> class SmallInlineBuffer {
140 public:
141 SmallInlineBuffer() = default;
143 if (!this->is_inline_())
144 delete[] this->heap_;
145 }
146
147 // Move constructor
148 SmallInlineBuffer(SmallInlineBuffer &&other) noexcept : len_(other.len_) {
149 if (other.is_inline_()) {
150 memcpy(this->inline_, other.inline_, this->len_);
151 } else {
152 this->heap_ = other.heap_;
153 other.heap_ = nullptr;
154 }
155 other.len_ = 0;
156 }
157
158 // Move assignment
160 if (this != &other) {
161 if (!this->is_inline_())
162 delete[] this->heap_;
163 this->len_ = other.len_;
164 if (other.is_inline_()) {
165 memcpy(this->inline_, other.inline_, this->len_);
166 } else {
167 this->heap_ = other.heap_;
168 other.heap_ = nullptr;
169 }
170 other.len_ = 0;
171 }
172 return *this;
173 }
174
175 // Disable copy (would need deep copy of heap data)
178
180 void set(const uint8_t *src, size_t size) {
181 // Free existing heap allocation if switching from heap to inline or different heap size
183 delete[] this->heap_;
184 this->heap_ = nullptr; // Defensive: prevent use-after-free if logic changes
185 }
186 // Allocate new heap buffer if needed
187 if (size > InlineSize && (this->is_inline_() || size != this->len_)) {
188 this->heap_ = new uint8_t[size]; // NOLINT(cppcoreguidelines-owning-memory)
189 }
190 this->len_ = size;
191 memcpy(this->data(), src, size);
192 }
193
194 uint8_t *data() { return this->is_inline_() ? this->inline_ : this->heap_; }
195 const uint8_t *data() const { return this->is_inline_() ? this->inline_ : this->heap_; }
196 size_t size() const { return this->len_; }
197
198 protected:
199 bool is_inline_() const { return this->len_ <= InlineSize; }
200
201 size_t len_{0};
202 union {
203 uint8_t inline_[InlineSize]{}; // Zero-init ensures clean initial state
204 uint8_t *heap_;
205 };
206};
207
209template<typename T, size_t N> class StaticVector {
210 public:
211 using value_type = T;
212 using iterator = typename std::array<T, N>::iterator;
213 using const_iterator = typename std::array<T, N>::const_iterator;
214 using reverse_iterator = std::reverse_iterator<iterator>;
215 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
216
217 private:
218 std::array<T, N> data_{};
219 size_t count_{0};
220
221 public:
222 // Default constructor
223 StaticVector() = default;
224
225 // Iterator range constructor
226 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
227 while (first != last && count_ < N) {
228 data_[count_++] = *first++;
229 }
230 }
231
232 // Initializer list constructor
233 StaticVector(std::initializer_list<T> init) {
234 for (const auto &val : init) {
235 if (count_ >= N)
236 break;
237 data_[count_++] = val;
238 }
239 }
240
241 // Minimal vector-compatible interface - only what we actually use
242 void push_back(const T &value) {
243 if (count_ < N) {
244 data_[count_++] = value;
245 }
246 }
247
248 // Clear all elements
249 void clear() { count_ = 0; }
250
251 // Assign from iterator range
252 template<typename InputIt> void assign(InputIt first, InputIt last) {
253 count_ = 0;
254 while (first != last && count_ < N) {
255 data_[count_++] = *first++;
256 }
257 }
258
259 // Return reference to next element and increment count (with bounds checking)
261 if (count_ >= N) {
262 // Should never happen with proper size calculation
263 // Return reference to last element to avoid crash
264 return data_[N - 1];
265 }
266 return data_[count_++];
267 }
268
269 size_t size() const { return count_; }
270 bool empty() const { return count_ == 0; }
271
272 // Direct access to underlying data
273 T *data() { return data_.data(); }
274 const T *data() const { return data_.data(); }
275
276 T &operator[](size_t i) { return data_[i]; }
277 const T &operator[](size_t i) const { return data_[i]; }
278
279 // For range-based for loops
280 iterator begin() { return data_.begin(); }
281 iterator end() { return data_.begin() + count_; }
282 const_iterator begin() const { return data_.begin(); }
283 const_iterator end() const { return data_.begin() + count_; }
284
285 // Reverse iterators
290
291 // Conversion to std::span for compatibility with span-based APIs
292 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
293 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
294};
295
299template<typename T> class FixedVector {
300 private:
301 T *data_{nullptr};
302 size_t size_{0};
303 size_t capacity_{0};
304
305 // Helper to destroy all elements without freeing memory
306 void destroy_elements_() {
307 // Only call destructors for non-trivially destructible types
308 if constexpr (!std::is_trivially_destructible<T>::value) {
309 for (size_t i = 0; i < size_; i++) {
310 data_[i].~T();
311 }
312 }
313 }
314
315 // Helper to destroy elements and free memory
316 void cleanup_() {
317 if (data_ != nullptr) {
318 destroy_elements_();
319 // Free raw memory
320 ::operator delete(data_);
321 }
322 }
323
324 // Helper to reset pointers after cleanup
325 void reset_() {
326 data_ = nullptr;
327 capacity_ = 0;
328 size_ = 0;
329 }
330
331 // Helper to assign from initializer list (shared by constructor and assignment operator)
332 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
333 init(init_list.size());
334 size_t idx = 0;
335 for (const auto &item : init_list) {
336 new (data_ + idx) T(item);
337 ++idx;
338 }
339 size_ = init_list.size();
340 }
341
342 public:
343 FixedVector() = default;
344
347 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
348
349 ~FixedVector() { cleanup_(); }
350
351 // Disable copy operations (avoid accidental expensive copies)
352 FixedVector(const FixedVector &) = delete;
354
355 // Enable move semantics (allows use in move-only containers like std::vector)
356 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
357 other.reset_();
358 }
359
360 // Allow conversion to std::vector
361 operator std::vector<T>() const { return {data_, data_ + size_}; }
362
363 FixedVector &operator=(FixedVector &&other) noexcept {
364 if (this != &other) {
365 // Delete our current data
366 cleanup_();
367 // Take ownership of other's data
368 data_ = other.data_;
369 size_ = other.size_;
370 capacity_ = other.capacity_;
371 // Leave other in valid empty state
372 other.reset_();
373 }
374 return *this;
375 }
376
379 FixedVector &operator=(std::initializer_list<T> init_list) {
380 cleanup_();
381 reset_();
382 assign_from_initializer_list_(init_list);
383 return *this;
384 }
385
386 // Allocate capacity - can be called multiple times to reinit
387 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
388 // Direct assignment via operator[] does NOT update the size counter.
389 void init(size_t n) {
390 cleanup_();
391 reset_();
392 if (n > 0) {
393 // Allocate raw memory without calling constructors
394 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
395 // NOLINTNEXTLINE(bugprone-sizeof-expression)
396 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
397 capacity_ = n;
398 }
399 }
400
401 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
402 void clear() {
403 destroy_elements_();
404 size_ = 0;
405 }
406
407 // Release all memory (destroys elements and frees memory)
408 void release() {
409 cleanup_();
410 reset_();
411 }
412
416 void push_back(const T &value) {
417 if (size_ < capacity_) {
418 // Use placement new to construct the object in pre-allocated memory
419 new (&data_[size_]) T(value);
420 size_++;
421 }
422 }
423
427 void push_back(T &&value) {
428 if (size_ < capacity_) {
429 // Use placement new to move-construct the object in pre-allocated memory
430 new (&data_[size_]) T(std::move(value));
431 size_++;
432 }
433 }
434
439 template<typename... Args> T &emplace_back(Args &&...args) {
440 // Use placement new to construct the object in pre-allocated memory
441 new (&data_[size_]) T(std::forward<Args>(args)...);
442 size_++;
443 return data_[size_ - 1];
444 }
445
448 T &front() { return data_[0]; }
449 const T &front() const { return data_[0]; }
450
453 T &back() { return data_[size_ - 1]; }
454 const T &back() const { return data_[size_ - 1]; }
455
456 size_t size() const { return size_; }
457 bool empty() const { return size_ == 0; }
458 size_t capacity() const { return capacity_; }
459 bool full() const { return size_ == capacity_; }
460
463 T &operator[](size_t i) { return data_[i]; }
464 const T &operator[](size_t i) const { return data_[i]; }
465
468 T &at(size_t i) { return data_[i]; }
469 const T &at(size_t i) const { return data_[i]; }
470
471 // Iterator support for range-based for loops
472 T *begin() { return data_; }
473 T *end() { return data_ + size_; }
474 const T *begin() const { return data_; }
475 const T *end() const { return data_ + size_; }
476};
477
483template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
484 public:
486 if (size <= STACK_SIZE) {
487 this->buffer_ = this->stack_buffer_;
488 } else {
489 this->heap_buffer_ = new T[size];
490 this->buffer_ = this->heap_buffer_;
491 }
492 }
493 ~SmallBufferWithHeapFallback() { delete[] this->heap_buffer_; }
494
495 // Delete copy and move operations to prevent double-delete
500
501 T *get() { return this->buffer_; }
502
503 private:
504 T stack_buffer_[STACK_SIZE];
505 T *heap_buffer_{nullptr};
506 T *buffer_;
507};
508
510
513
517inline float pow10_int(int8_t exp) {
518 float result = 1.0f;
519 if (exp >= 0) {
520 for (int8_t i = 0; i < exp; i++)
521 result *= 10.0f;
522 } else {
523 for (int8_t i = exp; i < 0; i++)
524 result /= 10.0f;
525 }
526 return result;
527}
528
530template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
531 return (value - min) * (max_out - min_out) / (max - min) + min_out;
532}
533
535uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
536
538uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
539 bool refin = false, bool refout = false);
540uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
541 bool refout = false);
542
545uint32_t fnv1_hash(const char *str);
546inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
547
549constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
551constexpr uint32_t FNV1_PRIME = 16777619UL;
552
554template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
555 using UnsignedT = std::make_unsigned_t<T>;
556 UnsignedT uvalue = static_cast<UnsignedT>(value);
557 for (size_t i = 0; i < sizeof(T); i++) {
558 hash *= FNV1_PRIME;
559 hash ^= (uvalue >> (i * 8)) & 0xFF;
560 }
561 return hash;
562}
564constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
565 if (str) {
566 while (*str) {
567 hash *= FNV1_PRIME;
568 hash ^= *str++;
569 }
570 }
571 return hash;
572}
573inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
574
576constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
577 if (str) {
578 while (*str) {
579 hash ^= *str++;
580 hash *= FNV1_PRIME;
581 }
582 }
583 return hash;
584}
585inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
586 return fnv1a_hash_extend(hash, str.c_str());
587}
589template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
590 using UnsignedT = std::make_unsigned_t<T>;
591 UnsignedT uvalue = static_cast<UnsignedT>(value);
592 for (size_t i = 0; i < sizeof(T); i++) {
593 hash ^= (uvalue >> (i * 8)) & 0xFF;
594 hash *= FNV1_PRIME;
595 }
596 return hash;
597}
599constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
600inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
601
625template<typename ReturnT = uint32_t> inline constexpr ESPHOME_ALWAYS_INLINE ReturnT micros_to_millis(uint64_t us) {
626 constexpr uint32_t d = 125U;
627 constexpr uint32_t q = static_cast<uint32_t>((1ULL << 32) / d); // 34359738
628 constexpr uint32_t r = static_cast<uint32_t>((1ULL << 32) % d); // 46
629 // 1000 = 8 * 125; divide-by-8 is a free shift
630 uint64_t x = us >> 3;
631 uint32_t lo = static_cast<uint32_t>(x);
632 uint32_t hi = static_cast<uint32_t>(x >> 32);
633 // Combine remainder term: hi * (2^32 % 125) + lo
634 uint32_t adj = hi * r + lo;
635 // If adj overflowed, the true value is 2^32 + adj; apply the identity again
636 // static_cast<ReturnT>(hi) widens to 64-bit when ReturnT=uint64_t, preserving upper bits of hi*q
637 return static_cast<ReturnT>(hi) * q + (adj < lo ? (adj + r) / d + q : adj / d);
638}
639
641uint32_t random_uint32();
643float random_float();
645bool random_bytes(uint8_t *data, size_t len);
646
648
651
653constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
654 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
655}
657constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
658 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
659}
661constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
662 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
663 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
664}
665
667template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
668 T val = 0;
669 for (size_t i = 0; i < sizeof(T); i++) {
670 val <<= 8;
671 val |= bytes[i];
672 }
673 return val;
674}
676template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
677constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
678 return encode_value<T>(bytes.data());
679}
681template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
682constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
683 std::array<uint8_t, sizeof(T)> ret{};
684 for (size_t i = sizeof(T); i > 0; i--) {
685 ret[i - 1] = val & 0xFF;
686 val >>= 8;
687 }
688 return ret;
689}
690
692inline uint8_t reverse_bits(uint8_t x) {
693 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
694 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
695 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
696 return x;
697}
699inline uint16_t reverse_bits(uint16_t x) {
700 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
701}
703inline uint32_t reverse_bits(uint32_t x) {
704 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
705 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
706}
707
709template<typename T> constexpr T convert_big_endian(T val) {
710#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
711 return byteswap(val);
712#else
713 return val;
714#endif
715}
716
718template<typename T> constexpr T convert_little_endian(T val) {
719#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
720 return val;
721#else
722 return byteswap(val);
723#endif
724}
725
727
730
732bool str_equals_case_insensitive(const std::string &a, const std::string &b);
734bool str_equals_case_insensitive(StringRef a, StringRef b);
736inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
737inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
738inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
739
741bool str_startswith(const std::string &str, const std::string &start);
743bool str_endswith(const std::string &str, const std::string &end);
744
746bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
747inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
748 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
749}
750inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
751 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
752}
753
756std::string str_truncate(const std::string &str, size_t length);
757
760std::string str_until(const char *str, char ch);
762std::string str_until(const std::string &str, char ch);
763
765std::string str_lower_case(const std::string &str);
768std::string str_upper_case(const std::string &str);
769
771constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
774std::string str_snake_case(const std::string &str);
775
777constexpr char to_sanitized_char(char c) {
778 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
779}
780
790char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
791
793template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
794 return str_sanitize_to(buffer, N, str);
795}
796
799std::string str_sanitize(const std::string &str);
800
805inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
806 uint32_t hash = FNV1_OFFSET_BASIS;
807 for (size_t i = 0; i < len; i++) {
808 hash *= FNV1_PRIME;
809 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
810 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(str[i])));
811 }
812 return hash;
813}
814
817std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
818
821std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
822
823#ifdef USE_ESP8266
824// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
825// Format strings must be wrapped with PSTR() macro
832inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
833 if (pos >= size) {
834 return size;
835 }
836 va_list args;
837 va_start(args, fmt);
838 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
839 va_end(args);
840 if (written < 0) {
841 return pos; // encoding error
842 }
843 return std::min(pos + static_cast<size_t>(written), size);
844}
845#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
846#else
854__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
855 const char *fmt, ...) {
856 if (pos >= size) {
857 return size;
858 }
859 va_list args;
860 va_start(args, fmt);
861 int written = vsnprintf(buf + pos, size - pos, fmt, args);
862 va_end(args);
863 if (written < 0) {
864 return pos; // encoding error
865 }
866 return std::min(pos + static_cast<size_t>(written), size);
867}
868#endif
869
878std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len);
879
888std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
889 size_t suffix_len);
890
900size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
901 const char *suffix_ptr, size_t suffix_len);
902
904
907
909template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
910optional<T> parse_number(const char *str) {
911 char *end = nullptr;
912 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
913 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
914 return {};
915 return value;
916}
918template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
919optional<T> parse_number(const std::string &str) {
920 return parse_number<T>(str.c_str());
921}
923template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
924optional<T> parse_number(const char *str) {
925 char *end = nullptr;
926 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
927 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
928 return {};
929 return value;
930}
932template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
933optional<T> parse_number(const std::string &str) {
934 return parse_number<T>(str.c_str());
935}
937template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
938 char *end = nullptr;
939 float value = ::strtof(str, &end);
940 if (end == str || *end != '\0' || value == HUGE_VALF)
941 return {};
942 return value;
943}
945template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
946optional<T> parse_number(const std::string &str) {
947 return parse_number<T>(str.c_str());
948}
949
961size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
963inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
964 return parse_hex(str, strlen(str), data, count) == 2 * count;
965}
967inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
968 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
969}
971inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
972 data.resize(count);
973 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
974}
976inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
977 data.resize(count);
978 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
979}
985template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
986optional<T> parse_hex(const char *str, size_t len) {
987 T val = 0;
988 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
989 return {};
990 return convert_big_endian(val);
991}
993template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
994 return parse_hex<T>(str, strlen(str));
995}
997template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
998 return parse_hex<T>(str.c_str(), str.length());
999}
1000
1003static constexpr uint8_t INVALID_HEX_CHAR = 255;
1004
1005constexpr uint8_t parse_hex_char(char c) {
1006 if (c >= '0' && c <= '9')
1007 return c - '0';
1008 if (c >= 'A' && c <= 'F')
1009 return c - 'A' + 10;
1010 if (c >= 'a' && c <= 'f')
1011 return c - 'a' + 10;
1012 return INVALID_HEX_CHAR;
1013}
1014
1016inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
1017
1019inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
1020
1022inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
1023
1026inline char *int8_to_str(char *buf, int8_t val) {
1027 int32_t v = val;
1028 if (v < 0) {
1029 *buf++ = '-';
1030 v = -v;
1031 }
1032 if (v >= 100) {
1033 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
1034 v -= 100;
1035 // Must write tens digit (even if 0) after hundreds
1036 int32_t tens = v / 10;
1037 *buf++ = '0' + tens;
1038 v -= tens * 10;
1039 } else if (v >= 10) {
1040 int32_t tens = v / 10;
1041 *buf++ = '0' + tens;
1042 v -= tens * 10;
1043 }
1044 *buf++ = '0' + v;
1045 return buf;
1046}
1047
1049char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1050
1053template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1054 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
1055 return format_hex_to(buffer, N, data, length);
1056}
1057
1059template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1060inline char *format_hex_to(char (&buffer)[N], T val) {
1061 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
1063 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1064}
1065
1067template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
1068 return format_hex_to(buffer, data.data(), data.size());
1069}
1070
1072template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
1073 return format_hex_to(buffer, data.data(), data.size());
1074}
1075
1077constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
1078
1080constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
1081
1083template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1084inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
1085 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
1086 buffer[0] = '0';
1087 buffer[1] = 'x';
1089 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1090 return buffer;
1091}
1092
1094template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1095 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
1096 buffer[0] = '0';
1097 buffer[1] = 'x';
1098 format_hex_to(buffer + 2, N - 2, data, length);
1099 return buffer;
1100}
1101
1103constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
1104
1116char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
1117
1119template<size_t N>
1120inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
1121 static_assert(N >= 3, "Buffer must hold at least one hex byte");
1122 return format_hex_pretty_to(buffer, N, data, length, separator);
1123}
1124
1126template<size_t N>
1127inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1128 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1129}
1130
1132template<size_t N, size_t M>
1133inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1134 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1135}
1136
1138constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1139
1153char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1154
1156template<size_t N>
1157inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1158 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1159 return format_hex_pretty_to(buffer, N, data, length, separator);
1160}
1161
1163static constexpr size_t MAC_ADDRESS_SIZE = 6;
1165static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1167static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1168
1170inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1171 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1172}
1173
1175inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1176 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1177}
1178
1182std::string format_mac_address_pretty(const uint8_t mac[6]);
1186std::string format_hex(const uint8_t *data, size_t length);
1190std::string format_hex(const std::vector<uint8_t> &data);
1194template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
1196 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1197}
1201template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
1202 return format_hex(data.data(), data.size());
1203}
1204
1233std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
1234
1258std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
1259
1284std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
1285
1309std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
1310
1334std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
1335
1362template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1363std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
1365 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
1366}
1367
1369constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1370
1390char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1391
1393template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1394 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1395 return format_bin_to(buffer, N, data, length);
1396}
1397
1414template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1415inline char *format_bin_to(char (&buffer)[N], T val) {
1416 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1418 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1419}
1420
1424std::string format_bin(const uint8_t *data, size_t length);
1428template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
1430 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1431}
1432
1441ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1442
1444ESPDEPRECATED("Allocates heap memory. Use value_accuracy_to_buf() instead. Removed in 2026.7.0.", "2026.1.0")
1445std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
1446
1448static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1449
1451size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1453size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1454 int8_t accuracy_decimals, StringRef unit_of_measurement);
1455
1457int8_t step_to_accuracy_decimals(float step);
1458
1459std::string base64_encode(const uint8_t *buf, size_t buf_len);
1460std::string base64_encode(const std::vector<uint8_t> &buf);
1461
1462std::vector<uint8_t> base64_decode(const std::string &encoded_string);
1463size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1464size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1465
1470bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1471
1473
1476
1478// Remove before 2026.9.0
1479ESPDEPRECATED("Use LightState::gamma_correct_lut() instead. Removed in 2026.9.0.", "2026.3.0")
1480float gamma_correct(float value, float gamma);
1482// Remove before 2026.9.0
1483ESPDEPRECATED("Use LightState::gamma_uncorrect_lut() instead. Removed in 2026.9.0.", "2026.3.0")
1484float gamma_uncorrect(float value, float gamma);
1485
1487void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1489void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1490
1492
1495
1497constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1499constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1500
1502
1505
1506template<typename... X> class CallbackManager;
1507
1512template<typename... Ts> class CallbackManager<void(Ts...)> {
1513 public:
1515 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
1516
1518 void call(Ts... args) {
1519 for (auto &cb : this->callbacks_)
1520 cb(args...);
1521 }
1522 size_t size() const { return this->callbacks_.size(); }
1523
1525 void operator()(Ts... args) { call(args...); }
1526
1527 protected:
1528 std::vector<std::function<void(Ts...)>> callbacks_;
1529};
1530
1531template<typename... X> class LazyCallbackManager;
1532
1548template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
1549 public:
1553 ~LazyCallbackManager() { delete this->callbacks_; }
1554
1555 // Non-copyable and non-movable (entities are never copied or moved)
1560
1562 void add(std::function<void(Ts...)> &&callback) {
1563 if (!this->callbacks_) {
1564 this->callbacks_ = new CallbackManager<void(Ts...)>();
1565 }
1566 this->callbacks_->add(std::move(callback));
1567 }
1568
1570 void call(Ts... args) {
1571 if (this->callbacks_) {
1572 this->callbacks_->call(args...);
1573 }
1574 }
1575
1577 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
1578
1580 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
1581
1583 void operator()(Ts... args) { this->call(args...); }
1584
1585 protected:
1586 CallbackManager<void(Ts...)> *callbacks_{nullptr};
1587};
1588
1590template<typename T> class Deduplicator {
1591 public:
1593 bool next(T value) {
1594 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
1595 return false;
1596 }
1597 this->has_value_ = true;
1598 this->value_unknown_ = false;
1599 this->last_value_ = value;
1600 return true;
1601 }
1604 bool ret = !this->value_unknown_;
1605 this->value_unknown_ = true;
1606 return ret;
1607 }
1609 bool has_value() const { return this->has_value_; }
1610
1611 protected:
1612 bool has_value_{false};
1613 bool value_unknown_{false};
1615};
1616
1618template<typename T> class Parented {
1619 public:
1621 Parented(T *parent) : parent_(parent) {}
1622
1624 T *get_parent() const { return parent_; }
1626 void set_parent(T *parent) { parent_ = parent; }
1627
1628 protected:
1629 T *parent_{nullptr};
1630};
1631
1633
1636
1641class Mutex {
1642 public:
1643 Mutex();
1644 Mutex(const Mutex &) = delete;
1645 ~Mutex();
1646 void lock();
1647 bool try_lock();
1648 void unlock();
1649
1650 Mutex &operator=(const Mutex &) = delete;
1651
1652 private:
1653#if defined(USE_ESP32) || defined(USE_LIBRETINY)
1654 SemaphoreHandle_t handle_;
1655#else
1656 // d-pointer to store private data on new platforms
1657 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
1658#endif
1659};
1660
1666 public:
1667 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
1668 ~LockGuard() { mutex_.unlock(); }
1669
1670 private:
1671 Mutex &mutex_;
1672};
1673
1695 public:
1696 InterruptLock();
1698
1699 protected:
1700#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
1701 uint32_t state_;
1702#endif
1703};
1704
1713 public:
1714 LwIPLock();
1715 ~LwIPLock();
1716
1717 // Delete copy constructor and copy assignment operator to prevent accidental copying
1718 LwIPLock(const LwIPLock &) = delete;
1719 LwIPLock &operator=(const LwIPLock &) = delete;
1720};
1721
1728 public:
1730 void start();
1732 void stop();
1733
1735 static bool is_high_frequency();
1736
1737 protected:
1738 bool started_{false};
1739 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1740};
1741
1743void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
1744
1748std::string get_mac_address();
1749
1753std::string get_mac_address_pretty();
1754
1758void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
1759
1763const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
1764
1765#ifdef USE_ESP32
1767void set_mac_address(uint8_t *mac);
1768#endif
1769
1773
1776bool mac_address_is_valid(const uint8_t *mac);
1777
1779void delay_microseconds_safe(uint32_t us);
1780
1782
1785
1794template<class T> class RAMAllocator {
1795 public:
1796 using value_type = T;
1797
1798 enum Flags {
1799 NONE = 0, // Perform external allocation and fall back to internal memory
1800 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
1801 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
1802 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
1803 };
1804
1805 constexpr RAMAllocator() = default;
1806 constexpr RAMAllocator(uint8_t flags)
1809 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
1810
1811 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
1812
1813 T *allocate(size_t n, size_t manual_size) {
1814 size_t size = n * manual_size;
1815 T *ptr = nullptr;
1816#ifdef USE_ESP32
1817 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1818 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1819 }
1820 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1821 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1822 }
1823#else
1824 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1825 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1826#endif
1827 return ptr;
1828 }
1829
1830 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
1831
1832 T *reallocate(T *p, size_t n, size_t manual_size) {
1833 size_t size = n * manual_size;
1834 T *ptr = nullptr;
1835#ifdef USE_ESP32
1836 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
1837 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1838 }
1839 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
1840 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1841 }
1842#else
1843 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
1844 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1845#endif
1846 return ptr;
1847 }
1848
1849 void deallocate(T *p, size_t n) {
1850 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
1851 }
1852
1856 size_t get_free_heap_size() const {
1857#ifdef USE_ESP8266
1858 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
1859#elif defined(USE_ESP32)
1860 auto max_internal =
1861 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1862 auto max_external =
1863 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1864 return max_internal + max_external;
1865#elif defined(USE_RP2040)
1866 return ::rp2040.getFreeHeap();
1867#elif defined(USE_LIBRETINY)
1868 return lt_heap_get_free();
1869#else
1870 return 100000;
1871#endif
1872 }
1873
1878#ifdef USE_ESP8266
1879 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
1880#elif defined(USE_ESP32)
1881 auto max_internal =
1882 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
1883 auto max_external =
1884 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
1885 return std::max(max_internal, max_external);
1886#else
1887 return this->get_free_heap_size();
1888#endif
1889 }
1890
1891 private:
1892 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
1893};
1894
1895template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
1896
1901template<typename T, typename U>
1902concept comparable_with = requires(T a, U b) {
1903 { a > b } -> std::convertible_to<bool>;
1904 { a < b } -> std::convertible_to<bool>;
1905};
1906
1907template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
1908 if (value < min)
1909 return min;
1910 return value;
1911}
1912template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
1913 if (value > max)
1914 return max;
1915 return value;
1916}
1917
1920
1925template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
1930template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
1931
1933
1934} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1525
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:1528
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1518
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:1515
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:1590
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:1593
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:1609
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:1603
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:299
const T & at(size_t i) const
Definition helpers.h:469
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:356
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:347
const T * begin() const
Definition helpers.h:474
bool full() const
Definition helpers.h:459
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:379
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:448
const T & operator[](size_t i) const
Definition helpers.h:464
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:463
size_t capacity() const
Definition helpers.h:458
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:453
bool empty() const
Definition helpers.h:457
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:427
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:439
size_t size() const
Definition helpers.h:456
const T & front() const
Definition helpers.h:449
const T & back() const
Definition helpers.h:454
const T * end() const
Definition helpers.h:475
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:363
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:468
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:416
void init(size_t n)
Definition helpers.h:389
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:1727
void stop()
Stop running the loop continuously.
Definition helpers.cpp:791
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:797
void start()
Start running the loop continuously.
Definition helpers.cpp:785
Helper class to disable interrupts.
Definition helpers.h:1694
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:1577
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1583
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:1562
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:1553
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:1570
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:1580
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1665
LockGuard(Mutex &mutex)
Definition helpers.h:1667
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:1712
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1641
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:1618
T * get_parent() const
Get the parent of this object.
Definition helpers.h:1624
Parented(T *parent)
Definition helpers.h:1621
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:1626
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1794
constexpr RAMAllocator(uint8_t flags)
Definition helpers.h:1806
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:1832
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:1856
T * reallocate(T *p, size_t n)
Definition helpers.h:1830
void deallocate(T *p, size_t n)
Definition helpers.h:1849
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:1877
T * allocate(size_t n)
Definition helpers.h:1811
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:1809
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:1813
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:483
SmallBufferWithHeapFallback(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback & operator=(SmallBufferWithHeapFallback &&)=delete
SmallBufferWithHeapFallback & operator=(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback(SmallBufferWithHeapFallback &&)=delete
Small buffer optimization - stores data inline when small, heap-allocates for large data This avoids ...
Definition helpers.h:139
SmallInlineBuffer(const SmallInlineBuffer &)=delete
bool is_inline_() const
Definition helpers.h:199
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
Definition helpers.h:180
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
size_t size() const
Definition helpers.h:196
uint8_t inline_[InlineSize]
Definition helpers.h:203
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
Definition helpers.h:159
const uint8_t * data() const
Definition helpers.h:195
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
Definition helpers.h:148
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:209
const_reverse_iterator rend() const
Definition helpers.h:289
size_t size() const
Definition helpers.h:269
reverse_iterator rbegin()
Definition helpers.h:286
const T & operator[](size_t i) const
Definition helpers.h:277
reverse_iterator rend()
Definition helpers.h:287
void push_back(const T &value)
Definition helpers.h:242
bool empty() const
Definition helpers.h:270
void assign(InputIt first, InputIt last)
Definition helpers.h:252
const_reverse_iterator rbegin() const
Definition helpers.h:288
T & operator[](size_t i)
Definition helpers.h:276
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:215
typename std::array< T, N >::iterator iterator
Definition helpers.h:212
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:213
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:214
const T * data() const
Definition helpers.h:274
const_iterator end() const
Definition helpers.h:283
StaticVector(InputIt first, InputIt last)
Definition helpers.h:226
StaticVector(std::initializer_list< T > init)
Definition helpers.h:233
const_iterator begin() const
Definition helpers.h:282
struct @65::@66 __attribute__
Functions to constrain the range of arithmetic values.
Definition helpers.h:1902
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:1912
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:576
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:159
float gamma_uncorrect(float value, float gamma)
Definition helpers.cpp:711
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:484
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:709
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1022
float gamma_correct(float value, float gamma)
Definition helpers.cpp:703
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:777
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:829
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1175
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:549
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:720
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:1016
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:490
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:718
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:554
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:665
va_end(args)
std::string size_t len
Definition helpers.h:817
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:1080
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:657
char * format_hex_prefixed_to(char(&buffer)[N], T val)
Format an unsigned integer as "0x" prefixed lowercase hex to buffer.
Definition helpers.h:1084
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:854
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:805
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:1907
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:910
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:807
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:514
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
size_t size_t pos
Definition helpers.h:854
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:818
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:844
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:1077
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
constexpr ESPHOME_ALWAYS_INLINE ReturnT micros_to_millis(uint64_t us)
Convert a 64-bit microsecond count to milliseconds without calling __udivdi3 (software 64-bit divide,...
Definition helpers.h:625
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:1026
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:500
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:1103
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:553
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:551
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:667
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:743
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:812
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:661
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:1497
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:653
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:855
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1005
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:682
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:799
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:1369
int written
Definition helpers.h:861
struct ESPDEPRECATED("Use std::index_sequence instead. Removed in 2026.6.0", "2025.12.0") seq
Definition automation.h:26
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:771
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1499
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:692
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:1138
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:530
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:599
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:832
float gamma
Definition helpers.h:1480
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:593
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1434
@ PARSE_ON
Definition helpers.h:1436
@ PARSE_TOGGLE
Definition helpers.h:1438
@ PARSE_OFF
Definition helpers.h:1437
@ PARSE_NONE
Definition helpers.h:1435
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:517
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:1170
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