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