ESPHome 2026.10.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 <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
187 bool empty() const { return this->len_ == 0; }
188
189 // Conversion to std::span for compatibility with span-based APIs
190 operator std::span<const uint8_t>() const { return std::span<const uint8_t>(this->data(), this->len_); }
191
195 uint8_t *init(size_t size) {
196 // Free existing heap allocation if switching from heap to inline or different heap size
198 delete[] this->heap_;
199 this->heap_ = nullptr; // Defensive: prevent use-after-free if logic changes
200 }
201 // Allocate new heap buffer if needed
202 if (size > InlineSize && (this->is_inline_() || size != this->len_)) {
203 this->heap_ = new uint8_t[size]; // NOLINT(cppcoreguidelines-owning-memory)
204 }
205 this->len_ = size;
206 return this->data();
207 }
208
210 void set(const uint8_t *src, size_t size) { memcpy(this->init(size), src, size); }
211
212 uint8_t *data() { return this->is_inline_() ? this->inline_ : this->heap_; }
213 const uint8_t *data() const { return this->is_inline_() ? this->inline_ : this->heap_; }
214 size_t size() const { return this->len_; }
215
216 protected:
217 bool is_inline_() const { return this->len_ <= InlineSize; }
218
219 size_t len_{0};
220 union {
221 uint8_t inline_[InlineSize]{}; // Zero-init ensures clean initial state
222 uint8_t *heap_;
223 };
224};
225
227template<typename T, size_t N> class StaticVector {
228 public:
229 using value_type = T;
230 using iterator = typename std::array<T, N>::iterator;
231 using const_iterator = typename std::array<T, N>::const_iterator;
232 using reverse_iterator = std::reverse_iterator<iterator>;
233 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
234
235 private:
236 std::array<T, N> data_; // intentionally not value-initialized to avoid memset
237 size_t count_{0};
238
239 public:
240 // Default constructor
241 StaticVector() = default;
242
243 // Iterator range constructor
244 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
245 while (first != last && count_ < N) {
246 data_[count_++] = *first++;
247 }
248 }
249
250 // Initializer list constructor
251 StaticVector(std::initializer_list<T> init) {
252 for (const auto &val : init) {
253 if (count_ >= N)
254 break;
255 data_[count_++] = val;
256 }
257 }
258
259 // Converting constructor from a smaller StaticVector of the same element type
260 template<size_t M> StaticVector(const StaticVector<T, M> &other) : StaticVector(other.begin(), other.end()) {
261 static_assert(M <= N, "Source StaticVector cannot be larger than the destination");
262 }
263
264 // Minimal vector-compatible interface - only what we actually use
265 void push_back(const T &value) {
266 if (count_ < N) {
267 data_[count_++] = value;
268 }
269 }
270
271 // Clear all elements
272 void clear() { count_ = 0; }
273
274 // Assign from iterator range
275 template<typename InputIt> void assign(InputIt first, InputIt last) {
276 count_ = 0;
277 while (first != last && count_ < N) {
278 data_[count_++] = *first++;
279 }
280 }
281
282 // Return reference to next element and increment count (with bounds checking)
284 if (count_ >= N) {
285 // Should never happen with proper size calculation
286 // Return reference to last element to avoid crash
287 return data_[N - 1];
288 }
289 return data_[count_++];
290 }
291
292 size_t size() const { return count_; }
293 static constexpr size_t capacity() { return N; }
294 bool empty() const { return count_ == 0; }
295
296 // Direct access to underlying data
297 T *data() { return data_.data(); }
298 const T *data() const { return data_.data(); }
299
300 T &operator[](size_t i) { return data_[i]; }
301 const T &operator[](size_t i) const { return data_[i]; }
302
303 // For range-based for loops
304 iterator begin() { return data_.begin(); }
305 iterator end() { return data_.begin() + count_; }
306 const_iterator begin() const { return data_.begin(); }
307 const_iterator end() const { return data_.begin() + count_; }
308
309 // Reverse iterators
314
315 // Conversion to std::span for compatibility with span-based APIs
316 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
317 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
318};
319
327template<typename T, size_t N> class StaticRingBuffer {
328 using index_type = std::conditional_t<(N <= std::numeric_limits<uint8_t>::max()), uint8_t, uint16_t>;
329
330 public:
331 class Iterator {
332 public:
333 Iterator(StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
334 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % N]; }
336 ++pos_;
337 return *this;
338 }
339 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
340
341 private:
342 StaticRingBuffer *buf_;
343 index_type pos_;
344 };
345
347 public:
348 ConstIterator(const StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
349 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % N]; }
351 ++pos_;
352 return *this;
353 }
354 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
355
356 private:
357 const StaticRingBuffer *buf_;
358 index_type pos_;
359 };
360
361 bool push(const T &value) {
362 if (this->count_ >= N) {
363 return false;
364 }
365 this->data_[this->tail_] = value;
366 this->tail_ = (this->tail_ + 1) % N;
367 ++this->count_;
368 return true;
369 }
370
371 void pop() {
372 if (this->count_ > 0) {
373 this->head_ = (this->head_ + 1) % N;
374 --this->count_;
375 }
376 }
377
378 T &front() { return this->data_[this->head_]; }
379 const T &front() const { return this->data_[this->head_]; }
380 index_type size() const { return this->count_; }
381 bool empty() const { return this->count_ == 0; }
382
384 void clear() {
385 this->head_ = 0;
386 this->tail_ = 0;
387 this->count_ = 0;
388 }
389
390 Iterator begin() { return Iterator(this, 0); }
391 Iterator end() { return Iterator(this, this->count_); }
392 ConstIterator begin() const { return ConstIterator(this, 0); }
393 ConstIterator end() const { return ConstIterator(this, this->count_); }
394
395 protected:
396 T data_[N];
397 index_type head_{0};
398 index_type tail_{0};
399 index_type count_{0};
400};
401
406template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::max()> class FixedRingBuffer {
407 using index_type = std::conditional_t<
408 (MAX_CAPACITY <= std::numeric_limits<uint8_t>::max()), uint8_t,
409 std::conditional_t<(MAX_CAPACITY <= std::numeric_limits<uint16_t>::max()), uint16_t, uint32_t>>;
410
411 public:
412 class Iterator {
413 public:
414 Iterator(FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
415 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
417 ++pos_;
418 return *this;
419 }
420 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
421
422 private:
423 FixedRingBuffer *buf_;
424 index_type pos_;
425 };
426
428 public:
429 ConstIterator(const FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
430 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
432 ++pos_;
433 return *this;
434 }
435 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
436
437 private:
438 const FixedRingBuffer *buf_;
439 index_type pos_;
440 };
441
442 FixedRingBuffer() = default;
444 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
445 ::operator delete(this->data_);
446 } else {
447 delete[] this->data_;
448 }
449 }
450
451 // Disable copy
454
456 void init(index_type capacity) {
457 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
458 // Raw allocation without initialization (elements are written before read)
459 // NOLINTNEXTLINE(bugprone-sizeof-expression)
460 this->data_ = static_cast<T *>(::operator new(capacity * sizeof(T)));
461 } else {
462 this->data_ = new T[capacity];
463 }
464 this->capacity_ = capacity;
465 }
466
468 bool push(const T &value) {
469 if (this->count_ >= this->capacity_)
470 return false;
471 this->data_[this->tail_] = value;
472 this->tail_ = (this->tail_ + 1) % this->capacity_;
473 ++this->count_;
474 return true;
475 }
476
478 void push_overwrite(const T &value) {
479 this->data_[this->tail_] = value;
480 this->tail_ = (this->tail_ + 1) % this->capacity_;
481 if (this->count_ >= this->capacity_) {
482 // Buffer full - advance head to drop oldest, count stays at capacity
483 this->head_ = this->tail_;
484 } else {
485 ++this->count_;
486 }
487 }
488
490 void pop() {
491 if (this->count_ > 0) {
492 this->head_ = (this->head_ + 1) % this->capacity_;
493 --this->count_;
494 }
495 }
496
497 T &front() { return this->data_[this->head_]; }
498 const T &front() const { return this->data_[this->head_]; }
499 index_type size() const { return this->count_; }
500 bool empty() const { return this->count_ == 0; }
501 index_type capacity() const { return this->capacity_; }
502 bool full() const { return this->count_ == this->capacity_; }
503
505 void clear() {
506 this->head_ = 0;
507 this->tail_ = 0;
508 this->count_ = 0;
509 }
510
511 Iterator begin() { return Iterator(this, 0); }
512 Iterator end() { return Iterator(this, this->count_); }
513 ConstIterator begin() const { return ConstIterator(this, 0); }
514 ConstIterator end() const { return ConstIterator(this, this->count_); }
515
516 protected:
517 T *data_{nullptr};
518 index_type head_{0};
519 index_type tail_{0};
520 index_type count_{0};
521 index_type capacity_{0};
522};
523
528template<typename T, size_t N> inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T> src) {
529#ifdef ESPHOME_DEBUG
530 assert(src.size() == N);
531#endif
532 if constexpr (std::is_trivially_copyable_v<T>) {
533 __builtin_memcpy(dest.data(), src.begin(), N * sizeof(T));
534 } else {
535 size_t i = 0;
536 for (const auto &v : src) {
537 dest[i++] = v;
538 }
539 }
540}
541
545template<typename T> class FixedVector {
546 private:
547 T *data_{nullptr};
548 size_t size_{0};
549 size_t capacity_{0};
550
551 // Helper to destroy all elements without freeing memory
552 void destroy_elements_() {
553 // Only call destructors for non-trivially destructible types
554 if constexpr (!std::is_trivially_destructible<T>::value) {
555 for (size_t i = 0; i < size_; i++) {
556 data_[i].~T();
557 }
558 }
559 }
560
561 // Helper to destroy elements and free memory
562 void cleanup_() {
563 if (data_ != nullptr) {
564 destroy_elements_();
565 // Free raw memory
566 ::operator delete(data_);
567 }
568 }
569
570 // Helper to reset pointers after cleanup
571 void reset_() {
572 data_ = nullptr;
573 capacity_ = 0;
574 size_ = 0;
575 }
576
577 // Helper to assign from initializer list (shared by constructor and assignment operator)
578 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
579 init(init_list.size());
580 size_t idx = 0;
581 for (const auto &item : init_list) {
582 new (data_ + idx) T(item);
583 ++idx;
584 }
585 size_ = init_list.size();
586 }
587
588 public:
589 FixedVector() = default;
590
593 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
594
595 ~FixedVector() { cleanup_(); }
596
597 // Disable copy operations (avoid accidental expensive copies)
598 FixedVector(const FixedVector &) = delete;
600
601 // Enable move semantics (allows use in move-only containers like std::vector)
602 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
603 other.reset_();
604 }
605
606 // Allow conversion to std::vector
607 operator std::vector<T>() const { return {data_, data_ + size_}; }
608
609 FixedVector &operator=(FixedVector &&other) noexcept {
610 if (this != &other) {
611 // Delete our current data
612 cleanup_();
613 // Take ownership of other's data
614 data_ = other.data_;
615 size_ = other.size_;
616 capacity_ = other.capacity_;
617 // Leave other in valid empty state
618 other.reset_();
619 }
620 return *this;
621 }
622
625 FixedVector &operator=(std::initializer_list<T> init_list) {
626 cleanup_();
627 reset_();
628 assign_from_initializer_list_(init_list);
629 return *this;
630 }
631
632 // Allocate capacity - can be called multiple times to reinit
633 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
634 // Direct assignment via operator[] does NOT update the size counter.
635 void init(size_t n) {
636 cleanup_();
637 reset_();
638 if (n > 0) {
639 // Allocate raw memory without calling constructors
640 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
641 // NOLINTNEXTLINE(bugprone-sizeof-expression)
642 data_ = static_cast<T *>(::operator new(n * sizeof(T)));
643 capacity_ = n;
644 }
645 }
646
647 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
648 void clear() {
649 destroy_elements_();
650 size_ = 0;
651 }
652
653 // Release all memory (destroys elements and frees memory)
654 void release() {
655 cleanup_();
656 reset_();
657 }
658
662 void push_back(const T &value) {
663 if (size_ < capacity_) {
664 // Use placement new to construct the object in pre-allocated memory
665 new (&data_[size_]) T(value);
666 size_++;
667 }
668 }
669
673 void push_back(T &&value) {
674 if (size_ < capacity_) {
675 // Use placement new to move-construct the object in pre-allocated memory
676 new (&data_[size_]) T(std::move(value));
677 size_++;
678 }
679 }
680
685 template<typename... Args> T &emplace_back(Args &&...args) {
686 // Use placement new to construct the object in pre-allocated memory
687 new (&data_[size_]) T(std::forward<Args>(args)...);
688 size_++;
689 return data_[size_ - 1];
690 }
691
694 T &front() { return data_[0]; }
695 const T &front() const { return data_[0]; }
696
699 T &back() { return data_[size_ - 1]; }
700 const T &back() const { return data_[size_ - 1]; }
701
704 void pop_back() {
705 if constexpr (!std::is_trivially_destructible<T>::value) {
706 data_[size_ - 1].~T();
707 }
708 size_--;
709 }
710
711 size_t size() const { return size_; }
712 bool empty() const { return size_ == 0; }
713 size_t capacity() const { return capacity_; }
714 bool full() const { return size_ == capacity_; }
715
718 T &operator[](size_t i) { return data_[i]; }
719 const T &operator[](size_t i) const { return data_[i]; }
720
723 T &at(size_t i) { return data_[i]; }
724 const T &at(size_t i) const { return data_[i]; }
725
726 // Iterator support for range-based for loops
727 T *begin() { return data_; }
728 T *end() { return data_ + size_; }
729 const T *begin() const { return data_; }
730 const T *end() const { return data_ + size_; }
731};
732
738template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
739 public:
741 if (size <= STACK_SIZE) {
742 this->buffer_ = this->stack_buffer_;
743 } else {
744 this->heap_buffer_ = new T[size];
745 this->buffer_ = this->heap_buffer_;
746 }
747 }
748 ~SmallBufferWithHeapFallback() { delete[] this->heap_buffer_; }
749
750 // Delete copy and move operations to prevent double-delete
755
756 T *get() { return this->buffer_; }
757
758 private:
759 T stack_buffer_[STACK_SIZE];
760 T *heap_buffer_{nullptr};
761 T *buffer_;
762};
763
765
768
772int8_t ilog10(float value);
773
777inline float pow10_int(int8_t exp) {
778 float result = 1.0f;
779 if (exp >= 0) {
780 for (int8_t i = 0; i < exp; i++)
781 result *= 10.0f;
782 } else {
783 for (int8_t i = exp; i < 0; i++)
784 result /= 10.0f;
785 }
786 return result;
787}
788
790template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
791 return (value - min) * (max_out - min_out) / (max - min) + min_out;
792}
793
795uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
796
798uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
799 bool refin = false, bool refout = false);
800uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
801 bool refout = false);
802
805uint32_t fnv1_hash(const char *str);
806inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
807
809constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
811constexpr uint32_t FNV1_PRIME = 16777619UL;
812
814template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
815 using UnsignedT = std::make_unsigned_t<T>;
816 UnsignedT uvalue = static_cast<UnsignedT>(value);
817 for (size_t i = 0; i < sizeof(T); i++) {
818 hash *= FNV1_PRIME;
819 hash ^= (uvalue >> (i * 8)) & 0xFF;
820 }
821 return hash;
822}
824constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
825 if (str) {
826 while (*str) {
827 hash *= FNV1_PRIME;
828 hash ^= *str++;
829 }
830 }
831 return hash;
832}
833inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
834
836constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
837 if (str) {
838 while (*str) {
839 hash ^= *str++;
840 hash *= FNV1_PRIME;
841 }
842 }
843 return hash;
844}
845inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
846 return fnv1a_hash_extend(hash, str.c_str());
847}
849template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
850 using UnsignedT = std::make_unsigned_t<T>;
851 UnsignedT uvalue = static_cast<UnsignedT>(value);
852 for (size_t i = 0; i < sizeof(T); i++) {
853 hash ^= (uvalue >> (i * 8)) & 0xFF;
854 hash *= FNV1_PRIME;
855 }
856 return hash;
857}
859constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
860inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
861
862// micros_to_millis<>() lives in its own lightweight header so hal.h can pull it
863// in for inline millis_64() without forcing every TU that includes hal.h to
864// also include the rest of helpers.h.
865
873float random_float();
876bool random_bytes(uint8_t *data, size_t len);
877
879
882
884constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
885 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
886}
888constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
889 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
890}
892constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
893 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
894 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
895}
896
898template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
899 T val = 0;
900 for (size_t i = 0; i < sizeof(T); i++) {
901 val <<= 8;
902 val |= bytes[i];
903 }
904 return val;
905}
907template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
908constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
909 return encode_value<T>(bytes.data());
910}
912template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
913constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
914 std::array<uint8_t, sizeof(T)> ret{};
915 for (size_t i = sizeof(T); i > 0; i--) {
916 ret[i - 1] = val & 0xFF;
917 val >>= 8;
918 }
919 return ret;
920}
921
923inline uint8_t reverse_bits(uint8_t x) {
924 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
925 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
926 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
927 return x;
928}
930inline uint16_t reverse_bits(uint16_t x) {
931 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
932}
935 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
936 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
937}
938
940template<typename T> constexpr T convert_big_endian(T val) {
941#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
942 return byteswap(val);
943#else
944 return val;
945#endif
946}
947
949template<typename T> constexpr T convert_little_endian(T val) {
950#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
951 return val;
952#else
953 return byteswap(val);
954#endif
955}
956
958
961
963bool str_equals_case_insensitive(const std::string &a, const std::string &b);
965bool str_equals_case_insensitive(StringRef a, StringRef b);
967inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
968inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
969inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
970
972bool str_startswith(const std::string &str, const std::string &start);
974bool str_endswith(const std::string &str, const std::string &end);
975
977bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
978inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
979 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
980}
981inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
982 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
983}
984
986bool str_contains_ignore_case_fallback(const char *haystack, const char *needle);
987
988#ifdef USE_ESP8266
991bool str_contains_ignore_case_p(const char *haystack, PGM_P needle);
995#define str_contains_ignore_case(haystack, needle) str_contains_ignore_case_p(haystack, PSTR(needle))
996#else
998inline bool str_contains_ignore_case(const char *haystack, const char *needle) {
999 if (!needle || !haystack) {
1000 return false;
1001 }
1002
1003// strcasestr is a GNU extension: newlib only declares it when _GNU_SOURCE is set.
1004// ESP32/host builds get it from their framework or from g++ on Linux;
1005// LibreTiny, RP2 and Zephyr do not, so they use the hand-rolled fallback.
1006#if defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1007 return str_contains_ignore_case_fallback(haystack, needle);
1008#else // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1009 return strcasestr(haystack, needle) != nullptr;
1010#endif // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1011}
1012#endif // USE_ESP8266
1013
1014// str_truncate moved to alloc_helpers.h - remove this include before 2026.11.0
1015
1016// str_until, str_lower_case, str_upper_case moved to alloc_helpers.h - remove this comment before 2026.11.0
1017
1019constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
1020// str_snake_case moved to alloc_helpers.h - remove this comment before 2026.11.0
1021
1023constexpr char to_sanitized_char(char c) {
1024 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
1025}
1026
1036char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
1037
1039template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
1040 return str_sanitize_to(buffer, N, str);
1041}
1042
1043// str_sanitize moved to alloc_helpers.h - remove this comment before 2026.11.0
1044
1049inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
1051 for (size_t i = 0; i < len; i++) {
1052 hash *= FNV1_PRIME;
1053 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
1054 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(str[i])));
1055 }
1056 return hash;
1057}
1058
1059// str_snprintf, str_sprintf moved to alloc_helpers.h - remove this comment before 2026.11.0
1060
1061#ifdef USE_ESP8266
1062// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
1063// Format strings must be wrapped with PSTR() macro
1070inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
1071 if (pos >= size) {
1072 return size;
1073 }
1074 va_list args;
1075 va_start(args, fmt);
1076 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
1077 va_end(args);
1078 if (written < 0) {
1079 return pos; // encoding error
1080 }
1081 return std::min(pos + static_cast<size_t>(written), size);
1082}
1083#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
1084#else
1092__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
1093 const char *fmt, ...) {
1094 if (pos >= size) {
1095 return size;
1096 }
1097 va_list args;
1099 int written = vsnprintf(buf + pos, size - pos, fmt, args);
1100 va_end(args);
1101 if (written < 0) {
1102 return pos; // encoding error
1103 }
1104 return std::min(pos + static_cast<size_t>(written), size);
1105}
1106#endif
1107
1108#ifdef USE_ESP8266
1118inline size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str) {
1119 if (pos >= size) {
1120 return size;
1121 }
1122 size_t remaining = size - pos - 1; // reserve space for null terminator
1123 size_t len = strnlen_P(str, remaining);
1124 memcpy_P(buf + pos, str, len);
1125 pos += len;
1126 buf[pos] = '\0';
1127 return pos;
1128}
1132#define buf_append_str(buf, size, pos, str) buf_append_str_p(buf, size, pos, PSTR(str))
1133#else
1141inline size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str) {
1142 if (pos >= size) {
1143 return size;
1144 }
1145 size_t remaining = size - pos - 1; // reserve space for null terminator
1146 size_t len = 0;
1147 while (len < remaining && str[len] != '\0') {
1148 len++;
1149 }
1150 memcpy(buf + pos, str, len);
1151 pos += len;
1152 buf[pos] = '\0';
1153 return pos;
1154}
1155#endif
1156
1158static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
1159
1169size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
1170 const char *suffix_ptr, size_t suffix_len);
1171
1173
1176
1178template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1179optional<T> parse_number(const char *str) {
1180 char *end = nullptr;
1181 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
1182 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
1183 return {};
1184 return value;
1185}
1187template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1188optional<T> parse_number(const std::string &str) {
1189 return parse_number<T>(str.c_str());
1190}
1192template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1193optional<T> parse_number(const char *str) {
1194 char *end = nullptr;
1195 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
1196 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
1197 return {};
1198 return value;
1199}
1201template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1202optional<T> parse_number(const std::string &str) {
1203 return parse_number<T>(str.c_str());
1204}
1206template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
1207 char *end = nullptr;
1208 float value = ::strtof(str, &end);
1209 if (end == str || *end != '\0' || value == HUGE_VALF)
1210 return {};
1211 return value;
1212}
1214template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
1215optional<T> parse_number(const std::string &str) {
1216 return parse_number<T>(str.c_str());
1217}
1218
1230size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
1232inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
1233 return parse_hex(str, strlen(str), data, count) == 2 * count;
1234}
1236inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
1237 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
1238}
1240inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
1241 data.resize(count);
1242 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
1243}
1245inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
1246 data.resize(count);
1247 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
1248}
1254template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1255optional<T> parse_hex(const char *str, size_t len) {
1256 T val = 0;
1257 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
1258 return {};
1259 return convert_big_endian(val);
1260}
1262template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
1263 return parse_hex<T>(str, strlen(str));
1264}
1266template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
1267 return parse_hex<T>(str.c_str(), str.length());
1268}
1269
1272static constexpr uint8_t INVALID_HEX_CHAR = 255;
1273
1274constexpr uint8_t parse_hex_char(char c) {
1275 if (c >= '0' && c <= '9')
1276 return c - '0';
1277 if (c >= 'A' && c <= 'F')
1278 return c - 'A' + 10;
1279 if (c >= 'a' && c <= 'f')
1280 return c - 'a' + 10;
1281 return INVALID_HEX_CHAR;
1282}
1283
1285ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
1286
1288ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
1289
1291ESPHOME_ALWAYS_INLINE inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
1292
1294static constexpr size_t JSON_ESCAPE_MAX_EXPANSION = 6;
1295
1307const char *json_escape_into_buffer(std::span<char> buf, StringRef value, bool short_control_escapes = true);
1308
1311inline char *int8_to_str(char *buf, int8_t val) {
1312 int32_t v = val;
1313 if (v < 0) {
1314 *buf++ = '-';
1315 v = -v;
1316 }
1317 if (v >= 100) {
1318 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
1319 v -= 100;
1320 // Must write tens digit (even if 0) after hundreds
1321 int32_t tens = v / 10;
1322 *buf++ = '0' + tens;
1323 v -= tens * 10;
1324 } else if (v >= 10) {
1325 int32_t tens = v / 10;
1326 *buf++ = '0' + tens;
1327 v -= tens * 10;
1328 }
1329 *buf++ = '0' + v;
1330 return buf;
1331}
1332
1337inline char *buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len) {
1338 if (remaining < 2) {
1339 if (remaining >= 1) {
1340 *buf = '\0';
1341 }
1342 return buf;
1343 }
1344 *buf++ = separator;
1345 remaining--;
1346 size_t copy_len = std::min(str_len, remaining - 1);
1347 memcpy(buf, str, copy_len);
1348 buf += copy_len;
1349 *buf = '\0';
1350 return buf;
1351}
1352
1354inline uint32_t small_pow10(int8_t n) { return n == 3 ? 1000 : n == 2 ? 100 : n == 1 ? 10 : 1; }
1355
1357static constexpr size_t UINT32_MAX_STR_SIZE = 11;
1358
1361char *uint32_to_str_unchecked(char *buf, uint32_t val);
1362
1365inline size_t uint32_to_str(std::span<char, UINT32_MAX_STR_SIZE> buf, uint32_t val) {
1366 char *end = uint32_to_str_unchecked(buf.data(), val);
1367 *end = '\0';
1368 return static_cast<size_t>(end - buf.data());
1369}
1370
1374inline char *frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor) {
1375 while (divisor > 0) {
1376 *buf++ = '0' + static_cast<char>(frac / divisor);
1377 frac %= divisor;
1378 divisor /= 10;
1379 }
1380 return buf;
1381}
1382
1384char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1385
1388template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1389 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
1390 return format_hex_to(buffer, N, data, length);
1391}
1392
1394template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1395inline char *format_hex_to(char (&buffer)[N], T val) {
1396 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
1398 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1399}
1400
1402template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
1403 return format_hex_to(buffer, data.data(), data.size());
1404}
1405
1407template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
1408 return format_hex_to(buffer, data.data(), data.size());
1409}
1410
1412constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
1413
1415constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
1416
1418template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1419inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
1420 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
1421 buffer[0] = '0';
1422 buffer[1] = 'x';
1424 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1425 return buffer;
1426}
1427
1429template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1430 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
1431 buffer[0] = '0';
1432 buffer[1] = 'x';
1433 format_hex_to(buffer + 2, N - 2, data, length);
1434 return buffer;
1435}
1436
1438constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
1439
1451char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
1452
1454template<size_t N>
1455inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
1456 static_assert(N >= 3, "Buffer must hold at least one hex byte");
1457 return format_hex_pretty_to(buffer, N, data, length, separator);
1458}
1459
1461template<size_t N>
1462inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1463 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1464}
1465
1467template<size_t N, size_t M>
1468inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1469 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1470}
1471
1473constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1474
1488char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1489
1491template<size_t N>
1492inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1493 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1494 return format_hex_pretty_to(buffer, N, data, length, separator);
1495}
1496
1498static constexpr size_t MAC_ADDRESS_SIZE = 6;
1500static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1502static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1503
1505inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1506 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1507}
1508
1510inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1511 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1512}
1513
1514// format_mac_address_pretty, format_hex (all overloads) moved to alloc_helpers.h
1515// Remove this comment and the template overloads below before 2026.11.0
1516
1519template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
1521 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1522}
1525template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
1526 return format_hex(data.data(), data.size());
1527}
1528
1529// format_hex_pretty (all overloads) moved to alloc_helpers.h
1530// Remove this comment and the template overload below before 2026.11.0
1531
1534template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1535std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
1537 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
1538}
1539
1541constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1542
1562char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1563
1565template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1566 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1567 return format_bin_to(buffer, N, data, length);
1568}
1569
1586template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1587inline char *format_bin_to(char (&buffer)[N], T val) {
1588 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1590 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1591}
1592
1593// format_bin moved to alloc_helpers.h - remove this comment and template overload before 2026.11.0
1594
1597template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
1599 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1600}
1601
1610ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1611
1612// value_accuracy_to_string moved to alloc_helpers.h - remove this comment before 2026.11.0
1613
1615static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1616
1618size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1620size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1621 int8_t accuracy_decimals, StringRef unit_of_measurement);
1622
1624int8_t step_to_accuracy_decimals(float step);
1625
1626// base64_encode (both overloads), base64_decode (vector overload) moved to alloc_helpers.h
1627// Remove this comment before 2026.11.0
1628size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1629size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1630
1635bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1636
1638
1641
1643void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1645void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1646
1648
1651
1653constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1655constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1656
1657enum class TemperatureUnit : uint8_t {
1658 CELSIUS = 0,
1659 FAHRENHEIT = 1,
1660 KELVIN = 2,
1661};
1662
1664
1667
1673template<typename... X> struct Callback;
1674
1675template<typename... Ts> struct Callback<void(Ts...)> {
1676 // The inline storage path stores callable bytes in ctx_ via memcpy.
1677 // sizeof equality with uintptr_t ensures void* can round-trip arbitrary bit patterns,
1678 // which combined with flat address spaces on all ESPHome targets means no trap representations.
1679 static_assert(sizeof(void *) == sizeof(std::uintptr_t), "void* must be the same size as uintptr_t");
1680
1681 void (*fn_)(void *, Ts...){nullptr};
1682 void *ctx_{nullptr};
1683
1685 void call(Ts... args) const { this->fn_(this->ctx_, std::forward<Ts>(args)...); }
1686
1689 template<typename F> static Callback create(F &&callable) {
1690 using DecayF = std::decay_t<F>;
1691 if constexpr (sizeof(DecayF) <= sizeof(void *) && std::is_trivially_copyable_v<DecayF>) {
1692 // Small trivial callable (e.g. [this]() { this->method(); }) - store inline in ctx.
1693 // Safe under C++20 (P0593R6): byte copy into aligned storage implicitly
1694 // creates objects of implicit-lifetime types (trivially copyable qualifies).
1695 Callback cb; // fn and ctx are zero-initialized by default
1696 // Decay callable to a local variable first. When F is a function reference
1697 // (e.g. void(&)(int)), &callable would point at machine code, not a pointer variable.
1698 DecayF decayed = std::forward<F>(callable);
1699 __builtin_memcpy(&cb.ctx_, &decayed, sizeof(DecayF));
1700 cb.fn_ = [](void *c, Ts... args) {
1701 alignas(DecayF) char buf[sizeof(DecayF)];
1702 __builtin_memcpy(buf, &c, sizeof(DecayF));
1703 (*std::launder(reinterpret_cast<DecayF *>(buf)))(args...);
1704 };
1705 return cb;
1706 } else {
1707 // Large or non-trivial callable - heap allocate.
1708 // Intentionally never freed: callbacks in ESPHome are registered during setup()
1709 // and live for device lifetime. Same lifetime as the previous std::function approach.
1710 auto *stored = new DecayF(std::forward<F>(callable));
1711 return {[](void *c, Ts... args) { (*static_cast<DecayF *>(c))(args...); }, static_cast<void *>(stored)};
1712 }
1713 }
1714};
1715
1717void *callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size);
1718
1719template<typename... X> class CallbackManager;
1720
1732template<typename... Ts> class CallbackManager<void(Ts...)> {
1733 using CbType = Callback<void(Ts...)>;
1734 static_assert(std::is_trivially_copyable_v<CbType>, "Callback must be trivially copyable");
1735
1736 public:
1737 CallbackManager() = default;
1738 ~CallbackManager() { ::operator delete(this->data_); }
1739
1740 // Non-copyable (would alias data_), movable (for std::map support)
1744 : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
1745 other.data_ = nullptr;
1746 other.size_ = 0;
1747 other.capacity_ = 0;
1748 }
1750 std::swap(this->data_, other.data_);
1751 std::swap(this->size_, other.size_);
1752 std::swap(this->capacity_, other.capacity_);
1753 return *this;
1754 }
1755
1758 template<typename F> void add(F &&callback) { this->add_(CbType::create(std::forward<F>(callback))); }
1759
1761 inline void ESPHOME_ALWAYS_INLINE call(const Ts &...args) {
1762 if (this->size_ != 0) {
1763 for (auto *it = this->data_, *end = it + this->size_; it != end; ++it) {
1764 it->call(args...);
1765 }
1766 }
1767 }
1768 uint16_t size() const { return this->size_; }
1769
1771 void operator()(const Ts &...args) { this->call(args...); }
1772
1773 protected:
1774 template<typename...> friend class LazyCallbackManager;
1777 void add_(CbType cb) {
1778 if (this->size_ == this->capacity_) {
1779 this->data_ =
1780 static_cast<CbType *>(callback_manager_grow(this->data_, this->size_, this->capacity_, sizeof(CbType)));
1781 }
1782 this->data_[this->size_++] = cb;
1783 }
1784 CbType *data_{nullptr};
1785 uint16_t size_{0};
1786 uint16_t capacity_{0};
1787};
1788
1797template<size_t N, typename... X> class StaticCallbackManager;
1798
1799template<size_t N, typename... Ts> class StaticCallbackManager<N, void(Ts...)> {
1800 public:
1803 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1804
1806 void call(Ts... args) {
1807 for (auto &cb : this->callbacks_)
1808 cb.call(args...);
1809 }
1810 size_t size() const { return this->callbacks_.size(); }
1811
1813 void operator()(Ts... args) { call(args...); }
1814
1815 protected:
1817 void add_(Callback<void(Ts...)> cb) { this->callbacks_.push_back(cb); }
1819};
1820
1821template<typename... X> class LazyCallbackManager;
1822
1838template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
1839 public:
1843 ~LazyCallbackManager() { delete this->callbacks_; }
1844
1845 // Non-copyable and non-movable (entities are never copied or moved)
1850
1852 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1853
1855 void call(Ts... args) {
1856 if (this->callbacks_) {
1857 this->callbacks_->call(args...);
1858 }
1859 }
1860
1862 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
1863
1865 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
1866
1868 void operator()(Ts... args) { this->call(args...); }
1869
1870 protected:
1872 void add_(Callback<void(Ts...)> cb) {
1873 if (!this->callbacks_) {
1874 this->callbacks_ = new CallbackManager<void(Ts...)>();
1875 }
1876 this->callbacks_->add_(cb);
1877 }
1878 CallbackManager<void(Ts...)> *callbacks_{nullptr};
1879};
1880
1882template<typename T> class Deduplicator {
1883 public:
1885 bool next(T value) {
1886 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
1887 return false;
1888 }
1889 this->has_value_ = true;
1890 this->value_unknown_ = false;
1891 this->last_value_ = value;
1892 return true;
1893 }
1896 bool ret = !this->value_unknown_;
1897 this->value_unknown_ = true;
1898 return ret;
1899 }
1901 bool has_value() const { return this->has_value_; }
1902
1903 protected:
1904 bool has_value_{false};
1905 bool value_unknown_{false};
1907};
1908
1910template<typename T> class Parented {
1911 public:
1913 Parented(T *parent) : parent_(parent) {}
1914
1916 T *get_parent() const { return parent_; }
1918 void set_parent(T *parent) { parent_ = parent; }
1919
1920 protected:
1921 T *parent_{nullptr};
1922};
1923
1925
1928
1933class Mutex {
1934 public:
1935 Mutex(const Mutex &) = delete;
1936 Mutex &operator=(const Mutex &) = delete;
1937
1938#if defined(USE_ESP8266) || defined(USE_RP2)
1939 // Single-threaded platforms: inline no-ops so the compiler eliminates all call overhead.
1940 Mutex() = default;
1941 ~Mutex() = default;
1942 void lock() {}
1943 bool try_lock() { return true; }
1944 void unlock() {}
1945#elif defined(USE_ESP32) || defined(USE_LIBRETINY)
1946 // FreeRTOS platforms: inline to avoid out-of-line call overhead.
1947 Mutex() { handle_ = xSemaphoreCreateMutex(); }
1948 ~Mutex() = default;
1949 void lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
1950 bool try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
1951 void unlock() { xSemaphoreGive(this->handle_); }
1952
1953 private:
1954 SemaphoreHandle_t handle_;
1955#else
1956 Mutex();
1957 ~Mutex();
1958 void lock();
1959 bool try_lock();
1960 void unlock();
1961
1962 private:
1963 // d-pointer to store private data on new platforms
1964 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
1965#endif
1966};
1967
1973 public:
1974 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
1975 ~LockGuard() { mutex_.unlock(); }
1976
1977 private:
1978 Mutex &mutex_;
1979};
1980
2002 public:
2003 InterruptLock();
2005
2006 protected:
2007#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
2009#endif
2010};
2011
2021 public:
2022 LwIPLock(const LwIPLock &) = delete;
2023 LwIPLock &operator=(const LwIPLock &) = delete;
2024
2025#if defined(USE_ESP32) || defined(USE_RP2)
2026 // Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
2027 LwIPLock();
2028 ~LwIPLock();
2029#else
2030 // No lwIP core locking — inline no-ops (empty bodies instead of = default
2031 // to prevent clang-tidy unused-variable warnings at call sites)
2034#endif
2035};
2036
2043 public:
2045 void start();
2047 void stop();
2048
2050 static bool is_high_frequency() { return num_requests > 0; }
2051
2052 protected:
2053 bool started_{false};
2054 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
2055};
2056
2058void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
2059
2060// get_mac_address, get_mac_address_pretty moved to alloc_helpers.h - remove this comment before 2026.11.0
2061
2065void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
2066
2070const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
2071
2072#ifdef USE_ESP32
2074void set_mac_address(uint8_t *mac);
2075
2079bool get_custom_mac_address(uint8_t *mac);
2080#endif
2081
2085
2088bool mac_address_is_valid(const uint8_t *mac);
2089
2092
2094
2097
2107template<class T> class RAMAllocator {
2108 public:
2109 using value_type = T;
2110
2111 enum Flags {
2112 NONE = 0, // Perform external allocation and fall back to internal memory
2113 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
2114 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
2115 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
2116 PREFER_INTERNAL = 1 << 3, // Perform internal allocation and fall back to external memory
2117 };
2118
2119 constexpr RAMAllocator() = default;
2120 constexpr RAMAllocator(uint8_t flags) {
2121 if (flags & PREFER_INTERNAL) {
2123 return;
2124 }
2125 const uint8_t alloc_bits = flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL);
2126 if (alloc_bits != 0) {
2127 this->flags_ = alloc_bits;
2128 return;
2129 }
2130 this->flags_ = ALLOC_INTERNAL | ALLOC_EXTERNAL;
2131 }
2132 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
2133
2134 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
2135
2136 T *allocate(size_t n, size_t manual_size) {
2137 size_t size = n * manual_size;
2138 T *ptr = nullptr;
2139#ifdef USE_ESP32
2140 const auto caps = this->get_caps_();
2141 ptr = static_cast<T *>(heap_caps_malloc_prefer(size, 2, caps[0], caps[1]));
2142#else
2143 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2144 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2145#endif
2146 return ptr;
2147 }
2148
2149 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
2150
2151 T *reallocate(T *p, size_t n, size_t manual_size) {
2152 size_t size = n * manual_size;
2153 T *ptr = nullptr;
2154#ifdef USE_ESP32
2155 const auto caps = this->get_caps_();
2156 ptr = static_cast<T *>(heap_caps_realloc_prefer(p, size, 2, caps[0], caps[1]));
2157#else
2158 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2159 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2160#endif
2161 return ptr;
2162 }
2163
2164 void deallocate(T *p, size_t n) {
2165 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2166 }
2167
2171 size_t get_free_heap_size() const {
2172#ifdef USE_ESP8266
2173 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
2174#elif defined(USE_ESP32)
2175 auto max_internal =
2176 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2177 auto max_external =
2178 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2179 return max_internal + max_external;
2180#elif defined(USE_RP2)
2181 return ::rp2040.getFreeHeap();
2182#elif defined(USE_LIBRETINY)
2183 return lt_heap_get_free();
2184#else
2185 return 100000;
2186#endif
2187 }
2188
2193#ifdef USE_ESP8266
2194 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
2195#elif defined(USE_ESP32)
2196 auto max_internal =
2197 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2198 auto max_external =
2199 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2200 return std::max(max_internal, max_external);
2201#else
2202 return this->get_free_heap_size();
2203#endif
2204 }
2205
2206 private:
2207#ifdef USE_ESP32
2213 std::array<uint32_t, 2> get_caps_() const {
2214 constexpr uint32_t external_caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
2215 constexpr uint32_t internal_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
2216 if (this->flags_ & PREFER_INTERNAL) {
2217 return {internal_caps, external_caps};
2218 }
2219 const uint32_t primary = (this->flags_ & ALLOC_EXTERNAL) ? external_caps : internal_caps;
2220 const uint32_t fallback = (this->flags_ & ALLOC_INTERNAL) ? internal_caps : external_caps;
2221 return {primary, fallback};
2222 }
2223#endif
2224
2225 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
2226};
2227
2228template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
2229
2234template<typename T, typename U>
2235concept comparable_with = requires(T a, U b) {
2236 { a > b } -> std::convertible_to<bool>;
2237 { a < b } -> std::convertible_to<bool>;
2238};
2239
2240template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
2241 if (value < min)
2242 return min;
2243 return value;
2244}
2245template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
2246 if (value > max)
2247 return max;
2248 return value;
2249}
2250
2253
2258template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
2263template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
2264
2266
2267} // 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:1761
CallbackManager & operator=(const CallbackManager &)=delete
void operator()(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:1771
CallbackManager & operator=(CallbackManager &&other) noexcept
Definition helpers.h:1749
void add(F &&callback)
Add any callable.
Definition helpers.h:1758
CallbackManager(CallbackManager &&other) noexcept
Definition helpers.h:1743
void add_(CbType cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1777
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:1882
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:1885
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:1901
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:1895
bool operator!=(const ConstIterator &other) const
Definition helpers.h:435
ConstIterator(const FixedRingBuffer *buf, index_type pos)
Definition helpers.h:429
bool operator!=(const Iterator &other) const
Definition helpers.h:420
Iterator(FixedRingBuffer *buf, index_type pos)
Definition helpers.h:414
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
Definition helpers.h:406
FixedRingBuffer & operator=(const FixedRingBuffer &)=delete
ConstIterator begin() const
Definition helpers.h:513
bool push(const T &value)
Push a value. Returns false if full.
Definition helpers.h:468
const T & front() const
Definition helpers.h:498
index_type capacity() const
Definition helpers.h:501
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
Definition helpers.h:478
void init(index_type capacity)
Allocate capacity - can only be called once.
Definition helpers.h:456
void pop()
Remove the oldest element.
Definition helpers.h:490
void clear()
Clear all elements (reset to empty, keep capacity)
Definition helpers.h:505
FixedRingBuffer(const FixedRingBuffer &)=delete
index_type size() const
Definition helpers.h:499
ConstIterator end() const
Definition helpers.h:514
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:545
const T & at(size_t i) const
Definition helpers.h:724
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:602
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:593
const T * begin() const
Definition helpers.h:729
bool full() const
Definition helpers.h:714
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:625
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:694
const T & operator[](size_t i) const
Definition helpers.h:719
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:718
size_t capacity() const
Definition helpers.h:713
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:699
bool empty() const
Definition helpers.h:712
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:673
void pop_back()
Remove the last element in place (no reallocation, keeps capacity) Caller must ensure vector is not e...
Definition helpers.h:704
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:685
size_t size() const
Definition helpers.h:711
const T & front() const
Definition helpers.h:695
const T & back() const
Definition helpers.h:700
const T * end() const
Definition helpers.h:730
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:609
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:723
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:662
void init(size_t n)
Definition helpers.h:635
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:2042
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2050
void stop()
Stop running the loop continuously.
Definition helpers.cpp:817
void start()
Start running the loop continuously.
Definition helpers.cpp:811
Helper class to disable interrupts.
Definition helpers.h:2001
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:1862
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1872
void add(F &&callback)
Add any callable. Allocates the underlying CallbackManager on first use.
Definition helpers.h:1852
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1868
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:1843
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:1855
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:1865
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1972
LockGuard(Mutex &mutex)
Definition helpers.h:1974
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2020
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1933
~Mutex()=default
Definition helpers.cpp:36
void unlock()
Definition helpers.h:1944
Mutex()=default
Definition helpers.cpp:35
bool try_lock()
Definition helpers.h:1943
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:1910
T * get_parent() const
Get the parent of this object.
Definition helpers.h:1916
Parented(T *parent)
Definition helpers.h:1913
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:1918
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2107
constexpr RAMAllocator(uint8_t flags)
Definition helpers.h:2120
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:2151
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:2171
T * reallocate(T *p, size_t n)
Definition helpers.h:2149
void deallocate(T *p, size_t n)
Definition helpers.h:2164
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2192
T * allocate(size_t n)
Definition helpers.h:2134
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:2132
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:2136
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:738
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:195
bool is_inline_() const
Definition helpers.h:217
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
Definition helpers.h:210
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
size_t size() const
Definition helpers.h:214
uint8_t inline_[InlineSize]
Definition helpers.h:221
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
Definition helpers.h:167
const uint8_t * data() const
Definition helpers.h:213
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
Definition helpers.h:156
void add(F &&callback)
Add any callable.
Definition helpers.h:1803
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1806
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1817
StaticVector< Callback< void(Ts...)>, N > callbacks_
Definition helpers.h:1818
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1813
CallbackManager backed by StaticVector for compile-time-known callback counts.
Definition helpers.h:1797
ConstIterator(const StaticRingBuffer *buf, index_type pos)
Definition helpers.h:348
bool operator!=(const ConstIterator &other) const
Definition helpers.h:354
bool operator!=(const Iterator &other) const
Definition helpers.h:339
Iterator(StaticRingBuffer *buf, index_type pos)
Definition helpers.h:333
Fixed-size circular buffer with FIFO semantics and iteration support.
Definition helpers.h:327
bool push(const T &value)
Definition helpers.h:361
ConstIterator begin() const
Definition helpers.h:392
ConstIterator end() const
Definition helpers.h:393
index_type size() const
Definition helpers.h:380
const T & front() const
Definition helpers.h:379
void clear()
Clear all elements (reset to empty)
Definition helpers.h:384
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:227
const_reverse_iterator rend() const
Definition helpers.h:313
size_t size() const
Definition helpers.h:292
reverse_iterator rbegin()
Definition helpers.h:310
const T & operator[](size_t i) const
Definition helpers.h:301
reverse_iterator rend()
Definition helpers.h:311
void push_back(const T &value)
Definition helpers.h:265
bool empty() const
Definition helpers.h:294
static constexpr size_t capacity()
Definition helpers.h:293
void assign(InputIt first, InputIt last)
Definition helpers.h:275
const_reverse_iterator rbegin() const
Definition helpers.h:312
T & operator[](size_t i)
Definition helpers.h:300
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:233
typename std::array< T, N >::iterator iterator
Definition helpers.h:230
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:231
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:232
const T * data() const
Definition helpers.h:298
const_iterator end() const
Definition helpers.h:307
StaticVector(InputIt first, InputIt last)
Definition helpers.h:244
StaticVector(const StaticVector< T, M > &other)
Definition helpers.h:260
StaticVector(std::initializer_list< T > init)
Definition helpers.h:251
const_iterator begin() const
Definition helpers.h:306
struct @66::@67 __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:2235
uint16_t flags
uint16_t id
int ret
const char * format
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:1118
T clamp_at_most(T value, U max)
Definition helpers.h:2245
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:1141
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:836
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:197
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:1285
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)
Format name + separator + suffix directly into buffer without heap allocation.
Definition helpers.cpp:271
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:940
bool str_contains_ignore_case(const char *haystack, const char *needle)
Case-insensitive check if needle string is contained in haystack (no heap allocation).
Definition helpers.h:998
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1023
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:843
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:1291
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1510
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:809
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:746
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:558
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:1070
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:485
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:949
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:814
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:708
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:1415
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:888
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:1354
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:1419
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:119
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:293
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:425
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:1365
uint16_t size
Definition helpers.cpp:25
bool str_contains_ignore_case_fallback(const char *haystack, const char *needle)
Fallback implementation for case insensitive substring comparison.
Definition helpers.cpp:223
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:500
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:1049
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:2240
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1179
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:1374
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:117
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:588
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
size_t size_t pos
Definition helpers.h:1092
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:832
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:1337
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:867
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:1412
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:257
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:528
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
Definition helpers.h:1311
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:577
const char * json_escape_into_buffer(std::span< char > buf, StringRef value, bool short_control_escapes)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition helpers.cpp:357
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:339
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:1438
TemperatureUnit
Definition helpers.h:1657
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:811
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:898
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:769
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:826
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:892
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:1653
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:884
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:87
size_t size_t const char * fmt
Definition helpers.h:1093
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1274
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:913
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:1541
int written
Definition helpers.h:1099
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:1019
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1655
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:923
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:353
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:1473
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:790
bool get_custom_mac_address(uint8_t *mac)
Read the custom MAC address from eFuse into the provided byte array (6 bytes).
Definition helpers.cpp:75
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:859
bool str_contains_ignore_case_p(const char *haystack, PGM_P needle)
ESP8266 internal implementation reading the needle from flash — prefer the str_contains_ignore_case m...
Definition helpers.cpp:239
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1603
@ PARSE_ON
Definition helpers.h:1605
@ PARSE_TOGGLE
Definition helpers.h:1607
@ PARSE_OFF
Definition helpers.h:1606
@ PARSE_NONE
Definition helpers.h:1604
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:777
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:462
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:1505
static void uint32_t
static Callback create(F &&callable)
Create from any callable.
Definition helpers.h:1689
void call(Ts... args) const
Invoke the callback. Only valid on Callbacks created via create(), never on default-constructed insta...
Definition helpers.h:1685
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1673
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