ESPHome 2025.7.0
Loading...
Searching...
No Matches
helpers.cpp
Go to the documentation of this file.
2
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7#include <strings.h>
8#include <algorithm>
9#include <cctype>
10#include <cmath>
11#include <cstdarg>
12#include <cstdio>
13#include <cstring>
14
15#ifdef USE_ESP32
16#include "rom/crc.h"
17#endif
18
19namespace esphome {
20
21static const char *const TAG = "helpers";
22
23static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
24 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
25static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
26 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
27
28#ifndef USE_ESP32
29static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
30 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
31static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
32 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
33#endif
34
35#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
36static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
37 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
38static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
39 0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
40#endif
41
42// Mathematics
43
44uint8_t crc8(const uint8_t *data, uint8_t len) {
45 uint8_t crc = 0;
46
47 while ((len--) != 0u) {
48 uint8_t inbyte = *data++;
49 for (uint8_t i = 8; i != 0u; i--) {
50 bool mix = (crc ^ inbyte) & 0x01;
51 crc >>= 1;
52 if (mix)
53 crc ^= 0x8C;
54 inbyte >>= 1;
55 }
56 }
57 return crc;
58}
59
60uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout) {
61#ifdef USE_ESP32
62 if (reverse_poly == 0x8408) {
63 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
64 return refout ? crc : (crc ^ 0xffff);
65 }
66#endif
67 if (refin) {
68 crc ^= 0xffff;
69 }
70#ifndef USE_ESP32
71 if (reverse_poly == 0x8408) {
72 while (len--) {
73 uint8_t combo = crc ^ (uint8_t) *data++;
74 crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
75 }
76 } else
77#endif
78 {
79 if (reverse_poly == 0xa001) {
80 while (len--) {
81 uint8_t combo = crc ^ (uint8_t) *data++;
82 crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
83 }
84 } else {
85 while (len--) {
86 crc ^= *data++;
87 for (uint8_t i = 0; i < 8; i++) {
88 if (crc & 0x0001) {
89 crc = (crc >> 1) ^ reverse_poly;
90 } else {
91 crc >>= 1;
92 }
93 }
94 }
95 }
96 }
97 return refout ? (crc ^ 0xffff) : crc;
98}
99
100uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout) {
101#if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32S2)
102 if (poly == 0x1021) {
103 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
104 return refout ? crc : (crc ^ 0xffff);
105 }
106#endif
107 if (refin) {
108 crc ^= 0xffff;
109 }
110#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
111 if (poly == 0x1021) {
112 while (len--) {
113 uint8_t combo = (crc >> 8) ^ *data++;
114 crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
115 }
116 } else {
117#endif
118 while (len--) {
119 crc ^= (((uint16_t) *data++) << 8);
120 for (uint8_t i = 0; i < 8; i++) {
121 if (crc & 0x8000) {
122 crc = (crc << 1) ^ poly;
123 } else {
124 crc <<= 1;
125 }
126 }
127 }
128#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
129 }
130#endif
131 return refout ? (crc ^ 0xffff) : crc;
132}
133
134uint32_t fnv1_hash(const std::string &str) {
135 uint32_t hash = 2166136261UL;
136 for (char c : str) {
137 hash *= 16777619UL;
138 hash ^= c;
139 }
140 return hash;
141}
142
143float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
144
145// Strings
146
147bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
148 return strcasecmp(a.c_str(), b.c_str()) == 0;
149}
150#if __cplusplus >= 202002L
151bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
152bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
153#else
154bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
155bool str_endswith(const std::string &str, const std::string &end) {
156 return str.rfind(end) == (str.size() - end.size());
157}
158#endif
159std::string str_truncate(const std::string &str, size_t length) {
160 return str.length() > length ? str.substr(0, length) : str;
161}
162std::string str_until(const char *str, char ch) {
163 const char *pos = strchr(str, ch);
164 return pos == nullptr ? std::string(str) : std::string(str, pos - str);
165}
166std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
167// wrapper around std::transform to run safely on functions from the ctype.h header
168// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
169template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
170 std::string result;
171 result.resize(str.length());
172 std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
173 return result;
174}
175std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
176std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
177std::string str_snake_case(const std::string &str) {
178 std::string result;
179 result.resize(str.length());
180 std::transform(str.begin(), str.end(), result.begin(), ::tolower);
181 std::replace(result.begin(), result.end(), ' ', '_');
182 return result;
183}
184std::string str_sanitize(const std::string &str) {
185 std::string out = str;
186 std::replace_if(
187 out.begin(), out.end(),
188 [](const char &c) {
189 return c != '-' && c != '_' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z');
190 },
191 '_');
192 return out;
193}
194std::string str_snprintf(const char *fmt, size_t len, ...) {
195 std::string str;
196 va_list args;
197
198 str.resize(len);
199 va_start(args, len);
200 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
201 va_end(args);
202
203 if (out_length < len)
204 str.resize(out_length);
205
206 return str;
207}
208std::string str_sprintf(const char *fmt, ...) {
209 std::string str;
210 va_list args;
211
212 va_start(args, fmt);
213 size_t length = vsnprintf(nullptr, 0, fmt, args);
214 va_end(args);
215
216 str.resize(length);
217 va_start(args, fmt);
218 vsnprintf(&str[0], length + 1, fmt, args);
219 va_end(args);
220
221 return str;
222}
223
224// Parsing & formatting
225
226size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
227 uint8_t val;
228 size_t chars = std::min(length, 2 * count);
229 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
230 if (*str >= '0' && *str <= '9') {
231 val = *str - '0';
232 } else if (*str >= 'A' && *str <= 'F') {
233 val = 10 + (*str - 'A');
234 } else if (*str >= 'a' && *str <= 'f') {
235 val = 10 + (*str - 'a');
236 } else {
237 return 0;
238 }
239 data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
240 }
241 return chars;
242}
243
244std::string format_mac_address_pretty(const uint8_t *mac) {
245 return str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
246}
247
248static char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
249std::string format_hex(const uint8_t *data, size_t length) {
250 std::string ret;
251 ret.resize(length * 2);
252 for (size_t i = 0; i < length; i++) {
253 ret[2 * i] = format_hex_char((data[i] & 0xF0) >> 4);
254 ret[2 * i + 1] = format_hex_char(data[i] & 0x0F);
255 }
256 return ret;
257}
258std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
259
260static char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
261std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
262 if (data == nullptr || length == 0)
263 return "";
264 std::string ret;
265 uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise
266 ret.resize(multiple * length - (separator ? 1 : 0));
267 for (size_t i = 0; i < length; i++) {
268 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4);
269 ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
270 if (separator && i != length - 1)
271 ret[multiple * i + 2] = separator;
272 }
273 if (show_length && length > 4)
274 return ret + " (" + std::to_string(length) + ")";
275 return ret;
276}
277std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
278 return format_hex_pretty(data.data(), data.size(), separator, show_length);
279}
280
281std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
282 if (data == nullptr || length == 0)
283 return "";
284 std::string ret;
285 uint8_t multiple = separator ? 5 : 4; // 5 if separator is not \0, 4 otherwise
286 ret.resize(multiple * length - (separator ? 1 : 0));
287 for (size_t i = 0; i < length; i++) {
288 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
289 ret[multiple * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
290 ret[multiple * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
291 ret[multiple * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
292 if (separator && i != length - 1)
293 ret[multiple * i + 4] = separator;
294 }
295 if (show_length && length > 4)
296 return ret + " (" + std::to_string(length) + ")";
297 return ret;
298}
299std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
300 return format_hex_pretty(data.data(), data.size(), separator, show_length);
301}
302std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
303 if (data.empty())
304 return "";
305 std::string ret;
306 uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise
307 ret.resize(multiple * data.length() - (separator ? 1 : 0));
308 for (size_t i = 0; i < data.length(); i++) {
309 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4);
310 ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
311 if (separator && i != data.length() - 1)
312 ret[multiple * i + 2] = separator;
313 }
314 if (show_length && data.length() > 4)
315 return ret + " (" + std::to_string(data.length()) + ")";
316 return ret;
317}
318
319std::string format_bin(const uint8_t *data, size_t length) {
320 std::string result;
321 result.resize(length * 8);
322 for (size_t byte_idx = 0; byte_idx < length; byte_idx++) {
323 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
324 result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
325 }
326 }
327
328 return result;
329}
330
331ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
332 if (on == nullptr && strcasecmp(str, "on") == 0)
333 return PARSE_ON;
334 if (on != nullptr && strcasecmp(str, on) == 0)
335 return PARSE_ON;
336 if (off == nullptr && strcasecmp(str, "off") == 0)
337 return PARSE_OFF;
338 if (off != nullptr && strcasecmp(str, off) == 0)
339 return PARSE_OFF;
340 if (strcasecmp(str, "toggle") == 0)
341 return PARSE_TOGGLE;
342
343 return PARSE_NONE;
344}
345
346std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
347 if (accuracy_decimals < 0) {
348 auto multiplier = powf(10.0f, accuracy_decimals);
349 value = roundf(value * multiplier) / multiplier;
350 accuracy_decimals = 0;
351 }
352 char tmp[32]; // should be enough, but we should maybe improve this at some point.
353 snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
354 return std::string(tmp);
355}
356
357int8_t step_to_accuracy_decimals(float step) {
358 // use printf %g to find number of digits based on temperature step
359 char buf[32];
360 snprintf(buf, sizeof buf, "%.5g", step);
361
362 std::string str{buf};
363 size_t dot_pos = str.find('.');
364 if (dot_pos == std::string::npos)
365 return 0;
366
367 return str.length() - dot_pos - 1;
368}
369
370// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
371static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
372 "abcdefghijklmnopqrstuvwxyz"
373 "0123456789+/";
374
375// Helper function to find the index of a base64 character in the lookup table.
376// Returns the character's position (0-63) if found, or 0 if not found.
377// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
378// This is safe because is_base64() is ALWAYS checked before calling this function,
379// preventing invalid characters from ever reaching here. The base64_decode function
380// stops processing at the first invalid character due to the is_base64() check in its
381// while loop condition, making this edge case harmless in practice.
382static inline uint8_t base64_find_char(char c) {
383 const char *pos = strchr(BASE64_CHARS, c);
384 return pos ? (pos - BASE64_CHARS) : 0;
385}
386
387static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
388
389std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
390
391std::string base64_encode(const uint8_t *buf, size_t buf_len) {
392 std::string ret;
393 int i = 0;
394 int j = 0;
395 char char_array_3[3];
396 char char_array_4[4];
397
398 while (buf_len--) {
399 char_array_3[i++] = *(buf++);
400 if (i == 3) {
401 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
402 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
403 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
404 char_array_4[3] = char_array_3[2] & 0x3f;
405
406 for (i = 0; (i < 4); i++)
407 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[i])];
408 i = 0;
409 }
410 }
411
412 if (i) {
413 for (j = i; j < 3; j++)
414 char_array_3[j] = '\0';
415
416 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
417 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
418 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
419 char_array_4[3] = char_array_3[2] & 0x3f;
420
421 for (j = 0; (j < i + 1); j++)
422 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
423
424 while ((i++ < 3))
425 ret += '=';
426 }
427
428 return ret;
429}
430
431size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
432 std::vector<uint8_t> decoded = base64_decode(encoded_string);
433 if (decoded.size() > buf_len) {
434 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
435 decoded.resize(buf_len);
436 }
437 memcpy(buf, decoded.data(), decoded.size());
438 return decoded.size();
439}
440
441std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
442 int in_len = encoded_string.size();
443 int i = 0;
444 int j = 0;
445 int in = 0;
446 uint8_t char_array_4[4], char_array_3[3];
447 std::vector<uint8_t> ret;
448
449 // SAFETY: The loop condition checks is_base64() before processing each character.
450 // This ensures base64_find_char() is only called on valid base64 characters,
451 // preventing the edge case where invalid chars would return 0 (same as 'A').
452 while (in_len-- && (encoded_string[in] != '=') && is_base64(encoded_string[in])) {
453 char_array_4[i++] = encoded_string[in];
454 in++;
455 if (i == 4) {
456 for (i = 0; i < 4; i++)
457 char_array_4[i] = base64_find_char(char_array_4[i]);
458
459 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
460 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
461 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
462
463 for (i = 0; (i < 3); i++)
464 ret.push_back(char_array_3[i]);
465 i = 0;
466 }
467 }
468
469 if (i) {
470 for (j = i; j < 4; j++)
471 char_array_4[j] = 0;
472
473 for (j = 0; j < 4; j++)
474 char_array_4[j] = base64_find_char(char_array_4[j]);
475
476 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
477 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
478 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
479
480 for (j = 0; (j < i - 1); j++)
481 ret.push_back(char_array_3[j]);
482 }
483
484 return ret;
485}
486
487// Colors
488
489float gamma_correct(float value, float gamma) {
490 if (value <= 0.0f)
491 return 0.0f;
492 if (gamma <= 0.0f)
493 return value;
494
495 return powf(value, gamma);
496}
497float gamma_uncorrect(float value, float gamma) {
498 if (value <= 0.0f)
499 return 0.0f;
500 if (gamma <= 0.0f)
501 return value;
502
503 return powf(value, 1 / gamma);
504}
505
506void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
507 float max_color_value = std::max(std::max(red, green), blue);
508 float min_color_value = std::min(std::min(red, green), blue);
509 float delta = max_color_value - min_color_value;
510
511 if (delta == 0) {
512 hue = 0;
513 } else if (max_color_value == red) {
514 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
515 } else if (max_color_value == green) {
516 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
517 } else if (max_color_value == blue) {
518 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
519 }
520
521 if (max_color_value == 0) {
522 saturation = 0;
523 } else {
524 saturation = delta / max_color_value;
525 }
526
527 value = max_color_value;
528}
529void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
530 float chroma = value * saturation;
531 float hue_prime = fmod(hue / 60.0, 6);
532 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
533 float delta = value - chroma;
534
535 if (0 <= hue_prime && hue_prime < 1) {
536 red = chroma;
537 green = intermediate;
538 blue = 0;
539 } else if (1 <= hue_prime && hue_prime < 2) {
540 red = intermediate;
541 green = chroma;
542 blue = 0;
543 } else if (2 <= hue_prime && hue_prime < 3) {
544 red = 0;
545 green = chroma;
546 blue = intermediate;
547 } else if (3 <= hue_prime && hue_prime < 4) {
548 red = 0;
549 green = intermediate;
550 blue = chroma;
551 } else if (4 <= hue_prime && hue_prime < 5) {
552 red = intermediate;
553 green = 0;
554 blue = chroma;
555 } else if (5 <= hue_prime && hue_prime < 6) {
556 red = chroma;
557 green = 0;
558 blue = intermediate;
559 } else {
560 red = 0;
561 green = 0;
562 blue = 0;
563 }
564
565 red += delta;
566 green += delta;
567 blue += delta;
568}
569
570uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
572 if (this->started_)
573 return;
574 num_requests++;
575 this->started_ = true;
576}
578 if (!this->started_)
579 return;
580 num_requests--;
581 this->started_ = false;
582}
584
585std::string get_mac_address() {
586 uint8_t mac[6];
588 return str_snprintf("%02x%02x%02x%02x%02x%02x", 12, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
589}
590
592 uint8_t mac[6];
594 return format_mac_address_pretty(mac);
595}
596
597#ifndef USE_ESP32
598bool has_custom_mac_address() { return false; }
599#endif
600
601bool mac_address_is_valid(const uint8_t *mac) {
602 bool is_all_zeros = true;
603 bool is_all_ones = true;
604
605 for (uint8_t i = 0; i < 6; i++) {
606 if (mac[i] != 0) {
607 is_all_zeros = false;
608 }
609 }
610 for (uint8_t i = 0; i < 6; i++) {
611 if (mac[i] != 0xFF) {
612 is_all_ones = false;
613 }
614 }
615 return !(is_all_zeros || is_all_ones);
616}
617
618void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
619 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
620 uint32_t start = micros();
621
622 const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
623 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
624 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
625 if (us > lag) {
626 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
627 while (micros() - start < us - lag)
628 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
629 }
630 while (micros() - start < us) // fine delay the remaining usecs
631 ;
632}
633
634} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:577
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:583
void start()
Start running the loop continuously.
Definition helpers.cpp:571
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
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:134
uint8_t crc8(const uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size len using the CRC-8-Dallas/Maxim polynomial.
Definition helpers.cpp:44
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:143
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:497
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:60
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:346
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:489
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:601
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:506
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:249
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:175
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:331
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:319
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:184
std::string size_t len
Definition helpers.h:229
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:53
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:226
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:591
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:194
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:357
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:30
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:16
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:618
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:176
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:261
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:147
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:162
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:244
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:389
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:529
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:100
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:208
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:33
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:151
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:585
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:177
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:152
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:431
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:501
@ PARSE_ON
Definition helpers.h:503
@ PARSE_TOGGLE
Definition helpers.h:505
@ PARSE_OFF
Definition helpers.h:504
@ PARSE_NONE
Definition helpers.h:502
std::string str_ctype_transform(const std::string &str)
Definition helpers.cpp:169
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:159
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t length
Definition tt21100.cpp:0