ESPHome 2026.7.0
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 <cassert>
6#include <cmath>
7#include <cstdarg>
8#include <cstdint>
9#include <cstdio>
10#include <cstring>
11#include <functional>
12#include <iterator>
13#include <limits>
14#include <memory>
15#include <span>
16#include <string>
17#include <type_traits>
18#include <vector>
19#include <concepts>
20#include <strings.h>
21
24
25// Backward compatibility re-export of heap-allocating helpers.
26// These functions have moved to alloc_helpers.h. External components should
27// update their includes to use #include "esphome/core/alloc_helpers.h" directly.
28// This re-export will be removed in 2026.11.0.
30
31#ifdef USE_ESP8266
32#include <Esp.h>
33#include <pgmspace.h>
34#endif
35
36#ifdef USE_RP2
37#include <Arduino.h>
38#endif
39
40#ifdef USE_ESP32
41#include <esp_heap_caps.h>
42#endif
43
44#if defined(USE_ESP32)
45#include <freertos/FreeRTOS.h>
46#include <freertos/semphr.h>
47#elif defined(USE_LIBRETINY)
48#include <FreeRTOS.h>
49#include <semphr.h>
50#endif
51
52#ifdef USE_HOST
53#include <mutex>
54#endif
55
56#define HOT __attribute__((hot))
57#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
58#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
59#define PACKED __attribute__((packed))
60
61namespace esphome {
62
63// Forward declaration to avoid circular dependency with string_ref.h
64class StringRef;
65
68
69// Keep "using" even after the removal of our backports, to avoid breaking existing code.
70using std::to_string;
71using std::is_trivially_copyable;
72using std::make_unique;
73using std::enable_if_t;
74using std::clamp;
75using std::is_invocable;
76#if __cpp_lib_bit_cast >= 201806
77using std::bit_cast;
78#else
80template<
81 typename To, typename From,
82 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
83 int> = 0>
84To bit_cast(const From &src) {
85 To dst;
86 memcpy(&dst, &src, sizeof(To));
87 return dst;
88}
89#endif
90
91// clang-format off
92inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
93// clang-format on
94
95// std::byteswap from C++23
96template<typename T> constexpr T byteswap(T n) {
97 T m;
98 for (size_t i = 0; i < sizeof(T); i++)
99 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
100 return m;
101}
102template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
103#ifdef USE_LIBRETINY
104// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
105template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
106template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
107template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
108template<> inline int8_t byteswap(int8_t n) { return n; }
109template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
110template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
111template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
112#else
113template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
114template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
115template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
116template<> constexpr int8_t byteswap(int8_t n) { return n; }
117template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
118template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
119template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
120#endif
121
123
126
130
131template<typename T> class ConstVector {
132 public:
133 constexpr ConstVector(const T *data, size_t size) : data_(data), size_(size) {}
134
135 const constexpr T &operator[](size_t i) const { return data_[i]; }
136 constexpr size_t size() const { return size_; }
137 constexpr bool empty() const { return size_ == 0; }
138
139 protected:
140 const T *data_;
141 size_t size_;
142};
143
147template<size_t InlineSize = 8> class SmallInlineBuffer {
148 public:
149 SmallInlineBuffer() = default;
151 if (!this->is_inline_())
152 delete[] this->heap_;
153 }
154
155 // Move constructor
156 SmallInlineBuffer(SmallInlineBuffer &&other) noexcept : len_(other.len_) {
157 if (other.is_inline_()) {
158 memcpy(this->inline_, other.inline_, this->len_);
159 } else {
160 this->heap_ = other.heap_;
161 other.heap_ = nullptr;
162 }
163 other.len_ = 0;
164 }
165
166 // Move assignment
168 if (this != &other) {
169 if (!this->is_inline_())
170 delete[] this->heap_;
171 this->len_ = other.len_;
172 if (other.is_inline_()) {
173 memcpy(this->inline_, other.inline_, this->len_);
174 } else {
175 this->heap_ = other.heap_;
176 other.heap_ = nullptr;
177 }
178 other.len_ = 0;
179 }
180 return *this;
181 }
182
183 // Disable copy (would need deep copy of heap data)
186
190 uint8_t *init(size_t size) {
191 // Free existing heap allocation if switching from heap to inline or different heap size
193 delete[] this->heap_;
194 this->heap_ = nullptr; // Defensive: prevent use-after-free if logic changes
195 }
196 // Allocate new heap buffer if needed
197 if (size > InlineSize && (this->is_inline_() || size != this->len_)) {
198 this->heap_ = new uint8_t[size]; // NOLINT(cppcoreguidelines-owning-memory)
199 }
200 this->len_ = size;
201 return this->data();
202 }
203
205 void set(const uint8_t *src, size_t size) { memcpy(this->init(size), src, size); }
206
207 uint8_t *data() { return this->is_inline_() ? this->inline_ : this->heap_; }
208 const uint8_t *data() const { return this->is_inline_() ? this->inline_ : this->heap_; }
209 size_t size() const { return this->len_; }
210
211 protected:
212 bool is_inline_() const { return this->len_ <= InlineSize; }
213
214 size_t len_{0};
215 union {
216 uint8_t inline_[InlineSize]{}; // Zero-init ensures clean initial state
217 uint8_t *heap_;
218 };
219};
220
222template<typename T, size_t N> class StaticVector {
223 public:
224 using value_type = T;
225 using iterator = typename std::array<T, N>::iterator;
226 using const_iterator = typename std::array<T, N>::const_iterator;
227 using reverse_iterator = std::reverse_iterator<iterator>;
228 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
229
230 private:
231 std::array<T, N> data_; // intentionally not value-initialized to avoid memset
232 size_t count_{0};
233
234 public:
235 // Default constructor
236 StaticVector() = default;
237
238 // Iterator range constructor
239 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
240 while (first != last && count_ < N) {
241 data_[count_++] = *first++;
242 }
243 }
244
245 // Initializer list constructor
246 StaticVector(std::initializer_list<T> init) {
247 for (const auto &val : init) {
248 if (count_ >= N)
249 break;
250 data_[count_++] = val;
251 }
252 }
253
254 // Minimal vector-compatible interface - only what we actually use
255 void push_back(const T &value) {
256 if (count_ < N) {
257 data_[count_++] = value;
258 }
259 }
260
261 // Clear all elements
262 void clear() { count_ = 0; }
263
264 // Assign from iterator range
265 template<typename InputIt> void assign(InputIt first, InputIt last) {
266 count_ = 0;
267 while (first != last && count_ < N) {
268 data_[count_++] = *first++;
269 }
270 }
271
272 // Return reference to next element and increment count (with bounds checking)
274 if (count_ >= N) {
275 // Should never happen with proper size calculation
276 // Return reference to last element to avoid crash
277 return data_[N - 1];
278 }
279 return data_[count_++];
280 }
281
282 size_t size() const { return count_; }
283 bool empty() const { return count_ == 0; }
284
285 // Direct access to underlying data
286 T *data() { return data_.data(); }
287 const T *data() const { return data_.data(); }
288
289 T &operator[](size_t i) { return data_[i]; }
290 const T &operator[](size_t i) const { return data_[i]; }
291
292 // For range-based for loops
293 iterator begin() { return data_.begin(); }
294 iterator end() { return data_.begin() + count_; }
295 const_iterator begin() const { return data_.begin(); }
296 const_iterator end() const { return data_.begin() + count_; }
297
298 // Reverse iterators
303
304 // Conversion to std::span for compatibility with span-based APIs
305 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
306 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
307};
308
316template<typename T, size_t N> class StaticRingBuffer {
317 using index_type = std::conditional_t<(N <= std::numeric_limits<uint8_t>::max()), uint8_t, uint16_t>;
318
319 public:
320 class Iterator {
321 public:
322 Iterator(StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
323 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % N]; }
325 ++pos_;
326 return *this;
327 }
328 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
329
330 private:
331 StaticRingBuffer *buf_;
332 index_type pos_;
333 };
334
336 public:
337 ConstIterator(const StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
338 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % N]; }
340 ++pos_;
341 return *this;
342 }
343 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
344
345 private:
346 const StaticRingBuffer *buf_;
347 index_type pos_;
348 };
349
350 bool push(const T &value) {
351 if (this->count_ >= N) {
352 return false;
353 }
354 this->data_[this->tail_] = value;
355 this->tail_ = (this->tail_ + 1) % N;
356 ++this->count_;
357 return true;
358 }
359
360 void pop() {
361 if (this->count_ > 0) {
362 this->head_ = (this->head_ + 1) % N;
363 --this->count_;
364 }
365 }
366
367 T &front() { return this->data_[this->head_]; }
368 const T &front() const { return this->data_[this->head_]; }
369 index_type size() const { return this->count_; }
370 bool empty() const { return this->count_ == 0; }
371
373 void clear() {
374 this->head_ = 0;
375 this->tail_ = 0;
376 this->count_ = 0;
377 }
378
379 Iterator begin() { return Iterator(this, 0); }
380 Iterator end() { return Iterator(this, this->count_); }
381 ConstIterator begin() const { return ConstIterator(this, 0); }
382 ConstIterator end() const { return ConstIterator(this, this->count_); }
383
384 protected:
385 T data_[N];
386 index_type head_{0};
387 index_type tail_{0};
388 index_type count_{0};
389};
390
395template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::max()> class FixedRingBuffer {
396 using index_type = std::conditional_t<
397 (MAX_CAPACITY <= std::numeric_limits<uint8_t>::max()), uint8_t,
398 std::conditional_t<(MAX_CAPACITY <= std::numeric_limits<uint16_t>::max()), uint16_t, uint32_t>>;
399
400 public:
401 class Iterator {
402 public:
403 Iterator(FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
404 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
406 ++pos_;
407 return *this;
408 }
409 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
410
411 private:
412 FixedRingBuffer *buf_;
413 index_type pos_;
414 };
415
417 public:
418 ConstIterator(const FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
419 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
421 ++pos_;
422 return *this;
423 }
424 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
425
426 private:
427 const FixedRingBuffer *buf_;
428 index_type pos_;
429 };
430
431 FixedRingBuffer() = default;
433 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
434 ::operator delete(this->data_);
435 } else {
436 delete[] this->data_;
437 }
438 }
439
440 // Disable copy
443
445 void init(index_type capacity) {
446 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
447 // Raw allocation without initialization (elements are written before read)
448 // NOLINTNEXTLINE(bugprone-sizeof-expression)
449 this->data_ = static_cast<T *>(::operator new(capacity * sizeof(T)));
450 } else {
451 this->data_ = new T[capacity];
452 }
453 this->capacity_ = capacity;
454 }
455
457 bool push(const T &value) {
458 if (this->count_ >= this->capacity_)
459 return false;
460 this->data_[this->tail_] = value;
461 this->tail_ = (this->tail_ + 1) % this->capacity_;
462 ++this->count_;
463 return true;
464 }
465
467 void push_overwrite(const T &value) {
468 this->data_[this->tail_] = value;
469 this->tail_ = (this->tail_ + 1) % this->capacity_;
470 if (this->count_ >= this->capacity_) {
471 // Buffer full - advance head to drop oldest, count stays at capacity
472 this->head_ = this->tail_;
473 } else {
474 ++this->count_;
475 }
476 }
477
479 void pop() {
480 if (this->count_ > 0) {
481 this->head_ = (this->head_ + 1) % this->capacity_;
482 --this->count_;
483 }
484 }
485
486 T &front() { return this->data_[this->head_]; }
487 const T &front() const { return this->data_[this->head_]; }
488 index_type size() const { return this->count_; }
489 bool empty() const { return this->count_ == 0; }
490 index_type capacity() const { return this->capacity_; }
491 bool full() const { return this->count_ == this->capacity_; }
492
494 void clear() {
495 this->head_ = 0;
496 this->tail_ = 0;
497 this->count_ = 0;
498 }
499
500 Iterator begin() { return Iterator(this, 0); }
501 Iterator end() { return Iterator(this, this->count_); }
502 ConstIterator begin() const { return ConstIterator(this, 0); }
503 ConstIterator end() const { return ConstIterator(this, this->count_); }
504
505 protected:
506 T *data_{nullptr};
507 index_type head_{0};
508 index_type tail_{0};
509 index_type count_{0};
510 index_type capacity_{0};
511};
512
517template<typename T, size_t N> inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T> src) {
518#ifdef ESPHOME_DEBUG
519 assert(src.size() == N);
520#endif
521 if constexpr (std::is_trivially_copyable_v<T>) {
522 __builtin_memcpy(dest.data(), src.begin(), N * sizeof(T));
523 } else {
524 size_t i = 0;
525 for (const auto &v : src) {
526 dest[i++] = v;
527 }
528 }
529}
530
534template<typename T> class FixedVector {
535 private:
536 T *data_{nullptr};
537 size_t size_{0};
538 size_t capacity_{0};
539
540 // Helper to destroy all elements without freeing memory
541 void destroy_elements_() {
542 // Only call destructors for non-trivially destructible types
543 if constexpr (!std::is_trivially_destructible<T>::value) {
544 for (size_t i = 0; i < size_; i++) {
545 data_[i].~T();
546 }
547 }
548 }
549
550 // Helper to destroy elements and free memory
551 void cleanup_() {
552 if (data_ != nullptr) {
553 destroy_elements_();
554 // Free raw memory
555 ::operator delete(data_);
556 }
557 }
558
559 // Helper to reset pointers after cleanup
560 void reset_() {
561 data_ = nullptr;
562 capacity_ = 0;
563 size_ = 0;
564 }
565
566 // Helper to assign from initializer list (shared by constructor and assignment operator)
567 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
568 init(init_list.size());
569 size_t idx = 0;
570 for (const auto &item : init_list) {
571 new (data_ + idx) T(item);
572 ++idx;
573 }
574 size_ = init_list.size();
575 }
576
577 public:
578 FixedVector() = default;
579
582 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
583
584 ~FixedVector() { cleanup_(); }
585
586 // Disable copy operations (avoid accidental expensive copies)
587 FixedVector(const FixedVector &) = delete;
589
590 // Enable move semantics (allows use in move-only containers like std::vector)
591 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
592 other.reset_();
593 }
594
595 // Allow conversion to std::vector
596 operator std::vector<T>() const { return {data_, data_ + size_}; }
597
598 FixedVector &operator=(FixedVector &&other) noexcept {
599 if (this != &other) {
600 // Delete our current data
601 cleanup_();
602 // Take ownership of other's data
603 data_ = other.data_;
604 size_ = other.size_;
605 capacity_ = other.capacity_;
606 // Leave other in valid empty state
607 other.reset_();
608 }
609 return *this;
610 }
611
614 FixedVector &operator=(std::initializer_list<T> init_list) {
615 cleanup_();
616 reset_();
617 assign_from_initializer_list_(init_list);
618 return *this;
619 }
620
621 // Allocate capacity - can be called multiple times to reinit
622 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
623 // Direct assignment via operator[] does NOT update the size counter.
624 void init(size_t n) {
625 cleanup_();
626 reset_();
627 if (n > 0) {
628 // Allocate raw memory without calling constructors
629 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
630 // NOLINTNEXTLINE(bugprone-sizeof-expression)
631 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
632 capacity_ = n;
633 }
634 }
635
636 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
637 void clear() {
638 destroy_elements_();
639 size_ = 0;
640 }
641
642 // Release all memory (destroys elements and frees memory)
643 void release() {
644 cleanup_();
645 reset_();
646 }
647
651 void push_back(const T &value) {
652 if (size_ < capacity_) {
653 // Use placement new to construct the object in pre-allocated memory
654 new (&data_[size_]) T(value);
655 size_++;
656 }
657 }
658
662 void push_back(T &&value) {
663 if (size_ < capacity_) {
664 // Use placement new to move-construct the object in pre-allocated memory
665 new (&data_[size_]) T(std::move(value));
666 size_++;
667 }
668 }
669
674 template<typename... Args> T &emplace_back(Args &&...args) {
675 // Use placement new to construct the object in pre-allocated memory
676 new (&data_[size_]) T(std::forward<Args>(args)...);
677 size_++;
678 return data_[size_ - 1];
679 }
680
683 T &front() { return data_[0]; }
684 const T &front() const { return data_[0]; }
685
688 T &back() { return data_[size_ - 1]; }
689 const T &back() const { return data_[size_ - 1]; }
690
693 void pop_back() {
694 if constexpr (!std::is_trivially_destructible<T>::value) {
695 data_[size_ - 1].~T();
696 }
697 size_--;
698 }
699
700 size_t size() const { return size_; }
701 bool empty() const { return size_ == 0; }
702 size_t capacity() const { return capacity_; }
703 bool full() const { return size_ == capacity_; }
704
707 T &operator[](size_t i) { return data_[i]; }
708 const T &operator[](size_t i) const { return data_[i]; }
709
712 T &at(size_t i) { return data_[i]; }
713 const T &at(size_t i) const { return data_[i]; }
714
715 // Iterator support for range-based for loops
716 T *begin() { return data_; }
717 T *end() { return data_ + size_; }
718 const T *begin() const { return data_; }
719 const T *end() const { return data_ + size_; }
720};
721
727template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
728 public:
730 if (size <= STACK_SIZE) {
731 this->buffer_ = this->stack_buffer_;
732 } else {
733 this->heap_buffer_ = new T[size];
734 this->buffer_ = this->heap_buffer_;
735 }
736 }
737 ~SmallBufferWithHeapFallback() { delete[] this->heap_buffer_; }
738
739 // Delete copy and move operations to prevent double-delete
744
745 T *get() { return this->buffer_; }
746
747 private:
748 T stack_buffer_[STACK_SIZE];
749 T *heap_buffer_{nullptr};
750 T *buffer_;
751};
752
754
757
761int8_t ilog10(float value);
762
766inline float pow10_int(int8_t exp) {
767 float result = 1.0f;
768 if (exp >= 0) {
769 for (int8_t i = 0; i < exp; i++)
770 result *= 10.0f;
771 } else {
772 for (int8_t i = exp; i < 0; i++)
773 result /= 10.0f;
774 }
775 return result;
776}
777
779template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
780 return (value - min) * (max_out - min_out) / (max - min) + min_out;
781}
782
784uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
785
787uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
788 bool refin = false, bool refout = false);
789uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
790 bool refout = false);
791
794uint32_t fnv1_hash(const char *str);
795inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
796
798constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
800constexpr uint32_t FNV1_PRIME = 16777619UL;
801
803template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
804 using UnsignedT = std::make_unsigned_t<T>;
805 UnsignedT uvalue = static_cast<UnsignedT>(value);
806 for (size_t i = 0; i < sizeof(T); i++) {
807 hash *= FNV1_PRIME;
808 hash ^= (uvalue >> (i * 8)) & 0xFF;
809 }
810 return hash;
811}
813constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
814 if (str) {
815 while (*str) {
816 hash *= FNV1_PRIME;
817 hash ^= *str++;
818 }
819 }
820 return hash;
821}
822inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
823
825constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
826 if (str) {
827 while (*str) {
828 hash ^= *str++;
829 hash *= FNV1_PRIME;
830 }
831 }
832 return hash;
833}
834inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
835 return fnv1a_hash_extend(hash, str.c_str());
836}
838template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
839 using UnsignedT = std::make_unsigned_t<T>;
840 UnsignedT uvalue = static_cast<UnsignedT>(value);
841 for (size_t i = 0; i < sizeof(T); i++) {
842 hash ^= (uvalue >> (i * 8)) & 0xFF;
843 hash *= FNV1_PRIME;
844 }
845 return hash;
846}
848constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
849inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
850
851// micros_to_millis<>() lives in its own lightweight header so hal.h can pull it
852// in for inline millis_64() without forcing every TU that includes hal.h to
853// also include the rest of helpers.h.
854
862float random_float();
865bool random_bytes(uint8_t *data, size_t len);
866
868
871
873constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
874 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
875}
877constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
878 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
879}
881constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
882 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
883 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
884}
885
887template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
888 T val = 0;
889 for (size_t i = 0; i < sizeof(T); i++) {
890 val <<= 8;
891 val |= bytes[i];
892 }
893 return val;
894}
896template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
897constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
898 return encode_value<T>(bytes.data());
899}
901template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
902constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
903 std::array<uint8_t, sizeof(T)> ret{};
904 for (size_t i = sizeof(T); i > 0; i--) {
905 ret[i - 1] = val & 0xFF;
906 val >>= 8;
907 }
908 return ret;
909}
910
912inline uint8_t reverse_bits(uint8_t x) {
913 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
914 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
915 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
916 return x;
917}
919inline uint16_t reverse_bits(uint16_t x) {
920 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
921}
924 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
925 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
926}
927
929template<typename T> constexpr T convert_big_endian(T val) {
930#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
931 return byteswap(val);
932#else
933 return val;
934#endif
935}
936
938template<typename T> constexpr T convert_little_endian(T val) {
939#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
940 return val;
941#else
942 return byteswap(val);
943#endif
944}
945
947
950
952bool str_equals_case_insensitive(const std::string &a, const std::string &b);
954bool str_equals_case_insensitive(StringRef a, StringRef b);
956inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
957inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
958inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
959
961bool str_startswith(const std::string &str, const std::string &start);
963bool str_endswith(const std::string &str, const std::string &end);
964
966bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
967inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
968 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
969}
970inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
971 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
972}
973
974// str_truncate moved to alloc_helpers.h - remove this include before 2026.11.0
975
976// str_until, str_lower_case, str_upper_case moved to alloc_helpers.h - remove this comment before 2026.11.0
977
979constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
980// str_snake_case moved to alloc_helpers.h - remove this comment before 2026.11.0
981
983constexpr char to_sanitized_char(char c) {
984 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
985}
986
996char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
997
999template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
1000 return str_sanitize_to(buffer, N, str);
1001}
1002
1003// str_sanitize moved to alloc_helpers.h - remove this comment before 2026.11.0
1004
1009inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
1011 for (size_t i = 0; i < len; i++) {
1012 hash *= FNV1_PRIME;
1013 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
1014 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(str[i])));
1015 }
1016 return hash;
1017}
1018
1019// str_snprintf, str_sprintf moved to alloc_helpers.h - remove this comment before 2026.11.0
1020
1021#ifdef USE_ESP8266
1022// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
1023// Format strings must be wrapped with PSTR() macro
1030inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
1031 if (pos >= size) {
1032 return size;
1033 }
1034 va_list args;
1035 va_start(args, fmt);
1036 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
1037 va_end(args);
1038 if (written < 0) {
1039 return pos; // encoding error
1040 }
1041 return std::min(pos + static_cast<size_t>(written), size);
1042}
1043#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
1044#else
1052__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
1053 const char *fmt, ...) {
1054 if (pos >= size) {
1055 return size;
1056 }
1057 va_list args;
1059 int written = vsnprintf(buf + pos, size - pos, fmt, args);
1061 if (written < 0) {
1062 return pos; // encoding error
1063 }
1064 return std::min(pos + static_cast<size_t>(written), size);
1065}
1066#endif
1067
1068#ifdef USE_ESP8266
1078inline size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str) {
1079 if (pos >= size) {
1080 return size;
1081 }
1082 size_t remaining = size - pos - 1; // reserve space for null terminator
1083 size_t len = strnlen_P(str, remaining);
1084 memcpy_P(buf + pos, str, len);
1085 pos += len;
1086 buf[pos] = '\0';
1087 return pos;
1088}
1092#define buf_append_str(buf, size, pos, str) buf_append_str_p(buf, size, pos, PSTR(str))
1093#else
1101inline size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str) {
1102 if (pos >= size) {
1103 return size;
1104 }
1105 size_t remaining = size - pos - 1; // reserve space for null terminator
1106 size_t len = 0;
1107 while (len < remaining && str[len] != '\0') {
1108 len++;
1109 }
1110 memcpy(buf + pos, str, len);
1111 pos += len;
1112 buf[pos] = '\0';
1113 return pos;
1114}
1115#endif
1116
1125std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len);
1126
1135std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
1136 size_t suffix_len);
1137
1147size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
1148 const char *suffix_ptr, size_t suffix_len);
1149
1151
1154
1156template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1157optional<T> parse_number(const char *str) {
1158 char *end = nullptr;
1159 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
1160 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
1161 return {};
1162 return value;
1163}
1165template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1166optional<T> parse_number(const std::string &str) {
1167 return parse_number<T>(str.c_str());
1168}
1170template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1171optional<T> parse_number(const char *str) {
1172 char *end = nullptr;
1173 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
1174 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
1175 return {};
1176 return value;
1177}
1179template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1180optional<T> parse_number(const std::string &str) {
1181 return parse_number<T>(str.c_str());
1182}
1184template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
1185 char *end = nullptr;
1186 float value = ::strtof(str, &end);
1187 if (end == str || *end != '\0' || value == HUGE_VALF)
1188 return {};
1189 return value;
1190}
1192template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
1193optional<T> parse_number(const std::string &str) {
1194 return parse_number<T>(str.c_str());
1195}
1196
1208size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
1210inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
1211 return parse_hex(str, strlen(str), data, count) == 2 * count;
1212}
1214inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
1215 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
1216}
1218inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
1219 data.resize(count);
1220 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
1221}
1223inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
1224 data.resize(count);
1225 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
1226}
1232template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1233optional<T> parse_hex(const char *str, size_t len) {
1234 T val = 0;
1235 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
1236 return {};
1237 return convert_big_endian(val);
1238}
1240template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
1241 return parse_hex<T>(str, strlen(str));
1242}
1244template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
1245 return parse_hex<T>(str.c_str(), str.length());
1246}
1247
1250static constexpr uint8_t INVALID_HEX_CHAR = 255;
1251
1252constexpr uint8_t parse_hex_char(char c) {
1253 if (c >= '0' && c <= '9')
1254 return c - '0';
1255 if (c >= 'A' && c <= 'F')
1256 return c - 'A' + 10;
1257 if (c >= 'a' && c <= 'f')
1258 return c - 'a' + 10;
1259 return INVALID_HEX_CHAR;
1260}
1261
1263ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
1264
1266ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
1267
1269ESPHOME_ALWAYS_INLINE inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
1270
1273inline char *int8_to_str(char *buf, int8_t val) {
1274 int32_t v = val;
1275 if (v < 0) {
1276 *buf++ = '-';
1277 v = -v;
1278 }
1279 if (v >= 100) {
1280 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
1281 v -= 100;
1282 // Must write tens digit (even if 0) after hundreds
1283 int32_t tens = v / 10;
1284 *buf++ = '0' + tens;
1285 v -= tens * 10;
1286 } else if (v >= 10) {
1287 int32_t tens = v / 10;
1288 *buf++ = '0' + tens;
1289 v -= tens * 10;
1290 }
1291 *buf++ = '0' + v;
1292 return buf;
1293}
1294
1299inline char *buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len) {
1300 if (remaining < 2) {
1301 if (remaining >= 1) {
1302 *buf = '\0';
1303 }
1304 return buf;
1305 }
1306 *buf++ = separator;
1307 remaining--;
1308 size_t copy_len = std::min(str_len, remaining - 1);
1309 memcpy(buf, str, copy_len);
1310 buf += copy_len;
1311 *buf = '\0';
1312 return buf;
1313}
1314
1316inline uint32_t small_pow10(int8_t n) { return n == 3 ? 1000 : n == 2 ? 100 : n == 1 ? 10 : 1; }
1317
1319static constexpr size_t UINT32_MAX_STR_SIZE = 11;
1320
1323char *uint32_to_str_unchecked(char *buf, uint32_t val);
1324
1327inline size_t uint32_to_str(std::span<char, UINT32_MAX_STR_SIZE> buf, uint32_t val) {
1328 char *end = uint32_to_str_unchecked(buf.data(), val);
1329 *end = '\0';
1330 return static_cast<size_t>(end - buf.data());
1331}
1332
1336inline char *frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor) {
1337 while (divisor > 0) {
1338 *buf++ = '0' + static_cast<char>(frac / divisor);
1339 frac %= divisor;
1340 divisor /= 10;
1341 }
1342 return buf;
1343}
1344
1346char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1347
1350template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1351 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
1352 return format_hex_to(buffer, N, data, length);
1353}
1354
1356template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1357inline char *format_hex_to(char (&buffer)[N], T val) {
1358 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
1360 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1361}
1362
1364template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
1365 return format_hex_to(buffer, data.data(), data.size());
1366}
1367
1369template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
1370 return format_hex_to(buffer, data.data(), data.size());
1371}
1372
1374constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
1375
1377constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
1378
1380template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1381inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
1382 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
1383 buffer[0] = '0';
1384 buffer[1] = 'x';
1386 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1387 return buffer;
1388}
1389
1391template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1392 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
1393 buffer[0] = '0';
1394 buffer[1] = 'x';
1395 format_hex_to(buffer + 2, N - 2, data, length);
1396 return buffer;
1397}
1398
1400constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
1401
1413char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
1414
1416template<size_t N>
1417inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
1418 static_assert(N >= 3, "Buffer must hold at least one hex byte");
1419 return format_hex_pretty_to(buffer, N, data, length, separator);
1420}
1421
1423template<size_t N>
1424inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1425 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1426}
1427
1429template<size_t N, size_t M>
1430inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1431 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1432}
1433
1435constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1436
1450char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1451
1453template<size_t N>
1454inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1455 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1456 return format_hex_pretty_to(buffer, N, data, length, separator);
1457}
1458
1460static constexpr size_t MAC_ADDRESS_SIZE = 6;
1462static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1464static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1465
1467inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1468 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1469}
1470
1472inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1473 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1474}
1475
1476// format_mac_address_pretty, format_hex (all overloads) moved to alloc_helpers.h
1477// Remove this comment and the template overloads below before 2026.11.0
1478
1481template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
1483 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1484}
1487template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
1488 return format_hex(data.data(), data.size());
1489}
1490
1491// format_hex_pretty (all overloads) moved to alloc_helpers.h
1492// Remove this comment and the template overload below before 2026.11.0
1493
1496template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1497std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
1499 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
1500}
1501
1503constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1504
1524char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1525
1527template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1528 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1529 return format_bin_to(buffer, N, data, length);
1530}
1531
1548template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1549inline char *format_bin_to(char (&buffer)[N], T val) {
1550 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1552 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1553}
1554
1555// format_bin moved to alloc_helpers.h - remove this comment and template overload before 2026.11.0
1556
1559template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
1561 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1562}
1563
1572ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1573
1574// value_accuracy_to_string moved to alloc_helpers.h - remove this comment before 2026.11.0
1575
1577static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1578
1580size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1582size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1583 int8_t accuracy_decimals, StringRef unit_of_measurement);
1584
1586int8_t step_to_accuracy_decimals(float step);
1587
1588// base64_encode (both overloads), base64_decode (vector overload) moved to alloc_helpers.h
1589// Remove this comment before 2026.11.0
1590size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1591size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1592
1597bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1598
1600
1603
1605// Remove before 2026.9.0
1606ESPDEPRECATED("Use LightState::gamma_correct_lut() instead. Removed in 2026.9.0.", "2026.3.0")
1607float gamma_correct(float value, float gamma);
1609// Remove before 2026.9.0
1610ESPDEPRECATED("Use LightState::gamma_uncorrect_lut() instead. Removed in 2026.9.0.", "2026.3.0")
1611float gamma_uncorrect(float value, float gamma);
1612
1614void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1616void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1617
1619
1622
1624constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1626constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1627
1629
1632
1638template<typename... X> struct Callback;
1639
1640template<typename... Ts> struct Callback<void(Ts...)> {
1641 // The inline storage path stores callable bytes in ctx_ via memcpy.
1642 // sizeof equality with uintptr_t ensures void* can round-trip arbitrary bit patterns,
1643 // which combined with flat address spaces on all ESPHome targets means no trap representations.
1644 static_assert(sizeof(void *) == sizeof(std::uintptr_t), "void* must be the same size as uintptr_t");
1645
1646 void (*fn_)(void *, Ts...){nullptr};
1647 void *ctx_{nullptr};
1648
1650 void call(Ts... args) const { this->fn_(this->ctx_, std::forward<Ts>(args)...); }
1651
1654 template<typename F> static Callback create(F &&callable) {
1655 using DecayF = std::decay_t<F>;
1656 if constexpr (sizeof(DecayF) <= sizeof(void *) && std::is_trivially_copyable_v<DecayF>) {
1657 // Small trivial callable (e.g. [this]() { this->method(); }) - store inline in ctx.
1658 // Safe under C++20 (P0593R6): byte copy into aligned storage implicitly
1659 // creates objects of implicit-lifetime types (trivially copyable qualifies).
1660 Callback cb; // fn and ctx are zero-initialized by default
1661 // Decay callable to a local variable first. When F is a function reference
1662 // (e.g. void(&)(int)), &callable would point at machine code, not a pointer variable.
1663 DecayF decayed = std::forward<F>(callable);
1664 __builtin_memcpy(&cb.ctx_, &decayed, sizeof(DecayF));
1665 cb.fn_ = [](void *c, Ts... args) {
1666 alignas(DecayF) char buf[sizeof(DecayF)];
1667 __builtin_memcpy(buf, &c, sizeof(DecayF));
1668 (*std::launder(reinterpret_cast<DecayF *>(buf)))(args...);
1669 };
1670 return cb;
1671 } else {
1672 // Large or non-trivial callable - heap allocate.
1673 // Intentionally never freed: callbacks in ESPHome are registered during setup()
1674 // and live for device lifetime. Same lifetime as the previous std::function approach.
1675 auto *stored = new DecayF(std::forward<F>(callable));
1676 return {[](void *c, Ts... args) { (*static_cast<DecayF *>(c))(args...); }, static_cast<void *>(stored)};
1677 }
1678 }
1679};
1680
1682void *callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size);
1683
1684template<typename... X> class CallbackManager;
1685
1697template<typename... Ts> class CallbackManager<void(Ts...)> {
1698 using CbType = Callback<void(Ts...)>;
1699 static_assert(std::is_trivially_copyable_v<CbType>, "Callback must be trivially copyable");
1700
1701 public:
1702 CallbackManager() = default;
1703 ~CallbackManager() { ::operator delete(this->data_); }
1704
1705 // Non-copyable (would alias data_), movable (for std::map support)
1709 : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
1710 other.data_ = nullptr;
1711 other.size_ = 0;
1712 other.capacity_ = 0;
1713 }
1715 std::swap(this->data_, other.data_);
1716 std::swap(this->size_, other.size_);
1717 std::swap(this->capacity_, other.capacity_);
1718 return *this;
1719 }
1720
1723 template<typename F> void add(F &&callback) { this->add_(CbType::create(std::forward<F>(callback))); }
1724
1726 inline void ESPHOME_ALWAYS_INLINE call(const Ts &...args) {
1727 if (this->size_ != 0) {
1728 for (auto *it = this->data_, *end = it + this->size_; it != end; ++it) {
1729 it->call(args...);
1730 }
1731 }
1732 }
1733 uint16_t size() const { return this->size_; }
1734
1736 void operator()(const Ts &...args) { this->call(args...); }
1737
1738 protected:
1739 template<typename...> friend class LazyCallbackManager;
1742 void add_(CbType cb) {
1743 if (this->size_ == this->capacity_) {
1744 this->data_ =
1745 static_cast<CbType *>(callback_manager_grow(this->data_, this->size_, this->capacity_, sizeof(CbType)));
1746 }
1747 this->data_[this->size_++] = cb;
1748 }
1749 CbType *data_{nullptr};
1750 uint16_t size_{0};
1751 uint16_t capacity_{0};
1752};
1753
1762template<size_t N, typename... X> class StaticCallbackManager;
1763
1764template<size_t N, typename... Ts> class StaticCallbackManager<N, void(Ts...)> {
1765 public:
1768 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1769
1771 void call(Ts... args) {
1772 for (auto &cb : this->callbacks_)
1773 cb.call(args...);
1774 }
1775 size_t size() const { return this->callbacks_.size(); }
1776
1778 void operator()(Ts... args) { call(args...); }
1779
1780 protected:
1782 void add_(Callback<void(Ts...)> cb) { this->callbacks_.push_back(cb); }
1784};
1785
1786template<typename... X> class LazyCallbackManager;
1787
1803template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
1804 public:
1808 ~LazyCallbackManager() { delete this->callbacks_; }
1809
1810 // Non-copyable and non-movable (entities are never copied or moved)
1815
1817 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1818
1820 void call(Ts... args) {
1821 if (this->callbacks_) {
1822 this->callbacks_->call(args...);
1823 }
1824 }
1825
1827 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
1828
1830 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
1831
1833 void operator()(Ts... args) { this->call(args...); }
1834
1835 protected:
1837 void add_(Callback<void(Ts...)> cb) {
1838 if (!this->callbacks_) {
1839 this->callbacks_ = new CallbackManager<void(Ts...)>();
1840 }
1841 this->callbacks_->add_(cb);
1842 }
1843 CallbackManager<void(Ts...)> *callbacks_{nullptr};
1844};
1845
1847template<typename T> class Deduplicator {
1848 public:
1850 bool next(T value) {
1851 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
1852 return false;
1853 }
1854 this->has_value_ = true;
1855 this->value_unknown_ = false;
1856 this->last_value_ = value;
1857 return true;
1858 }
1861 bool ret = !this->value_unknown_;
1862 this->value_unknown_ = true;
1863 return ret;
1864 }
1866 bool has_value() const { return this->has_value_; }
1867
1868 protected:
1869 bool has_value_{false};
1870 bool value_unknown_{false};
1872};
1873
1875template<typename T> class Parented {
1876 public:
1878 Parented(T *parent) : parent_(parent) {}
1879
1881 T *get_parent() const { return parent_; }
1883 void set_parent(T *parent) { parent_ = parent; }
1884
1885 protected:
1886 T *parent_{nullptr};
1887};
1888
1890
1893
1898class Mutex {
1899 public:
1900 Mutex(const Mutex &) = delete;
1901 Mutex &operator=(const Mutex &) = delete;
1902
1903#if defined(USE_ESP8266) || defined(USE_RP2)
1904 // Single-threaded platforms: inline no-ops so the compiler eliminates all call overhead.
1905 Mutex() = default;
1906 ~Mutex() = default;
1907 void lock() {}
1908 bool try_lock() { return true; }
1909 void unlock() {}
1910#elif defined(USE_ESP32) || defined(USE_LIBRETINY)
1911 // FreeRTOS platforms: inline to avoid out-of-line call overhead.
1912 Mutex() { handle_ = xSemaphoreCreateMutex(); }
1913 ~Mutex() = default;
1914 void lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
1915 bool try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
1916 void unlock() { xSemaphoreGive(this->handle_); }
1917
1918 private:
1919 SemaphoreHandle_t handle_;
1920#else
1921 Mutex();
1922 ~Mutex();
1923 void lock();
1924 bool try_lock();
1925 void unlock();
1926
1927 private:
1928 // d-pointer to store private data on new platforms
1929 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
1930#endif
1931};
1932
1938 public:
1939 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
1940 ~LockGuard() { mutex_.unlock(); }
1941
1942 private:
1943 Mutex &mutex_;
1944};
1945
1967 public:
1968 InterruptLock();
1970
1971 protected:
1972#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
1974#endif
1975};
1976
1986 public:
1987 LwIPLock(const LwIPLock &) = delete;
1988 LwIPLock &operator=(const LwIPLock &) = delete;
1989
1990#if defined(USE_ESP32) || defined(USE_RP2)
1991 // Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
1992 LwIPLock();
1993 ~LwIPLock();
1994#else
1995 // No lwIP core locking — inline no-ops (empty bodies instead of = default
1996 // to prevent clang-tidy unused-variable warnings at call sites)
1999#endif
2000};
2001
2008 public:
2010 void start();
2012 void stop();
2013
2015 static bool is_high_frequency() { return num_requests > 0; }
2016
2017 protected:
2018 bool started_{false};
2019 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
2020};
2021
2023void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
2024
2025// get_mac_address, get_mac_address_pretty moved to alloc_helpers.h - remove this comment before 2026.11.0
2026
2030void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
2031
2035const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
2036
2037#ifdef USE_ESP32
2039void set_mac_address(uint8_t *mac);
2040#endif
2041
2045
2048bool mac_address_is_valid(const uint8_t *mac);
2049
2052
2054
2057
2067template<class T> class RAMAllocator {
2068 public:
2069 using value_type = T;
2070
2071 enum Flags {
2072 NONE = 0, // Perform external allocation and fall back to internal memory
2073 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
2074 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
2075 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
2076 PREFER_INTERNAL = 1 << 3, // Perform internal allocation and fall back to external memory
2077 };
2078
2079 constexpr RAMAllocator() = default;
2080 constexpr RAMAllocator(uint8_t flags) {
2081 if (flags & PREFER_INTERNAL) {
2083 return;
2084 }
2085 const uint8_t alloc_bits = flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL);
2086 if (alloc_bits != 0) {
2087 this->flags_ = alloc_bits;
2088 return;
2089 }
2090 this->flags_ = ALLOC_INTERNAL | ALLOC_EXTERNAL;
2091 }
2092 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
2093
2094 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
2095
2096 T *allocate(size_t n, size_t manual_size) {
2097 size_t size = n * manual_size;
2098 T *ptr = nullptr;
2099#ifdef USE_ESP32
2100 const auto caps = this->get_caps_();
2101 ptr = static_cast<T *>(heap_caps_malloc_prefer(size, 2, caps[0], caps[1]));
2102#else
2103 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2104 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2105#endif
2106 return ptr;
2107 }
2108
2109 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
2110
2111 T *reallocate(T *p, size_t n, size_t manual_size) {
2112 size_t size = n * manual_size;
2113 T *ptr = nullptr;
2114#ifdef USE_ESP32
2115 const auto caps = this->get_caps_();
2116 ptr = static_cast<T *>(heap_caps_realloc_prefer(p, size, 2, caps[0], caps[1]));
2117#else
2118 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2119 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2120#endif
2121 return ptr;
2122 }
2123
2124 void deallocate(T *p, size_t n) {
2125 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2126 }
2127
2131 size_t get_free_heap_size() const {
2132#ifdef USE_ESP8266
2133 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
2134#elif defined(USE_ESP32)
2135 auto max_internal =
2136 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2137 auto max_external =
2138 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2139 return max_internal + max_external;
2140#elif defined(USE_RP2)
2141 return ::rp2040.getFreeHeap();
2142#elif defined(USE_LIBRETINY)
2143 return lt_heap_get_free();
2144#else
2145 return 100000;
2146#endif
2147 }
2148
2153#ifdef USE_ESP8266
2154 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
2155#elif defined(USE_ESP32)
2156 auto max_internal =
2157 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2158 auto max_external =
2159 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2160 return std::max(max_internal, max_external);
2161#else
2162 return this->get_free_heap_size();
2163#endif
2164 }
2165
2166 private:
2167#ifdef USE_ESP32
2173 std::array<uint32_t, 2> get_caps_() const {
2174 constexpr uint32_t external_caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
2175 constexpr uint32_t internal_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
2176 if (this->flags_ & PREFER_INTERNAL) {
2177 return {internal_caps, external_caps};
2178 }
2179 const uint32_t primary = (this->flags_ & ALLOC_EXTERNAL) ? external_caps : internal_caps;
2180 const uint32_t fallback = (this->flags_ & ALLOC_INTERNAL) ? internal_caps : external_caps;
2181 return {primary, fallback};
2182 }
2183#endif
2184
2185 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
2186};
2187
2188template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
2189
2194template<typename T, typename U>
2195concept comparable_with = requires(T a, U b) {
2196 { a > b } -> std::convertible_to<bool>;
2197 { a < b } -> std::convertible_to<bool>;
2198};
2199
2200template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
2201 if (value < min)
2202 return min;
2203 return value;
2204}
2205template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
2206 if (value > max)
2207 return max;
2208 return value;
2209}
2210
2213
2218template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
2223template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
2224
2226
2227} // namespace esphome
Heap-allocating helper functions.
uint8_t m
Definition bl0906.h:1
void ESPHOME_ALWAYS_INLINE call(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:1726
CallbackManager & operator=(const CallbackManager &)=delete
void operator()(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:1736
CallbackManager & operator=(CallbackManager &&other) noexcept
Definition helpers.h:1714
void add(F &&callback)
Add any callable.
Definition helpers.h:1723
CallbackManager(CallbackManager &&other) noexcept
Definition helpers.h:1708
void add_(CbType cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1742
CallbackManager(const CallbackManager &)=delete
Lightweight read-only view over a const array stored in RODATA (will typically be in flash memory) Av...
Definition helpers.h:131
const constexpr T & operator[](size_t i) const
Definition helpers.h:135
constexpr bool empty() const
Definition helpers.h:137
constexpr ConstVector(const T *data, size_t size)
Definition helpers.h:133
constexpr size_t size() const
Definition helpers.h:136
Helper class to deduplicate items in a series of values.
Definition helpers.h:1847
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:1850
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:1866
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:1860
bool operator!=(const ConstIterator &other) const
Definition helpers.h:424
ConstIterator(const FixedRingBuffer *buf, index_type pos)
Definition helpers.h:418
bool operator!=(const Iterator &other) const
Definition helpers.h:409
Iterator(FixedRingBuffer *buf, index_type pos)
Definition helpers.h:403
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
Definition helpers.h:395
FixedRingBuffer & operator=(const FixedRingBuffer &)=delete
ConstIterator begin() const
Definition helpers.h:502
bool push(const T &value)
Push a value. Returns false if full.
Definition helpers.h:457
const T & front() const
Definition helpers.h:487
index_type capacity() const
Definition helpers.h:490
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
Definition helpers.h:467
void init(index_type capacity)
Allocate capacity - can only be called once.
Definition helpers.h:445
void pop()
Remove the oldest element.
Definition helpers.h:479
void clear()
Clear all elements (reset to empty, keep capacity)
Definition helpers.h:494
FixedRingBuffer(const FixedRingBuffer &)=delete
index_type size() const
Definition helpers.h:488
ConstIterator end() const
Definition helpers.h:503
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:534
const T & at(size_t i) const
Definition helpers.h:713
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:591
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:582
const T * begin() const
Definition helpers.h:718
bool full() const
Definition helpers.h:703
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:614
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:683
const T & operator[](size_t i) const
Definition helpers.h:708
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:707
size_t capacity() const
Definition helpers.h:702
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:688
bool empty() const
Definition helpers.h:701
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:662
void pop_back()
Remove the last element in place (no reallocation, keeps capacity) Caller must ensure vector is not e...
Definition helpers.h:693
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:674
size_t size() const
Definition helpers.h:700
const T & front() const
Definition helpers.h:684
const T & back() const
Definition helpers.h:689
const T * end() const
Definition helpers.h:719
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:598
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:712
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:651
void init(size_t n)
Definition helpers.h:624
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:2007
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2015
void stop()
Stop running the loop continuously.
Definition helpers.cpp:735
void start()
Start running the loop continuously.
Definition helpers.cpp:729
Helper class to disable interrupts.
Definition helpers.h:1966
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:1827
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1837
void add(F &&callback)
Add any callable. Allocates the underlying CallbackManager on first use.
Definition helpers.h:1817
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1833
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:1808
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:1820
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:1830
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1937
LockGuard(Mutex &mutex)
Definition helpers.h:1939
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:1985
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1898
~Mutex()=default
Definition helpers.cpp:36
void unlock()
Definition helpers.h:1909
Mutex()=default
Definition helpers.cpp:35
bool try_lock()
Definition helpers.h:1908
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:1875
T * get_parent() const
Get the parent of this object.
Definition helpers.h:1881
Parented(T *parent)
Definition helpers.h:1878
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:1883
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2067
constexpr RAMAllocator(uint8_t flags)
Definition helpers.h:2080
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:2111
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:2131
T * reallocate(T *p, size_t n)
Definition helpers.h:2109
void deallocate(T *p, size_t n)
Definition helpers.h:2124
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2152
T * allocate(size_t n)
Definition helpers.h:2094
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:2092
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:2096
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:727
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:147
SmallInlineBuffer(const SmallInlineBuffer &)=delete
uint8_t * init(size_t size)
Resize to size bytes of (uninitialized) storage and return a writable pointer to fill.
Definition helpers.h:190
bool is_inline_() const
Definition helpers.h:212
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
Definition helpers.h:205
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
size_t size() const
Definition helpers.h:209
uint8_t inline_[InlineSize]
Definition helpers.h:216
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
Definition helpers.h:167
const uint8_t * data() const
Definition helpers.h:208
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
Definition helpers.h:156
void add(F &&callback)
Add any callable.
Definition helpers.h:1768
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1771
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1782
StaticVector< Callback< void(Ts...)>, N > callbacks_
Definition helpers.h:1783
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1778
CallbackManager backed by StaticVector for compile-time-known callback counts.
Definition helpers.h:1762
ConstIterator(const StaticRingBuffer *buf, index_type pos)
Definition helpers.h:337
bool operator!=(const ConstIterator &other) const
Definition helpers.h:343
bool operator!=(const Iterator &other) const
Definition helpers.h:328
Iterator(StaticRingBuffer *buf, index_type pos)
Definition helpers.h:322
Fixed-size circular buffer with FIFO semantics and iteration support.
Definition helpers.h:316
bool push(const T &value)
Definition helpers.h:350
ConstIterator begin() const
Definition helpers.h:381
ConstIterator end() const
Definition helpers.h:382
index_type size() const
Definition helpers.h:369
const T & front() const
Definition helpers.h:368
void clear()
Clear all elements (reset to empty)
Definition helpers.h:373
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:222
const_reverse_iterator rend() const
Definition helpers.h:302
size_t size() const
Definition helpers.h:282
reverse_iterator rbegin()
Definition helpers.h:299
const T & operator[](size_t i) const
Definition helpers.h:290
reverse_iterator rend()
Definition helpers.h:300
void push_back(const T &value)
Definition helpers.h:255
bool empty() const
Definition helpers.h:283
void assign(InputIt first, InputIt last)
Definition helpers.h:265
const_reverse_iterator rbegin() const
Definition helpers.h:301
T & operator[](size_t i)
Definition helpers.h:289
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:228
typename std::array< T, N >::iterator iterator
Definition helpers.h:225
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:226
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:227
const T * data() const
Definition helpers.h:287
const_iterator end() const
Definition helpers.h:296
StaticVector(InputIt first, InputIt last)
Definition helpers.h:239
StaticVector(std::initializer_list< T > init)
Definition helpers.h:246
const_iterator begin() const
Definition helpers.h:295
struct @65::@66 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
Functions to constrain the range of arithmetic values.
Definition helpers.h:2195
uint16_t flags
uint16_t id
mopeka_std_values val[3]
size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str)
Safely append a PROGMEM string to buffer, returning new position (capped at size).
Definition helpers.h:1078
T clamp_at_most(T value, U max)
Definition helpers.h:2205
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
Definition helpers.cpp:20
size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str)
Safely append a string to buffer, returning new position (capped at size).
Definition helpers.h:1101
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:825
ESPDEPRECATED("Use LightState::gamma_correct_lut() instead. Removed in 2026.9.0.", "2026.3.0") float gamma_correct(float value
Applies gamma correction of gamma to value.
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:197
const char int const __FlashStringHelper * format
Definition log.h:74
ESPHOME_ALWAYS_INLINE 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:1263
float gamma_uncorrect(float value, float gamma)
Definition helpers.cpp:655
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:86
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:241
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:929
float gamma_correct(float value, float gamma)
Definition helpers.cpp:647
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:983
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:761
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1269
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1472
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:798
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:664
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:26
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:473
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:1030
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:400
const char int const __FlashStringHelper va_list args
Definition log.h:74
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
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:938
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:803
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:609
va_end(args)
const void size_t len
Definition hal.h:64
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:1377
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:877
uint32_t small_pow10(int8_t n)
Return 10^n for small non-negative n (0-3) as uint32_t, avoiding float.
Definition helpers.h:1316
std::vector< uint8_t > base64_decode(const std::string &encoded_string)
Decode a base64 string to a byte vector.
char * format_hex_prefixed_to(char(&buffer)[N], T val)
Format an unsigned integer as "0x" prefixed lowercase hex to buffer.
Definition helpers.h:1381
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:110
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:274
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:340
size_t uint32_to_str(std::span< char, UINT32_MAX_STR_SIZE > buf, uint32_t val)
Write unsigned 32-bit integer to buffer with compile-time size check.
Definition helpers.h:1327
uint16_t size
Definition helpers.cpp:25
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:415
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:1009
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:160
T clamp_at_least(T value, U min)
Definition helpers.h:2200
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1157
char * frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor)
Write fractional digits with leading zeros to buffer (internal, no size check).
Definition helpers.h:1336
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:108
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:503
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
size_t size_t pos
Definition helpers.h:1052
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:750
char * buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len)
Append a separator char and a string to a buffer, respecting remaining space.
Definition helpers.h:1299
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:785
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.
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:1374
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:201
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:217
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:224
void init_array_from(std::array< T, N > &dest, std::initializer_list< T > src)
Initialize a std::array from an initializer_list.
Definition helpers.h:517
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
Definition helpers.h:1273
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:492
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:320
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:1400
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:800
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:887
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:687
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:744
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:126
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:881
const void * src
Definition hal.h:64
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:59
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:1624
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:873
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:74
size_t size_t const char * fmt
Definition helpers.h:1053
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1252
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:208
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:902
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:1503
int written
Definition helpers.h:1059
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:84
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:979
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1626
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:912
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:334
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:1435
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:779
void * callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size)
Grow a CallbackManager's backing array to exactly size+1. Defined in helpers.cpp.
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:209
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:848
float gamma
Definition helpers.h:1607
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1565
@ PARSE_ON
Definition helpers.h:1567
@ PARSE_TOGGLE
Definition helpers.h:1569
@ PARSE_OFF
Definition helpers.h:1568
@ PARSE_NONE
Definition helpers.h:1566
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:766
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:261
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:377
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:1467
static void uint32_t
static Callback create(F &&callable)
Create from any callable.
Definition helpers.h:1654
void call(Ts... args) const
Invoke the callback. Only valid on Callbacks created via create(), never on default-constructed insta...
Definition helpers.h:1650
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1638
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