ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
helpers.cpp
Go to the documentation of this file.
2
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
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}
165#if __cplusplus >= 202002L
166bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
167bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
168#else
169bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
170bool str_endswith(const std::string &str, const std::string &end) {
171 return str.rfind(end) == (str.size() - end.size());
172}
173#endif
174std::string str_truncate(const std::string &str, size_t length) {
175 return str.length() > length ? str.substr(0, length) : str;
176}
177std::string str_until(const char *str, char ch) {
178 const char *pos = strchr(str, ch);
179 return pos == nullptr ? std::string(str) : std::string(str, pos - str);
180}
181std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
182// wrapper around std::transform to run safely on functions from the ctype.h header
183// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
184template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
185 std::string result;
186 result.resize(str.length());
187 std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
188 return result;
189}
190std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
191std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
192std::string str_snake_case(const std::string &str) {
193 std::string result = str;
194 for (char &c : result) {
195 c = to_snake_case_char(c);
196 }
197 return result;
198}
199std::string str_sanitize(const std::string &str) {
200 std::string result = str;
201 for (char &c : result) {
202 c = to_sanitized_char(c);
203 }
204 return result;
205}
206std::string str_snprintf(const char *fmt, size_t len, ...) {
207 std::string str;
208 va_list args;
209
210 str.resize(len);
211 va_start(args, len);
212 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
213 va_end(args);
214
215 if (out_length < len)
216 str.resize(out_length);
217
218 return str;
219}
220std::string str_sprintf(const char *fmt, ...) {
221 std::string str;
222 va_list args;
223
224 va_start(args, fmt);
225 size_t length = vsnprintf(nullptr, 0, fmt, args);
226 va_end(args);
227
228 str.resize(length);
229 va_start(args, fmt);
230 vsnprintf(&str[0], length + 1, fmt, args);
231 va_end(args);
232
233 return str;
234}
235
236// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
237static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
238
239size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
240 const char *suffix_ptr, size_t suffix_len) {
241 size_t total_len = name_len + 1 + suffix_len;
242
243 // Silently truncate if needed: prioritize keeping the full suffix
244 if (total_len >= buffer_size) {
245 // NOTE: This calculation could underflow if suffix_len >= buffer_size - 2,
246 // but this is safe because this helper is only called with small suffixes:
247 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
248 name_len = buffer_size - suffix_len - 2; // -2 for separator and null terminator
249 total_len = name_len + 1 + suffix_len;
250 }
251
252 memcpy(buffer, name, name_len);
253 buffer[name_len] = sep;
254 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
255 buffer[total_len] = '\0';
256 return total_len;
257}
258
259std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
260 size_t suffix_len) {
261 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
262 size_t len = make_name_with_suffix_to(buffer, sizeof(buffer), name, name_len, sep, suffix_ptr, suffix_len);
263 return std::string(buffer, len);
264}
265
266std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
267 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
268}
269
270// Parsing & formatting
271
272size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
273 size_t chars = std::min(length, 2 * count);
274 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
275 uint8_t val = parse_hex_char(*str);
276 if (val > 15)
277 return 0;
278 data[i >> 1] = (i & 1) ? data[i >> 1] | val : val << 4;
279 }
280 return chars;
281}
282
283std::string format_mac_address_pretty(const uint8_t *mac) {
284 char buf[18];
285 format_mac_addr_upper(mac, buf);
286 return std::string(buf);
287}
288
289// Internal helper for hex formatting - base is 'a' for lowercase or 'A' for uppercase
290static char *format_hex_internal(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator,
291 char base) {
292 if (length == 0) {
293 buffer[0] = '\0';
294 return buffer;
295 }
296 // With separator: total length is 3*length (2*length hex chars, (length-1) separators, 1 null terminator)
297 // Without separator: total length is 2*length + 1 (2*length hex chars, 1 null terminator)
298 uint8_t stride = separator ? 3 : 2;
299 size_t max_bytes = separator ? (buffer_size / stride) : ((buffer_size - 1) / stride);
300 if (max_bytes == 0) {
301 buffer[0] = '\0';
302 return buffer;
303 }
304 if (length > max_bytes) {
305 length = max_bytes;
306 }
307 for (size_t i = 0; i < length; i++) {
308 size_t pos = i * stride;
309 buffer[pos] = format_hex_char(data[i] >> 4, base);
310 buffer[pos + 1] = format_hex_char(data[i] & 0x0F, base);
311 if (separator && i < length - 1) {
312 buffer[pos + 2] = separator;
313 }
314 }
315 buffer[length * stride - (separator ? 1 : 0)] = '\0';
316 return buffer;
317}
318
319char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length) {
320 return format_hex_internal(buffer, buffer_size, data, length, 0, 'a');
321}
322
323std::string format_hex(const uint8_t *data, size_t length) {
324 std::string ret;
325 ret.resize(length * 2);
326 format_hex_to(&ret[0], length * 2 + 1, data, length);
327 return ret;
328}
329std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
330
331char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator) {
332 return format_hex_internal(buffer, buffer_size, data, length, separator, 'A');
333}
334
335// Shared implementation for uint8_t and string hex formatting
336static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
337 if (data == nullptr || length == 0)
338 return "";
339 std::string ret;
340 size_t hex_len = separator ? (length * 3 - 1) : (length * 2);
341 ret.resize(hex_len);
342 format_hex_pretty_to(&ret[0], hex_len + 1, data, length, separator);
343 if (show_length && length > 4)
344 return ret + " (" + std::to_string(length) + ")";
345 return ret;
346}
347
348std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
349 return format_hex_pretty_uint8(data, length, separator, show_length);
350}
351std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
352 return format_hex_pretty(data.data(), data.size(), separator, show_length);
353}
354
355std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
356 if (data == nullptr || length == 0)
357 return "";
358 std::string ret;
359 uint8_t multiple = separator ? 5 : 4; // 5 if separator is not \0, 4 otherwise
360 ret.resize(multiple * length - (separator ? 1 : 0));
361 for (size_t i = 0; i < length; i++) {
362 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
363 ret[multiple * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
364 ret[multiple * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
365 ret[multiple * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
366 if (separator && i != length - 1)
367 ret[multiple * i + 4] = separator;
368 }
369 if (show_length && length > 4)
370 return ret + " (" + std::to_string(length) + ")";
371 return ret;
372}
373std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
374 return format_hex_pretty(data.data(), data.size(), separator, show_length);
375}
376std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
377 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
378}
379
380std::string format_bin(const uint8_t *data, size_t length) {
381 std::string result;
382 result.resize(length * 8);
383 for (size_t byte_idx = 0; byte_idx < length; byte_idx++) {
384 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
385 result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
386 }
387 }
388
389 return result;
390}
391
392ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
393 if (on == nullptr && strcasecmp(str, "on") == 0)
394 return PARSE_ON;
395 if (on != nullptr && strcasecmp(str, on) == 0)
396 return PARSE_ON;
397 if (off == nullptr && strcasecmp(str, "off") == 0)
398 return PARSE_OFF;
399 if (off != nullptr && strcasecmp(str, off) == 0)
400 return PARSE_OFF;
401 if (strcasecmp(str, "toggle") == 0)
402 return PARSE_TOGGLE;
403
404 return PARSE_NONE;
405}
406
407static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
408 if (accuracy_decimals < 0) {
409 auto multiplier = powf(10.0f, accuracy_decimals);
410 value = roundf(value * multiplier) / multiplier;
411 accuracy_decimals = 0;
412 }
413}
414
415std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
416 char buf[VALUE_ACCURACY_MAX_LEN];
417 value_accuracy_to_buf(buf, value, accuracy_decimals);
418 return std::string(buf);
419}
420
421size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals) {
422 normalize_accuracy_decimals(value, accuracy_decimals);
423 // snprintf returns chars that would be written (excluding null), or negative on error
424 int len = snprintf(buf.data(), buf.size(), "%.*f", accuracy_decimals, value);
425 if (len < 0)
426 return 0; // encoding error
427 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
428 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
429}
430
431size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
432 int8_t accuracy_decimals, StringRef unit_of_measurement) {
433 if (unit_of_measurement.empty()) {
434 return value_accuracy_to_buf(buf, value, accuracy_decimals);
435 }
436 normalize_accuracy_decimals(value, accuracy_decimals);
437 // snprintf returns chars that would be written (excluding null), or negative on error
438 int len = snprintf(buf.data(), buf.size(), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
439 if (len < 0)
440 return 0; // encoding error
441 // On truncation, snprintf returns would-be length; actual written is buf.size() - 1
442 return static_cast<size_t>(len) >= buf.size() ? buf.size() - 1 : static_cast<size_t>(len);
443}
444
445int8_t step_to_accuracy_decimals(float step) {
446 // use printf %g to find number of digits based on temperature step
447 char buf[32];
448 snprintf(buf, sizeof buf, "%.5g", step);
449
450 std::string str{buf};
451 size_t dot_pos = str.find('.');
452 if (dot_pos == std::string::npos)
453 return 0;
454
455 return str.length() - dot_pos - 1;
456}
457
458// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
459static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
460 "abcdefghijklmnopqrstuvwxyz"
461 "0123456789+/";
462
463// Helper function to find the index of a base64 character in the lookup table.
464// Returns the character's position (0-63) if found, or 0 if not found.
465// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
466// This is safe because is_base64() is ALWAYS checked before calling this function,
467// preventing invalid characters from ever reaching here. The base64_decode function
468// stops processing at the first invalid character due to the is_base64() check in its
469// while loop condition, making this edge case harmless in practice.
470static inline uint8_t base64_find_char(char c) {
471 const char *pos = strchr(BASE64_CHARS, c);
472 return pos ? (pos - BASE64_CHARS) : 0;
473}
474
475static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
476
477std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
478
479std::string base64_encode(const uint8_t *buf, size_t buf_len) {
480 std::string ret;
481 int i = 0;
482 int j = 0;
483 char char_array_3[3];
484 char char_array_4[4];
485
486 while (buf_len--) {
487 char_array_3[i++] = *(buf++);
488 if (i == 3) {
489 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
490 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
491 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
492 char_array_4[3] = char_array_3[2] & 0x3f;
493
494 for (i = 0; (i < 4); i++)
495 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[i])];
496 i = 0;
497 }
498 }
499
500 if (i) {
501 for (j = i; j < 3; j++)
502 char_array_3[j] = '\0';
503
504 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
505 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
506 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
507 char_array_4[3] = char_array_3[2] & 0x3f;
508
509 for (j = 0; (j < i + 1); j++)
510 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
511
512 while ((i++ < 3))
513 ret += '=';
514 }
515
516 return ret;
517}
518
519size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
520 return base64_decode(reinterpret_cast<const uint8_t *>(encoded_string.data()), encoded_string.size(), buf, buf_len);
521}
522
523size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) {
524 size_t in_len = encoded_len;
525 int i = 0;
526 int j = 0;
527 size_t in = 0;
528 size_t out = 0;
529 uint8_t char_array_4[4], char_array_3[3];
530 bool truncated = false;
531
532 // SAFETY: The loop condition checks is_base64() before processing each character.
533 // This ensures base64_find_char() is only called on valid base64 characters,
534 // preventing the edge case where invalid chars would return 0 (same as 'A').
535 while (in_len-- && (encoded_data[in] != '=') && is_base64(encoded_data[in])) {
536 char_array_4[i++] = encoded_data[in];
537 in++;
538 if (i == 4) {
539 for (i = 0; i < 4; i++)
540 char_array_4[i] = base64_find_char(char_array_4[i]);
541
542 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
543 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
544 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
545
546 for (i = 0; i < 3; i++) {
547 if (out < buf_len) {
548 buf[out++] = char_array_3[i];
549 } else {
550 truncated = true;
551 }
552 }
553 i = 0;
554 }
555 }
556
557 if (i) {
558 for (j = i; j < 4; j++)
559 char_array_4[j] = 0;
560
561 for (j = 0; j < 4; j++)
562 char_array_4[j] = base64_find_char(char_array_4[j]);
563
564 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
565 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
566 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
567
568 for (j = 0; j < i - 1; j++) {
569 if (out < buf_len) {
570 buf[out++] = char_array_3[j];
571 } else {
572 truncated = true;
573 }
574 }
575 }
576
577 if (truncated) {
578 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
579 }
580
581 return out;
582}
583
584std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
585 // Calculate maximum decoded size: every 4 base64 chars = 3 bytes
586 size_t max_len = ((encoded_string.size() + 3) / 4) * 3;
587 std::vector<uint8_t> ret(max_len);
588 size_t actual_len = base64_decode(encoded_string, ret.data(), max_len);
589 ret.resize(actual_len);
590 return ret;
591}
592
593// Colors
594
595float gamma_correct(float value, float gamma) {
596 if (value <= 0.0f)
597 return 0.0f;
598 if (gamma <= 0.0f)
599 return value;
600
601 return powf(value, gamma);
602}
603float gamma_uncorrect(float value, float gamma) {
604 if (value <= 0.0f)
605 return 0.0f;
606 if (gamma <= 0.0f)
607 return value;
608
609 return powf(value, 1 / gamma);
610}
611
612void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
613 float max_color_value = std::max(std::max(red, green), blue);
614 float min_color_value = std::min(std::min(red, green), blue);
615 float delta = max_color_value - min_color_value;
616
617 if (delta == 0) {
618 hue = 0;
619 } else if (max_color_value == red) {
620 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
621 } else if (max_color_value == green) {
622 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
623 } else if (max_color_value == blue) {
624 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
625 }
626
627 if (max_color_value == 0) {
628 saturation = 0;
629 } else {
630 saturation = delta / max_color_value;
631 }
632
633 value = max_color_value;
634}
635void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
636 float chroma = value * saturation;
637 float hue_prime = fmod(hue / 60.0, 6);
638 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
639 float delta = value - chroma;
640
641 if (0 <= hue_prime && hue_prime < 1) {
642 red = chroma;
643 green = intermediate;
644 blue = 0;
645 } else if (1 <= hue_prime && hue_prime < 2) {
646 red = intermediate;
647 green = chroma;
648 blue = 0;
649 } else if (2 <= hue_prime && hue_prime < 3) {
650 red = 0;
651 green = chroma;
652 blue = intermediate;
653 } else if (3 <= hue_prime && hue_prime < 4) {
654 red = 0;
655 green = intermediate;
656 blue = chroma;
657 } else if (4 <= hue_prime && hue_prime < 5) {
658 red = intermediate;
659 green = 0;
660 blue = chroma;
661 } else if (5 <= hue_prime && hue_prime < 6) {
662 red = chroma;
663 green = 0;
664 blue = intermediate;
665 } else {
666 red = 0;
667 green = 0;
668 blue = 0;
669 }
670
671 red += delta;
672 green += delta;
673 blue += delta;
674}
675
676uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
678 if (this->started_)
679 return;
680 num_requests++;
681 this->started_ = true;
682}
684 if (!this->started_)
685 return;
686 num_requests--;
687 this->started_ = false;
688}
690
691std::string get_mac_address() {
692 uint8_t mac[6];
694 char buf[13];
696 return std::string(buf);
697}
698
700 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
701 return std::string(get_mac_address_pretty_into_buffer(buf));
702}
703
704void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
705 uint8_t mac[6];
707 format_mac_addr_lower_no_sep(mac, buf.data());
708}
709
710const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
711 uint8_t mac[6];
713 format_mac_addr_upper(mac, buf.data());
714 return buf.data();
715}
716
717#ifndef USE_ESP32
718bool has_custom_mac_address() { return false; }
719#endif
720
721bool mac_address_is_valid(const uint8_t *mac) {
722 bool is_all_zeros = true;
723 bool is_all_ones = true;
724
725 for (uint8_t i = 0; i < 6; i++) {
726 if (mac[i] != 0) {
727 is_all_zeros = false;
728 }
729 if (mac[i] != 0xFF) {
730 is_all_ones = false;
731 }
732 }
733 return !(is_all_zeros || is_all_ones);
734}
735
736void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
737 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
738 uint32_t start = micros();
739
740 const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
741 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
742 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
743 if (us > lag) {
744 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
745 while (micros() - start < us - lag)
746 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
747 }
748 while (micros() - start < us) // fine delay the remaining usecs
749 ;
750}
751
752} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:683
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:689
void start()
Start running the loop continuously.
Definition helpers.cpp:677
StringRef is a reference to a string owned by something else.
Definition string_ref.h:22
constexpr const char * c_str() const
Definition string_ref.h:69
constexpr bool empty() const
Definition string_ref.h:71
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:158
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:603
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:239
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Create a string from a value and an accuracy in decimals.
Definition helpers.cpp:415
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:687
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:595
void 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:762
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:526
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:721
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:767
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:386
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:612
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:323
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:681
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:421
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:190
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:392
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:380
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:199
std::string size_t len
Definition helpers.h:533
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:272
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:331
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:699
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:206
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:445
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:710
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:736
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:191
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:348
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:177
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:283
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:431
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:477
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:388
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:635
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:704
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:220
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:670
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:166
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:691
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:521
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:319
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:192
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:167
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:519
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:940
@ PARSE_ON
Definition helpers.h:942
@ PARSE_TOGGLE
Definition helpers.h:944
@ PARSE_OFF
Definition helpers.h:943
@ PARSE_NONE
Definition helpers.h:941
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:259
std::string str_ctype_transform(const std::string &str)
Definition helpers.cpp:184
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:174
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0