ESPHome 2026.5.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 "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
224std::string str_truncate(const std::string &str, size_t length) {
225 return str.length() > length ? str.substr(0, length) : str;
226}
227std::string str_until(const char *str, char ch) {
228 const char *pos = strchr(str, ch);
229 return pos == nullptr ? std::string(str) : std::string(str, pos - str);
230}
231std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
232// wrapper around std::transform to run safely on functions from the ctype.h header
233// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
234template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
235 std::string result;
236 result.resize(str.length());
237 std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
238 return result;
239}
240std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
241std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
242std::string str_snake_case(const std::string &str) {
243 std::string result = str;
244 for (char &c : result) {
245 c = to_snake_case_char(c);
246 }
247 return result;
248}
249char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str) {
250 if (buffer_size == 0) {
251 return buffer;
252 }
253 size_t i = 0;
254 while (*str && i < buffer_size - 1) {
255 buffer[i++] = to_sanitized_char(*str++);
256 }
257 buffer[i] = '\0';
258 return buffer;
259}
260
261std::string str_sanitize(const std::string &str) {
262 std::string result;
263 result.resize(str.size());
264 str_sanitize_to(&result[0], str.size() + 1, str.c_str());
265 return result;
266}
267std::string str_snprintf(const char *fmt, size_t len, ...) {
268 std::string str;
269 va_list args;
270
271 str.resize(len);
272 va_start(args, len);
273 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
274 va_end(args);
275
276 if (out_length < len)
277 str.resize(out_length);
278
279 return str;
280}
281std::string str_sprintf(const char *fmt, ...) {
282 std::string str;
283 va_list args;
284
285 va_start(args, fmt);
286 size_t length = vsnprintf(nullptr, 0, fmt, args);
287 va_end(args);
288
289 str.resize(length);
290 va_start(args, fmt);
291 vsnprintf(&str[0], length + 1, fmt, args);
292 va_end(args);
293
294 return str;
295}
296
297// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
298static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
299
300size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
301 const char *suffix_ptr, size_t suffix_len) {
302 size_t total_len = name_len + 1 + suffix_len;
303
304 // Silently truncate if needed: prioritize keeping the full suffix
305 if (total_len >= buffer_size) {
306 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
307 // but this is safe because this helper is only called with small suffixes:
308 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
309 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
310 total_len = name_len + 1 + suffix_len;
311 }
312
313 memcpy(buffer, name, name_len);
314 buffer[name_len] = sep;
315 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
316 buffer[total_len] = '\0';
317 return total_len;
318}
319
320std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
321 size_t suffix_len) {
322 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
323 size_t len = make_name_with_suffix_to(buffer, sizeof(buffer), name, name_len, sep, suffix_ptr, suffix_len);
324 return std::string(buffer, len);
325}
326
327std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
328 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
329}
330
331// Parsing & formatting
332
333size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
334 size_t chars = std::min(length, 2 * count);
335 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
336 uint8_t val = parse_hex_char(*str);
337 if (val == INVALID_HEX_CHAR)
338 return 0;
339 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
340 }
341 return chars;
342}
343
344std::string format_mac_address_pretty(const uint8_t *mac) {
345 char buf[18];
346 format_mac_addr_upper(mac, buf);
347 return std::string(buf);
348}
349
350// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase.
351// When separator is set, it is written unconditionally after each byte and the last
352// one is overwritten with '\0', eliminating the per-byte `i < length - 1` check.
353static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
354 char base) {
355 if (length == 0 || buffer_size == 0) {
356 if (buffer_size > 0)
357 buffer[0] = '\0';
358 return buffer;
359 }
360 uint8_t stride = separator ? 3 : 2;
361 size_t max_bytes = separator ? (buffer_size / 3) : ((buffer_size - 1) / 2);
362 if (max_bytes == 0) {
363 buffer[0] = '\0';
364 return buffer;
365 }
366 if (length > max_bytes) {
367 length = max_bytes;
368 }
369 for (size_t i = 0; i < length; i++) {
370 size_t pos = i * stride;
371 buffer[pos] = format_hex_char(data[i] >> 4, base);
372 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
373 if (separator) {
374 buffer[pos + 2] = separator;
375 }
376 }
377 // With separator: overwrite last separator with '\0'
378 // Without: write '\0' after last hex char
379 buffer[length * stride - (separator ? 1 : 0)] = '\0';
380 return buffer;
381}
382
384 if (val == 0) {
385 *buf++ = '0';
386 return buf;
387 }
388 char *start = buf;
389 while (val > 0) {
390 *buf++ = '0' + (val % 10);
391 val /= 10;
392 }
393 std::reverse(start, buf);
394 return buf;
395}
396
397char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
398 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
399}
400
401std::string format_hex(const uint8_t *data, size_t length) {
402 std::string ret;
403 ret.resize(length * 2);
404 format_hex_to(&ret[0], length * 2 + 1, data, length);
405 return ret;
406}
407std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
408
409char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
410 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
411}
412
413char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
414 if (length == 0 || buffer_size == 0) {
415 if (buffer_size > 0)
416 buffer[0] = '\0';
417 return buffer;
418 }
419 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
420 // Without separator: each uint16_t needs 4 chars, plus null terminator
421 uint8_t stride = separator ? 5 : 4;
422 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
423 if (max_values == 0) {
424 buffer[0] = '\0';
425 return buffer;
426 }
427 if (length > max_values) {
428 length = max_values;
429 }
430 for (size_t i = 0; i < length; i++) {
431 size_t pos = i * stride;
432 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
433 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
434 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
435 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
436 if (separator && i < length - 1) {
437 buffer[pos + 4] = separator;
438 }
439 }
440 buffer[length * stride - (separator ? 1 : 0)] = '\0';
441 return buffer;
442}
443
444// Shared implementation for uint8_t and string hex formatting
445static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
446 if (data == nullptr || length == 0)
447 return "";
448 std::string ret;
449 size_t hex_len = separator ? (length * 3 - 1) : (length * 2);
450 ret.resize(hex_len);
451 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
452 if (show_length && length > 4)
453 return ret + " (" + std::to_string(length) + ")";
454 return ret;
455}
456
457std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
458 return format_hex_pretty_uint8(data, length, separator, show_length);
459}
460std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
461 return format_hex_pretty(data.data(), data.size(), separator, show_length);
462}
463
464std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
465 if (data == nullptr || length == 0)
466 return "";
467 std::string ret;
468 size_t hex_len = separator ? (length * 5 - 1) : (length * 4);
469 ret.resize(hex_len);
470 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
471 if (show_length && length > 4)
472 return ret + " (" + std::to_string(length) + ")";
473 return ret;
474}
475std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
476 return format_hex_pretty(data.data(), data.size(), separator, show_length);
477}
478std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
479 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
480}
481
482char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
483 if (buffer_size == 0) {
484 return buffer;
485 }
486 // Calculate max bytes we can format: each byte needs 8 chars
487 size_t max_bytes = (buffer_size - 1) / 8;
488 if (max_bytes == 0 || length == 0) {
489 buffer[0] = '\0';
490 return buffer;
491 }
492 size_t bytes_to_format = std::min(length, max_bytes);
493
494 for (size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
495 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
496 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
497 }
498 }
499 buffer[bytes_to_format * 8] = '\0';
500 return buffer;
501}
502
503std::string format_bin(const uint8_t *data, size_t length) {
504 std::string result;
505 result.resize(length * 8);
506 format_bin_to(&result[0], length * 8 + 1, data, length);
507 return result;
508}
509
510ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
511 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
512 return PARSE_ON;
513 if (on != nullptr && strcasecmp(str, on) == 0)
514 return PARSE_ON;
515 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
516 return PARSE_OFF;
517 if (off != nullptr && strcasecmp(str, off) == 0)
518 return PARSE_OFF;
519 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
520 return PARSE_TOGGLE;
521
522 return PARSE_NONE;
523}
524
525static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
526 if (accuracy_decimals < 0) {
527 float divisor;
528 if (accuracy_decimals == -1) {
529 divisor = 10.0f;
530 } else if (accuracy_decimals == -2) {
531 divisor = 100.0f;
532 } else {
533 divisor = pow10_int(-accuracy_decimals);
534 }
535 value = roundf(value / divisor) * divisor;
536 accuracy_decimals = 0;
537 }
538}
539
540std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
541 char buf[VALUE_ACCURACY_MAX_LEN];
542 value_accuracy_to_buf(buf, value, accuracy_decimals);
543 return std::string(buf);
544}
545
546size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
547 normalize_accuracy_decimals(value, accuracy_decimals);
548 // snprintf returns chars that would be written (excluding null), or negative on error
549 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
550 if (len < 0)
551 return 0; // encoding error
552 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
553 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
554}
555
556size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
557 int8_t accuracy_decimals, StringRef unit_of_measurement) {
558 if (unit_of_measurement.empty()) {
559 return value_accuracy_to_buf(buf, value, accuracy_decimals);
560 }
561 normalize_accuracy_decimals(value, accuracy_decimals);
562 // snprintf returns chars that would be written (excluding null), or negative on error
563 int len = snprintf(buf.data(), buf.size(), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
564 if (len < 0)
565 return 0; // encoding error
566 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
567 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
568}
569
570int8_t step_to_accuracy_decimals(float step) {
571 // use printf %g to find number of digits based on temperature step
572 char buf[32];
573 snprintf(buf, sizeof buf, "%.5g", step);
574
575 std::string str{buf};
576 size_t dot_pos = str.find('.');
577 if (dot_pos == std::string::npos)
578 return 0;
579
580 return str.length() - dot_pos - 1;
581}
582
583// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
584static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
585 "abcdefghijklmnopqrstuvwxyz"
586 "0123456789+/";
587
588// Helper function to find the index of a base64/base64url character in the lookup table.
589// Returns the character's position (0-63) if found, or 0 if not found.
590// Supports both standard base64 (+/) and base64url (-_) alphabets.
591// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
592// This is safe because is_base64() is ALWAYS checked before calling this function,
593// preventing invalid characters from ever reaching here. The base64_decode function
594// stops processing at the first invalid character due to the is_base64() check in its
595// while loop condition, making this edge case harmless in practice.
596static inline uint8_t base64_find_char(char c) {
597 // Handle base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
598 if (c == '-')
599 return 62;
600 if (c == '_')
601 return 63;
602 const char *pos = strchr(BASE64_CHARS, c);
603 return pos ? (pos - BASE64_CHARS) : 0;
604}
605
606// Check if character is valid base64 or base64url
607static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
608
609std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
610
611// Encode 3 input bytes to 4 base64 characters, append 'count' to ret.
612static inline void base64_encode_triple(const char *char_array_3, int count, std::string &ret) {
613 char char_array_4[4];
614 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
615 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
616 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
617 char_array_4[3] = char_array_3[2] & 0x3f;
618
619 for (int j = 0; j < count; j++)
620 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
621}
622
623std::string base64_encode(const uint8_t *buf, size_t buf_len) {
624 std::string ret;
625 int i = 0;
626 char char_array_3[3];
627
628 while (buf_len--) {
629 char_array_3[i++] = *(buf++);
630 if (i == 3) {
631 base64_encode_triple(char_array_3, 4, ret);
632 i = 0;
633 }
634 }
635
636 if (i) {
637 for (int j = i; j < 3; j++)
638 char_array_3[j] = '\0';
639
640 base64_encode_triple(char_array_3, i + 1, ret);
641
642 while ((i++ < 3))
643 ret += '=';
644 }
645
646 return ret;
647}
648
649size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
650 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
651}
652
653// Decode 4 base64 characters to up to 'count' output bytes, returns true if truncated.
654static inline bool base64_decode_quad(uint8_t *char_array_4, int count, uint8_t *buf, size_t buf_len, size_t &out) {
655 for (int i = 0; i < 4; i++)
656 char_array_4[i] = base64_find_char(char_array_4[i]);
657
658 uint8_t char_array_3[3];
659 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
660 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
661 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
662
663 bool truncated = false;
664 for (int j = 0; j < count; j++) {
665 if (out < buf_len) {
666 buf[out++] = char_array_3[j];
667 } else {
668 truncated = true;
669 }
670 }
671 return truncated;
672}
673
674size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
675 size_t in_len = encoded_len;
676 int i = 0;
677 size_t in = 0;
678 size_t out = 0;
679 uint8_t char_array_4[4];
680 bool truncated = false;
681
682 // SAFETY: The loop condition checks is_base64() before processing each character.
683 // This ensures base64_find_char() is only called on valid base64 characters,
684 // preventing the edge case where invalid chars would return 0 (same as 'A').
685 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
686 char_array_4[i++] = encoded_data[in];
687 in++;
688 if (i == 4) {
689 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
690 i = 0;
691 }
692 }
693
694 if (i) {
695 for (int j = i; j < 4; j++)
696 char_array_4[j] = 0;
697
698 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
699 }
700
701 if (truncated) {
702 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
703 }
704
705 return out;
706}
707
708std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
709 // Calculate maximum decoded size: every 4 base64 chars = 3 bytes
710 size_t max_len = ((encoded_string.size() + 3) / 4) * 3;
711 std::vector<uint8_t> ret(max_len);
712 size_t actual_len = base64_decode(encoded_string, ret.data(), max_len);
713 ret.resize(actual_len);
714 return ret;
715}
716
721bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
722 // Decode in chunks to minimize stack usage
723 constexpr size_t chunk_bytes = 48; // 12 int32 values
724 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
725 uint8_t chunk[chunk_bytes];
726
727 out.clear();
728
729 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
730 size_t remaining = base64.size();
731 size_t pos = 0;
732
733 while (remaining > 0) {
734 size_t chars_to_decode = std::min(remaining, chunk_chars);
735 size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
736
737 if (decoded_len == 0)
738 return false;
739
740 // Parse little-endian int32 values
741 for (size_t i = 0; i + 3 < decoded_len; i += 4) {
742 int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
743 out.push_back(timing);
744 }
745
746 // Check for incomplete int32 in last chunk
747 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
748 return false;
749
750 pos += chars_to_decode;
751 remaining -= chars_to_decode;
752 }
753
754 return !out.empty();
755}
756
757// Colors
758
759float gamma_correct(float value, float gamma) {
760 if (value <= 0.0f)
761 return 0.0f;
762 if (gamma <= 0.0f)
763 return value;
764
765 return powf(value, gamma); // NOLINT - deprecated, removal 2026.9.0
766}
767float gamma_uncorrect(float value, float gamma) {
768 if (value <= 0.0f)
769 return 0.0f;
770 if (gamma <= 0.0f)
771 return value;
772
773 return powf(value, 1 / gamma); // NOLINT - deprecated, removal 2026.9.0
774}
775
776void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
777 float max_color_value = std::max(std::max(red, green), blue);
778 float min_color_value = std::min(std::min(red, green), blue);
779 float delta = max_color_value - min_color_value;
780
781 if (delta == 0) {
782 hue = 0;
783 } else if (max_color_value == red) {
784 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
785 } else if (max_color_value == green) {
786 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
787 } else if (max_color_value == blue) {
788 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
789 }
790
791 if (max_color_value == 0) {
792 saturation = 0;
793 } else {
794 saturation = delta / max_color_value;
795 }
796
797 value = max_color_value;
798}
799void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
800 float chroma = value * saturation;
801 float hue_prime = fmod(hue / 60.0, 6);
802 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
803 float delta = value - chroma;
804
805 if (0 <= hue_prime && hue_prime < 1) {
806 red = chroma;
807 green = intermediate;
808 blue = 0;
809 } else if (1 <= hue_prime && hue_prime < 2) {
810 red = intermediate;
811 green = chroma;
812 blue = 0;
813 } else if (2 <= hue_prime && hue_prime < 3) {
814 red = 0;
815 green = chroma;
816 blue = intermediate;
817 } else if (3 <= hue_prime && hue_prime < 4) {
818 red = 0;
819 green = intermediate;
820 blue = chroma;
821 } else if (4 <= hue_prime && hue_prime < 5) {
822 red = intermediate;
823 green = 0;
824 blue = chroma;
825 } else if (5 <= hue_prime && hue_prime < 6) {
826 red = chroma;
827 green = 0;
828 blue = intermediate;
829 } else {
830 red = 0;
831 green = 0;
832 blue = 0;
833 }
834
835 red += delta;
836 green += delta;
837 blue += delta;
838}
839
840uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
842 if (this->started_)
843 return;
844 num_requests++;
845 this->started_ = true;
846}
848 if (!this->started_)
849 return;
850 num_requests--;
851 this->started_ = false;
852}
853
854std::string get_mac_address() {
855 uint8_t mac[6];
857 char buf[13];
859 return std::string(buf);
860}
861
863 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
864 return std::string(get_mac_address_pretty_into_buffer(buf));
865}
866
867void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
868 uint8_t mac[6];
870 format_mac_addr_lower_no_sep(mac, buf.data());
871}
872
873const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
874 uint8_t mac[6];
876 format_mac_addr_upper(mac, buf.data());
877 return buf.data();
878}
879
880#ifndef USE_ESP32
881bool has_custom_mac_address() { return false; }
882#endif
883
884bool mac_address_is_valid(const uint8_t *mac) {
885 bool is_all_zeros = true;
886 bool is_all_ones = true;
887
888 for (uint8_t i = 0; i < 6; i++) {
889 if (mac[i] != 0) {
890 is_all_zeros = false;
891 }
892 if (mac[i] != 0xFF) {
893 is_all_ones = false;
894 }
895 }
896 if (is_all_zeros || is_all_ones) {
897 return false;
898 }
899 // Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
900 // This catches garbage data from corrupted eFuse custom MAC areas, which often
901 // has random values that would otherwise pass the all-zeros/all-ones check.
902 if (mac[0] & 0x01) {
903 return false;
904 }
905 return true;
906}
907
908void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
909 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
910 uint32_t start = micros();
911
912 constexpr uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
913 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
914 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
915 if (us > lag) {
916 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
917 while (micros() - start < us - lag)
918 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
919 }
920 while (micros() - start < us) // fine delay the remaining usecs
921 ;
922}
923
924} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:847
void start()
Start running the loop continuously.
Definition helpers.cpp:841
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
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.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:1266
float gamma_uncorrect(float value, float gamma)
Definition helpers.cpp:767
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:300
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Definition helpers.cpp:540
float gamma_correct(float value, float gamma)
Definition helpers.cpp:759
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1005
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:884
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:1272
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1440
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:772
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:776
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
Definition helpers.cpp:401
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:546
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:240
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:510
const char int const __FlashStringHelper va_list args
Definition log.h:74
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:503
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:261
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:721
va_end(args)
std::string size_t len
Definition helpers.h:1045
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:333
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:409
uint16_t size
Definition helpers.cpp:25
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:161
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:862
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:267
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:570
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:29
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
size_t size_t pos
Definition helpers.h:1082
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:873
void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:908
uint16_t new_cap
Definition helpers.cpp:28
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:241
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:457
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
std::string str_until(const char *str, char ch)
Extract the part of the string until either the first occurrence of the specified character,...
Definition helpers.cpp:227
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:249
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:344
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:556
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:383
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:609
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:774
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:799
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:867
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:889
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
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:281
size_t size_t const char va_start(args, fmt)
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
size_t size_t const char * fmt
Definition helpers.h:1083
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1255
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 core.cpp:28
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:854
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:999
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:397
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:242
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:1745
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:649
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1699
@ PARSE_ON
Definition helpers.h:1701
@ PARSE_TOGGLE
Definition helpers.h:1703
@ PARSE_OFF
Definition helpers.h:1702
@ PARSE_NONE
Definition helpers.h:1700
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:740
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:320
std::string str_ctype_transform(const std::string &str)
Definition helpers.cpp:234
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:482
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:1435
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:224
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0