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