32#include <core_esp8266_features.h>
41#include <esp_system.h>
42#include <esp_heap_caps.h>
46#include <freertos/FreeRTOS.h>
47#include <freertos/semphr.h>
48#elif defined(USE_LIBRETINY)
57#define HOT __attribute__((hot))
58#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
59#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
60#define PACKED __attribute__((packed))
72using std::is_trivially_copyable;
73using std::make_unique;
74using std::enable_if_t;
76using std::is_invocable;
77#if __cpp_lib_bit_cast >= 201806
82 typename To,
typename From,
83 enable_if_t<
sizeof(To) ==
sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
87 memcpy(&dst, &
src,
sizeof(To));
93inline float lerp(
float completion,
float start,
float end) =
delete;
97template<
typename T>
constexpr T
byteswap(T n) {
99 for (
size_t i = 0; i <
sizeof(T); i++)
100 reinterpret_cast<uint8_t *
>(&
m)[i] =
reinterpret_cast<uint8_t *
>(&n)[
sizeof(T) - 1 - i];
103template<>
constexpr uint8_t
byteswap(uint8_t n) {
return n; }
106template<>
inline uint16_t
byteswap(uint16_t n) {
return __builtin_bswap16(n); }
108template<>
inline uint64_t
byteswap(uint64_t n) {
return __builtin_bswap64(n); }
109template<>
inline int8_t
byteswap(int8_t n) {
return n; }
110template<>
inline int16_t
byteswap(int16_t n) {
return __builtin_bswap16(n); }
111template<>
inline int32_t
byteswap(int32_t n) {
return __builtin_bswap32(n); }
112template<>
inline int64_t
byteswap(int64_t n) {
return __builtin_bswap64(n); }
114template<>
constexpr uint16_t
byteswap(uint16_t n) {
return __builtin_bswap16(n); }
116template<>
constexpr uint64_t
byteswap(uint64_t n) {
return __builtin_bswap64(n); }
117template<>
constexpr int8_t
byteswap(int8_t n) {
return n; }
118template<>
constexpr int16_t
byteswap(int16_t n) {
return __builtin_bswap16(n); }
119template<>
constexpr int32_t
byteswap(int32_t n) {
return __builtin_bswap32(n); }
120template<>
constexpr int64_t
byteswap(int64_t n) {
return __builtin_bswap64(n); }
144 const T &
at(
size_t i)
const {
return this->
data_[i]; }
155 static_assert(std::is_trivially_copyable_v<T> &&
sizeof(T) %
sizeof(
uint32_t) == 0,
156 "ConstVector elements must be whole words so ESP8266 can index them in flash");
170 size_t size()
const {
return this->
size_ & ~OWNED_BIT; }
173 const T &
at(
size_t index)
const {
return this->
data_[index]; }
190 static constexpr size_t OWNED_BIT =
size_t{1} << (
sizeof(size_t) * 8 - 1);
193 if (this->
size_ & OWNED_BIT)
194 delete[] this->
data_;
197 auto *table =
new T[first_count + second_count];
198 copy_items(first, first_count, table);
199 copy_items(
second, second_count, table + first_count);
202 this->
size_ = (first_count + second_count) | OWNED_BIT;
209 memcpy_P(dst,
src,
count *
sizeof(T));
218static_assert(
sizeof(ConstVector<const char *, true>) == 2 *
sizeof(
void *),
219 "ConstVector must stay a pointer and a size");
229 delete[] this->
heap_;
234 if (other.is_inline_()) {
235 memcpy(this->
inline_, other.inline_, this->len_);
237 this->
heap_ = other.heap_;
238 other.heap_ =
nullptr;
245 if (
this != &other) {
247 delete[] this->
heap_;
248 this->
len_ = other.len_;
249 if (other.is_inline_()) {
250 memcpy(this->
inline_, other.inline_, this->len_);
252 this->
heap_ = other.heap_;
253 other.heap_ =
nullptr;
267 operator std::span<const uint8_t>()
const {
return std::span<const uint8_t>(this->
data(), this->
len_); }
275 delete[] this->
heap_;
276 this->
heap_ =
nullptr;
279 if (size > InlineSize && (this->
is_inline_() || size != this->len_)) {
307 using iterator =
typename std::array<T, N>::iterator;
313 std::array<T, N> data_;
323 while (first != last && count_ < N) {
324 data_[count_++] = *first++;
330 for (
const auto &
val : init) {
333 data_[count_++] =
val;
339 static_assert(M <= N,
"Source StaticVector cannot be larger than the destination");
345 data_[count_++] =
value;
353 void resize(
size_t n) { count_ = n < N ? n : N; }
356 template<
typename InputIt>
void assign(InputIt first, InputIt last) {
358 while (first != last && count_ < N) {
359 data_[count_++] = *first++;
370 return data_[count_++];
373 size_t size()
const {
return count_; }
375 bool empty()
const {
return count_ == 0; }
378 T *
data() {
return data_.data(); }
379 const T *
data()
const {
return data_.data(); }
397 operator std::span<T>() {
return std::span<T>(data_.data(), count_); }
398 operator std::span<const T>()
const {
return std::span<const T>(data_.data(), count_); }
409 using index_type = std::conditional_t<(N <= std::numeric_limits<uint8_t>::max()), uint8_t, uint16_t>;
487template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::max()>
class FixedRingBuffer {
488 using index_type = std::conditional_t<
489 (MAX_CAPACITY <= std::numeric_limits<uint8_t>::max()), uint8_t,
490 std::conditional_t<(MAX_CAPACITY <= std::numeric_limits<uint16_t>::max()), uint16_t,
uint32_t>>;
525 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
526 ::operator
delete(this->
data_);
528 delete[] this->
data_;
538 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
541 this->
data_ =
static_cast<T *
>(::operator
new(
capacity *
sizeof(T)));
572 static_assert(std::is_trivially_copyable<T>::value,
"bulk push copies with memcpy");
577 std::memcpy(this->
data_ + this->
tail_, data, first *
sizeof(T));
578 std::memcpy(this->
data_, data + first, (
len - first) *
sizeof(T));
594 static_assert(std::is_trivially_copyable<T>::value,
"bulk pop copies with memcpy");
599 std::memcpy(
out, this->
data_ + this->
head_, first *
sizeof(T));
600 std::memcpy(
out + first, this->
data_, (len - first) *
sizeof(T));
644template<
typename T,
size_t N>
inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T>
src) {
646 assert(
src.size() == N);
648 if constexpr (std::is_trivially_copyable_v<T>) {
649 __builtin_memcpy(dest.data(),
src.begin(), N *
sizeof(T));
652 for (
const auto &v :
src) {
661#define ESPHOME_ABORT_WITH_REASON(reason) esp_system_abort(reason)
663#define ESPHOME_ABORT_WITH_REASON(reason) abort()
676 void destroy_elements_() {
678 if constexpr (!std::is_trivially_destructible<T>::value) {
679 for (
size_t i = 0; i < size_; i++) {
687 if (data_ !=
nullptr) {
701 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
702 init(init_list.size());
704 for (
const auto &item : init_list) {
705 new (data_ + idx) T(item);
708 size_ = init_list.size();
716 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
730 operator std::vector<T>()
const {
return {data_, data_ + size_}; }
733 if (
this != &other) {
739 capacity_ = other.capacity_;
751 assign_from_initializer_list_(init_list);
761 ESPHOME_ABORT_WITH_REASON(
"FixedVector: out of memory");
770 if (n > SIZE_MAX /
sizeof(T))
774 data_ =
static_cast<T *
>(malloc(n *
sizeof(T)));
775 if (data_ ==
nullptr)
797 if (size_ < capacity_) {
799 new (&data_[size_]) T(
value);
808 if (size_ < capacity_) {
810 new (&data_[size_]) T(std::move(
value));
821 new (&data_[size_]) T(std::forward<Args>(args)...);
823 return data_[size_ - 1];
829 const T &
front()
const {
return data_[0]; }
833 T &
back() {
return data_[size_ - 1]; }
834 const T &
back()
const {
return data_[size_ - 1]; }
839 if constexpr (!std::is_trivially_destructible<T>::value) {
840 data_[size_ - 1].~T();
845 size_t size()
const {
return size_; }
846 bool empty()
const {
return size_ == 0; }
848 bool full()
const {
return size_ == capacity_; }
857 T &
at(
size_t i) {
return data_[i]; }
858 const T &
at(
size_t i)
const {
return data_[i]; }
862 T *
end() {
return data_ + size_; }
863 const T *
begin()
const {
return data_; }
864 const T *
end()
const {
return data_ + size_; }
875 static_assert(std::is_trivially_default_constructible_v<T> && std::is_trivially_destructible_v<T>,
876 "the heap fallback leaves elements unconstructed");
877 if (
size <= STACK_SIZE) {
878 this->buffer_ = this->stack_buffer_;
880 if (
size <= SIZE_MAX /
sizeof(T)) {
882 this->heap_buffer_ =
static_cast<T *
>(malloc(
size *
sizeof(T)));
885 if (this->heap_buffer_ ==
nullptr)
886 ESPHOME_ABORT_WITH_REASON(
"SmallBufferWithHeapFallback: out of memory");
887 this->buffer_ = this->heap_buffer_;
898 T *
get() {
return this->buffer_; }
901 T stack_buffer_[STACK_SIZE];
902 T *heap_buffer_{
nullptr};
922 for (int8_t i = 0; i < exp; i++)
925 for (int8_t i = exp; i < 0; i++)
932template<
typename T,
typename U> T
remap(U
value, U min, U max, T min_out, T max_out) {
933 return (
value - min) * (max_out - min_out) / (max - min) + min_out;
939constexpr uint8_t
sum_bytes(
const uint8_t *data,
size_t len, uint8_t sum = 0) {
940 return std::accumulate(data, data +
len, sum);
944constexpr uint16_t
sum16_bytes(
const uint8_t *data,
size_t len, uint16_t sum = 0) {
945 return std::accumulate(data, data +
len, sum);
949constexpr uint8_t
xor_bytes(
const uint8_t *data,
size_t len, uint8_t init = 0) {
950 return std::accumulate(data, data +
len, init, std::bit_xor<>());
954uint8_t
crc8(
const uint8_t *data, uint8_t
len, uint8_t crc = 0x00, uint8_t poly = 0x8C,
bool msb_first =
false);
957uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
958 bool refin =
false,
bool refout =
false);
959uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t crc = 0, uint16_t poly = 0x1021,
bool refin =
false,
960 bool refout =
false);
974 using UnsignedT = std::make_unsigned_t<T>;
975 UnsignedT uvalue =
static_cast<UnsignedT
>(
value);
976 for (
size_t i = 0; i <
sizeof(T); i++) {
978 hash ^= (uvalue >> (i * 8)) & 0xFF;
1009 using UnsignedT = std::make_unsigned_t<T>;
1010 UnsignedT uvalue =
static_cast<UnsignedT
>(
value);
1011 for (
size_t i = 0; i <
sizeof(T); i++) {
1012 hash ^= (uvalue >> (i * 8)) & 0xFF;
1044 return (
static_cast<uint16_t
>(msb) << 8) | (
static_cast<uint16_t
>(lsb));
1048 return (
static_cast<uint32_t>(byte1) << 16) | (
static_cast<uint32_t>(byte2) << 8) | (
static_cast<uint32_t>(byte3));
1052 return (
static_cast<uint32_t>(byte1) << 24) | (
static_cast<uint32_t>(byte2) << 16) |
1058 static_assert(BITS > 0 && BITS <= 32,
"BITS must be 1 to 32");
1059 return static_cast<int32_t
>(
value << (32 - BITS)) >> (32 - BITS);
1064template<typename T, enable_if_t<std::is_integral<T>::value,
int> = 0>
constexpr T
encode_value(
const uint8_t *bytes) {
1065 if constexpr (
sizeof(T) == 1) {
1066 return static_cast<T
>(bytes[0]);
1068 std::make_unsigned_t<T>
val = 0;
1069 for (
size_t i = 0; i <
sizeof(T); i++) {
1073 return static_cast<T
>(
val);
1077template<typename T, enable_if_t<std::is_integral<T>::value,
int> = 0>
1083template<typename T, enable_if_t<std::is_integral<T>::value,
int> = 0>
1086 if constexpr (
sizeof(T) == 1) {
1087 return static_cast<T
>(bytes[0]);
1088 }
else if constexpr (
sizeof(T) == 2) {
1091 std::make_unsigned_t<T>
val = 0;
1092 for (
size_t i =
sizeof(T); i > 0; i--) {
1094 val |= bytes[i - 1];
1096 return static_cast<T
>(
val);
1100template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
1102 std::array<uint8_t,
sizeof(T)>
ret{};
1103 for (
size_t i =
sizeof(T); i > 0; i--) {
1113 dst[0] =
static_cast<uint8_t
>(
value >> 8);
1114 dst[1] =
static_cast<uint8_t
>(
value);
1118 dst[0] =
static_cast<uint8_t
>(
value >> 16);
1119 dst[1] =
static_cast<uint8_t
>(
value >> 8);
1120 dst[2] =
static_cast<uint8_t
>(
value);
1124 dst[0] =
static_cast<uint8_t
>(
value >> 24);
1125 dst[1] =
static_cast<uint8_t
>(
value >> 16);
1126 dst[2] =
static_cast<uint8_t
>(
value >> 8);
1127 dst[3] =
static_cast<uint8_t
>(
value);
1131 dst[0] =
static_cast<uint8_t
>(
value);
1132 dst[1] =
static_cast<uint8_t
>(
value >> 8);
1136 dst[0] =
static_cast<uint8_t
>(
value);
1137 dst[1] =
static_cast<uint8_t
>(
value >> 8);
1138 dst[2] =
static_cast<uint8_t
>(
value >> 16);
1139 dst[3] =
static_cast<uint8_t
>(
value >> 24);
1144constexpr uint8_t
bcd_to_uint8(uint8_t bcd) {
return (bcd >> 4) * 10 + (bcd & 0x0F); }
1150template<
typename T> ESPHOME_ALWAYS_INLINE
constexpr void assign_bits(T &
value, std::type_identity_t<T> mask,
bool on) {
1160 x = ((
x & 0xAA) >> 1) | ((
x & 0x55) << 1);
1161 x = ((
x & 0xCC) >> 2) | ((
x & 0x33) << 2);
1162 x = ((
x & 0xF0) >> 4) | ((
x & 0x0F) << 4);
1171 return (
reverse_bits(
static_cast<uint16_t
>(
x & 0xFFFF)) << 16) |
1177#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1186#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1196 volatile uint8_t diff = 0;
1197 for (
size_t i = 0; i <
len; i++) {
1198 diff = diff | (a[i] ^ b[i]);
1218bool str_startswith(
const std::string &str,
const std::string &start);
1241#define str_contains_ignore_case(haystack, needle) str_contains_ignore_case_p(haystack, PSTR(needle))
1245 if (!needle || !haystack) {
1252#if defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1255 return strcasestr(haystack, needle) !=
nullptr;
1261constexpr char to_snake_case_char(
char c) {
return (c ==
' ') ?
'_' : (c >=
'A' && c <=
'Z') ? c + (
'a' -
'A') : c; }
1265 return (c ==
'-' || c ==
'_' || (c >=
'0' && c <=
'9') || (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z')) ? c :
'_';
1291 for (
size_t i = 0; i <
len; i++) {
1324#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
1363 size_t remaining =
size -
pos - 1;
1364 size_t len = strnlen_P(str, remaining);
1365 memcpy_P(buf +
pos, str,
len);
1373#define buf_append_str(buf, size, pos, str) buf_append_str_p(buf, size, pos, PSTR(str))
1386 size_t remaining =
size -
pos - 1;
1388 while (
len < remaining && str[
len] !=
'\0') {
1391 memcpy(buf +
pos, str,
len);
1399static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
1411 const char *suffix_ptr,
size_t suffix_len);
1414static constexpr size_t MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN = 7;
1421size_t truncate_name_to(
char *
buffer,
size_t buffer_size,
const char *name,
size_t name_len,
size_t keep_suffix_len);
1429template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
unsigned<T>::value),
int> = 0>
1431 char *
end =
nullptr;
1432 unsigned long value = ::strtoul(str, &
end, 10);
1433 if (
end == str || *
end !=
'\0' ||
value > std::numeric_limits<T>::max())
1438template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
unsigned<T>::value),
int> = 0>
1443template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
signed<T>::value),
int> = 0>
1445 char *
end =
nullptr;
1446 signed long value = ::strtol(str, &
end, 10);
1447 if (
end == str || *
end !=
'\0' ||
value < std::numeric_limits<T>::min() ||
value > std::numeric_limits<T>::max())
1452template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
signed<T>::value),
int> = 0>
1459template<
typename T, enable_if_t<(std::is_same<T,
float>::value),
int> = 0> optional<T>
parse_number(
const char *str) {
1463template<
typename T, enable_if_t<(std::is_same<T,
float>::value),
int> = 0>
1494inline bool parse_hex(
const std::string &str, std::vector<uint8_t> &data,
size_t count) {
1503template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
1506 if (
len > 2 *
sizeof(T) ||
parse_hex(str,
len,
reinterpret_cast<uint8_t *
>(&
val),
sizeof(T)) == 0)
1511template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0> optional<T>
parse_hex(
const char *str) {
1515template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0> optional<T>
parse_hex(
const std::string &str) {
1521static constexpr uint8_t INVALID_HEX_CHAR = 255;
1524 if (c >=
'0' && c <=
'9')
1526 if (c >=
'A' && c <=
'F')
1527 return c -
'A' + 10;
1528 if (c >=
'a' && c <=
'f')
1529 return c -
'a' + 10;
1530 return INVALID_HEX_CHAR;
1534ESPHOME_ALWAYS_INLINE
inline char format_hex_char(uint8_t v,
char base) {
return v >= 10 ? base + (v - 10) :
'0' + v; }
1543static constexpr size_t JSON_ESCAPE_MAX_EXPANSION = 6;
1570 int32_t tens = v / 10;
1571 *buf++ =
'0' + tens;
1573 }
else if (v >= 10) {
1574 int32_t tens = v / 10;
1575 *buf++ =
'0' + tens;
1586inline char *
buf_append_sep_str(
char *buf,
size_t remaining,
char separator,
const char *str,
size_t str_len) {
1587 if (remaining < 2) {
1588 if (remaining >= 1) {
1595 size_t copy_len = std::min(str_len, remaining - 1);
1596 memcpy(buf, str, copy_len);
1603inline uint32_t small_pow10(int8_t n) {
return n == 4 ? 10000 : n == 3 ? 1000 : n == 2 ? 100 : n == 1 ? 10 : 1; }
1606static constexpr size_t UINT32_MAX_STR_SIZE = 11;
1617 return static_cast<size_t>(
end - buf.data());
1624 while (divisor > 0) {
1625 *buf++ =
'0' +
static_cast<char>(frac / divisor);
1638 static_assert(N >= 3,
"Buffer must hold at least one hex byte (3 chars)");
1643template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
1645 static_assert(N >=
sizeof(T) * 2 + 1,
"Buffer too small for type");
1656template<
size_t N,
size_t M>
inline char *
format_hex_to(
char (&
buffer)[N],
const std::array<uint8_t, M> &data) {
1667template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
1669 static_assert(N >=
sizeof(T) * 2 + 3,
"Buffer too small for prefixed hex");
1679 static_assert(N >= 5,
"Buffer must hold at least '0x' + one hex byte + null");
1705 static_assert(N >= 3,
"Buffer must hold at least one hex byte");
1716template<
size_t N,
size_t M>
1742 static_assert(N >= 5,
"Buffer must hold at least one hex uint16_t");
1747static constexpr size_t MAC_ADDRESS_SIZE = 6;
1751static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1755 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE,
':');
1760 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1789 static_assert(N >= 9,
"Buffer must hold at least one binary byte (9 chars)");
1809template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
1811 static_assert(N >=
sizeof(T) * 8 + 1,
"Buffer too small for type");
1827static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1833 int8_t accuracy_decimals, StringRef unit_of_measurement);
1838size_t base64_decode(std::string
const &encoded_string, uint8_t *buf,
size_t buf_len);
1839size_t base64_decode(
const uint8_t *encoded_data,
size_t encoded_len, uint8_t *buf,
size_t buf_len);
1853void rgb_to_hsv(
float red,
float green,
float blue,
int &hue,
float &saturation,
float &
value);
1855void hsv_to_rgb(
int hue,
float saturation,
float value,
float &red,
float &green,
float &blue);
1878 return value + 273.15f;
1899 static_assert(
sizeof(
void *) ==
sizeof(std::uintptr_t),
"void* must be the same size as uintptr_t");
1901 void (*fn_)(
void *, Ts...){
nullptr};
1902 void *ctx_{
nullptr};
1905 void call(Ts... args)
const { this->fn_(this->ctx_, std::forward<Ts>(args)...); }
1910 using DecayF = std::decay_t<F>;
1911 return sizeof(DecayF) <=
sizeof(
void *) && std::is_trivially_copyable_v<DecayF> &&
1912 std::is_invocable_v<
const DecayF &, Ts...>;
1918 using DecayF = std::decay_t<F>;
1919 if constexpr (fits_inline<F>()) {
1926 DecayF decayed = std::forward<F>(callable);
1927 __builtin_memcpy(&cb.ctx_, &decayed,
sizeof(DecayF));
1928 cb.fn_ = [](
void *c, Ts... args) {
1929 alignas(DecayF)
char buf[
sizeof(DecayF)];
1930 __builtin_memcpy(buf, &c,
sizeof(DecayF));
1931 (*std::launder(
reinterpret_cast<DecayF *
>(buf)))(args...);
1938 auto *stored =
new DecayF(std::forward<F>(callable));
1939 return {[](
void *c, Ts... args) { (*
static_cast<DecayF *
>(c))(args...); },
static_cast<void *
>(stored)};
1950 struct Boxed :
Box {
1953 auto *box =
new Boxed{{[](
Box *b) {
delete static_cast<Boxed *
>(b); }},
1954 std::forward<F>(callable)};
1955 return {[](
void *c, Ts... args) {
static_cast<Boxed *
>(
static_cast<Box *
>(c))->fn(args...); },
1956 static_cast<Box *
>(box)};
1961 auto *box =
static_cast<Box *
>(this->ctx_);
1984 static_assert(std::is_trivially_copyable_v<CbType>,
"Callback must be trivially copyable");
1994 : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
1995 other.data_ =
nullptr;
1997 other.capacity_ = 0;
2000 std::swap(this->data_, other.data_);
2001 std::swap(this->size_, other.size_);
2002 std::swap(this->capacity_, other.capacity_);
2008 template<
typename F>
void add(F &&callback) { this->add_(CbType::create(std::forward<F>(callback))); }
2011 inline void ESPHOME_ALWAYS_INLINE
call(
const Ts &...args) {
2012 if (this->size_ != 0) {
2013 for (
auto *it = this->data_, *
end = it + this->size_; it !=
end; ++it) {
2018 uint16_t
size()
const {
return this->size_; }
2028 if (this->size_ == this->capacity_) {
2032 this->data_[this->size_++] = cb;
2036 uint16_t capacity_{0};
2053 template<
typename F>
void add(F &&callback) { this->add_(
Callback<
void(Ts...)>::create(std::forward<F>(callback))); }
2057 for (
auto &cb : this->callbacks_)
2060 size_t size()
const {
return this->callbacks_.size(); }
2102 template<
typename F>
void add(F &&callback) { this->add_(
Callback<
void(Ts...)>::create(std::forward<F>(callback))); }
2106 if (this->callbacks_) {
2107 this->callbacks_->call(args...);
2112 size_t size()
const {
return this->callbacks_ ? this->callbacks_->size() : 0; }
2115 bool empty()
const {
return !this->callbacks_ || this->callbacks_->size() == 0; }
2123 if (!this->callbacks_) {
2126 this->callbacks_->add_(cb);
2188#if defined(USE_ESP8266) || defined(USE_RP2)
2195#elif defined(USE_ESP32) || defined(USE_LIBRETINY)
2197 Mutex() { handle_ = xSemaphoreCreateMutex(); }
2199 void lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
2200 bool try_lock() {
return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
2201 void unlock() { xSemaphoreGive(this->handle_); }
2204 SemaphoreHandle_t handle_;
2263#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
2281#if defined(USE_ESP32) || defined(USE_RP2)
2288 [[maybe_unused]]
bool locked_{
false};
2298#if defined(USE_ESP8266) && F_CPU != 160000000L
2314#if defined(USE_ESP8266) && F_CPU != 160000000L
2385template<
typename T>
using RAMUniquePtr = std::unique_ptr<T, RAMDeleter<T>>;
2415 if (alloc_bits != 0) {
2416 this->flags_ = alloc_bits;
2426 size_t size = n * manual_size;
2429 const auto caps = this->get_caps_();
2430 ptr =
static_cast<T *
>(heap_caps_malloc_prefer(
size, caps.num, caps.primary, caps.fallback));
2433 ptr =
static_cast<T *
>(malloc(
size));
2441 size_t size = n * manual_size;
2444 const auto caps = this->get_caps_();
2445 ptr =
static_cast<T *
>(heap_caps_realloc_prefer(p,
size, caps.num, caps.primary, caps.fallback));
2448 ptr =
static_cast<T *
>(realloc(p,
size));
2460 static_assert(
alignof(T) <=
alignof(std::max_align_t),
"malloc storage cannot hold an over aligned type");
2470 static_assert(std::is_trivially_default_constructible_v<T>,
"elements are left unconstructed");
2471 static_assert(
alignof(T) <=
alignof(std::max_align_t),
"malloc storage cannot hold an over aligned type");
2472 if (n == 0 || n > SIZE_MAX /
sizeof(T))
2482 return ESP.getFreeHeap();
2483#elif defined(USE_ESP32)
2485 this->flags_ &
ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2487 this->flags_ &
ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2488 return max_internal + max_external;
2489#elif defined(USE_RP2)
2490 return ::rp2040.getFreeHeap();
2491#elif defined(USE_LIBRETINY)
2492 return lt_heap_get_free();
2503 return ESP.getMaxFreeBlockSize();
2504#elif defined(USE_ESP32)
2506 this->flags_ &
ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2508 this->flags_ &
ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2509 return std::max(max_internal, max_external);
2522 : primary(primary_caps), fallback(fallback_caps), num(primary_caps == fallback_caps ? 1 : 2) {}
2531 constexpr Caps get_caps_()
const {
2532 constexpr uint32_t external_caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
2533 constexpr uint32_t internal_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
2535 return {internal_caps, external_caps};
2539 return {primary, fallback};
2557 static_assert(std::is_trivially_destructible_v<T>,
"RAMUniquePtr<T[]> is for trivially destructible elements");
2565template<
typename T,
typename U>
2567 { a > b } -> std::convertible_to<bool>;
2568 { a < b } -> std::convertible_to<bool>;
2589template<typename T, enable_if_t<!std::is_pointer<T>::value,
int> = 0> T
id(T
value) {
return value; }
2594template<typename T, enable_if_t<std::is_pointer<T *>::value,
int> = 0> T &
id(T *
value) {
return *
value; }
void ESPHOME_ALWAYS_INLINE call(const Ts &...args)
Call all callbacks in this manager.
CallbackManager & operator=(const CallbackManager &)=delete
void operator()(const Ts &...args)
Call all callbacks in this manager.
CallbackManager & operator=(CallbackManager &&other) noexcept
friend class LazyCallbackManager
CallbackManager()=default
void add(F &&callback)
Add any callable.
CallbackManager(CallbackManager &&other) noexcept
void add_(CbType cb)
Non-template core to avoid code duplication per lambda type.
CallbackManager(const CallbackManager &)=delete
void append_copy(const T *extra, size_t count)
Appends count elements into one new heap array this owns; the current list and extra may be codegen t...
const T & operator[](size_t index) const
void merge_copy_(const T *first, size_t first_count, const T *second, size_t second_count)
const T & at(size_t index) const
constexpr ConstVector()=default
void prepend_copy(const T *extra, size_t count)
Like append_copy(), with extra placed in front of the current list.
void assign_static(const T *data, size_t size)
Codegen only: call before any runtime copy; it does not free a previous owned copy (generated setup()...
constexpr ConstVector(const T *data, size_t size)
static void copy_items(const T *src, size_t count, T *dst)
ConstVector(const ConstVector &)=delete
ConstVector & operator=(const ConstVector &)=delete
void assign_copy(const T *data, size_t size)
Copies the list into a heap array this owns, freeing a previous owned copy.
Lightweight read-only view over a const array stored in RODATA (will typically be in flash memory).
constexpr bool empty() const
constexpr ConstVector(const T *data, size_t size)
const T & at(size_t i) const
const constexpr T & operator[](size_t i) const
constexpr size_t size() const
constexpr ConstVector()=default
Runs the CPU at 160 MHz while alive.
CpuFrequencyBoost & operator=(const CpuFrequencyBoost &)=delete
CpuFrequencyBoost(const CpuFrequencyBoost &)=delete
Helper class to deduplicate items in a series of values.
bool next(T value)
Feeds the next item in the series to the deduplicator and returns false if this is a duplicate.
bool has_value() const
Returns true if this deduplicator has processed any items.
bool next_unknown()
Returns true if the deduplicator's value was previously known.
const T & operator*() const
bool operator!=(const ConstIterator &other) const
ConstIterator & operator++()
ConstIterator(const FixedRingBuffer *buf, index_type pos)
bool operator!=(const Iterator &other) const
Iterator(FixedRingBuffer *buf, index_type pos)
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
FixedRingBuffer & operator=(const FixedRingBuffer &)=delete
ConstIterator begin() const
index_type free_space() const
bool push(const T &value)
Push a value. Returns false if full.
index_type capacity() const
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
void init(index_type capacity)
Allocate capacity - can only be called once.
const T & operator[](index_type pos) const
The element pos places after the oldest one; the sum is widened so a small index type cannot truncate...
void pop()
Remove the oldest element.
void clear()
Clear all elements (reset to empty, keep capacity)
index_type wrap_(size_t index) const
Fold an index below 2 * capacity back into the buffer.
size_t pop(T *out, size_t len)
Move up to len of the oldest values into out. Returns how many were copied.
FixedRingBuffer()=default
size_t push(const T *data, size_t len)
Push up to len values without overwriting. Returns how many fit.
FixedRingBuffer(const FixedRingBuffer &)=delete
ConstIterator end() const
Fixed-capacity vector - sized once through init() or try_init(); push_back never reallocates This avo...
const T & at(size_t i) const
FixedVector(FixedVector &&other) noexcept
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
const T & operator[](size_t i) const
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
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 ...
void pop_back()
Remove the last element in place (no reallocation, keeps capacity) Caller must ensure vector is not e...
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
FixedVector & operator=(FixedVector &&other) noexcept
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Helper class to request loop() to be called as fast as possible.
static bool is_high_frequency()
Check whether the loop is running continuously.
void stop()
Stop running the loop continuously.
static uint8_t num_requests
void start()
Start running the loop continuously.
Helper class to disable interrupts.
ESPHOME_ALWAYS_INLINE InterruptLock()
ESPHOME_ALWAYS_INLINE ~InterruptLock()
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
LazyCallbackManager()=default
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
void add(F &&callback)
Add any callable. Allocates the underlying CallbackManager on first use.
void operator()(Ts... args)
Call all callbacks in this manager.
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
bool empty() const
Check if any callbacks are registered.
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
T * get_parent() const
Get the parent of this object.
void set_parent(T *parent)
Set the parent of this object.
An STL allocator that uses SPI or internal RAM.
constexpr RAMAllocator(uint8_t flags)
T * reallocate(T *p, size_t n, size_t manual_size)
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
T * reallocate(T *p, size_t n)
void deallocate(T *p, size_t n)
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
constexpr RAMAllocator(const RAMAllocator< U > &other)
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
T * allocate(size_t n, size_t manual_size)
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
SmallBufferWithHeapFallback(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback & operator=(SmallBufferWithHeapFallback &&)=delete
~SmallBufferWithHeapFallback()
SmallBufferWithHeapFallback & operator=(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback(size_t size)
SmallBufferWithHeapFallback(SmallBufferWithHeapFallback &&)=delete
Small buffer optimization - stores data inline when small, heap-allocates for large data This avoids ...
SmallInlineBuffer()=default
SmallInlineBuffer(const SmallInlineBuffer &)=delete
uint8_t * init(size_t size)
Resize to size bytes of (uninitialized) storage and return a writable pointer to fill.
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
uint8_t inline_[InlineSize]
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
const uint8_t * data() const
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
void add(F &&callback)
Add any callable.
void call(Ts... args)
Call all callbacks in this manager.
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
StaticVector< Callback< void(Ts...)>, N > callbacks_
void operator()(Ts... args)
Call all callbacks in this manager.
CallbackManager backed by StaticVector for compile-time-known callback counts.
const T & operator*() const
ConstIterator(const StaticRingBuffer *buf, index_type pos)
ConstIterator & operator++()
bool operator!=(const ConstIterator &other) const
bool operator!=(const Iterator &other) const
Iterator(StaticRingBuffer *buf, index_type pos)
Fixed-size circular buffer with FIFO semantics and iteration support.
bool push(const T &value)
ConstIterator begin() const
ConstIterator end() const
void clear()
Clear all elements (reset to empty)
Minimal static vector - saves memory by avoiding std::vector overhead.
const_reverse_iterator rend() const
constexpr StaticVector() noexcept
reverse_iterator rbegin()
const T & operator[](size_t i) const
void push_back(const T &value)
static constexpr size_t capacity()
void assign(InputIt first, InputIt last)
const_reverse_iterator rbegin() const
std::reverse_iterator< const_iterator > const_reverse_iterator
typename std::array< T, N >::iterator iterator
typename std::array< T, N >::const_iterator const_iterator
std::reverse_iterator< iterator > reverse_iterator
const_iterator end() const
StaticVector(InputIt first, InputIt last)
StaticVector(const StaticVector< T, M > &other)
StaticVector(std::initializer_list< T > init)
const_iterator begin() const
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Functions to constrain the range of arithmetic values.
std::vector< uint8_t > & out
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).
T clamp_at_most(T value, U max)
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init=0)
XOR the bytes of data with size len, starting from init.
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).
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
float random_float()
Return a random float between 0 and 1.
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)
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.
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.
constexpr T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order.
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
bool str_contains_ignore_case(const char *haystack, const char *needle)
Case-insensitive check if needle string is contained in haystack (no heap allocation).
bool system_update_cpu_freq(uint8_t freq)
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
constexpr uint8_t uint8_to_bcd(uint8_t value)
Encode a value from 0 to 99 as a two-digit packed BCD byte, e.g. 59 to 0x59.
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
constexpr float celsius_to(float value, TemperatureUnit unit)
Convert degrees Celsius into the given unit.
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).
uint16_t uint16_t size_t elem_size
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)
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).
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
constexpr T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order.
constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value)
Extend a FNV-1 hash with an integer (hashes each byte).
ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value, std::type_identity_t< T > mask, bool on)
Set the bits of mask in value when on is true, clear them otherwise.
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.
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.
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.
uint32_t small_pow10(int8_t n)
Return 10^n for small non-negative n (0-4) as uint32_t, avoiding float.
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.
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
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.
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).
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.
bool str_contains_ignore_case_fallback(const char *haystack, const char *needle)
Fallback implementation for case insensitive substring comparison.
uint32_t fnv1_hash_object_id(size_t len, ReadByte read_byte)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
T clamp_at_least(T value, U min)
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
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).
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
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.
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.
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
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).
constexpr uint8_t bcd_to_uint8(uint8_t bcd)
Decode a two-digit packed BCD byte (tens in the high nibble) to its value, e.g. 0x59 to 59.
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
void init_array_from(std::array< T, N > &dest, std::initializer_list< T > src)
Initialize a std::array from an initializer_list.
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
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)
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.
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
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".
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
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...
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).
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.
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
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.
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
constexpr uint8_t * put_be24(uint8_t *dst, uint32_t value)
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.
constexpr int32_t sign_extend(uint32_t value)
Sign-extend the low BITS bits of value, e.g. sign_extend<24>(0xFFFFFE) == -2. Higher bits are ignored...
constexpr uint8_t * put_le32(uint8_t *dst, uint32_t value)
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
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.
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
size_t size_t const char * fmt
constexpr uint8_t parse_hex_char(char c)
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
bool constant_time_equals(const uint8_t *a, const uint8_t *b, size_t len)
Compare len bytes of a and b in a time that does not depend on where they first differ.
constexpr size_t format_bin_size(size_t byte_count)
Calculate buffer size needed for format_bin_to: "01234567...\0" = bytes * 8 + 1.
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
optional< float > parse_float(const char *str)
Parse a decimal floating-point number; plain decimals skip the libc parser.
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).
float lerp(float completion, float start, float end)=delete
constexpr uint16_t sum16_bytes(const uint8_t *data, size_t len, uint16_t sum=0)
Add up the bytes of data with size len, truncated to 16 bits.
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:....
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).
bool get_custom_mac_address(uint8_t *mac)
Read the custom MAC address from eFuse into the provided byte array (6 bytes).
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.
constexpr uint8_t * put_be32(uint8_t *dst, uint32_t value)
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
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...
uint16_t uint16_t & capacity
ParseOnOffState
Return values for parse_on_off().
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
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.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Heap home of a callable stored by create_boxed(); the header knows how to free it.
static Callback create(F &&callable)
Create from any callable.
void free_boxed() const
Free the callable of a Callback made by create_boxed(); the Callback must not be called afterwards.
static constexpr bool fits_inline()
Whether create() stores F inline in the ctx pointer.
static Callback create_boxed(F &&callable)
Store any callable on the heap with a deleter, for an owner that can later free_boxed() it.
void call(Ts... args) const
Invoke the callback. Only valid on Callbacks created via create(), never on default-constructed insta...
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
void operator()(T *p) const
Destroys and frees RAMAllocator storage. Not convertible: free() needs the address malloc returned.
void operator()(T *p) const