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