ESPHome 2026.5.1
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 "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#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};
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 = 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#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);
131 }
132#endif
133 if (refin) {
134 crc ^= 0xffff;
135 }
136#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
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 while (len--) {
145 crc ^= (((uint16_t) *data++) << 8);
146 for (uint8_t i = 0; i < 8; i++) {
147 if (crc & 0x8000) {
148 crc = (crc << 1) ^ poly;
149 } else {
150 crc <<= 1;
151 }
152 }
153 }
154#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
155 }
156#endif
157 return refout ? (crc ^ 0xffff) : crc;
158}
159
160// FNV-1 hash - deprecated, use fnv1a_hash() for new code
161uint32_t fnv1_hash(const char *str) {
163 if (str) {
164 while (*str) {
165 hash *= FNV1_PRIME;
166 hash ^= *str++;
167 }
168 }
169 return hash;
170}
171
172// SplitMix32 — a fast, non-cryptographic PRNG from the SplitMix family
173// (Steele et al., 2014). Uses a Weyl sequence with golden-ratio increment
174// and the MurmurHash3 32-bit finalizer as output mixing function.
175// Reference: https://doi.org/10.1145/2714064.2660195
176// Test results: https://lemire.me/blog/2017/08/22/testing-non-cryptographic-random-number-generators-my-results/
177// Seeded lazily from the platform's secure RNG via random_bytes().
178// ESP8266 uses os_random() instead (defined in esp8266/helpers.cpp).
179#ifndef USE_ESP8266
180static uint32_t splitmix32_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
181
183 // State of 0 means unseeded. The state will wrap back to 0 after 2^32 calls,
184 // triggering one extra random_bytes() call — an acceptable trade-off vs. adding
185 // a separate bool flag (4 bytes BSS + branch on every call).
186 if (splitmix32_state == 0) {
187 random_bytes(reinterpret_cast<uint8_t *>(&splitmix32_state), sizeof(splitmix32_state));
188 splitmix32_state |= 1; // ensure non-zero seed
189 }
190 splitmix32_state += 0x9e3779b9u;
191 uint32_t z = splitmix32_state;
192 z = (z ^ (z >> 16)) * 0x85ebca6bu;
193 z = (z ^ (z >> 13)) * 0xc2b2ae35u;
194 return z ^ (z >> 16);
195}
196#endif
197
198float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
199
200// Strings
201
202bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
203 return strcasecmp(a.c_str(), b.c_str()) == 0;
204}
206 return a.size() == b.size() && strncasecmp(a.c_str(), b.c_str(), a.size()) == 0;
207}
208#if __cplusplus >= 202002L
209bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
210bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
211#else
212bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
213bool str_endswith(const std::string &str, const std::string &end) {
214 return str.rfind(end) == (str.size() - end.size());
215}
216#endif
217
218bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len) {
219 if (suffix_len > str_len)
220 return false;
221 return strncasecmp(str + str_len - suffix_len, suffix, suffix_len) == 0;
222}
223
224// str_truncate, str_until, str_lower_case, str_upper_case, str_snake_case moved to alloc_helpers.cpp
225char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str) {
226 if (buffer_size == 0) {
227 return buffer;
228 }
229 size_t i = 0;
230 while (*str && i < buffer_size - 1) {
231 buffer[i++] = to_sanitized_char(*str++);
232 }
233 buffer[i] = '\0';
234 return buffer;
235}
236
237// str_sanitize, str_snprintf, str_sprintf moved to alloc_helpers.cpp
238
239// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
240static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
241
242size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
243 const char *suffix_ptr, size_t suffix_len) {
244 size_t total_len = name_len + 1 + suffix_len;
245
246 // Silently truncate if needed: prioritize keeping the full suffix
247 if (total_len >= buffer_size) {
248 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
249 // but this is safe because this helper is only called with small suffixes:
250 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
251 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
252 total_len = name_len + 1 + suffix_len;
253 }
254
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';
259 return total_len;
260}
261
262std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
263 size_t suffix_len) {
264 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
265 size_t len = make_name_with_suffix_to(buffer, sizeof(buffer), name, name_len, sep, suffix_ptr, suffix_len);
266 return std::string(buffer, len);
267}
268
269std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
270 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
271}
272
273// Parsing & formatting
274
275size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
276 size_t chars = std::min(length, 2 * count);
277 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
278 uint8_t val = parse_hex_char(*str);
279 if (val == INVALID_HEX_CHAR)
280 return 0;
281 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
282 }
283 return chars;
284}
285
286// format_mac_address_pretty moved to alloc_helpers.cpp
287
288// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase.
289// When separator is set, it is written unconditionally after each byte and the last
290// one is overwritten with '\0', eliminating the per-byte `i < length - 1` check.
291static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
292 char base) {
293 if (length == 0 || buffer_size == 0) {
294 if (buffer_size > 0)
295 buffer[0] = '\0';
296 return buffer;
297 }
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) {
301 buffer[0] = '\0';
302 return buffer;
303 }
304 if (length > max_bytes) {
305 length = max_bytes;
306 }
307 for (size_t i = 0; i < length; i++) {
308 size_t pos = i * stride;
309 buffer[pos] = format_hex_char(data[i] >> 4, base);
310 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
311 if (separator) {
312 buffer[pos + 2] = separator;
313 }
314 }
315 // With separator: overwrite last separator with '\0'
316 // Without: write '\0' after last hex char
317 buffer[length * stride - (separator ? 1 : 0)] = '\0';
318 return buffer;
319}
320
322 if (val == 0) {
323 *buf++ = '0';
324 return buf;
325 }
326 char *start = buf;
327 while (val > 0) {
328 *buf++ = '0' + (val % 10);
329 val /= 10;
330 }
331 std::reverse(start, buf);
332 return buf;
333}
334
335char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
336 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
337}
338
339// format_hex (std::string returning overloads) moved to alloc_helpers.cpp
340
341char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
342 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
343}
344
345char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
346 if (length == 0 || buffer_size == 0) {
347 if (buffer_size > 0)
348 buffer[0] = '\0';
349 return buffer;
350 }
351 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
352 // Without separator: each uint16_t needs 4 chars, plus null terminator
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) {
356 buffer[0] = '\0';
357 return buffer;
358 }
359 if (length > max_values) {
360 length = max_values;
361 }
362 for (size_t i = 0; i < length; i++) {
363 size_t pos = i * stride;
364 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
365 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
366 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
367 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
368 if (separator && i < length - 1) {
369 buffer[pos + 4] = separator;
370 }
371 }
372 buffer[length * stride - (separator ? 1 : 0)] = '\0';
373 return buffer;
374}
375
376// format_hex_pretty (all std::string returning overloads) moved to alloc_helpers.cpp
377
378char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
379 if (buffer_size == 0) {
380 return buffer;
381 }
382 // Calculate max bytes we can format: each byte needs 8 chars
383 size_t max_bytes = (buffer_size - 1) / 8;
384 if (max_bytes == 0 || length == 0) {
385 buffer[0] = '\0';
386 return buffer;
387 }
388 size_t bytes_to_format = std::min(length, max_bytes);
389
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';
393 }
394 }
395 buffer[bytes_to_format * 8] = '\0';
396 return buffer;
397}
398
399// format_bin moved to alloc_helpers.cpp
400
401ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
402 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
403 return PARSE_ON;
404 if (on != nullptr && strcasecmp(str, on) == 0)
405 return PARSE_ON;
406 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
407 return PARSE_OFF;
408 if (off != nullptr && strcasecmp(str, off) == 0)
409 return PARSE_OFF;
410 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
411 return PARSE_TOGGLE;
412
413 return PARSE_NONE;
414}
415
416int8_t ilog10(float value) {
417 float abs_val = fabsf(value);
418 int8_t exp = 0;
419 if (abs_val >= 10.0f) {
420 while (abs_val >= 10.0f) {
421 abs_val /= 10.0f;
422 exp++;
423 }
424 } else if (abs_val < 1.0f) {
425 while (abs_val < 1.0f) {
426 abs_val *= 10.0f;
427 exp--;
428 }
429 }
430 return exp;
431}
432
433static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
434 if (accuracy_decimals < 0) {
435 float divisor;
436 if (accuracy_decimals == -1) {
437 divisor = 10.0f;
438 } else if (accuracy_decimals == -2) {
439 divisor = 100.0f;
440 } else {
441 divisor = pow10_int(-accuracy_decimals);
442 }
443 value = roundf(value / divisor) * divisor;
444 accuracy_decimals = 0;
445 }
446}
447
448// value_accuracy_to_string moved to alloc_helpers.cpp
449
450// Fast float-to-string for accuracy_decimals 0-3 (covers virtually all sensor usage).
451// Avoids snprintf("%.*f") which pulls in heavy float formatting machinery.
452// Caller must guarantee value is finite and |value| * mult fits in uint32_t.
453static size_t value_accuracy_to_buf_fast(char *buf, float value, int8_t accuracy_decimals, uint32_t mult) {
454 char *p = buf;
455 if (std::signbit(value)) {
456 *p++ = '-';
457 value = -value;
458 }
459 // Cast to double for the multiply to match snprintf's rounding precision.
460 // float*int loses bits at exact-half boundaries (e.g. 23.45f*10 = 234.5 in float,
461 // but snprintf sees 234.500007... via double promotion and rounds differently).
462 // llrint returns long long so the result fits even on 32-bit targets where
463 // long is 32-bit; caller has already bounded |value * mult| to UINT32_MAX.
464 uint32_t scaled = static_cast<uint32_t>(llrint(static_cast<double>(value) * mult));
465 p = uint32_to_str_unchecked(p, scaled / mult);
466 if (accuracy_decimals > 0) {
467 *p++ = '.';
468 p = frac_to_str_unchecked(p, scaled % mult, mult / 10);
469 }
470 *p = '\0';
471 return static_cast<size_t>(p - buf);
472}
473
474size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
475 normalize_accuracy_decimals(value, accuracy_decimals);
476
477 // Fast path for accuracy 0-3, finite values whose scaled magnitude fits in uint32_t.
478 // For 3 decimals that's |value| < ~4.29e6; larger totals fall through to snprintf.
479 if (accuracy_decimals <= 3 && std::isfinite(value)) {
480 const uint32_t mult = small_pow10(accuracy_decimals);
481 if (std::fabs(value) < static_cast<float>(UINT32_MAX) / mult) {
482 return value_accuracy_to_buf_fast(buf.data(), value, accuracy_decimals, mult);
483 }
484 }
485
486 // Fallback for NaN/Inf/high accuracy/out-of-range
487 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
488 if (len < 0)
489 return 0;
490 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
491}
492
493size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
494 int8_t accuracy_decimals, StringRef unit_of_measurement) {
495 size_t len = value_accuracy_to_buf(buf, value, accuracy_decimals);
496 if (len == 0 || unit_of_measurement.empty()) {
497 return len;
498 }
499 char *end = buf_append_sep_str(buf.data() + len, buf.size() - len, ' ', unit_of_measurement.c_str(),
500 unit_of_measurement.size());
501 return static_cast<size_t>(end - buf.data());
502}
503
504int8_t step_to_accuracy_decimals(float step) {
505 // use printf %g to find number of digits based on temperature step
506 char buf[32];
507 snprintf(buf, sizeof buf, "%.5g", step);
508
509 std::string str{buf};
510 size_t dot_pos = str.find('.');
511 if (dot_pos == std::string::npos)
512 return 0;
513
514 return str.length() - dot_pos - 1;
515}
516
517// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
518static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
519 "abcdefghijklmnopqrstuvwxyz"
520 "0123456789+/";
521
522// Helper function to find the index of a base64/base64url character in the lookup table.
523// Returns the character's position (0-63) if found, or 0 if not found.
524// Supports both standard base64 (+/) and base64url (-_) alphabets.
525// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
526// This is safe because is_base64() is ALWAYS checked before calling this function,
527// preventing invalid characters from ever reaching here. The base64_decode function
528// stops processing at the first invalid character due to the is_base64() check in its
529// while loop condition, making this edge case harmless in practice.
530static inline uint8_t base64_find_char(char c) {
531 // Handle base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
532 if (c == '-')
533 return 62;
534 if (c == '_')
535 return 63;
536 const char *pos = strchr(BASE64_CHARS, c);
537 return pos ? (pos - BASE64_CHARS) : 0;
538}
539
540// Check if character is valid base64 or base64url
541static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
542
543// base64_encode (both overloads) moved to alloc_helpers.cpp
544
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);
547}
548
549// Decode 4 base64 characters to up to 'count' output bytes, returns true if truncated.
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]);
553
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];
558
559 bool truncated = false;
560 for (int j = 0; j < count; j++) {
561 if (out < buf_len) {
562 buf[out++] = char_array_3[j];
563 } else {
564 truncated = true;
565 }
566 }
567 return truncated;
568}
569
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;
572 int i = 0;
573 size_t in = 0;
574 size_t out = 0;
575 uint8_t char_array_4[4];
576 bool truncated = false;
577
578 // SAFETY: The loop condition checks is_base64() before processing each character.
579 // This ensures base64_find_char() is only called on valid base64 characters,
580 // preventing the edge case where invalid chars would return 0 (same as 'A').
581 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
582 char_array_4[i++] = encoded_data[in];
583 in++;
584 if (i == 4) {
585 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
586 i = 0;
587 }
588 }
589
590 if (i) {
591 for (int j = i; j < 4; j++)
592 char_array_4[j] = 0;
593
594 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
595 }
596
597 if (truncated) {
598 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
599 }
600
601 return out;
602}
603
604// base64_decode (vector-returning overload) moved to alloc_helpers.cpp
605
610bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
611 // Decode in chunks to minimize stack usage
612 constexpr size_t chunk_bytes = 48; // 12 int32 values
613 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
614 uint8_t chunk[chunk_bytes];
615
616 out.clear();
617
618 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
619 size_t remaining = base64.size();
620 size_t pos = 0;
621
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);
625
626 if (decoded_len == 0)
627 return false;
628
629 // Parse little-endian int32 values
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);
633 }
634
635 // Check for incomplete int32 in last chunk
636 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
637 return false;
638
639 pos += chars_to_decode;
640 remaining -= chars_to_decode;
641 }
642
643 return !out.empty();
644}
645
646// Colors
647
648float gamma_correct(float value, float gamma) {
649 if (value <= 0.0f)
650 return 0.0f;
651 if (gamma <= 0.0f)
652 return value;
653
654 return powf(value, gamma); // NOLINT - deprecated, removal 2026.9.0
655}
656float gamma_uncorrect(float value, float gamma) {
657 if (value <= 0.0f)
658 return 0.0f;
659 if (gamma <= 0.0f)
660 return value;
661
662 return powf(value, 1 / gamma); // NOLINT - deprecated, removal 2026.9.0
663}
664
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;
669
670 if (delta == 0) {
671 hue = 0;
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));
678 }
679
680 if (max_color_value == 0) {
681 saturation = 0;
682 } else {
683 saturation = delta / max_color_value;
684 }
685
686 value = max_color_value;
687}
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;
693
694 if (0 <= hue_prime && hue_prime < 1) {
695 red = chroma;
696 green = intermediate;
697 blue = 0;
698 } else if (1 <= hue_prime && hue_prime < 2) {
699 red = intermediate;
700 green = chroma;
701 blue = 0;
702 } else if (2 <= hue_prime && hue_prime < 3) {
703 red = 0;
704 green = chroma;
705 blue = intermediate;
706 } else if (3 <= hue_prime && hue_prime < 4) {
707 red = 0;
708 green = intermediate;
709 blue = chroma;
710 } else if (4 <= hue_prime && hue_prime < 5) {
711 red = intermediate;
712 green = 0;
713 blue = chroma;
714 } else if (5 <= hue_prime && hue_prime < 6) {
715 red = chroma;
716 green = 0;
717 blue = intermediate;
718 } else {
719 red = 0;
720 green = 0;
721 blue = 0;
722 }
723
724 red += delta;
725 green += delta;
726 blue += delta;
727}
728
729uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
731 if (this->started_)
732 return;
733 num_requests++;
734 this->started_ = true;
735}
737 if (!this->started_)
738 return;
739 num_requests--;
740 this->started_ = false;
741}
742
743// get_mac_address, get_mac_address_pretty moved to alloc_helpers.cpp
744
745void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
746 uint8_t mac[6];
748 format_mac_addr_lower_no_sep(mac, buf.data());
749}
750
751const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
752 uint8_t mac[6];
754 format_mac_addr_upper(mac, buf.data());
755 return buf.data();
756}
757
758#ifndef USE_ESP32
759bool has_custom_mac_address() { return false; }
760#endif
761
762bool mac_address_is_valid(const uint8_t *mac) {
763 bool is_all_zeros = true;
764 bool is_all_ones = true;
765
766 for (uint8_t i = 0; i < 6; i++) {
767 if (mac[i] != 0) {
768 is_all_zeros = false;
769 }
770 if (mac[i] != 0xFF) {
771 is_all_ones = false;
772 }
773 }
774 if (is_all_zeros || is_all_ones) {
775 return false;
776 }
777 // Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
778 // This catches garbage data from corrupted eFuse custom MAC areas, which often
779 // has random values that would otherwise pass the all-zeros/all-ones check.
780 if (mac[0] & 0x01) {
781 return false;
782 }
783 return true;
784}
785
786void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
787 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
788 uint32_t start = micros();
789
790 constexpr uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
791 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
792 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
793 if (us > lag) {
794 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
795 while (micros() - start < us - lag)
796 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
797 }
798 while (micros() - start < us) // fine delay the remaining usecs
799 ;
800}
801
802} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:736
void start()
Start running the loop continuously.
Definition helpers.cpp:730
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:198
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:656
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:242
float gamma_correct(float value, float gamma)
Definition helpers.cpp:648
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:762
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:665
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:474
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:401
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:610
std::string size_t len
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:275
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:341
uint16_t size
Definition helpers.cpp:25
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:416
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:161
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:504
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:751
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:786
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:202
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:218
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:225
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:493
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:321
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:688
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:745
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:209
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:335
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:210
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:262
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:378
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