ESPHome 2025.12.5
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// Maximum size for name with suffix: 120 (max friendly name) + 1 (separator) + 6 (MAC suffix) + 1 (null term)
239static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
240
241std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr,
242 size_t suffix_len) {
243 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
244 size_t total_len = name_len + 1 + suffix_len;
245
246 // Silently truncate if needed: prioritize keeping the full suffix
247 if (total_len >= MAX_NAME_WITH_SUFFIX_SIZE) {
248 // NOTE: This calculation could underflow if suffix_len >= MAX_NAME_WITH_SUFFIX_SIZE - 2,
249 // but this is safe because this helper is only called with small suffixes:
250 // MAC suffixes (6-12 bytes), ".local" (5 bytes), etc.
251 name_len = MAX_NAME_WITH_SUFFIX_SIZE - suffix_len - 2; // -2 for separator and null terminator
252 total_len = name_len + 1 + suffix_len;
253 }
254
255 memcpy(buffer, name, name_len);
256 buffer[name_len] = sep;
257 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
258 buffer[total_len] = '\0';
259 return std::string(buffer, total_len);
260}
261
262std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len) {
263 return make_name_with_suffix(name.c_str(), name.size(), sep, suffix_ptr, suffix_len);
264}
265
266// Parsing & formatting
267
268size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
269 uint8_t val;
270 size_t chars = std::min(length, 2 * count);
271 for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
272 if (*str >= '0' && *str <= '9') {
273 val = *str - '0';
274 } else if (*str >= 'A' && *str <= 'F') {
275 val = 10 + (*str - 'A');
276 } else if (*str >= 'a' && *str <= 'f') {
277 val = 10 + (*str - 'a');
278 } else {
279 return 0;
280 }
281 data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
282 }
283 return chars;
284}
285
286std::string format_mac_address_pretty(const uint8_t *mac) {
287 char buf[18];
288 format_mac_addr_upper(mac, buf);
289 return std::string(buf);
290}
291
292std::string format_hex(const uint8_t *data, size_t length) {
293 std::string ret;
294 ret.resize(length * 2);
295 for (size_t i = 0; i < length; i++) {
296 ret[2 * i] = format_hex_char(data[i] >> 4);
297 ret[2 * i + 1] = format_hex_char(data[i] & 0x0F);
298 }
299 return ret;
300}
301std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
302
303// Shared implementation for uint8_t and string hex formatting
304static std::string format_hex_pretty_uint8(const uint8_t *data, size_t length, char separator, bool show_length) {
305 if (data == nullptr || length == 0)
306 return "";
307 std::string ret;
308 uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise
309 ret.resize(multiple * length - (separator ? 1 : 0));
310 for (size_t i = 0; i < length; i++) {
311 ret[multiple * i] = format_hex_pretty_char(data[i] >> 4);
312 ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
313 if (separator && i != length - 1)
314 ret[multiple * i + 2] = separator;
315 }
316 if (show_length && length > 4)
317 return ret + " (" + std::to_string(length) + ")";
318 return ret;
319}
320
321std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) {
322 return format_hex_pretty_uint8(data, length, separator, show_length);
323}
324std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator, bool show_length) {
325 return format_hex_pretty(data.data(), data.size(), separator, show_length);
326}
327
328std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) {
329 if (data == nullptr || length == 0)
330 return "";
331 std::string ret;
332 uint8_t multiple = separator ? 5 : 4; // 5 if separator is not \0, 4 otherwise
333 ret.resize(multiple * length - (separator ? 1 : 0));
334 for (size_t i = 0; i < length; i++) {
335 ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
336 ret[multiple * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
337 ret[multiple * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
338 ret[multiple * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
339 if (separator && i != length - 1)
340 ret[multiple * i + 4] = separator;
341 }
342 if (show_length && length > 4)
343 return ret + " (" + std::to_string(length) + ")";
344 return ret;
345}
346std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator, bool show_length) {
347 return format_hex_pretty(data.data(), data.size(), separator, show_length);
348}
349std::string format_hex_pretty(const std::string &data, char separator, bool show_length) {
350 return format_hex_pretty_uint8(reinterpret_cast<const uint8_t *>(data.data()), data.length(), separator, show_length);
351}
352
353std::string format_bin(const uint8_t *data, size_t length) {
354 std::string result;
355 result.resize(length * 8);
356 for (size_t byte_idx = 0; byte_idx < length; byte_idx++) {
357 for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
358 result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
359 }
360 }
361
362 return result;
363}
364
365ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
366 if (on == nullptr && strcasecmp(str, "on") == 0)
367 return PARSE_ON;
368 if (on != nullptr && strcasecmp(str, on) == 0)
369 return PARSE_ON;
370 if (off == nullptr && strcasecmp(str, "off") == 0)
371 return PARSE_OFF;
372 if (off != nullptr && strcasecmp(str, off) == 0)
373 return PARSE_OFF;
374 if (strcasecmp(str, "toggle") == 0)
375 return PARSE_TOGGLE;
376
377 return PARSE_NONE;
378}
379
380static inline void normalize_accuracy_decimals(float &value, int8_t &accuracy_decimals) {
381 if (accuracy_decimals < 0) {
382 auto multiplier = powf(10.0f, accuracy_decimals);
383 value = roundf(value * multiplier) / multiplier;
384 accuracy_decimals = 0;
385 }
386}
387
388std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
389 normalize_accuracy_decimals(value, accuracy_decimals);
390 char tmp[32]; // should be enough, but we should maybe improve this at some point.
391 snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
392 return std::string(tmp);
393}
394
395std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement) {
396 normalize_accuracy_decimals(value, accuracy_decimals);
397 // Buffer sized for float (up to ~15 chars) + space + typical UOM (usually <20 chars like "μS/cm")
398 // snprintf truncates safely if exceeded, though ESPHome UOMs are typically short
399 char tmp[64];
400 if (unit_of_measurement.empty()) {
401 snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
402 } else {
403 snprintf(tmp, sizeof(tmp), "%.*f %s", accuracy_decimals, value, unit_of_measurement.c_str());
404 }
405 return std::string(tmp);
406}
407
408int8_t step_to_accuracy_decimals(float step) {
409 // use printf %g to find number of digits based on temperature step
410 char buf[32];
411 snprintf(buf, sizeof buf, "%.5g", step);
412
413 std::string str{buf};
414 size_t dot_pos = str.find('.');
415 if (dot_pos == std::string::npos)
416 return 0;
417
418 return str.length() - dot_pos - 1;
419}
420
421// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
422static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
423 "abcdefghijklmnopqrstuvwxyz"
424 "0123456789+/";
425
426// Helper function to find the index of a base64 character in the lookup table.
427// Returns the character's position (0-63) if found, or 0 if not found.
428// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters.
429// This is safe because is_base64() is ALWAYS checked before calling this function,
430// preventing invalid characters from ever reaching here. The base64_decode function
431// stops processing at the first invalid character due to the is_base64() check in its
432// while loop condition, making this edge case harmless in practice.
433static inline uint8_t base64_find_char(char c) {
434 const char *pos = strchr(BASE64_CHARS, c);
435 return pos ? (pos - BASE64_CHARS) : 0;
436}
437
438static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
439
440std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
441
442std::string base64_encode(const uint8_t *buf, size_t buf_len) {
443 std::string ret;
444 int i = 0;
445 int j = 0;
446 char char_array_3[3];
447 char char_array_4[4];
448
449 while (buf_len--) {
450 char_array_3[i++] = *(buf++);
451 if (i == 3) {
452 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
453 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
454 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
455 char_array_4[3] = char_array_3[2] & 0x3f;
456
457 for (i = 0; (i < 4); i++)
458 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[i])];
459 i = 0;
460 }
461 }
462
463 if (i) {
464 for (j = i; j < 3; j++)
465 char_array_3[j] = '\0';
466
467 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
468 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
469 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
470 char_array_4[3] = char_array_3[2] & 0x3f;
471
472 for (j = 0; (j < i + 1); j++)
473 ret += BASE64_CHARS[static_cast<uint8_t>(char_array_4[j])];
474
475 while ((i++ < 3))
476 ret += '=';
477 }
478
479 return ret;
480}
481
482size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
483 int in_len = encoded_string.size();
484 int i = 0;
485 int j = 0;
486 int in = 0;
487 size_t out = 0;
488 uint8_t char_array_4[4], char_array_3[3];
489 bool truncated = false;
490
491 // SAFETY: The loop condition checks is_base64() before processing each character.
492 // This ensures base64_find_char() is only called on valid base64 characters,
493 // preventing the edge case where invalid chars would return 0 (same as 'A').
494 while (in_len-- && (encoded_string[in] != '=') && is_base64(encoded_string[in])) {
495 char_array_4[i++] = encoded_string[in];
496 in++;
497 if (i == 4) {
498 for (i = 0; i < 4; i++)
499 char_array_4[i] = base64_find_char(char_array_4[i]);
500
501 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
502 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
503 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
504
505 for (i = 0; i < 3; i++) {
506 if (out < buf_len) {
507 buf[out++] = char_array_3[i];
508 } else {
509 truncated = true;
510 }
511 }
512 i = 0;
513 }
514 }
515
516 if (i) {
517 for (j = i; j < 4; j++)
518 char_array_4[j] = 0;
519
520 for (j = 0; j < 4; j++)
521 char_array_4[j] = base64_find_char(char_array_4[j]);
522
523 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
524 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
525 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
526
527 for (j = 0; j < i - 1; j++) {
528 if (out < buf_len) {
529 buf[out++] = char_array_3[j];
530 } else {
531 truncated = true;
532 }
533 }
534 }
535
536 if (truncated) {
537 ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
538 }
539
540 return out;
541}
542
543std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
544 // Calculate maximum decoded size: every 4 base64 chars = 3 bytes
545 size_t max_len = ((encoded_string.size() + 3) / 4) * 3;
546 std::vector<uint8_t> ret(max_len);
547 size_t actual_len = base64_decode(encoded_string, ret.data(), max_len);
548 ret.resize(actual_len);
549 return ret;
550}
551
552// Colors
553
554float gamma_correct(float value, float gamma) {
555 if (value <= 0.0f)
556 return 0.0f;
557 if (gamma <= 0.0f)
558 return value;
559
560 return powf(value, gamma);
561}
562float gamma_uncorrect(float value, float gamma) {
563 if (value <= 0.0f)
564 return 0.0f;
565 if (gamma <= 0.0f)
566 return value;
567
568 return powf(value, 1 / gamma);
569}
570
571void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
572 float max_color_value = std::max(std::max(red, green), blue);
573 float min_color_value = std::min(std::min(red, green), blue);
574 float delta = max_color_value - min_color_value;
575
576 if (delta == 0) {
577 hue = 0;
578 } else if (max_color_value == red) {
579 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
580 } else if (max_color_value == green) {
581 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
582 } else if (max_color_value == blue) {
583 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
584 }
585
586 if (max_color_value == 0) {
587 saturation = 0;
588 } else {
589 saturation = delta / max_color_value;
590 }
591
592 value = max_color_value;
593}
594void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
595 float chroma = value * saturation;
596 float hue_prime = fmod(hue / 60.0, 6);
597 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
598 float delta = value - chroma;
599
600 if (0 <= hue_prime && hue_prime < 1) {
601 red = chroma;
602 green = intermediate;
603 blue = 0;
604 } else if (1 <= hue_prime && hue_prime < 2) {
605 red = intermediate;
606 green = chroma;
607 blue = 0;
608 } else if (2 <= hue_prime && hue_prime < 3) {
609 red = 0;
610 green = chroma;
611 blue = intermediate;
612 } else if (3 <= hue_prime && hue_prime < 4) {
613 red = 0;
614 green = intermediate;
615 blue = chroma;
616 } else if (4 <= hue_prime && hue_prime < 5) {
617 red = intermediate;
618 green = 0;
619 blue = chroma;
620 } else if (5 <= hue_prime && hue_prime < 6) {
621 red = chroma;
622 green = 0;
623 blue = intermediate;
624 } else {
625 red = 0;
626 green = 0;
627 blue = 0;
628 }
629
630 red += delta;
631 green += delta;
632 blue += delta;
633}
634
635uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
637 if (this->started_)
638 return;
639 num_requests++;
640 this->started_ = true;
641}
643 if (!this->started_)
644 return;
645 num_requests--;
646 this->started_ = false;
647}
649
650std::string get_mac_address() {
651 uint8_t mac[6];
653 char buf[13];
655 return std::string(buf);
656}
657
660 return std::string(get_mac_address_pretty_into_buffer(buf));
661}
662
663void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf) {
664 uint8_t mac[6];
666 format_mac_addr_lower_no_sep(mac, buf.data());
667}
668
669const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
670 uint8_t mac[6];
672 format_mac_addr_upper(mac, buf.data());
673 return buf.data();
674}
675
676#ifndef USE_ESP32
677bool has_custom_mac_address() { return false; }
678#endif
679
680bool mac_address_is_valid(const uint8_t *mac) {
681 bool is_all_zeros = true;
682 bool is_all_ones = true;
683
684 for (uint8_t i = 0; i < 6; i++) {
685 if (mac[i] != 0) {
686 is_all_zeros = false;
687 }
688 if (mac[i] != 0xFF) {
689 is_all_ones = false;
690 }
691 }
692 return !(is_all_zeros || is_all_ones);
693}
694
695void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
696 // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
697 uint32_t start = micros();
698
699 const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
700 // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
701 // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
702 if (us > lag) {
703 delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
704 while (micros() - start < us - lag)
705 delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
706 }
707 while (micros() - start < us) // fine delay the remaining usecs
708 ;
709}
710
711} // namespace esphome
void stop()
Stop running the loop continuously.
Definition helpers.cpp:642
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:648
void start()
Start running the loop continuously.
Definition helpers.cpp:636
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:562
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:388
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:632
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:554
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:635
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:680
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:647
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:571
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:292
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:365
constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE
Buffer size for MAC address in colon-separated uppercase hex notation (17 chars + null terminator)
Definition helpers.h:1063
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:353
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:503
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:395
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:268
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:658
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:408
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:32
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:669
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:695
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:321
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:286
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:440
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:594
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:663
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:31
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
Definition helpers.h:628
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:650
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:482
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:825
@ PARSE_ON
Definition helpers.h:827
@ PARSE_TOGGLE
Definition helpers.h:829
@ PARSE_OFF
Definition helpers.h:828
@ PARSE_NONE
Definition helpers.h:826
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:241
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