ESPHome 2025.10.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
146uint32_t fnv1_hash(const char *str) {
147 uint32_t hash = 2166136261UL;
148 if (str) {
149 while (*str) {
150 hash *= 16777619UL;
151 hash ^= *str++;
152 }
153 }
154 return hash;
155}
156
157float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
158
159// Strings
160
161bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
162 return strcasecmp(a.c_str(), b.c_str()) == 0;
163}
164#if __cplusplus >= 202002L
165bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
166bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
167#else
168bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
169bool str_endswith(const std::string &str, const std::string &end) {
170 return str.rfind(end) == (str.size() - end.size());
171}
172#endif
173std::string str_truncate(const std::string &str, size_t length) {
174 return str.length() > length ? str.substr(0, length) : str;
175}
176std::string str_until(const char *str, char ch) {
177 const char *pos = strchr(str, ch);
178 return pos == nullptr ? std::string(str) : std::string(str, pos - str);
179}
180std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
181// wrapper around std::transform to run safely on functions from the ctype.h header
182// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
183template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
184 std::string result;
185 result.resize(str.length());
186 std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
187 return result;
188}
189std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
190std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
191std::string str_snake_case(const std::string &str) {
192 std::string result;
193 result.resize(str.length());
194 std::transform(str.begin(), str.end(), result.begin(), ::tolower);
195 std::replace(result.begin(), result.end(), ' ', '_');
196 return result;
197}
198std::string str_sanitize(const std::string &str) {
199 std::string out = str;
200 std::replace_if(
201 out.begin(), out.end(),
202 [](const char &c) {
203 return c != '-' && c != '_' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z');
204 },
205 '_');
206 return out;
207}
208std::string str_snprintf(const char *fmt, size_t len, ...) {
209 std::string str;
210 va_list args;
211
212 str.resize(len);
213 va_start(args, len);
214 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
215 va_end(args);
216
217 if (out_length < len)
218 str.resize(out_length);
219
220 return str;
221}
222std::string str_sprintf(const char *fmt, ...) {
223 std::string str;
224 va_list args;
225
226 va_start(args, fmt);
227 size_t length = vsnprintf(nullptr, 0, fmt, args);
228 va_end(args);
229
230 str.resize(length);
231 va_start(args, fmt);
232 vsnprintf(&str[0], length + 1, fmt, args);
233 va_end(args);
234
235 return str;
236}
237
238// Parsing & formatting
239
240size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
241 uint8_t val;
242 size_t chars = std::min(length, 2 * count);
243 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
244 if (*str >= '0' && *str <= '9') {
245 val = *str - '0';
246 } else if (*str >= 'A' && *str <= 'F') {
247 val = 10 + (*str - 'A');
248 } else if (*str >= 'a' && *str <= 'f') {
249 val = 10 + (*str - 'a');
250 } else {
251 return 0;
252 }
253 data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
254 }
255 return chars;
256}
257
258std::string format_mac_address_pretty(const uint8_t *mac) {
259 char buf[18];
260 format_mac_addr_upper(mac, buf);
261 return std::string(buf);
262}
263
264std::string format_hex(const uint8_t *data, size_t length) {
265 std::string ret;
266 ret.resize(length * 2);
267 for (size_t i = 0; i < length; i++) {
268 ret[2 * i] = format_hex_char(data[i] >> 4);
269 ret[2 * i + 1] = format_hex_char(data[i] & 0x0F);
270 }
271 return ret;
272}
273std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
274
275// Shared implementation for uint8_t and string hex formatting
276static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
277 if (data == nullptr || length == 0)
278 return "";
279 std::string ret;
280 uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise
281 ret.resize(multiple * length - (separator ? 1 : 0));
282 for (size_t i = 0; i < length; i++) {
283 ret[multiple * i] = format_hex_pretty_char(data[i] >> 4);
284 ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
285 if (separator && i != length - 1)
286 ret[multiple * i + 2] = separator;
287 }
288 if (show_length && length > 4)
289 return ret + " (" + std::to_string(length) + ")";
290 return ret;
291}
292
293std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
294 return format_hex_pretty_uint8(data, length, separator, show_length);
295}
296std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
297 return format_hex_pretty(data.data(), data.size(), separator, show_length);
298}
299
300std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
301 if (data == nullptr || length == 0)
302 return "";
303 std::string ret;
304 uint8_t multiple = separator ? 5 : 4; // 5 if separator is not \0, 4 otherwise
305 ret.resize(multiple * length - (separator ? 1 : 0));
306 for (size_t i = 0; i < length; i++) {
307 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
308 ret[multiple * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
309 ret[multiple * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
310 ret[multiple * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
311 if (separator && i != length - 1)
312 ret[multiple * i + 4] = separator;
313 }
314 if (show_length && length > 4)
315 return ret + " (" + std::to_string(length) + ")";
316 return ret;
317}
318std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
319 return format_hex_pretty(data.data(), data.size(), separator, show_length);
320}
321std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
322 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
323}
324
325std::string format_bin(const uint8_t *data, size_t length) {
326 std::string result;
327 result.resize(length * 8);
328 for (size_t byte_idx = 0; byte_idx < length; byte_idx++) {
329 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
330 result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
331 }
332 }
333
334 return result;
335}
336
337ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
338 if (on == nullptr && strcasecmp(str, "on") == 0)
339 return PARSE_ON;
340 if (on != nullptr && strcasecmp(str, on) == 0)
341 return PARSE_ON;
342 if (off == nullptr && strcasecmp(str, "off") == 0)
343 return PARSE_OFF;
344 if (off != nullptr && strcasecmp(str, off) == 0)
345 return PARSE_OFF;
346 if (strcasecmp(str, "toggle") == 0)
347 return PARSE_TOGGLE;
348
349 return PARSE_NONE;
350}
351
352static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
353 if (accuracy_decimals < 0) {
354 auto multiplier = powf(10.0f, accuracy_decimals);
355 value = roundf(value * multiplier) / multiplier;
356 accuracy_decimals = 0;
357 }
358}
359
360std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
361 normalize_accuracy_decimals(value, accuracy_decimals);
362 char tmp[32]; // should be enough, but we should maybe improve this at some point.
363 snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
364 return std::string(tmp);
365}
366
367std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement) {
368 normalize_accuracy_decimals(value, accuracy_decimals);
369 // Buffer sized for float (up to ~15 chars) + space + typical UOM (usually <20 chars like "μS/cm")
370 // snprintf truncates safely if exceeded, though ESPHome UOMs are typically short
371 char tmp[64];
372 if (unit_of_measurement.empty()) {
373 snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
374 } else {
375 snprintf(tmp, sizeof(tmp), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
376 }
377 return std::string(tmp);
378}
379
380int8_t step_to_accuracy_decimals(float step) {
381 // use printf %g to find number of digits based on temperature step
382 char buf[32];
383 snprintf(buf, sizeof buf, "%.5g", step);
384
385 std::string str{buf};
386 size_t dot_pos = str.find('.');
387 if (dot_pos == std::string::npos)
388 return 0;
389
390 return str.length() - dot_pos - 1;
391}
392
393// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
394static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
395 "abcdefghijklmnopqrstuvwxyz"
396 "0123456789+/";
397
398// Helper function to find the index of a base64 character in the lookup table.
399// Returns the character's position (0-63) if found, or 0 if not found.
400// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
401// This is safe because is_base64() is ALWAYS checked before calling this function,
402// preventing invalid characters from ever reaching here. The base64_decode function
403// stops processing at the first invalid character due to the is_base64() check in its
404// while loop condition, making this edge case harmless in practice.
405static inline uint8_t base64_find_char(char c) {
406 const char *pos = strchr(BASE64_CHARS, c);
407 return pos ? (pos - BASE64_CHARS) : 0;
408}
409
410static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
411
412std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
413
414std::string base64_encode(const uint8_t *buf, size_t buf_len) {
415 std::string ret;
416 int i = 0;
417 int j = 0;
418 char char_array_3[3];
419 char char_array_4[4];
420
421 while (buf_len--) {
422 char_array_3[i++] = *(buf++);
423 if (i == 3) {
424 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
425 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
426 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
427 char_array_4[3] = char_array_3[2] & 0x3f;
428
429 for (i = 0; (i < 4); i++)
430 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[i])];
431 i = 0;
432 }
433 }
434
435 if (i) {
436 for (j = i; j < 3; j++)
437 char_array_3[j] = '\0';
438
439 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
440 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
441 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
442 char_array_4[3] = char_array_3[2] & 0x3f;
443
444 for (j = 0; (j < i + 1); j++)
445 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
446
447 while ((i++ < 3))
448 ret += '=';
449 }
450
451 return ret;
452}
453
454size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
455 std::vector<uint8_t> decoded = base64_decode(encoded_string);
456 if (decoded.size() > buf_len) {
457 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
458 decoded.resize(buf_len);
459 }
460 memcpy(buf, decoded.data(), decoded.size());
461 return decoded.size();
462}
463
464std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
465 int in_len = encoded_string.size();
466 int i = 0;
467 int j = 0;
468 int in = 0;
469 uint8_t char_array_4[4], char_array_3[3];
470 std::vector<uint8_t> ret;
471
472 // SAFETY: The loop condition checks is_base64() before processing each character.
473 // This ensures base64_find_char() is only called on valid base64 characters,
474 // preventing the edge case where invalid chars would return 0 (same as 'A').
475 while (in_len-- && (encoded_string[in] != '=') && is_base64(encoded_string[in])) {
476 char_array_4[i++] = encoded_string[in];
477 in++;
478 if (i == 4) {
479 for (i = 0; i < 4; i++)
480 char_array_4[i] = base64_find_char(char_array_4[i]);
481
482 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
483 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
484 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
485
486 for (i = 0; (i < 3); i++)
487 ret.push_back(char_array_3[i]);
488 i = 0;
489 }
490 }
491
492 if (i) {
493 for (j = i; j < 4; j++)
494 char_array_4[j] = 0;
495
496 for (j = 0; j < 4; j++)
497 char_array_4[j] = base64_find_char(char_array_4[j]);
498
499 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
500 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
501 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
502
503 for (j = 0; (j < i - 1); j++)
504 ret.push_back(char_array_3[j]);
505 }
506
507 return ret;
508}
509
510// Colors
511
512float gamma_correct(float value, float gamma) {
513 if (value <= 0.0f)
514 return 0.0f;
515 if (gamma <= 0.0f)
516 return value;
517
518 return powf(value, gamma);
519}
520float gamma_uncorrect(float value, float gamma) {
521 if (value <= 0.0f)
522 return 0.0f;
523 if (gamma <= 0.0f)
524 return value;
525
526 return powf(value, 1 / gamma);
527}
528
529void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
530 float max_color_value = std::max(std::max(red, green), blue);
531 float min_color_value = std::min(std::min(red, green), blue);
532 float delta = max_color_value - min_color_value;
533
534 if (delta == 0) {
535 hue = 0;
536 } else if (max_color_value == red) {
537 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
538 } else if (max_color_value == green) {
539 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
540 } else if (max_color_value == blue) {
541 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
542 }
543
544 if (max_color_value == 0) {
545 saturation = 0;
546 } else {
547 saturation = delta / max_color_value;
548 }
549
550 value = max_color_value;
551}
552void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
553 float chroma = value * saturation;
554 float hue_prime = fmod(hue / 60.0, 6);
555 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
556 float delta = value - chroma;
557
558 if (0 <= hue_prime && hue_prime < 1) {
559 red = chroma;
560 green = intermediate;
561 blue = 0;
562 } else if (1 <= hue_prime && hue_prime < 2) {
563 red = intermediate;
564 green = chroma;
565 blue = 0;
566 } else if (2 <= hue_prime && hue_prime < 3) {
567 red = 0;
568 green = chroma;
569 blue = intermediate;
570 } else if (3 <= hue_prime && hue_prime < 4) {
571 red = 0;
572 green = intermediate;
573 blue = chroma;
574 } else if (4 <= hue_prime && hue_prime < 5) {
575 red = intermediate;
576 green = 0;
577 blue = chroma;
578 } else if (5 <= hue_prime && hue_prime < 6) {
579 red = chroma;
580 green = 0;
581 blue = intermediate;
582 } else {
583 red = 0;
584 green = 0;
585 blue = 0;
586 }
587
588 red += delta;
589 green += delta;
590 blue += delta;
591}
592
593uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
595 if (this->started_)
596 return;
597 num_requests++;
598 this->started_ = true;
599}
601 if (!this->started_)
602 return;
603 num_requests--;
604 this->started_ = false;
605}
607
608std::string get_mac_address() {
609 uint8_t mac[6];
611 char buf[13];
613 return std::string(buf);
614}
615
617 uint8_t mac[6];
619 return format_mac_address_pretty(mac);
620}
621
622#ifndef USE_ESP32
623bool has_custom_mac_address() { return false; }
624#endif
625
626bool mac_address_is_valid(const uint8_t *mac) {
627 bool is_all_zeros = true;
628 bool is_all_ones = true;
629
630 for (uint8_t i = 0; i < 6; i++) {
631 if (mac[i] != 0) {
632 is_all_zeros = false;
633 }
634 if (mac[i] != 0xFF) {
635 is_all_ones = false;
636 }
637 }
638 return !(is_all_zeros || is_all_ones);
639}
640
641void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
642 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
643 uint32_t start = micros();
644
645 const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
646 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
647 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
648 if (us > lag) {
649 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
650 while (micros() - start < us - lag)
651 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
652 }
653 while (micros() - start < us) // fine delay the remaining usecs
654 ;
655}
656
657} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:600
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:606
void start()
Start running the loop continuously.
Definition helpers.cpp:594
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:8
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:157
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:520
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
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:360
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing) This always uses uppercase (...
Definition helpers.h:412
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:512
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:415
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:626
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:427
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:529
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:264
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:189
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:337
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:325
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:198
std::string size_t len
Definition helpers.h:304
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:93
std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Create a string from a value, an accuracy in decimals, and a unit of measurement.
Definition helpers.cpp:367
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:240
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:146
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:616
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:208
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:380
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:30
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
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:641
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:190
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:293
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:161
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:176
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:258
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:412
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:552
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:222
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
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:165
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
Definition helpers.h:408
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:608
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:191
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:166
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:454
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:605
@ PARSE_ON
Definition helpers.h:607
@ PARSE_TOGGLE
Definition helpers.h:609
@ PARSE_OFF
Definition helpers.h:608
@ PARSE_NONE
Definition helpers.h:606
std::string str_ctype_transform(const std::string &str)
Definition helpers.cpp:183
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:173
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0