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