23static const char *
const TAG =
"helpers";
27 ESPHOME_DEBUG_ASSERT(
size < UINT16_MAX);
32 ::operator
delete(data);
38static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
39 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
40static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
41 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
44static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
45 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
46static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
47 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
50#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
51static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
52 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
53static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
54 0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
59uint8_t
crc8(
const uint8_t *data, uint8_t
len, uint8_t crc, uint8_t poly,
bool msb_first) {
60 while ((
len--) != 0u) {
61 uint8_t inbyte = *data++;
65 for (uint8_t i = 8; i != 0u; i--) {
67 crc = (crc << 1) ^ poly;
74 for (uint8_t i = 8; i != 0u; i--) {
75 bool mix = (crc ^ inbyte) & 0x01;
86uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t crc, uint16_t reverse_poly,
bool refin,
bool refout) {
88 if (reverse_poly == 0x8408) {
89 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data,
len);
90 return refout ? crc : (crc ^ 0xffff);
97 if (reverse_poly == 0x8408) {
99 uint8_t combo = crc ^ (uint8_t) *data++;
100 crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
105 if (reverse_poly == 0xa001) {
107 uint8_t combo = crc ^ (uint8_t) *data++;
108 crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
113 for (uint8_t i = 0; i < 8; i++) {
115 crc = (crc >> 1) ^ reverse_poly;
123 return refout ? (crc ^ 0xffff) : crc;
126uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t crc, uint16_t poly,
bool refin,
bool refout) {
127#if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32S2)
128 if (poly == 0x1021) {
129 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data,
len);
130 return refout ? crc : (crc ^ 0xffff);
136#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
137 if (poly == 0x1021) {
139 uint8_t combo = (crc >> 8) ^ *data++;
140 crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
145 crc ^= (((uint16_t) *data++) << 8);
146 for (uint8_t i = 0; i < 8; i++) {
148 crc = (crc << 1) ^ poly;
154#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
157 return refout ? (crc ^ 0xffff) : crc;
186 if (splitmix32_state == 0) {
187 random_bytes(
reinterpret_cast<uint8_t *
>(&splitmix32_state),
sizeof(splitmix32_state));
188 splitmix32_state |= 1;
190 splitmix32_state += 0x9e3779b9u;
192 z = (
z ^ (
z >> 16)) * 0x85ebca6bu;
193 z = (
z ^ (
z >> 13)) * 0xc2b2ae35u;
194 return z ^ (
z >> 16);
203 return strcasecmp(a.c_str(), b.c_str()) == 0;
206 return a.
size() == b.size() && strncasecmp(a.
c_str(), b.c_str(), a.
size()) == 0;
208#if __cplusplus >= 202002L
209bool str_startswith(
const std::string &str,
const std::string &start) {
return str.starts_with(start); }
212bool str_startswith(
const std::string &str,
const std::string &start) {
return str.rfind(start, 0) == 0; }
214 return str.rfind(
end) == (str.size() -
end.size());
219 if (suffix_len > str_len)
221 return strncasecmp(str + str_len - suffix_len, suffix, suffix_len) == 0;
226 if (buffer_size == 0) {
230 while (*str && i < buffer_size - 1) {
240static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
243 const char *suffix_ptr,
size_t suffix_len) {
244 size_t total_len = name_len + 1 + suffix_len;
247 if (total_len >= buffer_size) {
251 name_len = buffer_size - suffix_len - 2;
252 total_len = name_len + 1 + suffix_len;
255 memcpy(buffer, name, name_len);
256 buffer[name_len] = sep;
257 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
258 buffer[total_len] =
'\0';
264 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
266 return std::string(buffer,
len);
276 size_t chars = std::min(
length, 2 * count);
277 for (
size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
279 if (
val == INVALID_HEX_CHAR)
281 data[i >> 1] = (i & 1) ? data[i >> 1] |
val :
val << 4;
291static char *format_hex_internal(
char *buffer,
size_t buffer_size,
const uint8_t *data,
size_t length,
char separator,
293 if (
length == 0 || buffer_size == 0) {
298 uint8_t stride = separator ? 3 : 2;
299 size_t max_bytes = separator ? (buffer_size / 3) : ((buffer_size - 1) / 2);
300 if (max_bytes == 0) {
307 for (
size_t i = 0; i <
length; i++) {
308 size_t pos = i * stride;
312 buffer[
pos + 2] = separator;
317 buffer[
length * stride - (separator ? 1 : 0)] =
'\0';
328 *buf++ =
'0' + (
val % 10);
331 std::reverse(start, buf);
336 return format_hex_internal(buffer, buffer_size, data,
length, 0,
'a');
342 return format_hex_internal(buffer, buffer_size, data,
length, separator,
'A');
346 if (
length == 0 || buffer_size == 0) {
353 uint8_t stride = separator ? 5 : 4;
354 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
355 if (max_values == 0) {
359 if (
length > max_values) {
362 for (
size_t i = 0; i <
length; i++) {
363 size_t pos = i * stride;
368 if (separator && i <
length - 1) {
369 buffer[
pos + 4] = separator;
372 buffer[
length * stride - (separator ? 1 : 0)] =
'\0';
379 if (buffer_size == 0) {
383 size_t max_bytes = (buffer_size - 1) / 8;
384 if (max_bytes == 0 ||
length == 0) {
388 size_t bytes_to_format = std::min(
length, max_bytes);
390 for (
size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
391 for (
size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
392 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) +
'0';
395 buffer[bytes_to_format * 8] =
'\0';
402 if (on ==
nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR(
"on")) == 0)
404 if (on !=
nullptr && strcasecmp(str, on) == 0)
406 if (off ==
nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR(
"off")) == 0)
408 if (off !=
nullptr && strcasecmp(str, off) == 0)
410 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR(
"toggle")) == 0)
417 float abs_val = fabsf(value);
419 if (abs_val >= 10.0f) {
420 while (abs_val >= 10.0f) {
424 }
else if (abs_val < 1.0f) {
425 while (abs_val < 1.0f) {
433static inline void normalize_accuracy_decimals(
float &value, int8_t &accuracy_decimals) {
434 if (accuracy_decimals < 0) {
436 if (accuracy_decimals == -1) {
438 }
else if (accuracy_decimals == -2) {
443 value = roundf(value / divisor) * divisor;
444 accuracy_decimals = 0;
453static size_t value_accuracy_to_buf_fast(
char *buf,
float value, int8_t accuracy_decimals,
uint32_t mult) {
455 if (std::signbit(value)) {
464 uint32_t scaled =
static_cast<uint32_t>(llrint(
static_cast<double>(value) * mult));
466 if (accuracy_decimals > 0) {
471 return static_cast<size_t>(p - buf);
475 normalize_accuracy_decimals(value, accuracy_decimals);
479 if (accuracy_decimals <= 3 && std::isfinite(value)) {
481 if (std::fabs(value) <
static_cast<float>(UINT32_MAX) / mult) {
482 return value_accuracy_to_buf_fast(buf.data(), value, accuracy_decimals, mult);
487 int len = snprintf(buf.data(), buf.size(),
"%.*f", accuracy_decimals, value);
490 return static_cast<size_t>(
len) >= buf.size() ? buf.size() - 1 :
static_cast<size_t>(
len);
494 int8_t accuracy_decimals,
StringRef unit_of_measurement) {
496 if (
len == 0 || unit_of_measurement.
empty()) {
500 unit_of_measurement.
size());
501 return static_cast<size_t>(
end - buf.data());
507 snprintf(buf,
sizeof buf,
"%.5g", step);
509 std::string str{buf};
510 size_t dot_pos = str.find(
'.');
511 if (dot_pos == std::string::npos)
514 return str.length() - dot_pos - 1;
518static constexpr const char *BASE64_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
519 "abcdefghijklmnopqrstuvwxyz"
530static inline uint8_t base64_find_char(
char c) {
536 const char *
pos = strchr(BASE64_CHARS, c);
537 return pos ? (
pos - BASE64_CHARS) : 0;
541static inline bool is_base64(
char c) {
return (isalnum(c) || (c ==
'+') || (c ==
'/') || (c ==
'-') || (c ==
'_')); }
545size_t base64_decode(
const std::string &encoded_string, uint8_t *buf,
size_t buf_len) {
546 return base64_decode(
reinterpret_cast<const uint8_t *
>(encoded_string.data()), encoded_string.size(), buf, buf_len);
550static inline bool base64_decode_quad(uint8_t *char_array_4,
int count, uint8_t *buf,
size_t buf_len,
size_t &out) {
551 for (
int i = 0; i < 4; i++)
552 char_array_4[i] = base64_find_char(char_array_4[i]);
554 uint8_t char_array_3[3];
555 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
556 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
557 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
559 bool truncated =
false;
560 for (
int j = 0; j < count; j++) {
562 buf[out++] = char_array_3[j];
570size_t base64_decode(
const uint8_t *encoded_data,
size_t encoded_len, uint8_t *buf,
size_t buf_len) {
571 size_t in_len = encoded_len;
575 uint8_t char_array_4[4];
576 bool truncated =
false;
581 while (in_len-- && (encoded_data[in] !=
'=') && is_base64(encoded_data[in])) {
582 char_array_4[i++] = encoded_data[in];
585 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
591 for (
int j = i; j < 4; j++)
594 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
598 ESP_LOGW(TAG,
"Base64 decode: buffer too small, truncating");
612 constexpr size_t chunk_bytes = 48;
613 constexpr size_t chunk_chars = 64;
614 uint8_t chunk[chunk_bytes];
618 const uint8_t *input =
reinterpret_cast<const uint8_t *
>(base64.data());
619 size_t remaining = base64.size();
622 while (remaining > 0) {
623 size_t chars_to_decode = std::min(remaining, chunk_chars);
624 size_t decoded_len =
base64_decode(input +
pos, chars_to_decode, chunk, chunk_bytes);
626 if (decoded_len == 0)
630 for (
size_t i = 0; i + 3 < decoded_len; i += 4) {
631 int32_t timing =
static_cast<int32_t
>(
encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
632 out.push_back(timing);
636 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
639 pos += chars_to_decode;
640 remaining -= chars_to_decode;
654 return powf(value,
gamma);
662 return powf(value, 1 /
gamma);
665void rgb_to_hsv(
float red,
float green,
float blue,
int &hue,
float &saturation,
float &value) {
666 float max_color_value = std::max({red, green, blue});
667 float min_color_value = std::min({red, green, blue});
668 float delta = max_color_value - min_color_value;
672 }
else if (max_color_value == red) {
673 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
674 }
else if (max_color_value == green) {
675 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
676 }
else if (max_color_value == blue) {
677 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
680 if (max_color_value == 0) {
683 saturation = delta / max_color_value;
686 value = max_color_value;
688void hsv_to_rgb(
int hue,
float saturation,
float value,
float &red,
float &green,
float &blue) {
689 float chroma = value * saturation;
690 float hue_prime = fmod(hue / 60.0, 6);
691 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
692 float delta = value - chroma;
694 if (0 <= hue_prime && hue_prime < 1) {
696 green = intermediate;
698 }
else if (1 <= hue_prime && hue_prime < 2) {
702 }
else if (2 <= hue_prime && hue_prime < 3) {
706 }
else if (3 <= hue_prime && hue_prime < 4) {
708 green = intermediate;
710 }
else if (4 <= hue_prime && hue_prime < 5) {
714 }
else if (5 <= hue_prime && hue_prime < 6) {
763 bool is_all_zeros =
true;
764 bool is_all_ones =
true;
766 for (uint8_t i = 0; i < 6; i++) {
768 is_all_zeros =
false;
770 if (mac[i] != 0xFF) {
774 if (is_all_zeros || is_all_ones) {
794 delay((us - lag) / 1000UL);
795 while (
micros() - start < us - lag)
798 while (
micros() - start < us)
void stop()
Stop running the loop continuously.
static uint8_t num_requests
void start()
Start running the loop continuously.
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr bool empty() const
constexpr size_type size() const
struct @65::@66 __attribute__
Wake the main loop task from an ISR. ISR-safe.
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
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)
float gamma_uncorrect(float value, float gamma)
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)
Zero-allocation version: format name + separator + suffix directly into buffer.
float gamma_correct(float value, float gamma)
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.
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.
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)
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
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.
uint32_t small_pow10(int8_t n)
Return 10^n for small non-negative n (0-3) as uint32_t, avoiding float.
std::vector< uint8_t > base64_decode(const std::string &encoded_string)
Decode a base64 string to a byte vector.
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).
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.
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).
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
uint32_t IRAM_ATTR HOT micros()
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.
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).
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
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)
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
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.
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.
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
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.
void HOT delay(uint32_t ms)
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).
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.
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.
std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Optimized string concatenation: name + separator + suffix (const char* overload) Uses a fixed stack b...
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)