ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
helpers.cpp
Go to the documentation of this file.
2
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
8
9#include <strings.h>
10#include <algorithm>
11#include <cctype>
12#include <cmath>
13#include <cstdarg>
14#include <cstdio>
15#include <cstring>
16
17#ifdef USE_ESP32
18#include "esp_rom_crc.h"
19#endif
20
21namespace esphome {
22
23static const char *const TAG = "helpers";
24
25__attribute__((noinline, cold)) void *callback_manager_grow(void *data, uint16_t size, uint16_t &capacity,
26 size_t elem_size) {
27 ESPHOME_DEBUG_ASSERT(size < UINT16_MAX);
28 uint16_t new_cap = size + 1;
29 auto *new_data = ::operator new(new_cap *elem_size);
30 if (data) {
31 __builtin_memcpy(new_data, data, size * elem_size);
32 ::operator delete(data);
33 }
35 return new_data;
36}
37
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};
42
43#ifndef USE_ESP32
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};
48#endif
49
50#ifndef USE_ESP32
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};
55#endif
56
57// Mathematics
58
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++;
62 if (msb_first) {
63 // MSB first processing (for polynomials like 0x31, 0x07)
64 crc ^= inbyte;
65 for (uint8_t i = 8; i != 0u; i--) {
66 if (crc & 0x80) {
67 crc = (crc << 1) ^ poly;
68 } else {
69 crc <<= 1;
70 }
71 }
72 } else {
73 // LSB first processing (default for Dallas/Maxim 0x8C)
74 for (uint8_t i = 8; i != 0u; i--) {
75 bool mix = (crc ^ inbyte) & 0x01;
76 crc >>= 1;
77 if (mix)
78 crc ^= poly;
79 inbyte >>= 1;
80 }
81 }
82 }
83 return crc;
84}
85
86uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout) {
87#ifdef USE_ESP32
88 if (reverse_poly == 0x8408) {
89 crc = esp_rom_crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
90 return refout ? crc : (crc ^ 0xffff);
91 }
92#endif
93 if (refin) {
94 crc ^= 0xffff;
95 }
96#ifndef USE_ESP32
97 if (reverse_poly == 0x8408) {
98 while (len--) {
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];
101 }
102 } else
103#endif
104 {
105 if (reverse_poly == 0xa001) {
106 while (len--) {
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];
109 }
110 } else {
111 while (len--) {
112 crc ^= *data++;
113 for (uint8_t i = 0; i < 8; i++) {
114 if (crc & 0x0001) {
115 crc = (crc >> 1) ^ reverse_poly;
116 } else {
117 crc >>= 1;
118 }
119 }
120 }
121 }
122 }
123 return refout ? (crc ^ 0xffff) : crc;
124}
125
126uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout) {
127#ifdef USE_ESP32
128 if (poly == 0x1021) {
129 crc = esp_rom_crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
130 return refout ? crc : (crc ^ 0xffff);
131 }
132#endif
133 if (refin) {
134 crc ^= 0xffff;
135 }
136#ifndef USE_ESP32
137 if (poly == 0x1021) {
138 while (len--) {
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];
141 }
142 } else
143#endif
144 {
145 while (len--) {
146 crc ^= (((uint16_t) *data++) << 8);
147 for (uint8_t i = 0; i < 8; i++) {
148 if (crc & 0x8000) {
149 crc = (crc << 1) ^ poly;
150 } else {
151 crc <<= 1;
152 }
153 }
154 }
155 }
156 return refout ? (crc ^ 0xffff) : crc;
157}
158
159// FNV-1 hash - deprecated, use fnv1a_hash() for new code
160uint32_t fnv1_hash(const char *str) {
162 if (str) {
163 while (*str) {
164 hash *= FNV1_PRIME;
165 hash ^= *str++;
166 }
167 }
168 return hash;
169}
170
171// SplitMix32 — a fast, non-cryptographic PRNG from the SplitMix family
172// (Steele et al., 2014). Uses a Weyl sequence with golden-ratio increment
173// and the MurmurHash3 32-bit finalizer as output mixing function.
174// Reference: https://doi.org/10.1145/2714064.2660195
175// Test results: https://lemire.me/blog/2017/08/22/testing-non-cryptographic-random-number-generators-my-results/
176// Seeded lazily from the platform's secure RNG via random_bytes().
177// ESP8266 uses os_random() instead (defined in esp8266/helpers.cpp).
178#ifndef USE_ESP8266
179static uint32_t splitmix32_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
180
182 // State of 0 means unseeded. The state will wrap back to 0 after 2^32 calls,
183 // triggering one extra random_bytes() call — an acceptable trade-off vs. adding
184 // a separate bool flag (4 bytes BSS + branch on every call).
185 if (splitmix32_state == 0) {
186 random_bytes(reinterpret_cast<uint8_t *>(&splitmix32_state), sizeof(splitmix32_state));
187 splitmix32_state |= 1; // ensure non-zero seed
188 }
189 splitmix32_state += 0x9e3779b9u;
190 uint32_t z = splitmix32_state;
191 z = (z ^ (z >> 16)) * 0x85ebca6bu;
192 z = (z ^ (z >> 13)) * 0xc2b2ae35u;
193 return z ^ (z >> 16);
194}
195#endif
196
197float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
198
199// Strings
200
201bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
202 return strcasecmp(a.c_str(), b.c_str()) == 0;
203}
205 return a.size() == b.size() && strncasecmp(a.c_str(), b.c_str(), a.size()) == 0;
206}
207#if __cplusplus >= 202002L
208bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
209bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
210#else
211bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
212bool str_endswith(const std::string &str, const std::string &end) {
213 return str.rfind(end) == (str.size() - end.size());
214}
215#endif
216
217bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len) {
218 if (suffix_len > str_len)
219 return false;
220 return strncasecmp(str + str_len - suffix_len, suffix, suffix_len) == 0;
221}
222
223// str_truncate, str_until, str_lower_case, str_upper_case, str_snake_case moved to alloc_helpers.cpp
224char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str) {
225 if (buffer_size == 0) {
226 return buffer;
227 }
228 size_t i = 0;
229 while (*str && i < buffer_size - 1) {
230 buffer[i++] = to_sanitized_char(*str++);
231 }
232 buffer[i] = '\0';
233 return buffer;
234}
235
236// str_sanitize, str_snprintf, str_sprintf moved to alloc_helpers.cpp
237
238// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
239static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
240
241size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
242 const char *suffix_ptr, size_t suffix_len) {
243 size_t total_len = name_len + 1 + suffix_len;
244
245 // Silently truncate if needed: prioritize keeping the full suffix
246 if (total_len >= buffer_size) {
247 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
248 // but this is safe because this helper is only called with small suffixes:
249 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
250 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
251 total_len = name_len + 1 + suffix_len;
252 }
253
254 memcpy(buffer, name, name_len);
255 buffer[name_len] = sep;
256 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
257 buffer[total_len] = '\0';
258 return total_len;
259}
260
261std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
262 size_t suffix_len) {
263 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
264 size_t len = make_name_with_suffix_to(buffer, sizeof(buffer), name, name_len, sep, suffix_ptr, suffix_len);
265 return std::string(buffer, len);
266}
267
268std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
269 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
270}
271
272// Parsing & formatting
273
274size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
275 size_t chars = std::min(length, 2 * count);
276 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
277 uint8_t val = parse_hex_char(*str);
278 if (val == INVALID_HEX_CHAR)
279 return 0;
280 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
281 }
282 return chars;
283}
284
285// format_mac_address_pretty moved to alloc_helpers.cpp
286
287// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase.
288// When separator is set, it is written unconditionally after each byte and the last
289// one is overwritten with '\0', eliminating the per-byte `i < length - 1` check.
290static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
291 char base) {
292 if (length == 0 || buffer_size == 0) {
293 if (buffer_size > 0)
294 buffer[0] = '\0';
295 return buffer;
296 }
297 uint8_t stride = separator ? 3 : 2;
298 size_t max_bytes = separator ? (buffer_size / 3) : ((buffer_size - 1) / 2);
299 if (max_bytes == 0) {
300 buffer[0] = '\0';
301 return buffer;
302 }
303 if (length > max_bytes) {
304 length = max_bytes;
305 }
306 for (size_t i = 0; i < length; i++) {
307 size_t pos = i * stride;
308 buffer[pos] = format_hex_char(data[i] >> 4, base);
309 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
310 if (separator) {
311 buffer[pos + 2] = separator;
312 }
313 }
314 // With separator: overwrite last separator with '\0'
315 // Without: write '\0' after last hex char
316 buffer[length * stride - (separator ? 1 : 0)] = '\0';
317 return buffer;
318}
319
321 if (val == 0) {
322 *buf++ = '0';
323 return buf;
324 }
325 char *start = buf;
326 while (val > 0) {
327 *buf++ = '0' + (val % 10);
328 val /= 10;
329 }
330 std::reverse(start, buf);
331 return buf;
332}
333
334char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
335 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
336}
337
338// format_hex (std::string returning overloads) moved to alloc_helpers.cpp
339
340char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
341 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
342}
343
344char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
345 if (length == 0 || buffer_size == 0) {
346 if (buffer_size > 0)
347 buffer[0] = '\0';
348 return buffer;
349 }
350 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
351 // Without separator: each uint16_t needs 4 chars, plus null terminator
352 uint8_t stride = separator ? 5 : 4;
353 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
354 if (max_values == 0) {
355 buffer[0] = '\0';
356 return buffer;
357 }
358 if (length > max_values) {
359 length = max_values;
360 }
361 for (size_t i = 0; i < length; i++) {
362 size_t pos = i * stride;
363 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
364 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
365 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
366 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
367 if (separator && i < length - 1) {
368 buffer[pos + 4] = separator;
369 }
370 }
371 buffer[length * stride - (separator ? 1 : 0)] = '\0';
372 return buffer;
373}
374
375// format_hex_pretty (all std::string returning overloads) moved to alloc_helpers.cpp
376
377char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
378 if (buffer_size == 0) {
379 return buffer;
380 }
381 // Calculate max bytes we can format: each byte needs 8 chars
382 size_t max_bytes = (buffer_size - 1) / 8;
383 if (max_bytes == 0 || length == 0) {
384 buffer[0] = '\0';
385 return buffer;
386 }
387 size_t bytes_to_format = std::min(length, max_bytes);
388
389 for (size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
390 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
391 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
392 }
393 }
394 buffer[bytes_to_format * 8] = '\0';
395 return buffer;
396}
397
398// format_bin moved to alloc_helpers.cpp
399
400ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
401 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
402 return PARSE_ON;
403 if (on != nullptr && strcasecmp(str, on) == 0)
404 return PARSE_ON;
405 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
406 return PARSE_OFF;
407 if (off != nullptr && strcasecmp(str, off) == 0)
408 return PARSE_OFF;
409 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
410 return PARSE_TOGGLE;
411
412 return PARSE_NONE;
413}
414
415int8_t ilog10(float value) {
416 float abs_val = fabsf(value);
417 int8_t exp = 0;
418 if (abs_val >= 10.0f) {
419 while (abs_val >= 10.0f) {
420 abs_val /= 10.0f;
421 exp++;
422 }
423 } else if (abs_val < 1.0f) {
424 while (abs_val < 1.0f) {
425 abs_val *= 10.0f;
426 exp--;
427 }
428 }
429 return exp;
430}
431
432static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
433 if (accuracy_decimals < 0) {
434 float divisor;
435 if (accuracy_decimals == -1) {
436 divisor = 10.0f;
437 } else if (accuracy_decimals == -2) {
438 divisor = 100.0f;
439 } else {
440 divisor = pow10_int(-accuracy_decimals);
441 }
442 value = roundf(value / divisor) * divisor;
443 accuracy_decimals = 0;
444 }
445}
446
447// value_accuracy_to_string moved to alloc_helpers.cpp
448
449// Fast float-to-string for accuracy_decimals 0-3 (covers virtually all sensor usage).
450// Avoids snprintf("%.*f") which pulls in heavy float formatting machinery.
451// Caller must guarantee value is finite and |value| * mult fits in uint32_t.
452static size_t value_accuracy_to_buf_fast(char *buf, float value, int8_t accuracy_decimals, uint32_t mult) {
453 char *p = buf;
454 if (std::signbit(value)) {
455 *p++ = '-';
456 value = -value;
457 }
458 // Cast to double for the multiply to match snprintf's rounding precision.
459 // float*int loses bits at exact-half boundaries (e.g. 23.45f*10 = 234.5 in float,
460 // but snprintf sees 234.500007... via double promotion and rounds differently).
461 // llrint returns long long so the result fits even on 32-bit targets where
462 // long is 32-bit; caller has already bounded |value * mult| to UINT32_MAX.
463 uint32_t scaled = static_cast<uint32_t>(llrint(static_cast<double>(value) * mult));
464 p = uint32_to_str_unchecked(p, scaled / mult);
465 if (accuracy_decimals > 0) {
466 *p++ = '.';
467 p = frac_to_str_unchecked(p, scaled % mult, mult / 10);
468 }
469 *p = '\0';
470 return static_cast<size_t>(p - buf);
471}
472
473size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
474 normalize_accuracy_decimals(value, accuracy_decimals);
475
476 // Fast path for accuracy 0-3, finite values whose scaled magnitude fits in uint32_t.
477 // For 3 decimals that's |value| < ~4.29e6; larger totals fall through to snprintf.
478 if (accuracy_decimals <= 3 && std::isfinite(value)) {
479 const uint32_t mult = small_pow10(accuracy_decimals);
480 if (std::fabs(value) < static_cast<float>(UINT32_MAX) / mult) {
481 return value_accuracy_to_buf_fast(buf.data(), value, accuracy_decimals, mult);
482 }
483 }
484
485 // Fallback for NaN/Inf/high accuracy/out-of-range
486 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
487 if (len < 0)
488 return 0;
489 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
490}
491
492size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
493 int8_t accuracy_decimals, StringRef unit_of_measurement) {
494 size_t len = value_accuracy_to_buf(buf, value, accuracy_decimals);
495 if (len == 0 || unit_of_measurement.empty()) {
496 return len;
497 }
498 char *end = buf_append_sep_str(buf.data() + len, buf.size() - len, ' ', unit_of_measurement.c_str(),
499 unit_of_measurement.size());
500 return static_cast<size_t>(end - buf.data());
501}
502
503int8_t step_to_accuracy_decimals(float step) {
504 // use printf %g to find number of digits based on temperature step
505 char buf[32];
506 snprintf(buf, sizeof buf, "%.5g", step);
507
508 std::string str{buf};
509 size_t dot_pos = str.find('.');
510 if (dot_pos == std::string::npos)
511 return 0;
512
513 return str.length() - dot_pos - 1;
514}
515
516// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
517static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
518 "abcdefghijklmnopqrstuvwxyz"
519 "0123456789+/";
520
521// Helper function to find the index of a base64/base64url character in the lookup table.
522// Returns the character's position (0-63) if found, or 0 if not found.
523// Supports both standard base64 (+/) and base64url (-_) alphabets.
524// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
525// This is safe because is_base64() is ALWAYS checked before calling this function,
526// preventing invalid characters from ever reaching here. The base64_decode function
527// stops processing at the first invalid character due to the is_base64() check in its
528// while loop condition, making this edge case harmless in practice.
529static inline uint8_t base64_find_char(char c) {
530 // Handle base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
531 if (c == '-')
532 return 62;
533 if (c == '_')
534 return 63;
535 const char *pos = strchr(BASE64_CHARS, c);
536 return pos ? (pos - BASE64_CHARS) : 0;
537}
538
539// Check if character is valid base64 or base64url
540static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
541
542// base64_encode (both overloads) moved to alloc_helpers.cpp
543
544size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
545 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
546}
547
548// Decode 4 base64 characters to up to 'count' output bytes, returns true if truncated.
549static inline bool base64_decode_quad(uint8_t *char_array_4, int count, uint8_t *buf, size_t buf_len, size_t &out) {
550 for (int i = 0; i < 4; i++)
551 char_array_4[i] = base64_find_char(char_array_4[i]);
552
553 uint8_t char_array_3[3];
554 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
555 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
556 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
557
558 bool truncated = false;
559 for (int j = 0; j < count; j++) {
560 if (out < buf_len) {
561 buf[out++] = char_array_3[j];
562 } else {
563 truncated = true;
564 }
565 }
566 return truncated;
567}
568
569size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
570 size_t in_len = encoded_len;
571 int i = 0;
572 size_t in = 0;
573 size_t out = 0;
574 uint8_t char_array_4[4];
575 bool truncated = false;
576
577 // SAFETY: The loop condition checks is_base64() before processing each character.
578 // This ensures base64_find_char() is only called on valid base64 characters,
579 // preventing the edge case where invalid chars would return 0 (same as 'A').
580 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
581 char_array_4[i++] = encoded_data[in];
582 in++;
583 if (i == 4) {
584 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
585 i = 0;
586 }
587 }
588
589 if (i) {
590 for (int j = i; j < 4; j++)
591 char_array_4[j] = 0;
592
593 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
594 }
595
596 if (truncated) {
597 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
598 }
599
600 return out;
601}
602
603// base64_decode (vector-returning overload) moved to alloc_helpers.cpp
604
609bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
610 // Decode in chunks to minimize stack usage
611 constexpr size_t chunk_bytes = 48; // 12 int32 values
612 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
613 uint8_t chunk[chunk_bytes];
614
615 out.clear();
616
617 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
618 size_t remaining = base64.size();
619 size_t pos = 0;
620
621 while (remaining > 0) {
622 size_t chars_to_decode = std::min(remaining, chunk_chars);
623 size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
624
625 if (decoded_len == 0)
626 return false;
627
628 // Parse little-endian int32 values
629 for (size_t i = 0; i + 3 < decoded_len; i += 4) {
630 int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
631 out.push_back(timing);
632 }
633
634 // Check for incomplete int32 in last chunk
635 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
636 return false;
637
638 pos += chars_to_decode;
639 remaining -= chars_to_decode;
640 }
641
642 return !out.empty();
643}
644
645// Colors
646
647float gamma_correct(float value, float gamma) {
648 if (value <= 0.0f)
649 return 0.0f;
650 if (gamma <= 0.0f)
651 return value;
652
653 return powf(value, gamma); // NOLINT - deprecated, removal 2026.9.0
654}
655float gamma_uncorrect(float value, float gamma) {
656 if (value <= 0.0f)
657 return 0.0f;
658 if (gamma <= 0.0f)
659 return value;
660
661 return powf(value, 1 / gamma); // NOLINT - deprecated, removal 2026.9.0
662}
663
664void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
665 float max_color_value = std::max({red, green, blue});
666 float min_color_value = std::min({red, green, blue});
667 float delta = max_color_value - min_color_value;
668
669 if (delta == 0) {
670 hue = 0;
671 } else if (max_color_value == red) {
672 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
673 } else if (max_color_value == green) {
674 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
675 } else if (max_color_value == blue) {
676 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
677 }
678
679 if (max_color_value == 0) {
680 saturation = 0;
681 } else {
682 saturation = delta / max_color_value;
683 }
684
685 value = max_color_value;
686}
687void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
688 float chroma = value * saturation;
689 float hue_prime = fmod(hue / 60.0, 6);
690 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
691 float delta = value - chroma;
692
693 if (0 <= hue_prime && hue_prime < 1) {
694 red = chroma;
695 green = intermediate;
696 blue = 0;
697 } else if (1 <= hue_prime && hue_prime < 2) {
698 red = intermediate;
699 green = chroma;
700 blue = 0;
701 } else if (2 <= hue_prime && hue_prime < 3) {
702 red = 0;
703 green = chroma;
704 blue = intermediate;
705 } else if (3 <= hue_prime && hue_prime < 4) {
706 red = 0;
707 green = intermediate;
708 blue = chroma;
709 } else if (4 <= hue_prime && hue_prime < 5) {
710 red = intermediate;
711 green = 0;
712 blue = chroma;
713 } else if (5 <= hue_prime && hue_prime < 6) {
714 red = chroma;
715 green = 0;
716 blue = intermediate;
717 } else {
718 red = 0;
719 green = 0;
720 blue = 0;
721 }
722
723 red += delta;
724 green += delta;
725 blue += delta;
726}
727
728uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
730 if (this->started_)
731 return;
732 num_requests++;
733 this->started_ = true;
734}
736 if (!this->started_)
737 return;
738 num_requests--;
739 this->started_ = false;
740}
741
742// get_mac_address, get_mac_address_pretty moved to alloc_helpers.cpp
743
744void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
745 uint8_t mac[6];
747 format_mac_addr_lower_no_sep(mac, buf.data());
748}
749
750const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
751 uint8_t mac[6];
753 format_mac_addr_upper(mac, buf.data());
754 return buf.data();
755}
756
757#ifndef USE_ESP32
758bool has_custom_mac_address() { return false; }
759#endif
760
761bool mac_address_is_valid(const uint8_t *mac) {
762 bool is_all_zeros = true;
763 bool is_all_ones = true;
764
765 for (uint8_t i = 0; i < 6; i++) {
766 if (mac[i] != 0) {
767 is_all_zeros = false;
768 }
769 if (mac[i] != 0xFF) {
770 is_all_ones = false;
771 }
772 }
773 if (is_all_zeros || is_all_ones) {
774 return false;
775 }
776 // Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
777 // This catches garbage data from corrupted eFuse custom MAC areas, which often
778 // has random values that would otherwise pass the all-zeros/all-ones check.
779 if (mac[0] & 0x01) {
780 return false;
781 }
782 return true;
783}
784
785void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
786 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
787 uint32_t start = micros();
788
789 constexpr uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
790 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
791 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
792 if (us > lag) {
793 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
794 while (micros() - start < us - lag)
795 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
796 }
797 while (micros() - start < us) // fine delay the remaining usecs
798 ;
799}
800
801} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:735
void start()
Start running the loop continuously.
Definition helpers.cpp:729
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
constexpr const char * c_str() const
Definition string_ref.h:73
constexpr bool empty() const
Definition string_ref.h:76
constexpr size_type size() const
Definition string_ref.h:74
struct @65::@66 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
mopeka_std_values val[3]
bool z
Definition msa3xx.h:1
const char *const TAG
Definition spi.cpp:7
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
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:1249
float gamma_uncorrect(float value, float gamma)
Definition helpers.cpp:655
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:86
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Zero-allocation version: format name + separator + suffix directly into buffer.
Definition helpers.cpp:241
float gamma_correct(float value, float gamma)
Definition helpers.cpp:647
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:969
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:761
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1255
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1458
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:784
void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value)
Convert red, green and blue (all 0-1) values to hue (0-360), saturation (0-1) and value (0-1).
Definition helpers.cpp:664
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:26
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:473
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:400
bool base64_decode_int32_vector(const std::string &base64, std::vector< int32_t > &out)
Decode base64/base64url string directly into vector of little-endian int32 values.
Definition helpers.cpp:609
const void size_t len
Definition hal.h:64
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:1302
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)
Definition helpers.cpp:110
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:274
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:340
uint16_t size
Definition helpers.cpp:25
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:415
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:160
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:1322
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:503
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
size_t size_t pos
Definition helpers.h:1038
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:750
char * buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len)
Append a separator char and a string to a buffer, respecting remaining space.
Definition helpers.h:1285
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:785
uint16_t new_cap
Definition helpers.cpp:28
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:201
bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len)
Case-insensitive check if string ends with suffix (no heap allocation).
Definition helpers.cpp:217
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
Definition helpers.cpp:224
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:492
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:320
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:786
void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue)
Convert hue (0-360), saturation (0-1) and value (0-1) to red, green and blue (all 0-1).
Definition helpers.cpp:687
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:744
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:126
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:867
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
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:74
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1238
auto * new_data
Definition helpers.cpp:29
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:208
void HOT delay(uint32_t ms)
Definition hal.cpp:85
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:334
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
float gamma
Definition helpers.h:1593
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1551
@ PARSE_ON
Definition helpers.h:1553
@ PARSE_TOGGLE
Definition helpers.h:1555
@ PARSE_OFF
Definition helpers.h:1554
@ PARSE_NONE
Definition helpers.h:1552
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:752
std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Optimized string concatenation: name + separator + suffix (const char* overload) Uses a fixed stack b...
Definition helpers.cpp:261
char * format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as binary string to buffer.
Definition helpers.cpp:377
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1453
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0