ESPHome 2026.4.0
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
351static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
352 char base) {
353 if (length == 0) {
354 buffer[0] = '\0';
355 return buffer;
356 }
357 // With separator: total length is 3*length (2*length hex chars, (length-1) separators, 1 null terminator)
358 // Without separator: total length is 2*length + 1 (2*length hex chars, 1 null terminator)
359 uint8_t stride = separator ? 3 : 2;
360 size_t max_bytes = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
361 if (max_bytes == 0) {
362 buffer[0] = '\0';
363 return buffer;
364 }
365 if (length > max_bytes) {
366 length = max_bytes;
367 }
368 for (size_t i = 0; i < length; i++) {
369 size_t pos = i * stride;
370 buffer[pos] = format_hex_char(data[i] >> 4, base);
371 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
372 if (separator && i < length - 1) {
373 buffer[pos + 2] = separator;
374 }
375 }
376 buffer[length * stride - (separator ? 1 : 0)] = '\0';
377 return buffer;
378}
379
380char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
381 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
382}
383
384std::string format_hex(const uint8_t *data, size_t length) {
385 std::string ret;
386 ret.resize(length * 2);
387 format_hex_to(&ret[0], length * 2 + 1, data, length);
388 return ret;
389}
390std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
391
392char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
393 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
394}
395
396char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
397 if (length == 0 || buffer_size == 0) {
398 if (buffer_size > 0)
399 buffer[0] = '\0';
400 return buffer;
401 }
402 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
403 // Without separator: each uint16_t needs 4 chars, plus null terminator
404 uint8_t stride = separator ? 5 : 4;
405 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
406 if (max_values == 0) {
407 buffer[0] = '\0';
408 return buffer;
409 }
410 if (length > max_values) {
411 length = max_values;
412 }
413 for (size_t i = 0; i < length; i++) {
414 size_t pos = i * stride;
415 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
416 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
417 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
418 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
419 if (separator && i < length - 1) {
420 buffer[pos + 4] = separator;
421 }
422 }
423 buffer[length * stride - (separator ? 1 : 0)] = '\0';
424 return buffer;
425}
426
427// Shared implementation for uint8_t and string hex formatting
428static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
429 if (data == nullptr || length == 0)
430 return "";
431 std::string ret;
432 size_t hex_len = separator ? (length * 3 - 1) : (length * 2);
433 ret.resize(hex_len);
434 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
435 if (show_length && length > 4)
436 return ret + " (" + std::to_string(length) + ")";
437 return ret;
438}
439
440std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
441 return format_hex_pretty_uint8(data, length, separator, show_length);
442}
443std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
444 return format_hex_pretty(data.data(), data.size(), separator, show_length);
445}
446
447std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
448 if (data == nullptr || length == 0)
449 return "";
450 std::string ret;
451 size_t hex_len = separator ? (length * 5 - 1) : (length * 4);
452 ret.resize(hex_len);
453 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
454 if (show_length && length > 4)
455 return ret + " (" + std::to_string(length) + ")";
456 return ret;
457}
458std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
459 return format_hex_pretty(data.data(), data.size(), separator, show_length);
460}
461std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
462 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
463}
464
465char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
466 if (buffer_size == 0) {
467 return buffer;
468 }
469 // Calculate max bytes we can format: each byte needs 8 chars
470 size_t max_bytes = (buffer_size - 1) / 8;
471 if (max_bytes == 0 || length == 0) {
472 buffer[0] = '\0';
473 return buffer;
474 }
475 size_t bytes_to_format = std::min(length, max_bytes);
476
477 for (size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
478 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
479 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
480 }
481 }
482 buffer[bytes_to_format * 8] = '\0';
483 return buffer;
484}
485
486std::string format_bin(const uint8_t *data, size_t length) {
487 std::string result;
488 result.resize(length * 8);
489 format_bin_to(&result[0], length * 8 + 1, data, length);
490 return result;
491}
492
493ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
494 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
495 return PARSE_ON;
496 if (on != nullptr && strcasecmp(str, on) == 0)
497 return PARSE_ON;
498 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
499 return PARSE_OFF;
500 if (off != nullptr && strcasecmp(str, off) == 0)
501 return PARSE_OFF;
502 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
503 return PARSE_TOGGLE;
504
505 return PARSE_NONE;
506}
507
508static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
509 if (accuracy_decimals < 0) {
510 float divisor;
511 if (accuracy_decimals == -1) {
512 divisor = 10.0f;
513 } else if (accuracy_decimals == -2) {
514 divisor = 100.0f;
515 } else {
516 divisor = pow10_int(-accuracy_decimals);
517 }
518 value = roundf(value / divisor) * divisor;
519 accuracy_decimals = 0;
520 }
521}
522
523std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
524 char buf[VALUE_ACCURACY_MAX_LEN];
525 value_accuracy_to_buf(buf, value, accuracy_decimals);
526 return std::string(buf);
527}
528
529size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
530 normalize_accuracy_decimals(value, accuracy_decimals);
531 // snprintf returns chars that would be written (excluding null), or negative on error
532 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
533 if (len < 0)
534 return 0; // encoding error
535 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
536 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
537}
538
539size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
540 int8_t accuracy_decimals, StringRef unit_of_measurement) {
541 if (unit_of_measurement.empty()) {
542 return value_accuracy_to_buf(buf, value, accuracy_decimals);
543 }
544 normalize_accuracy_decimals(value, accuracy_decimals);
545 // snprintf returns chars that would be written (excluding null), or negative on error
546 int len = snprintf(buf.data(), buf.size(), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
547 if (len < 0)
548 return 0; // encoding error
549 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
550 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
551}
552
553int8_t step_to_accuracy_decimals(float step) {
554 // use printf %g to find number of digits based on temperature step
555 char buf[32];
556 snprintf(buf, sizeof buf, "%.5g", step);
557
558 std::string str{buf};
559 size_t dot_pos = str.find('.');
560 if (dot_pos == std::string::npos)
561 return 0;
562
563 return str.length() - dot_pos - 1;
564}
565
566// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
567static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
568 "abcdefghijklmnopqrstuvwxyz"
569 "0123456789+/";
570
571// Helper function to find the index of a base64/base64url character in the lookup table.
572// Returns the character's position (0-63) if found, or 0 if not found.
573// Supports both standard base64 (+/) and base64url (-_) alphabets.
574// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
575// This is safe because is_base64() is ALWAYS checked before calling this function,
576// preventing invalid characters from ever reaching here. The base64_decode function
577// stops processing at the first invalid character due to the is_base64() check in its
578// while loop condition, making this edge case harmless in practice.
579static inline uint8_t base64_find_char(char c) {
580 // Handle base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
581 if (c == '-')
582 return 62;
583 if (c == '_')
584 return 63;
585 const char *pos = strchr(BASE64_CHARS, c);
586 return pos ? (pos - BASE64_CHARS) : 0;
587}
588
589// Check if character is valid base64 or base64url
590static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
591
592std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
593
594// Encode 3 input bytes to 4 base64 characters, append 'count' to ret.
595static inline void base64_encode_triple(const char *char_array_3, int count, std::string &ret) {
596 char char_array_4[4];
597 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
598 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
599 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
600 char_array_4[3] = char_array_3[2] & 0x3f;
601
602 for (int j = 0; j < count; j++)
603 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
604}
605
606std::string base64_encode(const uint8_t *buf, size_t buf_len) {
607 std::string ret;
608 int i = 0;
609 char char_array_3[3];
610
611 while (buf_len--) {
612 char_array_3[i++] = *(buf++);
613 if (i == 3) {
614 base64_encode_triple(char_array_3, 4, ret);
615 i = 0;
616 }
617 }
618
619 if (i) {
620 for (int j = i; j < 3; j++)
621 char_array_3[j] = '\0';
622
623 base64_encode_triple(char_array_3, i + 1, ret);
624
625 while ((i++ < 3))
626 ret += '=';
627 }
628
629 return ret;
630}
631
632size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
633 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
634}
635
636// Decode 4 base64 characters to up to 'count' output bytes, returns true if truncated.
637static inline bool base64_decode_quad(uint8_t *char_array_4, int count, uint8_t *buf, size_t buf_len, size_t &out) {
638 for (int i = 0; i < 4; i++)
639 char_array_4[i] = base64_find_char(char_array_4[i]);
640
641 uint8_t char_array_3[3];
642 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
643 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
644 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
645
646 bool truncated = false;
647 for (int j = 0; j < count; j++) {
648 if (out < buf_len) {
649 buf[out++] = char_array_3[j];
650 } else {
651 truncated = true;
652 }
653 }
654 return truncated;
655}
656
657size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
658 size_t in_len = encoded_len;
659 int i = 0;
660 size_t in = 0;
661 size_t out = 0;
662 uint8_t char_array_4[4];
663 bool truncated = false;
664
665 // SAFETY: The loop condition checks is_base64() before processing each character.
666 // This ensures base64_find_char() is only called on valid base64 characters,
667 // preventing the edge case where invalid chars would return 0 (same as 'A').
668 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
669 char_array_4[i++] = encoded_data[in];
670 in++;
671 if (i == 4) {
672 truncated |= base64_decode_quad(char_array_4, 3, buf, buf_len, out);
673 i = 0;
674 }
675 }
676
677 if (i) {
678 for (int j = i; j < 4; j++)
679 char_array_4[j] = 0;
680
681 truncated |= base64_decode_quad(char_array_4, i - 1, buf, buf_len, out);
682 }
683
684 if (truncated) {
685 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
686 }
687
688 return out;
689}
690
691std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
692 // Calculate maximum decoded size: every 4 base64 chars = 3 bytes
693 size_t max_len = ((encoded_string.size() + 3) / 4) * 3;
694 std::vector<uint8_t> ret(max_len);
695 size_t actual_len = base64_decode(encoded_string, ret.data(), max_len);
696 ret.resize(actual_len);
697 return ret;
698}
699
704bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
705 // Decode in chunks to minimize stack usage
706 constexpr size_t chunk_bytes = 48; // 12 int32 values
707 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
708 uint8_t chunk[chunk_bytes];
709
710 out.clear();
711
712 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
713 size_t remaining = base64.size();
714 size_t pos = 0;
715
716 while (remaining > 0) {
717 size_t chars_to_decode = std::min(remaining, chunk_chars);
718 size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
719
720 if (decoded_len == 0)
721 return false;
722
723 // Parse little-endian int32 values
724 for (size_t i = 0; i + 3 < decoded_len; i += 4) {
725 int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
726 out.push_back(timing);
727 }
728
729 // Check for incomplete int32 in last chunk
730 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
731 return false;
732
733 pos += chars_to_decode;
734 remaining -= chars_to_decode;
735 }
736
737 return !out.empty();
738}
739
740// Colors
741
742float gamma_correct(float value, float gamma) {
743 if (value <= 0.0f)
744 return 0.0f;
745 if (gamma <= 0.0f)
746 return value;
747
748 return powf(value, gamma); // NOLINT - deprecated, removal 2026.9.0
749}
750float gamma_uncorrect(float value, float gamma) {
751 if (value <= 0.0f)
752 return 0.0f;
753 if (gamma <= 0.0f)
754 return value;
755
756 return powf(value, 1 / gamma); // NOLINT - deprecated, removal 2026.9.0
757}
758
759void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
760 float max_color_value = std::max(std::max(red, green), blue);
761 float min_color_value = std::min(std::min(red, green), blue);
762 float delta = max_color_value - min_color_value;
763
764 if (delta == 0) {
765 hue = 0;
766 } else if (max_color_value == red) {
767 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
768 } else if (max_color_value == green) {
769 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
770 } else if (max_color_value == blue) {
771 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
772 }
773
774 if (max_color_value == 0) {
775 saturation = 0;
776 } else {
777 saturation = delta / max_color_value;
778 }
779
780 value = max_color_value;
781}
782void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
783 float chroma = value * saturation;
784 float hue_prime = fmod(hue / 60.0, 6);
785 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
786 float delta = value - chroma;
787
788 if (0 <= hue_prime && hue_prime < 1) {
789 red = chroma;
790 green = intermediate;
791 blue = 0;
792 } else if (1 <= hue_prime && hue_prime < 2) {
793 red = intermediate;
794 green = chroma;
795 blue = 0;
796 } else if (2 <= hue_prime && hue_prime < 3) {
797 red = 0;
798 green = chroma;
799 blue = intermediate;
800 } else if (3 <= hue_prime && hue_prime < 4) {
801 red = 0;
802 green = intermediate;
803 blue = chroma;
804 } else if (4 <= hue_prime && hue_prime < 5) {
805 red = intermediate;
806 green = 0;
807 blue = chroma;
808 } else if (5 <= hue_prime && hue_prime < 6) {
809 red = chroma;
810 green = 0;
811 blue = intermediate;
812 } else {
813 red = 0;
814 green = 0;
815 blue = 0;
816 }
817
818 red += delta;
819 green += delta;
820 blue += delta;
821}
822
823uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
825 if (this->started_)
826 return;
827 num_requests++;
828 this->started_ = true;
829}
831 if (!this->started_)
832 return;
833 num_requests--;
834 this->started_ = false;
835}
836
837std::string get_mac_address() {
838 uint8_t mac[6];
840 char buf[13];
842 return std::string(buf);
843}
844
846 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
847 return std::string(get_mac_address_pretty_into_buffer(buf));
848}
849
850void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
851 uint8_t mac[6];
853 format_mac_addr_lower_no_sep(mac, buf.data());
854}
855
856const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
857 uint8_t mac[6];
859 format_mac_addr_upper(mac, buf.data());
860 return buf.data();
861}
862
863#ifndef USE_ESP32
864bool has_custom_mac_address() { return false; }
865#endif
866
867bool mac_address_is_valid(const uint8_t *mac) {
868 bool is_all_zeros = true;
869 bool is_all_ones = true;
870
871 for (uint8_t i = 0; i < 6; i++) {
872 if (mac[i] != 0) {
873 is_all_zeros = false;
874 }
875 if (mac[i] != 0xFF) {
876 is_all_ones = false;
877 }
878 }
879 if (is_all_zeros || is_all_ones) {
880 return false;
881 }
882 // Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
883 // This catches garbage data from corrupted eFuse custom MAC areas, which often
884 // has random values that would otherwise pass the all-zeros/all-ones check.
885 if (mac[0] & 0x01) {
886 return false;
887 }
888 return true;
889}
890
891void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
892 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
893 uint32_t start = micros();
894
895 constexpr uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
896 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
897 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
898 if (us > lag) {
899 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
900 while (micros() - start < us - lag)
901 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
902 }
903 while (micros() - start < us) // fine delay the remaining usecs
904 ;
905}
906
907} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:830
void start()
Start running the loop continuously.
Definition helpers.cpp:824
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__
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
float gamma_uncorrect(float value, float gamma)
Definition helpers.cpp:750
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:523
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
float gamma_correct(float value, float gamma)
Definition helpers.cpp:742
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:867
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1425
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:759
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:384
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:26
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
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:529
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:493
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:486
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:704
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:392
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:845
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:553
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:856
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:891
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:440
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:539
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:592
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:782
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:850
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:837
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:380
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:1730
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:632
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1684
@ PARSE_ON
Definition helpers.h:1686
@ PARSE_TOGGLE
Definition helpers.h:1688
@ PARSE_OFF
Definition helpers.h:1687
@ PARSE_NONE
Definition helpers.h:1685
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:465
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:1420
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