18 #include <netinet/in.h> 19 #include <sys/ioctl.h> 23 #if defined(USE_ESP8266) 25 #include <user_interface.h> 28 #elif defined(USE_ESP32_FRAMEWORK_ARDUINO) 30 #elif defined(USE_ESP_IDF) 31 #include <freertos/FreeRTOS.h> 32 #include <freertos/portmacro.h> 34 #include "esp_random.h" 35 #include "esp_system.h" 36 #elif defined(USE_RP2040) 40 #include <hardware/structs/rosc.h> 41 #include <hardware/sync.h> 42 #elif defined(USE_HOST) 47 #include "esp32/rom/crc.h" 49 #include "esp_efuse.h" 50 #include "esp_efuse_table.h" 59 static const char *
const TAG =
"helpers";
61 static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
62 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
63 static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
64 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
67 static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
68 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
69 static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
70 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
72 static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
73 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
74 static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
75 0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
80 #if _GLIBCXX_RELEASE < 8 94 float lerp(
float completion,
float start,
float end) {
return start + (end - start) * completion; }
95 uint8_t
crc8(
const uint8_t *data, uint8_t
len) {
98 while ((len--) != 0u) {
99 uint8_t inbyte = *data++;
100 for (uint8_t i = 8; i != 0u; i--) {
101 bool mix = (crc ^ inbyte) & 0x01;
111 uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t
crc, uint16_t reverse_poly,
bool refin,
bool refout) {
113 if (reverse_poly == 0x8408) {
114 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
115 return refout ?
crc : (crc ^ 0xffff);
122 if (reverse_poly == 0x8408) {
124 uint8_t combo = crc ^ (uint8_t) *data++;
125 crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
129 if (reverse_poly == 0xa001) {
131 uint8_t combo = crc ^ (uint8_t) *data++;
132 crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
137 for (uint8_t i = 0; i < 8; i++) {
139 crc = (crc >> 1) ^ reverse_poly;
146 return refout ? (crc ^ 0xffff) : crc;
149 uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t
crc, uint16_t poly,
bool refin,
bool refout) {
151 if (poly == 0x1021) {
152 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
153 return refout ?
crc : (crc ^ 0xffff);
160 if (poly == 0x1021) {
162 uint8_t combo = (crc >> 8) ^ *data++;
163 crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
168 crc ^= (((uint16_t) *data++) << 8);
169 for (uint8_t i = 0; i < 8; i++) {
171 crc = (crc << 1) ^ poly;
180 return refout ? (crc ^ 0xffff) : crc;
184 uint32_t hash = 2166136261UL;
194 #elif defined(USE_ESP8266) 196 #elif defined(USE_RP2040) 199 for (uint8_t i = 0; i < 32; i++) {
201 result |= rosc_hw->randombit;
205 #elif defined(USE_LIBRETINY) 207 #elif defined(USE_HOST) 209 std::random_device
dev;
210 std::mt19937 rng(
dev());
211 std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max());
218 esp_fill_random(data, len);
221 #elif defined(USE_ESP8266) 222 bool random_bytes(uint8_t *data,
size_t len) {
return os_get_random(data, len) == 0; }
223 #elif defined(USE_RP2040) 227 for (uint8_t i = 0; i < 8; i++) {
229 result |= rosc_hw->randombit;
235 #elif defined(USE_LIBRETINY) 237 lt_rand_bytes(data, len);
240 #elif defined(USE_HOST) 242 FILE *fp = fopen(
"/dev/urandom",
"r");
244 ESP_LOGW(TAG,
"Could not open /dev/urandom, errno=%d", errno);
247 size_t read = fread(data, 1, len, fp);
249 ESP_LOGW(TAG,
"Not enough data from /dev/urandom");
260 return strcasecmp(a.c_str(), b.c_str()) == 0;
262 bool str_startswith(
const std::string &str,
const std::string &start) {
return str.rfind(start, 0) == 0; }
264 return str.rfind(end) == (str.size() - end.size());
267 return str.length() > length ? str.substr(0, length) : str;
270 const char *pos = strchr(str, ch);
271 return pos ==
nullptr ? std::string(str) : std::string(str, pos - str);
273 std::string
str_until(
const std::string &str,
char ch) {
return str.substr(0, str.find(ch)); }
278 result.resize(str.length());
279 std::transform(str.begin(), str.end(), result.begin(), [](
unsigned char ch) {
return fn(ch); });
282 std::string
str_lower_case(
const std::string &str) {
return str_ctype_transform<std::tolower>(str); }
283 std::string
str_upper_case(
const std::string &str) {
return str_ctype_transform<std::toupper>(str); }
286 result.resize(str.length());
287 std::transform(str.begin(), str.end(), result.begin(), ::tolower);
288 std::replace(result.begin(), result.end(),
' ',
'_');
292 std::string out = str;
294 out.begin(), out.end(),
296 return !(c ==
'-' || c ==
'_' || (c >=
'0' && c <= '9') || (c >=
'a' && c <= 'z') || (c >=
'A' && c <=
'Z'));
307 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
310 if (out_length < len)
311 str.resize(out_length);
320 size_t length = vsnprintf(
nullptr, 0, fmt, args);
325 vsnprintf(&str[0], length + 1, fmt, args);
335 size_t chars = std::min(length, 2 * count);
336 for (
size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
337 if (*str >=
'0' && *str <=
'9') {
339 }
else if (*str >=
'A' && *str <=
'F') {
340 val = 10 + (*str -
'A');
341 }
else if (*str >=
'a' && *str <=
'f') {
342 val = 10 + (*str -
'a');
346 data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
351 static char format_hex_char(uint8_t v) {
return v >= 10 ?
'a' + (v - 10) :
'0' + v; }
354 ret.resize(length * 2);
355 for (
size_t i = 0; i <
length; i++) {
356 ret[2 * i] = format_hex_char((data[i] & 0xF0) >> 4);
357 ret[2 * i + 1] = format_hex_char(data[i] & 0x0F);
363 static char format_hex_pretty_char(uint8_t v) {
return v >= 10 ?
'A' + (v - 10) :
'0' + v; }
368 ret.resize(3 * length - 1);
369 for (
size_t i = 0; i <
length; i++) {
370 ret[3 * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4);
371 ret[3 * i + 1] = format_hex_pretty_char(data[i] & 0x0F);
373 ret[3 * i + 2] =
'.';
376 return ret +
" (" +
to_string(length) +
")";
385 ret.resize(5 * length - 1);
386 for (
size_t i = 0; i <
length; i++) {
387 ret[5 * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12);
388 ret[5 * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8);
389 ret[5 * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4);
390 ret[5 * i + 3] = format_hex_pretty_char(data[i] & 0x000F);
392 ret[5 * i + 2] =
'.';
395 return ret +
" (" +
to_string(length) +
")";
401 if (on ==
nullptr && strcasecmp(str,
"on") == 0)
403 if (on !=
nullptr && strcasecmp(str, on) == 0)
405 if (off ==
nullptr && strcasecmp(str,
"off") == 0)
407 if (off !=
nullptr && strcasecmp(str, off) == 0)
409 if (strcasecmp(str,
"toggle") == 0)
416 if (accuracy_decimals < 0) {
417 auto multiplier = powf(10.0f, accuracy_decimals);
418 value = roundf(value * multiplier) / multiplier;
419 accuracy_decimals = 0;
422 snprintf(tmp,
sizeof(tmp),
"%.*f", accuracy_decimals, value);
423 return std::string(tmp);
429 snprintf(buf,
sizeof buf,
"%.5g", step);
431 std::string str{buf};
432 size_t dot_pos = str.find(
'.');
433 if (dot_pos == std::string::npos)
436 return str.length() - dot_pos - 1;
439 static const std::string BASE64_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" 440 "abcdefghijklmnopqrstuvwxyz" 443 static inline bool is_base64(
char c) {
return (isalnum(c) || (c ==
'+') || (c ==
'/')); }
451 char char_array_3[3];
452 char char_array_4[4];
455 char_array_3[i++] = *(buf++);
457 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
458 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
459 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
460 char_array_4[3] = char_array_3[2] & 0x3f;
462 for (i = 0; (i < 4); i++)
463 ret += BASE64_CHARS[char_array_4[i]];
469 for (j = i; j < 3; j++)
470 char_array_3[j] =
'\0';
472 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
473 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
474 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
475 char_array_4[3] = char_array_3[2] & 0x3f;
477 for (j = 0; (j < i + 1); j++)
478 ret += BASE64_CHARS[char_array_4[j]];
487 size_t base64_decode(
const std::string &encoded_string, uint8_t *buf,
size_t buf_len) {
488 std::vector<uint8_t> decoded =
base64_decode(encoded_string);
489 if (decoded.size() > buf_len) {
490 ESP_LOGW(TAG,
"Base64 decode: buffer too small, truncating");
491 decoded.resize(buf_len);
493 memcpy(buf, decoded.data(), decoded.size());
494 return decoded.size();
498 int in_len = encoded_string.size();
502 uint8_t char_array_4[4], char_array_3[3];
503 std::vector<uint8_t> ret;
505 while (in_len-- && (encoded_string[in] !=
'=') && is_base64(encoded_string[in])) {
506 char_array_4[i++] = encoded_string[in];
509 for (i = 0; i < 4; i++)
510 char_array_4[i] = BASE64_CHARS.find(char_array_4[i]);
512 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
513 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
514 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
516 for (i = 0; (i < 3); i++)
517 ret.push_back(char_array_3[i]);
523 for (j = i; j < 4; j++)
526 for (j = 0; j < 4; j++)
527 char_array_4[j] = BASE64_CHARS.find(char_array_4[j]);
529 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
530 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
531 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
533 for (j = 0; (j < i - 1); j++)
534 ret.push_back(char_array_3[j]);
548 return powf(value, gamma);
556 return powf(value, 1 / gamma);
559 void rgb_to_hsv(
float red,
float green,
float blue,
int &hue,
float &saturation,
float &value) {
560 float max_color_value = std::max(std::max(red, green), blue);
561 float min_color_value = std::min(std::min(red, green), blue);
562 float delta = max_color_value - min_color_value;
566 }
else if (max_color_value == red) {
567 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
568 }
else if (max_color_value == green) {
569 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
570 }
else if (max_color_value == blue) {
571 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
574 if (max_color_value == 0) {
577 saturation = delta / max_color_value;
580 value = max_color_value;
582 void hsv_to_rgb(
int hue,
float saturation,
float value,
float &red,
float &green,
float &blue) {
583 float chroma = value * saturation;
584 float hue_prime = fmod(hue / 60.0, 6);
585 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
586 float delta = value - chroma;
588 if (0 <= hue_prime && hue_prime < 1) {
590 green = intermediate;
592 }
else if (1 <= hue_prime && hue_prime < 2) {
596 }
else if (2 <= hue_prime && hue_prime < 3) {
600 }
else if (3 <= hue_prime && hue_prime < 4) {
602 green = intermediate;
604 }
else if (4 <= hue_prime && hue_prime < 5) {
608 }
else if (5 <= hue_prime && hue_prime < 6) {
624 #if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST) 631 #elif defined(USE_ESP32) || defined(USE_LIBRETINY) 634 void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
635 bool Mutex::try_lock() {
return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
639 #if defined(USE_ESP8266) 642 #elif defined(USE_ESP32) || defined(USE_LIBRETINY) 647 #elif defined(USE_RP2040) 657 this->started_ =
true;
663 this->started_ =
false;
667 #if defined(USE_HOST) 669 static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS;
670 memcpy(mac, esphome_host_mac_address,
sizeof(esphome_host_mac_address));
672 #elif defined(USE_ESP32) 674 #if defined(CONFIG_SOC_IEEE802154_SUPPORTED) 678 esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48);
680 esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48);
684 esp_efuse_mac_get_custom(mac);
686 esp_efuse_mac_get_default(mac);
690 #elif defined(USE_ESP8266) 692 wifi_get_macaddr(STATION_IF, mac);
694 #elif defined(USE_RP2040) 697 WiFi.macAddress(mac);
700 #elif defined(USE_LIBRETINY) 702 WiFi.macAddress(mac);
709 return str_snprintf(
"%02x%02x%02x%02x%02x%02x", 12, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
715 return str_snprintf(
"%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
723 #if defined(USE_ESP32) && !defined(USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC) 726 #ifndef USE_ESP32_VARIANT_ESP32 727 return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) &&
mac_address_is_valid(mac);
729 return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) &&
mac_address_is_valid(mac);
737 bool is_all_zeros =
true;
738 bool is_all_ones =
true;
740 for (uint8_t i = 0; i < 6; i++) {
742 is_all_zeros =
false;
745 for (uint8_t i = 0; i < 6; i++) {
746 if (mac[i] != 0xFF) {
750 return !(is_all_zeros || is_all_ones);
754 uint32_t start =
micros();
756 const uint32_t lag = 5000;
760 delay((us - lag) / 1000UL);
761 while (
micros() - start < us - lag)
764 while (
micros() - start < us)
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)...
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Create a string from a value and an accuracy in decimals.
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.
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
static bool is_high_frequency()
Check whether the loop is running continuously.
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
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.
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
std::string str_until(const char *str, char ch)
Extract the part of the string until either the first occurrence of the specified character...
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
std::string str_ctype_transform(const std::string &str)
float lerp(float completion, float start, float end)
Linearly interpolate between start and end by completion (between 0 and 1).
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait...
uint32_t IRAM_ATTR HOT micros()
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
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.
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
ParseOnOffState
Return values for parse_on_off().
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
std::string base64_encode(const std::vector< uint8_t > &buf)
void start()
Start running the loop continuously.
uint8_t crc8(const uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size len.
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)...
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
std::string str_sprintf(const char *fmt,...)
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
void stop()
Stop running the loop continuously.
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores...
std::string to_string(int value)
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Implementation of SPI Controller mode.
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
static uint8_t num_requests
std::string str_snprintf(const char *fmt, size_t len,...)
float random_float()
Return a random float between 0 and 1.
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
void IRAM_ATTR HOT delay(uint32_t ms)
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.