ESPHome 2026.10.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
223bool str_contains_ignore_case_fallback(const char *haystack, const char *needle) {
224 const size_t needle_len = strlen(needle);
225 if (needle_len == 0) {
226 return true;
227 }
228 for (const char *p = haystack; *p != '\0'; p++) {
229 if (strncasecmp(p, needle, needle_len) == 0) {
230 return true;
231 }
232 }
233 return false;
234}
235
236#ifdef USE_ESP8266
237// _P mirror of str_contains_ignore_case_fallback above; host tests cover only the fallback,
238// so keep the two bodies in sync.
239bool str_contains_ignore_case_p(const char *haystack, PGM_P needle) {
240 if (haystack == nullptr || needle == nullptr) {
241 return false;
242 }
243 const size_t needle_len = strlen_P(needle);
244 if (needle_len == 0) {
245 return true;
246 }
247 for (const char *p = haystack; *p != '\0'; p++) {
248 if (strncasecmp_P(p, needle, needle_len) == 0) {
249 return true;
250 }
251 }
252 return false;
253}
254#endif // USE_ESP8266
255
256// str_truncate, str_until, str_lower_case, str_upper_case, str_snake_case moved to alloc_helpers.cpp
257char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str) {
258 if (buffer_size == 0) {
259 return buffer;
260 }
261 size_t i = 0;
262 while (*str && i < buffer_size - 1) {
263 buffer[i++] = to_sanitized_char(*str++);
264 }
265 buffer[i] = '\0';
266 return buffer;
267}
268
269// str_sanitize, str_snprintf, str_sprintf moved to alloc_helpers.cpp
270
271size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
272 const char *suffix_ptr, size_t suffix_len) {
273 size_t total_len = name_len + 1 + suffix_len;
274
275 // Silently truncate if needed: prioritize keeping the full suffix
276 if (total_len >= buffer_size) {
277 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
278 // but this is safe because this helper is only called with small suffixes:
279 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
280 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
281 total_len = name_len + 1 + suffix_len;
282 }
283
284 memcpy(buffer, name, name_len);
285 buffer[name_len] = sep;
286 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
287 buffer[total_len] = '\0';
288 return total_len;
289}
290
291// Parsing & formatting
292
293size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
294 size_t chars = std::min(length, 2 * count);
295 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
296 uint8_t val = parse_hex_char(*str);
297 if (val == INVALID_HEX_CHAR)
298 return 0;
299 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
300 }
301 return chars;
302}
303
304// format_mac_address_pretty moved to alloc_helpers.cpp
305
306// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase.
307// When separator is set, it is written unconditionally after each byte and the last
308// one is overwritten with '\0', eliminating the per-byte `i < length - 1` check.
309static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
310 char base) {
311 if (length == 0 || buffer_size == 0) {
312 if (buffer_size > 0)
313 buffer[0] = '\0';
314 return buffer;
315 }
316 uint8_t stride = separator ? 3 : 2;
317 size_t max_bytes = separator ? (buffer_size / 3) : ((buffer_size - 1) / 2);
318 if (max_bytes == 0) {
319 buffer[0] = '\0';
320 return buffer;
321 }
322 if (length > max_bytes) {
323 length = max_bytes;
324 }
325 for (size_t i = 0; i < length; i++) {
326 size_t pos = i * stride;
327 buffer[pos] = format_hex_char(data[i] >> 4, base);
328 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
329 if (separator) {
330 buffer[pos + 2] = separator;
331 }
332 }
333 // With separator: overwrite last separator with '\0'
334 // Without: write '\0' after last hex char
335 buffer[length * stride - (separator ? 1 : 0)] = '\0';
336 return buffer;
337}
338
340 if (val == 0) {
341 *buf++ = '0';
342 return buf;
343 }
344 char *start = buf;
345 while (val > 0) {
346 *buf++ = '0' + (val % 10);
347 val /= 10;
348 }
349 std::reverse(start, buf);
350 return buf;
351}
352
353char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
354 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
355}
356
357const char *json_escape_into_buffer(std::span<char> buf, StringRef value, bool short_control_escapes) {
358 if (buf.empty())
359 return "";
360 // Reserve one byte for the null terminator.
361 const size_t limit = buf.size() - 1;
362 size_t pos = 0;
363 for (char ch : value) {
364 auto c = static_cast<unsigned char>(ch);
365 // Every short form is a backslash followed by a single character, so only that character is needed here. Keeping
366 // it a char rather than a string avoids putting the sequences in read only data, which is RAM on the ESP8266.
367 char escape = '\0';
368 switch (c) {
369 case '"':
370 escape = '"';
371 break;
372 case '\\':
373 escape = '\\';
374 break;
375 case '\n':
376 escape = 'n';
377 break;
378 case '\r':
379 escape = 'r';
380 break;
381 case '\t':
382 escape = 't';
383 break;
384 case '\b':
385 escape = 'b';
386 break;
387 case '\f':
388 escape = 'f';
389 break;
390 default:
391 break;
392 }
393 // " and \ are always written as two characters, but the control characters fall through to \u00XX when the
394 // caller did not ask for the short forms.
395 if (!short_control_escapes && c < 0x20)
396 escape = '\0';
397 if (escape != '\0') {
398 if (pos + 2 > limit)
399 break;
400 buf[pos++] = '\\';
401 buf[pos++] = escape;
402 } else if (c < 0x20) {
403 // Remaining control characters have no short form and must be written as \u00XX. The value is below 0x20, so
404 // the two high hex digits are always zero.
405 if (pos + JSON_ESCAPE_MAX_EXPANSION > limit)
406 break;
407 buf[pos++] = '\\';
408 buf[pos++] = 'u';
409 buf[pos++] = '0';
410 buf[pos++] = '0';
411 buf[pos++] = format_hex_char(static_cast<uint8_t>(c >> 4));
412 buf[pos++] = format_hex_char(static_cast<uint8_t>(c & 0x0F));
413 } else {
414 if (pos + 1 > limit)
415 break;
416 buf[pos++] = static_cast<char>(c);
417 }
418 }
419 buf[pos] = '\0';
420 return buf.data();
421}
422
423// format_hex (std::string returning overloads) moved to alloc_helpers.cpp
424
425char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
426 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
427}
428
429char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
430 if (length == 0 || buffer_size == 0) {
431 if (buffer_size > 0)
432 buffer[0] = '\0';
433 return buffer;
434 }
435 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
436 // Without separator: each uint16_t needs 4 chars, plus null terminator
437 uint8_t stride = separator ? 5 : 4;
438 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
439 if (max_values == 0) {
440 buffer[0] = '\0';
441 return buffer;
442 }
443 if (length > max_values) {
444 length = max_values;
445 }
446 for (size_t i = 0; i < length; i++) {
447 size_t pos = i * stride;
448 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
449 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
450 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
451 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
452 if (separator && i < length - 1) {
453 buffer[pos + 4] = separator;
454 }
455 }
456 buffer[length * stride - (separator ? 1 : 0)] = '\0';
457 return buffer;
458}
459
460// format_hex_pretty (all std::string returning overloads) moved to alloc_helpers.cpp
461
462char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
463 if (buffer_size == 0) {
464 return buffer;
465 }
466 // Calculate max bytes we can format: each byte needs 8 chars
467 size_t max_bytes = (buffer_size - 1) / 8;
468 if (max_bytes == 0 || length == 0) {
469 buffer[0] = '\0';
470 return buffer;
471 }
472 size_t bytes_to_format = std::min(length, max_bytes);
473
474 for (size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
475 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
476 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
477 }
478 }
479 buffer[bytes_to_format * 8] = '\0';
480 return buffer;
481}
482
483// format_bin moved to alloc_helpers.cpp
484
485ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
486 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
487 return PARSE_ON;
488 if (on != nullptr && strcasecmp(str, on) == 0)
489 return PARSE_ON;
490 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
491 return PARSE_OFF;
492 if (off != nullptr && strcasecmp(str, off) == 0)
493 return PARSE_OFF;
494 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
495 return PARSE_TOGGLE;
496
497 return PARSE_NONE;
498}
499
500int8_t ilog10(float value) {
501 float abs_val = fabsf(value);
502 int8_t exp = 0;
503 if (abs_val >= 10.0f) {
504 while (abs_val >= 10.0f) {
505 abs_val /= 10.0f;
506 exp++;
507 }
508 } else if (abs_val < 1.0f) {
509 while (abs_val < 1.0f) {
510 abs_val *= 10.0f;
511 exp--;
512 }
513 }
514 return exp;
515}
516
517static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
518 if (accuracy_decimals < 0) {
519 float divisor;
520 if (accuracy_decimals == -1) {
521 divisor = 10.0f;
522 } else if (accuracy_decimals == -2) {
523 divisor = 100.0f;
524 } else {
525 divisor = pow10_int(-accuracy_decimals);
526 }
527 value = roundf(value / divisor) * divisor;
528 accuracy_decimals = 0;
529 }
530}
531
532// value_accuracy_to_string moved to alloc_helpers.cpp
533
534// Fast float-to-string for accuracy_decimals 0-3 (covers virtually all sensor usage).
535// Avoids snprintf("%.*f") which pulls in heavy float formatting machinery.
536// Caller must guarantee value is finite and |value| * mult fits in uint32_t.
537static size_t value_accuracy_to_buf_fast(char *buf, float value, int8_t accuracy_decimals, uint32_t mult) {
538 char *p = buf;
539 if (std::signbit(value)) {
540 *p++ = '-';
541 value = -value;
542 }
543 // Cast to double for the multiply to match snprintf's rounding precision.
544 // float*int loses bits at exact-half boundaries (e.g. 23.45f*10 = 234.5 in float,
545 // but snprintf sees 234.500007... via double promotion and rounds differently).
546 // llrint returns long long so the result fits even on 32-bit targets where
547 // long is 32-bit; caller has already bounded |value * mult| to UINT32_MAX.
548 uint32_t scaled = static_cast<uint32_t>(llrint(static_cast<double>(value) * mult));
549 p = uint32_to_str_unchecked(p, scaled / mult);
550 if (accuracy_decimals > 0) {
551 *p++ = '.';
552 p = frac_to_str_unchecked(p, scaled % mult, mult / 10);
553 }
554 *p = '\0';
555 return static_cast<size_t>(p - buf);
556}
557
558size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
559 normalize_accuracy_decimals(value, accuracy_decimals);
560
561 // Fast path for accuracy 0-3, finite values whose scaled magnitude fits in uint32_t.
562 // For 3 decimals that's |value| < ~4.29e6; larger totals fall through to snprintf.
563 if (accuracy_decimals <= 3 && std::isfinite(value)) {
564 const uint32_t mult = small_pow10(accuracy_decimals);
565 if (std::fabs(value) < static_cast<float>(UINT32_MAX) / mult) {
566 return value_accuracy_to_buf_fast(buf.data(), value, accuracy_decimals, mult);
567 }
568 }
569
570 // Fallback for NaN/Inf/high accuracy/out-of-range
571 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, static_cast<double>(value));
572 if (len < 0)
573 return 0;
574 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
575}
576
577size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
578 int8_t accuracy_decimals, StringRef unit_of_measurement) {
579 size_t len = value_accuracy_to_buf(buf, value, accuracy_decimals);
580 if (len == 0 || unit_of_measurement.empty()) {
581 return len;
582 }
583 char *end = buf_append_sep_str(buf.data() + len, buf.size() - len, ' ', unit_of_measurement.c_str(),
584 unit_of_measurement.size());
585 return static_cast<size_t>(end - buf.data());
586}
587
588int8_t step_to_accuracy_decimals(float step) {
589 // Decimals needed to show the step at five significant digits, trailing zeros dropped.
590 if (!std::isfinite(step) || step == 0.0f)
591 return 0;
592 float mantissa = std::fabs(step);
593 int8_t decimals = 4; // decimals needed for five significant digits when mantissa is in [1, 10)
594 while (mantissa >= 10.0f) {
595 mantissa /= 10.0f;
596 decimals--;
597 }
598 while (mantissa < 1.0f) {
599 mantissa *= 10.0f;
600 decimals++;
601 }
602 if (decimals <= 0)
603 return 0;
604 float scaled = mantissa * 10000.0f;
605 auto digits = static_cast<uint32_t>(scaled);
606 if (scaled - static_cast<float>(digits) >= 0.5f)
607 digits++;
608 while (decimals > 0 && digits % 10 == 0) {
609 digits /= 10;
610 decimals--;
611 }
612 return decimals;
613}
614
615// Map a base64/base64url character to its 6-bit value (0-63) arithmetically.
616// No lookup table: a table would occupy RAM on ESP8266 (.rodata lives in DRAM there).
617// Supports both standard base64 (+/) and base64url (-_) alphabets.
618// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
619// This is safe because is_base64() is ALWAYS checked before calling this function,
620// preventing invalid characters from ever reaching here. The base64_decode function
621// stops processing at the first invalid character due to the is_base64() check in its
622// while loop condition, making this edge case harmless in practice.
623static inline uint8_t base64_find_char(char c) {
624 if (c >= 'A' && c <= 'Z')
625 return c - 'A';
626 if (c >= 'a' && c <= 'z')
627 return c - 'a' + 26;
628 if (c >= '0' && c <= '9')
629 return c - '0' + 52;
630 // base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
631 if (c == '+' || c == '-')
632 return 62;
633 if (c == '/' || c == '_')
634 return 63;
635 return 0;
636}
637
638// Check if character is valid base64 or base64url
639static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
640
641// base64_encode (both overloads) moved to alloc_helpers.cpp
642
643size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
644 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
645}
646
647// Decode 4 base64 characters to up to 'count' output bytes, returns true if truncated.
648static inline bool base64_decode_quad(uint8_t *char_array_4, int count, uint8_t *buf, size_t buf_len, size_t &out) {
649 for (int i = 0; i < 4; i++)
650 char_array_4[i] = base64_find_char(char_array_4[i]);
651
652 uint8_t char_array_3[3];
653 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
654 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
655 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
656
657 bool truncated = false;
658 for (int j = 0; j < count; j++) {
659 if (out < buf_len) {
660 buf[out++] = char_array_3[j];
661 } else {
662 truncated = true;
663 }
664 }
665 return truncated;
666}
667
668size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
669 size_t in_len = encoded_len;
670 int i = 0;
671 size_t in = 0;
672 size_t out = 0;
673 uint8_t char_array_4[4];
674 bool truncated = false;
675
676 // SAFETY: The loop condition checks is_base64() before processing each character.
677 // This ensures base64_find_char() is only called on valid base64 characters,
678 // preventing the edge case where invalid chars would return 0 (same as 'A').
679 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
680 char_array_4[i++] = encoded_data[in];
681 in++;
682 if (i == 4) {
683 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
684 i = 0;
685 }
686 }
687
688 if (i) {
689 for (int j = i; j < 4; j++)
690 char_array_4[j] = 0;
691
692 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
693 }
694
695 if (truncated) {
696 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
697 }
698
699 return out;
700}
701
702// base64_decode (vector-returning overload) moved to alloc_helpers.cpp
703
708bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
709 // Decode in chunks to minimize stack usage
710 constexpr size_t chunk_bytes = 48; // 12 int32 values
711 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
712 uint8_t chunk[chunk_bytes];
713
714 out.clear();
715
716 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
717 size_t remaining = base64.size();
718 size_t pos = 0;
719
720 while (remaining > 0) {
721 size_t chars_to_decode = std::min(remaining, chunk_chars);
722 size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
723
724 if (decoded_len == 0)
725 return false;
726
727 // Parse little-endian int32 values
728 for (size_t i = 0; i + 3 < decoded_len; i += 4) {
729 int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
730 out.push_back(timing);
731 }
732
733 // Check for incomplete int32 in last chunk
734 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
735 return false;
736
737 pos += chars_to_decode;
738 remaining -= chars_to_decode;
739 }
740
741 return !out.empty();
742}
743
744// Colors
745
746void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
747 float max_color_value = std::max({red, green, blue});
748 float min_color_value = std::min({red, green, blue});
749 float delta = max_color_value - min_color_value;
750
751 if (delta == 0) {
752 hue = 0;
753 } else if (max_color_value == red) {
754 hue = int(fmodf((60.0f * ((green - blue) / delta)) + 360.0f, 360.0f));
755 } else if (max_color_value == green) {
756 hue = int(fmodf((60.0f * ((blue - red) / delta)) + 120.0f, 360.0f));
757 } else if (max_color_value == blue) {
758 hue = int(fmodf((60.0f * ((red - green) / delta)) + 240.0f, 360.0f));
759 }
760
761 if (max_color_value == 0) {
762 saturation = 0;
763 } else {
764 saturation = delta / max_color_value;
765 }
766
767 value = max_color_value;
768}
769void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
770 float chroma = value * saturation;
771 float hue_prime = fmodf(hue / 60.0f, 6.0f);
772 float intermediate = chroma * (1.0f - fabsf(fmodf(hue_prime, 2.0f) - 1.0f));
773 float delta = value - chroma;
774
775 if (0 <= hue_prime && hue_prime < 1) {
776 red = chroma;
777 green = intermediate;
778 blue = 0;
779 } else if (1 <= hue_prime && hue_prime < 2) {
780 red = intermediate;
781 green = chroma;
782 blue = 0;
783 } else if (2 <= hue_prime && hue_prime < 3) {
784 red = 0;
785 green = chroma;
786 blue = intermediate;
787 } else if (3 <= hue_prime && hue_prime < 4) {
788 red = 0;
789 green = intermediate;
790 blue = chroma;
791 } else if (4 <= hue_prime && hue_prime < 5) {
792 red = intermediate;
793 green = 0;
794 blue = chroma;
795 } else if (5 <= hue_prime && hue_prime < 6) {
796 red = chroma;
797 green = 0;
798 blue = intermediate;
799 } else {
800 red = 0;
801 green = 0;
802 blue = 0;
803 }
804
805 red += delta;
806 green += delta;
807 blue += delta;
808}
809
810uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
812 if (this->started_)
813 return;
814 num_requests++;
815 this->started_ = true;
816}
818 if (!this->started_)
819 return;
820 num_requests--;
821 this->started_ = false;
822}
823
824// get_mac_address, get_mac_address_pretty moved to alloc_helpers.cpp
825
826void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
827 uint8_t mac[MAC_ADDRESS_SIZE];
829 format_mac_addr_lower_no_sep(mac, buf.data());
830}
831
832const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
833 uint8_t mac[MAC_ADDRESS_SIZE];
835 format_mac_addr_upper(mac, buf.data());
836 return buf.data();
837}
838
839#ifndef USE_ESP32
840bool has_custom_mac_address() { return false; }
841#endif
842
843bool mac_address_is_valid(const uint8_t *mac) {
844 bool is_all_zeros = true;
845 bool is_all_ones = true;
846
847 for (uint8_t i = 0; i < 6; i++) {
848 if (mac[i] != 0) {
849 is_all_zeros = false;
850 }
851 if (mac[i] != 0xFF) {
852 is_all_ones = false;
853 }
854 }
855 if (is_all_zeros || is_all_ones) {
856 return false;
857 }
858 // Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
859 // This catches garbage data from corrupted eFuse custom MAC areas, which often
860 // has random values that would otherwise pass the all-zeros/all-ones check.
861 if (mac[0] & 0x01) {
862 return false;
863 }
864 return true;
865}
866
867void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
868 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
869 uint32_t start = micros();
870
871 constexpr uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
872 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
873 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
874 if (us > lag) {
875 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
876 while (micros() - start < us - lag)
877 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
878 }
879 while (micros() - start < us) // fine delay the remaining usecs
880 ;
881}
882
883} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:817
void start()
Start running the loop continuously.
Definition helpers.cpp:811
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 @66::@67 __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:1285
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:86
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Format name + separator + suffix directly into buffer without heap allocation.
Definition helpers.cpp:271
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1023
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:843
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1291
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1510
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:809
void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value)
Convert red, green and blue (all 0-1) values to hue (0-360), saturation (0-1) and value (0-1).
Definition helpers.cpp:746
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:26
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:558
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:485
bool base64_decode_int32_vector(const std::string &base64, std::vector< int32_t > &out)
Decode base64/base64url string directly into vector of little-endian int32 values.
Definition helpers.cpp:708
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:1354
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:119
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:293
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:425
uint16_t size
Definition helpers.cpp:25
bool str_contains_ignore_case_fallback(const char *haystack, const char *needle)
Fallback implementation for case insensitive substring comparison.
Definition helpers.cpp:223
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:500
uint32_t fnv1_hash(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:1374
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:588
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:1092
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:832
char * buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len)
Append a separator char and a string to a buffer, respecting remaining space.
Definition helpers.h:1337
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:867
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:257
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:577
const char * json_escape_into_buffer(std::span< char > buf, StringRef value, bool short_control_escapes)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition helpers.cpp:357
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:339
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:811
void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue)
Convert hue (0-360), saturation (0-1) and value (0-1) to red, green and blue (all 0-1).
Definition helpers.cpp:769
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:826
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:126
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:892
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:87
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1274
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:353
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
bool str_contains_ignore_case_p(const char *haystack, PGM_P needle)
ESP8266 internal implementation reading the needle from flash — prefer the str_contains_ignore_case m...
Definition helpers.cpp:239
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1603
@ PARSE_ON
Definition helpers.h:1605
@ PARSE_TOGGLE
Definition helpers.h:1607
@ PARSE_OFF
Definition helpers.h:1606
@ PARSE_NONE
Definition helpers.h:1604
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:777
char * format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as binary string to buffer.
Definition helpers.cpp:462
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1505
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0