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