ESPHome  2025.4.0
helpers.cpp
Go to the documentation of this file.
1 #include "esphome/core/helpers.h"
2 
3 #include "esphome/core/defines.h"
4 #include "esphome/core/hal.h"
5 #include "esphome/core/log.h"
6 
7 #include <algorithm>
8 #include <cctype>
9 #include <cmath>
10 #include <cstdarg>
11 #include <cstdio>
12 #include <cstring>
13 #include <strings.h>
14 
15 #ifdef USE_HOST
16 #ifndef _WIN32
17 #include <net/if.h>
18 #include <netinet/in.h>
19 #include <sys/ioctl.h>
20 #endif
21 #include <unistd.h>
22 #endif
23 #if defined(USE_ESP8266)
24 #include <osapi.h>
25 #include <user_interface.h>
26 // for xt_rsil()/xt_wsr_ps()
27 #include <Arduino.h>
28 #elif defined(USE_ESP32_FRAMEWORK_ARDUINO)
29 #include <Esp.h>
30 #elif defined(USE_ESP_IDF)
31 #include <freertos/FreeRTOS.h>
32 #include <freertos/portmacro.h>
33 #include "esp_mac.h"
34 #include "esp_random.h"
35 #include "esp_system.h"
36 #elif defined(USE_RP2040)
37 #if defined(USE_WIFI)
38 #include <WiFi.h>
39 #endif
40 #include <hardware/structs/rosc.h>
41 #include <hardware/sync.h>
42 #elif defined(USE_HOST)
43 #include <limits>
44 #include <random>
45 #endif
46 #ifdef USE_ESP32
47 #include "rom/crc.h"
48 #include "esp_efuse.h"
49 #include "esp_efuse_table.h"
50 #endif
51 
52 #ifdef USE_LIBRETINY
53 #include <WiFi.h> // for macAddress()
54 #endif
55 
56 namespace esphome {
57 
58 static const char *const TAG = "helpers";
59 
60 static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
61  0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
62 static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
63  0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
64 
65 #ifndef USE_ESP32
66 static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
67  0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
68 static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
69  0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
70 #endif
71 
72 #if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
73 static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
74  0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
75 static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
76  0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
77 #endif
78 
79 // STL backports
80 
81 #if _GLIBCXX_RELEASE < 8
82 std::string to_string(int value) { return str_snprintf("%d", 32, value); } // NOLINT
83 std::string to_string(long value) { return str_snprintf("%ld", 32, value); } // NOLINT
84 std::string to_string(long long value) { return str_snprintf("%lld", 32, value); } // NOLINT
85 std::string to_string(unsigned value) { return str_snprintf("%u", 32, value); } // NOLINT
86 std::string to_string(unsigned long value) { return str_snprintf("%lu", 32, value); } // NOLINT
87 std::string to_string(unsigned long long value) { return str_snprintf("%llu", 32, value); } // NOLINT
88 std::string to_string(float value) { return str_snprintf("%f", 32, value); }
89 std::string to_string(double value) { return str_snprintf("%f", 32, value); }
90 std::string to_string(long double value) { return str_snprintf("%Lf", 32, value); }
91 #endif
92 
93 // Mathematics
94 
95 float lerp(float completion, float start, float end) { return start + (end - start) * completion; }
96 uint8_t crc8(const uint8_t *data, uint8_t len) {
97  uint8_t crc = 0;
98 
99  while ((len--) != 0u) {
100  uint8_t inbyte = *data++;
101  for (uint8_t i = 8; i != 0u; i--) {
102  bool mix = (crc ^ inbyte) & 0x01;
103  crc >>= 1;
104  if (mix)
105  crc ^= 0x8C;
106  inbyte >>= 1;
107  }
108  }
109  return crc;
110 }
111 
112 uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout) {
113 #ifdef USE_ESP32
114  if (reverse_poly == 0x8408) {
115  crc = crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
116  return refout ? crc : (crc ^ 0xffff);
117  }
118 #endif
119  if (refin) {
120  crc ^= 0xffff;
121  }
122 #ifndef USE_ESP32
123  if (reverse_poly == 0x8408) {
124  while (len--) {
125  uint8_t combo = crc ^ (uint8_t) *data++;
126  crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
127  }
128  } else
129 #endif
130  {
131  if (reverse_poly == 0xa001) {
132  while (len--) {
133  uint8_t combo = crc ^ (uint8_t) *data++;
134  crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
135  }
136  } else {
137  while (len--) {
138  crc ^= *data++;
139  for (uint8_t i = 0; i < 8; i++) {
140  if (crc & 0x0001) {
141  crc = (crc >> 1) ^ reverse_poly;
142  } else {
143  crc >>= 1;
144  }
145  }
146  }
147  }
148  }
149  return refout ? (crc ^ 0xffff) : crc;
150 }
151 
152 uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout) {
153 #if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32S2)
154  if (poly == 0x1021) {
155  crc = crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
156  return refout ? crc : (crc ^ 0xffff);
157  }
158 #endif
159  if (refin) {
160  crc ^= 0xffff;
161  }
162 #if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
163  if (poly == 0x1021) {
164  while (len--) {
165  uint8_t combo = (crc >> 8) ^ *data++;
166  crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
167  }
168  } else {
169 #endif
170  while (len--) {
171  crc ^= (((uint16_t) *data++) << 8);
172  for (uint8_t i = 0; i < 8; i++) {
173  if (crc & 0x8000) {
174  crc = (crc << 1) ^ poly;
175  } else {
176  crc <<= 1;
177  }
178  }
179  }
180 #if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
181  }
182 #endif
183  return refout ? (crc ^ 0xffff) : crc;
184 }
185 
186 uint32_t fnv1_hash(const std::string &str) {
187  uint32_t hash = 2166136261UL;
188  for (char c : str) {
189  hash *= 16777619UL;
190  hash ^= c;
191  }
192  return hash;
193 }
194 
195 #ifdef USE_ESP32
196 uint32_t random_uint32() { return esp_random(); }
197 #elif defined(USE_ESP8266)
198 uint32_t random_uint32() { return os_random(); }
199 #elif defined(USE_RP2040)
200 uint32_t random_uint32() {
201  uint32_t result = 0;
202  for (uint8_t i = 0; i < 32; i++) {
203  result <<= 1;
204  result |= rosc_hw->randombit;
205  }
206  return result;
207 }
208 #elif defined(USE_LIBRETINY)
209 uint32_t random_uint32() { return rand(); }
210 #elif defined(USE_HOST)
211 uint32_t random_uint32() {
212  std::random_device dev;
213  std::mt19937 rng(dev());
214  std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max());
215  return dist(rng);
216 }
217 #endif
218 float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
219 #ifdef USE_ESP32
220 bool random_bytes(uint8_t *data, size_t len) {
221  esp_fill_random(data, len);
222  return true;
223 }
224 #elif defined(USE_ESP8266)
225 bool random_bytes(uint8_t *data, size_t len) { return os_get_random(data, len) == 0; }
226 #elif defined(USE_RP2040)
227 bool random_bytes(uint8_t *data, size_t len) {
228  while (len-- != 0) {
229  uint8_t result = 0;
230  for (uint8_t i = 0; i < 8; i++) {
231  result <<= 1;
232  result |= rosc_hw->randombit;
233  }
234  *data++ = result;
235  }
236  return true;
237 }
238 #elif defined(USE_LIBRETINY)
239 bool random_bytes(uint8_t *data, size_t len) {
240  lt_rand_bytes(data, len);
241  return true;
242 }
243 #elif defined(USE_HOST)
244 bool random_bytes(uint8_t *data, size_t len) {
245  FILE *fp = fopen("/dev/urandom", "r");
246  if (fp == nullptr) {
247  ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno);
248  exit(1);
249  }
250  size_t read = fread(data, 1, len, fp);
251  if (read != len) {
252  ESP_LOGW(TAG, "Not enough data from /dev/urandom");
253  exit(1);
254  }
255  fclose(fp);
256  return true;
257 }
258 #endif
259 
260 // Strings
261 
262 bool str_equals_case_insensitive(const std::string &a, const std::string &b) {
263  return strcasecmp(a.c_str(), b.c_str()) == 0;
264 }
265 #if __cplusplus >= 202002L
266 bool str_startswith(const std::string &str, const std::string &start) { return str.starts_with(start); }
267 bool str_endswith(const std::string &str, const std::string &end) { return str.ends_with(end); }
268 #else
269 bool str_startswith(const std::string &str, const std::string &start) { return str.rfind(start, 0) == 0; }
270 bool str_endswith(const std::string &str, const std::string &end) {
271  return str.rfind(end) == (str.size() - end.size());
272 }
273 #endif
274 std::string str_truncate(const std::string &str, size_t length) {
275  return str.length() > length ? str.substr(0, length) : str;
276 }
277 std::string str_until(const char *str, char ch) {
278  const char *pos = strchr(str, ch);
279  return pos == nullptr ? std::string(str) : std::string(str, pos - str);
280 }
281 std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
282 // wrapper around std::transform to run safely on functions from the ctype.h header
283 // see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
284 template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
285  std::string result;
286  result.resize(str.length());
287  std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
288  return result;
289 }
290 std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
291 std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
292 std::string str_snake_case(const std::string &str) {
293  std::string result;
294  result.resize(str.length());
295  std::transform(str.begin(), str.end(), result.begin(), ::tolower);
296  std::replace(result.begin(), result.end(), ' ', '_');
297  return result;
298 }
299 std::string str_sanitize(const std::string &str) {
300  std::string out = str;
301  std::replace_if(
302  out.begin(), out.end(),
303  [](const char &c) {
304  return c != '-' && c != '_' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z');
305  },
306  '_');
307  return out;
308 }
309 std::string str_snprintf(const char *fmt, size_t len, ...) {
310  std::string str;
311  va_list args;
312 
313  str.resize(len);
314  va_start(args, len);
315  size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
316  va_end(args);
317 
318  if (out_length < len)
319  str.resize(out_length);
320 
321  return str;
322 }
323 std::string str_sprintf(const char *fmt, ...) {
324  std::string str;
325  va_list args;
326 
327  va_start(args, fmt);
328  size_t length = vsnprintf(nullptr, 0, fmt, args);
329  va_end(args);
330 
331  str.resize(length);
332  va_start(args, fmt);
333  vsnprintf(&str[0], length + 1, fmt, args);
334  va_end(args);
335 
336  return str;
337 }
338 
339 // Parsing & formatting
340 
341 size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count) {
342  uint8_t val;
343  size_t chars = std::min(length, 2 * count);
344  for (size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
345  if (*str >= '0' && *str <= '9') {
346  val = *str - '0';
347  } else if (*str >= 'A' && *str <= 'F') {
348  val = 10 + (*str - 'A');
349  } else if (*str >= 'a' && *str <= 'f') {
350  val = 10 + (*str - 'a');
351  } else {
352  return 0;
353  }
354  data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
355  }
356  return chars;
357 }
358 
359 static char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
360 std::string format_hex(const uint8_t *data, size_t length) {
361  std::string ret;
362  ret.resize(length * 2);
363  for (size_t i = 0; i < length; i++) {
364  ret[2 * i] = format_hex_char((data[i] & 0xF0) >> 4);
365  ret[2 * i + 1] = format_hex_char(data[i] & 0x0F);
366  }
367  return ret;
368 }
369 std::string format_hex(const std::vector<uint8_t> &data) { return format_hex(data.data(), data.size()); }
370 
371 static char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
372 std::string format_hex_pretty(const uint8_t *data, size_t length) {
373  if (length == 0)
374  return "";
375  std::string ret;
376  ret.resize(3 * length - 1);
377  for (size_t i = 0; i < length; i++) {
378  ret[3 * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4);
379  ret[3 * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
380  if (i != length - 1)
381  ret[3 * i + 2] = '.';
382  }
383  if (length > 4)
384  return ret + " (" + to_string(length) + ")";
385  return ret;
386 }
387 std::string format_hex_pretty(const std::vector<uint8_t> &data) { return format_hex_pretty(data.data(), data.size()); }
388 
389 std::string format_hex_pretty(const uint16_t *data, size_t length) {
390  if (length == 0)
391  return "";
392  std::string ret;
393  ret.resize(5 * length - 1);
394  for (size_t i = 0; i < length; i++) {
395  ret[5 * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
396  ret[5 * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
397  ret[5 * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
398  ret[5 * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
399  if (i != length - 1)
400  ret[5 * i + 2] = '.';
401  }
402  if (length > 4)
403  return ret + " (" + to_string(length) + ")";
404  return ret;
405 }
406 std::string format_hex_pretty(const std::vector<uint16_t> &data) { return format_hex_pretty(data.data(), data.size()); }
407 
408 std::string format_bin(const uint8_t *data, size_t length) {
409  std::string result;
410  result.resize(length * 8);
411  for (size_t byte_idx = 0; byte_idx < length; byte_idx++) {
412  for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
413  result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0';
414  }
415  }
416 
417  return result;
418 }
419 
420 ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
421  if (on == nullptr && strcasecmp(str, "on") == 0)
422  return PARSE_ON;
423  if (on != nullptr && strcasecmp(str, on) == 0)
424  return PARSE_ON;
425  if (off == nullptr && strcasecmp(str, "off") == 0)
426  return PARSE_OFF;
427  if (off != nullptr && strcasecmp(str, off) == 0)
428  return PARSE_OFF;
429  if (strcasecmp(str, "toggle") == 0)
430  return PARSE_TOGGLE;
431 
432  return PARSE_NONE;
433 }
434 
435 std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) {
436  if (accuracy_decimals < 0) {
437  auto multiplier = powf(10.0f, accuracy_decimals);
438  value = roundf(value * multiplier) / multiplier;
439  accuracy_decimals = 0;
440  }
441  char tmp[32]; // should be enough, but we should maybe improve this at some point.
442  snprintf(tmp, sizeof(tmp), "%.*f", accuracy_decimals, value);
443  return std::string(tmp);
444 }
445 
446 int8_t step_to_accuracy_decimals(float step) {
447  // use printf %g to find number of digits based on temperature step
448  char buf[32];
449  snprintf(buf, sizeof buf, "%.5g", step);
450 
451  std::string str{buf};
452  size_t dot_pos = str.find('.');
453  if (dot_pos == std::string::npos)
454  return 0;
455 
456  return str.length() - dot_pos - 1;
457 }
458 
459 static const std::string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
460  "abcdefghijklmnopqrstuvwxyz"
461  "0123456789+/";
462 
463 static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
464 
465 std::string base64_encode(const std::vector<uint8_t> &buf) { return base64_encode(buf.data(), buf.size()); }
466 
467 std::string base64_encode(const uint8_t *buf, size_t buf_len) {
468  std::string ret;
469  int i = 0;
470  int j = 0;
471  char char_array_3[3];
472  char char_array_4[4];
473 
474  while (buf_len--) {
475  char_array_3[i++] = *(buf++);
476  if (i == 3) {
477  char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
478  char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
479  char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
480  char_array_4[3] = char_array_3[2] & 0x3f;
481 
482  for (i = 0; (i < 4); i++)
483  ret += BASE64_CHARS[char_array_4[i]];
484  i = 0;
485  }
486  }
487 
488  if (i) {
489  for (j = i; j < 3; j++)
490  char_array_3[j] = '\0';
491 
492  char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
493  char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
494  char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
495  char_array_4[3] = char_array_3[2] & 0x3f;
496 
497  for (j = 0; (j < i + 1); j++)
498  ret += BASE64_CHARS[char_array_4[j]];
499 
500  while ((i++ < 3))
501  ret += '=';
502  }
503 
504  return ret;
505 }
506 
507 size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len) {
508  std::vector<uint8_t> decoded = base64_decode(encoded_string);
509  if (decoded.size() > buf_len) {
510  ESP_LOGW(TAG, "Base64 decode: buffer too small, truncating");
511  decoded.resize(buf_len);
512  }
513  memcpy(buf, decoded.data(), decoded.size());
514  return decoded.size();
515 }
516 
517 std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
518  int in_len = encoded_string.size();
519  int i = 0;
520  int j = 0;
521  int in = 0;
522  uint8_t char_array_4[4], char_array_3[3];
523  std::vector<uint8_t> ret;
524 
525  while (in_len-- && (encoded_string[in] != '=') && is_base64(encoded_string[in])) {
526  char_array_4[i++] = encoded_string[in];
527  in++;
528  if (i == 4) {
529  for (i = 0; i < 4; i++)
530  char_array_4[i] = BASE64_CHARS.find(char_array_4[i]);
531 
532  char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
533  char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
534  char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
535 
536  for (i = 0; (i < 3); i++)
537  ret.push_back(char_array_3[i]);
538  i = 0;
539  }
540  }
541 
542  if (i) {
543  for (j = i; j < 4; j++)
544  char_array_4[j] = 0;
545 
546  for (j = 0; j < 4; j++)
547  char_array_4[j] = BASE64_CHARS.find(char_array_4[j]);
548 
549  char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
550  char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
551  char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
552 
553  for (j = 0; (j < i - 1); j++)
554  ret.push_back(char_array_3[j]);
555  }
556 
557  return ret;
558 }
559 
560 // Colors
561 
562 float gamma_correct(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, gamma);
569 }
570 float gamma_uncorrect(float value, float gamma) {
571  if (value <= 0.0f)
572  return 0.0f;
573  if (gamma <= 0.0f)
574  return value;
575 
576  return powf(value, 1 / gamma);
577 }
578 
579 void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value) {
580  float max_color_value = std::max(std::max(red, green), blue);
581  float min_color_value = std::min(std::min(red, green), blue);
582  float delta = max_color_value - min_color_value;
583 
584  if (delta == 0) {
585  hue = 0;
586  } else if (max_color_value == red) {
587  hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
588  } else if (max_color_value == green) {
589  hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
590  } else if (max_color_value == blue) {
591  hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
592  }
593 
594  if (max_color_value == 0) {
595  saturation = 0;
596  } else {
597  saturation = delta / max_color_value;
598  }
599 
600  value = max_color_value;
601 }
602 void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue) {
603  float chroma = value * saturation;
604  float hue_prime = fmod(hue / 60.0, 6);
605  float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
606  float delta = value - chroma;
607 
608  if (0 <= hue_prime && hue_prime < 1) {
609  red = chroma;
610  green = intermediate;
611  blue = 0;
612  } else if (1 <= hue_prime && hue_prime < 2) {
613  red = intermediate;
614  green = chroma;
615  blue = 0;
616  } else if (2 <= hue_prime && hue_prime < 3) {
617  red = 0;
618  green = chroma;
619  blue = intermediate;
620  } else if (3 <= hue_prime && hue_prime < 4) {
621  red = 0;
622  green = intermediate;
623  blue = chroma;
624  } else if (4 <= hue_prime && hue_prime < 5) {
625  red = intermediate;
626  green = 0;
627  blue = chroma;
628  } else if (5 <= hue_prime && hue_prime < 6) {
629  red = chroma;
630  green = 0;
631  blue = intermediate;
632  } else {
633  red = 0;
634  green = 0;
635  blue = 0;
636  }
637 
638  red += delta;
639  green += delta;
640  blue += delta;
641 }
642 
643 // System APIs
644 #if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST)
645 // ESP8266 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS.
648 void Mutex::lock() {}
649 bool Mutex::try_lock() { return true; }
650 void Mutex::unlock() {}
651 #elif defined(USE_ESP32) || defined(USE_LIBRETINY)
652 Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); }
653 Mutex::~Mutex() {}
654 void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
655 bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
656 void Mutex::unlock() { xSemaphoreGive(this->handle_); }
657 #endif
658 
659 #if defined(USE_ESP8266)
660 IRAM_ATTR InterruptLock::InterruptLock() { state_ = xt_rsil(15); }
661 IRAM_ATTR InterruptLock::~InterruptLock() { xt_wsr_ps(state_); }
662 #elif defined(USE_ESP32) || defined(USE_LIBRETINY)
663 // only affects the executing core
664 // so should not be used as a mutex lock, only to get accurate timing
665 IRAM_ATTR InterruptLock::InterruptLock() { portDISABLE_INTERRUPTS(); }
666 IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); }
667 #elif defined(USE_RP2040)
668 IRAM_ATTR InterruptLock::InterruptLock() { state_ = save_and_disable_interrupts(); }
669 IRAM_ATTR InterruptLock::~InterruptLock() { restore_interrupts(state_); }
670 #endif
671 
672 uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
674  if (this->started_)
675  return;
676  num_requests++;
677  this->started_ = true;
678 }
680  if (!this->started_)
681  return;
682  num_requests--;
683  this->started_ = false;
684 }
685 bool HighFrequencyLoopRequester::is_high_frequency() { return num_requests > 0; }
686 
687 #if defined(USE_HOST)
688 void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
689  static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS;
690  memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address));
691 }
692 #elif defined(USE_ESP32)
693 void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
694 #if defined(CONFIG_SOC_IEEE802154_SUPPORTED)
695  // When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default
696  // returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead.
697  if (has_custom_mac_address()) {
698  esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48);
699  } else {
700  esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48);
701  }
702 #else
703  if (has_custom_mac_address()) {
704  esp_efuse_mac_get_custom(mac);
705  } else {
706  esp_efuse_mac_get_default(mac);
707  }
708 #endif
709 }
710 #elif defined(USE_ESP8266)
711 void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
712  wifi_get_macaddr(STATION_IF, mac);
713 }
714 #elif defined(USE_RP2040)
715 void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
716 #ifdef USE_WIFI
717  WiFi.macAddress(mac);
718 #endif
719 }
720 #elif defined(USE_LIBRETINY)
721 void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
722  WiFi.macAddress(mac);
723 }
724 #endif
725 
726 std::string get_mac_address() {
727  uint8_t mac[6];
728  get_mac_address_raw(mac);
729  return str_snprintf("%02x%02x%02x%02x%02x%02x", 12, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
730 }
731 
732 std::string get_mac_address_pretty() {
733  uint8_t mac[6];
734  get_mac_address_raw(mac);
735  return str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
736 }
737 
738 #ifdef USE_ESP32
739 void set_mac_address(uint8_t *mac) { esp_base_mac_addr_set(mac); }
740 #endif
741 
743 #if defined(USE_ESP32) && !defined(USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC)
744  uint8_t mac[6];
745  // do not use 'esp_efuse_mac_get_custom(mac)' because it drops an error in the logs whenever it fails
746 #ifndef USE_ESP32_VARIANT_ESP32
747  return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
748 #else
749  return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
750 #endif
751 #else
752  return false;
753 #endif
754 }
755 
756 bool mac_address_is_valid(const uint8_t *mac) {
757  bool is_all_zeros = true;
758  bool is_all_ones = true;
759 
760  for (uint8_t i = 0; i < 6; i++) {
761  if (mac[i] != 0) {
762  is_all_zeros = false;
763  }
764  }
765  for (uint8_t i = 0; i < 6; i++) {
766  if (mac[i] != 0xFF) {
767  is_all_ones = false;
768  }
769  }
770  return !(is_all_zeros || is_all_ones);
771 }
772 
773 void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
774  // avoids CPU locks that could trigger WDT or affect WiFi/BT stability
775  uint32_t start = micros();
776 
777  const uint32_t lag = 5000; // microseconds, specifies the maximum time for a CPU busy-loop.
778  // it must be larger than the worst-case duration of a delay(1) call (hardware tasks)
779  // 5ms is conservative, it could be reduced when exact BT/WiFi stack delays are known
780  if (us > lag) {
781  delay((us - lag) / 1000UL); // note: in disabled-interrupt contexts delay() won't actually sleep
782  while (micros() - start < us - lag)
783  delay(1); // in those cases, this loop allows to yield for BT/WiFi stack tasks
784  }
785  while (micros() - start < us) // fine delay the remaining usecs
786  ;
787 }
788 
789 } // namespace esphome
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:602
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition: helpers.cpp:292
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition: helpers.cpp:274
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition: helpers.cpp:152
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:435
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:372
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition: helpers.cpp:742
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition: helpers.cpp:685
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition: helpers.cpp:291
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:360
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:341
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition: helpers.cpp:408
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition: helpers.cpp:196
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:277
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition: helpers.cpp:507
std::string str_ctype_transform(const std::string &str)
Definition: helpers.cpp:284
float lerp(float completion, float start, float end)
Linearly interpolate between start and end by completion (between 0 and 1).
Definition: helpers.cpp:95
mopeka_std_values val[4]
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:773
uint32_t IRAM_ATTR HOT micros()
Definition: core.cpp:27
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition: helpers.cpp:220
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:112
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:420
const stm32_dev_t * dev
Definition: stm32flash.h:97
const char *const TAG
Definition: spi.cpp:8
ParseOnOffState
Return values for parse_on_off().
Definition: helpers.h:440
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition: helpers.cpp:562
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition: helpers.cpp:266
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition: helpers.cpp:465
void start()
Start running the loop continuously.
Definition: helpers.cpp:673
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:96
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:579
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition: helpers.cpp:290
std::string str_sprintf(const char *fmt,...)
Definition: helpers.cpp:323
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:726
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition: helpers.cpp:267
void stop()
Stop running the loop continuously.
Definition: helpers.cpp:679
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition: helpers.cpp:739
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition: helpers.cpp:446
bool try_lock()
Definition: helpers.cpp:649
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores...
Definition: helpers.cpp:299
std::string to_string(int value)
Definition: helpers.cpp:82
std::string size_t len
Definition: helpers.h:301
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:186
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition: helpers.cpp:756
uint16_t length
Definition: tt21100.cpp:12
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint8_t end[39]
Definition: sun_gtil2.cpp:31
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition: helpers.cpp:732
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:309
void unlock()
Definition: helpers.cpp:650
float random_float()
Return a random float between 0 and 1.
Definition: helpers.cpp:218
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition: helpers.cpp:262
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
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:688
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition: helpers.cpp:570