ESPHome 2026.2.3
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
25static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
26 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
27static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
28 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
29
30#ifndef USE_ESP32
31static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
32 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
33static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
34 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
35#endif
36
37#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
38static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
39 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
40static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
41 0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
42#endif
43
44// Mathematics
45
46uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first) {
47 while ((len--) != 0u) {
48 uint8_t inbyte = *data++;
49 if (msb_first) {
50 // MSB first processing (for polynomials like 0x31, 0x07)
51 crc ^= inbyte;
52 for (uint8_t i = 8; i != 0u; i--) {
53 if (crc & 0x80) {
54 crc = (crc << 1) ^ poly;
55 } else {
56 crc <<= 1;
57 }
58 }
59 } else {
60 // LSB first processing (default for Dallas/Maxim 0x8C)
61 for (uint8_t i = 8; i != 0u; i--) {
62 bool mix = (crc ^ inbyte) & 0x01;
63 crc >>= 1;
64 if (mix)
65 crc ^= poly;
66 inbyte >>= 1;
67 }
68 }
69 }
70 return crc;
71}
72
73uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout) {
74#ifdef USE_ESP32
75 if (reverse_poly == 0x8408) {
76 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
77 return refout ? crc : (crc ^ 0xffff);
78 }
79#endif
80 if (refin) {
81 crc ^= 0xffff;
82 }
83#ifndef USE_ESP32
84 if (reverse_poly == 0x8408) {
85 while (len--) {
86 uint8_t combo = crc ^ (uint8_t) *data++;
87 crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
88 }
89 } else
90#endif
91 {
92 if (reverse_poly == 0xa001) {
93 while (len--) {
94 uint8_t combo = crc ^ (uint8_t) *data++;
95 crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
96 }
97 } else {
98 while (len--) {
99 crc ^= *data++;
100 for (uint8_t i = 0; i < 8; i++) {
101 if (crc & 0x0001) {
102 crc = (crc >> 1) ^ reverse_poly;
103 } else {
104 crc >>= 1;
105 }
106 }
107 }
108 }
109 }
110 return refout ? (crc ^ 0xffff) : crc;
111}
112
113uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout) {
114#if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32S2)
115 if (poly == 0x1021) {
116 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
117 return refout ? crc : (crc ^ 0xffff);
118 }
119#endif
120 if (refin) {
121 crc ^= 0xffff;
122 }
123#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
124 if (poly == 0x1021) {
125 while (len--) {
126 uint8_t combo = (crc >> 8) ^ *data++;
127 crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
128 }
129 } else {
130#endif
131 while (len--) {
132 crc ^= (((uint16_t) *data++) << 8);
133 for (uint8_t i = 0; i < 8; i++) {
134 if (crc & 0x8000) {
135 crc = (crc << 1) ^ poly;
136 } else {
137 crc <<= 1;
138 }
139 }
140 }
141#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
142 }
143#endif
144 return refout ? (crc ^ 0xffff) : crc;
145}
146
147// FNV-1 hash - deprecated, use fnv1a_hash() for new code
148uint32_t fnv1_hash(const char *str) {
149 uint32_t hash = FNV1_OFFSET_BASIS;
150 if (str) {
151 while (*str) {
152 hash *= FNV1_PRIME;
153 hash ^= *str++;
154 }
155 }
156 return hash;
157}
158
159float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
160
161// Strings
162
163bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
164 return strcasecmp(a.c_str(), b.c_str()) == 0;
165}
167 return a.size() == b.size() && strncasecmp(a.c_str(), b.c_str(), a.size()) == 0;
168}
169#if __cplusplus >= 202002L
170bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
171bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
172#else
173bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
174bool str_endswith(const std::string &str, const std::string &end) {
175 return str.rfind(end) == (str.size() - end.size());
176}
177#endif
178
179bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len) {
180 if (suffix_len > str_len)
181 return false;
182 return strncasecmp(str + str_len - suffix_len, suffix, suffix_len) == 0;
183}
184
185std::string str_truncate(const std::string &str, size_t length) {
186 return str.length() > length ? str.substr(0, length) : str;
187}
188std::string str_until(const char *str, char ch) {
189 const char *pos = strchr(str, ch);
190 return pos == nullptr ? std::string(str) : std::string(str, pos - str);
191}
192std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
193// wrapper around std::transform to run safely on functions from the ctype.h header
194// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
195template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
196 std::string result;
197 result.resize(str.length());
198 std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
199 return result;
200}
201std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
202std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
203std::string str_snake_case(const std::string &str) {
204 std::string result = str;
205 for (char &c : result) {
206 c = to_snake_case_char(c);
207 }
208 return result;
209}
210char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str) {
211 if (buffer_size == 0) {
212 return buffer;
213 }
214 size_t i = 0;
215 while (*str && i < buffer_size - 1) {
216 buffer[i++] = to_sanitized_char(*str++);
217 }
218 buffer[i] = '\0';
219 return buffer;
220}
221
222std::string str_sanitize(const std::string &str) {
223 std::string result;
224 result.resize(str.size());
225 str_sanitize_to(&result[0], str.size() + 1, str.c_str());
226 return result;
227}
228std::string str_snprintf(const char *fmt, size_t len, ...) {
229 std::string str;
230 va_list args;
231
232 str.resize(len);
233 va_start(args, len);
234 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
235 va_end(args);
236
237 if (out_length < len)
238 str.resize(out_length);
239
240 return str;
241}
242std::string str_sprintf(const char *fmt, ...) {
243 std::string str;
244 va_list args;
245
246 va_start(args, fmt);
247 size_t length = vsnprintf(nullptr, 0, fmt, args);
248 va_end(args);
249
250 str.resize(length);
251 va_start(args, fmt);
252 vsnprintf(&str[0], length + 1, fmt, args);
253 va_end(args);
254
255 return str;
256}
257
258// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
259static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
260
261size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
262 const char *suffix_ptr, size_t suffix_len) {
263 size_t total_len = name_len + 1 + suffix_len;
264
265 // Silently truncate if needed: prioritize keeping the full suffix
266 if (total_len >= buffer_size) {
267 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
268 // but this is safe because this helper is only called with small suffixes:
269 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
270 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
271 total_len = name_len + 1 + suffix_len;
272 }
273
274 memcpy(buffer, name, name_len);
275 buffer[name_len] = sep;
276 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
277 buffer[total_len] = '\0';
278 return total_len;
279}
280
281std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
282 size_t suffix_len) {
283 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
284 size_t len = make_name_with_suffix_to(buffer, sizeof(buffer), name, name_len, sep, suffix_ptr, suffix_len);
285 return std::string(buffer, len);
286}
287
288std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
289 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
290}
291
292// Parsing & formatting
293
294size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
295 size_t chars = std::min(length, 2 * count);
296 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
297 uint8_t val = parse_hex_char(*str);
298 if (val == INVALID_HEX_CHAR)
299 return 0;
300 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
301 }
302 return chars;
303}
304
305std::string format_mac_address_pretty(const uint8_t *mac) {
306 char buf[18];
307 format_mac_addr_upper(mac, buf);
308 return std::string(buf);
309}
310
311// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase
312static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
313 char base) {
314 if (length == 0) {
315 buffer[0] = '\0';
316 return buffer;
317 }
318 // With separator: total length is 3*length (2*length hex chars, (length-1) separators, 1 null terminator)
319 // Without separator: total length is 2*length + 1 (2*length hex chars, 1 null terminator)
320 uint8_t stride = separator ? 3 : 2;
321 size_t max_bytes = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
322 if (max_bytes == 0) {
323 buffer[0] = '\0';
324 return buffer;
325 }
326 if (length > max_bytes) {
327 length = max_bytes;
328 }
329 for (size_t i = 0; i < length; i++) {
330 size_t pos = i * stride;
331 buffer[pos] = format_hex_char(data[i] >> 4, base);
332 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
333 if (separator && i < length - 1) {
334 buffer[pos + 2] = separator;
335 }
336 }
337 buffer[length * stride - (separator ? 1 : 0)] = '\0';
338 return buffer;
339}
340
341char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
342 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
343}
344
345std::string format_hex(const uint8_t *data, size_t length) {
346 std::string ret;
347 ret.resize(length * 2);
348 format_hex_to(&ret[0], length * 2 + 1, data, length);
349 return ret;
350}
351std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
352
353char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
354 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
355}
356
357char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator) {
358 if (length == 0 || buffer_size == 0) {
359 if (buffer_size > 0)
360 buffer[0] = '\0';
361 return buffer;
362 }
363 // With separator: each uint16_t needs 5 chars (4 hex + 1 sep), except last has no separator
364 // Without separator: each uint16_t needs 4 chars, plus null terminator
365 uint8_t stride = separator ? 5 : 4;
366 size_t max_values = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
367 if (max_values == 0) {
368 buffer[0] = '\0';
369 return buffer;
370 }
371 if (length > max_values) {
372 length = max_values;
373 }
374 for (size_t i = 0; i < length; i++) {
375 size_t pos = i * stride;
376 buffer[pos] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
377 buffer[pos + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
378 buffer[pos + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
379 buffer[pos + 3] = format_hex_pretty_char(data[i] & 0x000F);
380 if (separator && i < length - 1) {
381 buffer[pos + 4] = separator;
382 }
383 }
384 buffer[length * stride - (separator ? 1 : 0)] = '\0';
385 return buffer;
386}
387
388// Shared implementation for uint8_t and string hex formatting
389static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
390 if (data == nullptr || length == 0)
391 return "";
392 std::string ret;
393 size_t hex_len = separator ? (length * 3 - 1) : (length * 2);
394 ret.resize(hex_len);
395 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
396 if (show_length && length > 4)
397 return ret + " (" + std::to_string(length) + ")";
398 return ret;
399}
400
401std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
402 return format_hex_pretty_uint8(data, length, separator, show_length);
403}
404std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
405 return format_hex_pretty(data.data(), data.size(), separator, show_length);
406}
407
408std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
409 if (data == nullptr || length == 0)
410 return "";
411 std::string ret;
412 size_t hex_len = separator ? (length * 5 - 1) : (length * 4);
413 ret.resize(hex_len);
414 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
415 if (show_length && length > 4)
416 return ret + " (" + std::to_string(length) + ")";
417 return ret;
418}
419std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
420 return format_hex_pretty(data.data(), data.size(), separator, show_length);
421}
422std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
423 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
424}
425
426char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
427 if (buffer_size == 0) {
428 return buffer;
429 }
430 // Calculate max bytes we can format: each byte needs 8 chars
431 size_t max_bytes = (buffer_size - 1) / 8;
432 if (max_bytes == 0 || length == 0) {
433 buffer[0] = '\0';
434 return buffer;
435 }
436 size_t bytes_to_format = std::min(length, max_bytes);
437
438 for (size_t byte_idx = 0; byte_idx < bytes_to_format; byte_idx++) {
439 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
440 buffer[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
441 }
442 }
443 buffer[bytes_to_format * 8] = '\0';
444 return buffer;
445}
446
447std::string format_bin(const uint8_t *data, size_t length) {
448 std::string result;
449 result.resize(length * 8);
450 format_bin_to(&result[0], length * 8 + 1, data, length);
451 return result;
452}
453
454ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
455 if (on == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("on")) == 0)
456 return PARSE_ON;
457 if (on != nullptr && strcasecmp(str, on) == 0)
458 return PARSE_ON;
459 if (off == nullptr && ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("off")) == 0)
460 return PARSE_OFF;
461 if (off != nullptr && strcasecmp(str, off) == 0)
462 return PARSE_OFF;
463 if (ESPHOME_strcasecmp_P(str, ESPHOME_PSTR("toggle")) == 0)
464 return PARSE_TOGGLE;
465
466 return PARSE_NONE;
467}
468
469static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
470 if (accuracy_decimals < 0) {
471 auto multiplier = powf(10.0f, accuracy_decimals);
472 value = roundf(value * multiplier) / multiplier;
473 accuracy_decimals = 0;
474 }
475}
476
477std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
478 char buf[VALUE_ACCURACY_MAX_LEN];
479 value_accuracy_to_buf(buf, value, accuracy_decimals);
480 return std::string(buf);
481}
482
483size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
484 normalize_accuracy_decimals(value, accuracy_decimals);
485 // snprintf returns chars that would be written (excluding null), or negative on error
486 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
487 if (len < 0)
488 return 0; // encoding error
489 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
490 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
491}
492
493size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
494 int8_t accuracy_decimals, StringRef unit_of_measurement) {
495 if (unit_of_measurement.empty()) {
496 return value_accuracy_to_buf(buf, value, accuracy_decimals);
497 }
498 normalize_accuracy_decimals(value, accuracy_decimals);
499 // snprintf returns chars that would be written (excluding null), or negative on error
500 int len = snprintf(buf.data(), buf.size(), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
501 if (len < 0)
502 return 0; // encoding error
503 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
504 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
505}
506
507int8_t step_to_accuracy_decimals(float step) {
508 // use printf %g to find number of digits based on temperature step
509 char buf[32];
510 snprintf(buf, sizeof buf, "%.5g", step);
511
512 std::string str{buf};
513 size_t dot_pos = str.find('.');
514 if (dot_pos == std::string::npos)
515 return 0;
516
517 return str.length() - dot_pos - 1;
518}
519
520// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
521static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
522 "abcdefghijklmnopqrstuvwxyz"
523 "0123456789+/";
524
525// Helper function to find the index of a base64/base64url character in the lookup table.
526// Returns the character's position (0-63) if found, or 0 if not found.
527// Supports both standard base64 (+/) and base64url (-_) alphabets.
528// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
529// This is safe because is_base64() is ALWAYS checked before calling this function,
530// preventing invalid characters from ever reaching here. The base64_decode function
531// stops processing at the first invalid character due to the is_base64() check in its
532// while loop condition, making this edge case harmless in practice.
533static inline uint8_t base64_find_char(char c) {
534 // Handle base64url variants: '-' maps to '+' (index 62), '_' maps to '/' (index 63)
535 if (c == '-')
536 return 62;
537 if (c == '_')
538 return 63;
539 const char *pos = strchr(BASE64_CHARS, c);
540 return pos ? (pos - BASE64_CHARS) : 0;
541}
542
543// Check if character is valid base64 or base64url
544static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/') || (c == '-') || (c == '_')); }
545
546std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
547
548std::string base64_encode(const uint8_t *buf, size_t buf_len) {
549 std::string ret;
550 int i = 0;
551 int j = 0;
552 char char_array_3[3];
553 char char_array_4[4];
554
555 while (buf_len--) {
556 char_array_3[i++] = *(buf++);
557 if (i == 3) {
558 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
559 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
560 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
561 char_array_4[3] = char_array_3[2] & 0x3f;
562
563 for (i = 0; (i < 4); i++)
564 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[i])];
565 i = 0;
566 }
567 }
568
569 if (i) {
570 for (j = i; j < 3; j++)
571 char_array_3[j] = '\0';
572
573 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
574 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
575 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
576 char_array_4[3] = char_array_3[2] & 0x3f;
577
578 for (j = 0; (j < i + 1); j++)
579 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
580
581 while ((i++ < 3))
582 ret += '=';
583 }
584
585 return ret;
586}
587
588size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
589 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
590}
591
592size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
593 size_t in_len = encoded_len;
594 int i = 0;
595 int j = 0;
596 size_t in = 0;
597 size_t out = 0;
598 uint8_t char_array_4[4], char_array_3[3];
599 bool truncated = false;
600
601 // SAFETY: The loop condition checks is_base64() before processing each character.
602 // This ensures base64_find_char() is only called on valid base64 characters,
603 // preventing the edge case where invalid chars would return 0 (same as 'A').
604 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
605 char_array_4[i++] = encoded_data[in];
606 in++;
607 if (i == 4) {
608 for (i = 0; i < 4; i++)
609 char_array_4[i] = base64_find_char(char_array_4[i]);
610
611 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
612 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
613 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
614
615 for (i = 0; i < 3; i++) {
616 if (out < buf_len) {
617 buf[out++] = char_array_3[i];
618 } else {
619 truncated = true;
620 }
621 }
622 i = 0;
623 }
624 }
625
626 if (i) {
627 for (j = i; j < 4; j++)
628 char_array_4[j] = 0;
629
630 for (j = 0; j < 4; j++)
631 char_array_4[j] = base64_find_char(char_array_4[j]);
632
633 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
634 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
635 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
636
637 for (j = 0; j < i - 1; j++) {
638 if (out < buf_len) {
639 buf[out++] = char_array_3[j];
640 } else {
641 truncated = true;
642 }
643 }
644 }
645
646 if (truncated) {
647 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
648 }
649
650 return out;
651}
652
653std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
654 // Calculate maximum decoded size: every 4 base64 chars = 3 bytes
655 size_t max_len = ((encoded_string.size() + 3) / 4) * 3;
656 std::vector<uint8_t> ret(max_len);
657 size_t actual_len = base64_decode(encoded_string, ret.data(), max_len);
658 ret.resize(actual_len);
659 return ret;
660}
661
666bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
667 // Decode in chunks to minimize stack usage
668 constexpr size_t chunk_bytes = 48; // 12 int32 values
669 constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
670 uint8_t chunk[chunk_bytes];
671
672 out.clear();
673
674 const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
675 size_t remaining = base64.size();
676 size_t pos = 0;
677
678 while (remaining > 0) {
679 size_t chars_to_decode = std::min(remaining, chunk_chars);
680 size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
681
682 if (decoded_len == 0)
683 return false;
684
685 // Parse little-endian int32 values
686 for (size_t i = 0; i + 3 < decoded_len; i += 4) {
687 int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
688 out.push_back(timing);
689 }
690
691 // Check for incomplete int32 in last chunk
692 if (remaining <= chunk_chars && (decoded_len % 4) != 0)
693 return false;
694
695 pos += chars_to_decode;
696 remaining -= chars_to_decode;
697 }
698
699 return !out.empty();
700}
701
702// Colors
703
704float gamma_correct(float value, float gamma) {
705 if (value <= 0.0f)
706 return 0.0f;
707 if (gamma <= 0.0f)
708 return value;
709
710 return powf(value, gamma);
711}
712float gamma_uncorrect(float value, float gamma) {
713 if (value <= 0.0f)
714 return 0.0f;
715 if (gamma <= 0.0f)
716 return value;
717
718 return powf(value, 1 / gamma);
719}
720
721void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
722 float max_color_value = std::max(std::max(red, green), blue);
723 float min_color_value = std::min(std::min(red, green), blue);
724 float delta = max_color_value - min_color_value;
725
726 if (delta == 0) {
727 hue = 0;
728 } else if (max_color_value == red) {
729 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
730 } else if (max_color_value == green) {
731 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
732 } else if (max_color_value == blue) {
733 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
734 }
735
736 if (max_color_value == 0) {
737 saturation = 0;
738 } else {
739 saturation = delta / max_color_value;
740 }
741
742 value = max_color_value;
743}
744void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
745 float chroma = value * saturation;
746 float hue_prime = fmod(hue / 60.0, 6);
747 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
748 float delta = value - chroma;
749
750 if (0 <= hue_prime && hue_prime < 1) {
751 red = chroma;
752 green = intermediate;
753 blue = 0;
754 } else if (1 <= hue_prime && hue_prime < 2) {
755 red = intermediate;
756 green = chroma;
757 blue = 0;
758 } else if (2 <= hue_prime && hue_prime < 3) {
759 red = 0;
760 green = chroma;
761 blue = intermediate;
762 } else if (3 <= hue_prime && hue_prime < 4) {
763 red = 0;
764 green = intermediate;
765 blue = chroma;
766 } else if (4 <= hue_prime && hue_prime < 5) {
767 red = intermediate;
768 green = 0;
769 blue = chroma;
770 } else if (5 <= hue_prime && hue_prime < 6) {
771 red = chroma;
772 green = 0;
773 blue = intermediate;
774 } else {
775 red = 0;
776 green = 0;
777 blue = 0;
778 }
779
780 red += delta;
781 green += delta;
782 blue += delta;
783}
784
785uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
787 if (this->started_)
788 return;
789 num_requests++;
790 this->started_ = true;
791}
793 if (!this->started_)
794 return;
795 num_requests--;
796 this->started_ = false;
797}
799
800std::string get_mac_address() {
801 uint8_t mac[6];
803 char buf[13];
805 return std::string(buf);
806}
807
809 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
810 return std::string(get_mac_address_pretty_into_buffer(buf));
811}
812
813void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
814 uint8_t mac[6];
816 format_mac_addr_lower_no_sep(mac, buf.data());
817}
818
819const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
820 uint8_t mac[6];
822 format_mac_addr_upper(mac, buf.data());
823 return buf.data();
824}
825
826#ifndef USE_ESP32
827bool has_custom_mac_address() { return false; }
828#endif
829
830bool mac_address_is_valid(const uint8_t *mac) {
831 bool is_all_zeros = true;
832 bool is_all_ones = true;
833
834 for (uint8_t i = 0; i < 6; i++) {
835 if (mac[i] != 0) {
836 is_all_zeros = false;
837 }
838 if (mac[i] != 0xFF) {
839 is_all_ones = false;
840 }
841 }
842 return !(is_all_zeros || is_all_ones);
843}
844
845void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
846 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
847 uint32_t start = micros();
848
849 const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
850 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
851 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
852 if (us > lag) {
853 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
854 while (micros() - start < us - lag)
855 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
856 }
857 while (micros() - start < us) // fine delay the remaining usecs
858 ;
859}
860
861} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:792
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:798
void start()
Start running the loop continuously.
Definition helpers.cpp:786
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
mopeka_std_values val[4]
const char *const TAG
Definition spi.cpp:7
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:159
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:712
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:73
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:261
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Definition helpers.cpp:477
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:897
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:704
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:652
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:830
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1050
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:462
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:721
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:345
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:891
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:483
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:201
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:454
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:447
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:222
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:666
va_end(args)
std::string size_t len
Definition helpers.h:692
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:93
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:294
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:353
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:148
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:808
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:228
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:507
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:27
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
size_t size_t pos
Definition helpers.h:729
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:819
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:845
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:202
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:401
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:163
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:188
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:179
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:210
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:305
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:493
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:546
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:464
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:744
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:813
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:113
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:536
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:46
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:242
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:73
size_t size_t const char * fmt
Definition helpers.h:730
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:880
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:170
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:800
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:646
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:341
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:203
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:171
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:588
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1291
@ PARSE_ON
Definition helpers.h:1293
@ PARSE_TOGGLE
Definition helpers.h:1295
@ PARSE_OFF
Definition helpers.h:1294
@ PARSE_NONE
Definition helpers.h:1292
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:281
std::string str_ctype_transform(const std::string &str)
Definition helpers.cpp:195
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:426
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:1045
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:185
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0