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