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