14 #if defined(USE_ESP8266) 16 #include <user_interface.h> 19 #elif defined(USE_ESP32_FRAMEWORK_ARDUINO) 21 #elif defined(USE_ESP_IDF) 22 #include <freertos/FreeRTOS.h> 23 #include <freertos/portmacro.h> 25 #include "esp_random.h" 26 #include "esp_system.h" 27 #elif defined(USE_RP2040) 31 #include <hardware/structs/rosc.h> 32 #include <hardware/sync.h> 33 #elif defined(USE_HOST) 38 #include "esp32/rom/crc.h" 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" 52 static const char *
const TAG =
"helpers";
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};
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};
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};
73 #if _GLIBCXX_RELEASE < 7 87 float lerp(
float completion,
float start,
float end) {
return start + (end - start) * completion; }
88 uint8_t
crc8(uint8_t *data, uint8_t
len) {
91 while ((len--) != 0u) {
92 uint8_t inbyte = *data++;
93 for (uint8_t i = 8; i != 0u; i--) {
94 bool mix = (crc ^ inbyte) & 0x01;
104 uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t
crc, uint16_t reverse_poly,
bool refin,
bool refout) {
106 if (reverse_poly == 0x8408) {
107 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data, len);
108 return refout ?
crc : (crc ^ 0xffff);
115 if (reverse_poly == 0x8408) {
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];
122 if (reverse_poly == 0xa001) {
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];
130 for (uint8_t i = 0; i < 8; i++) {
132 crc = (crc >> 1) ^ reverse_poly;
139 return refout ? (crc ^ 0xffff) : crc;
142 uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t
crc, uint16_t poly,
bool refin,
bool refout) {
144 if (poly == 0x1021) {
145 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data, len);
146 return refout ?
crc : (crc ^ 0xffff);
153 if (poly == 0x1021) {
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];
161 crc ^= (((uint16_t) *data++) << 8);
162 for (uint8_t i = 0; i < 8; i++) {
164 crc = (crc << 1) ^ poly;
173 return refout ? (crc ^ 0xffff) : crc;
177 uint32_t hash = 2166136261UL;
188 #elif defined(USE_ESP8266) 190 #elif defined(USE_RP2040) 192 for (uint8_t i = 0; i < 32; i++) {
194 result |= rosc_hw->randombit;
197 #elif defined(USE_LIBRETINY) 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());
205 #error "No random source available for this configuration." 211 esp_fill_random(data, len);
213 #elif defined(USE_ESP8266) 214 return os_get_random(data, len) == 0;
215 #elif defined(USE_RP2040) 218 for (uint8_t i = 0; i < 8; i++) {
220 result |= rosc_hw->randombit;
225 #elif defined(USE_LIBRETINY) 226 lt_rand_bytes(data, len);
228 #elif defined(USE_HOST) 229 FILE *fp = fopen(
"/dev/urandom",
"r");
231 ESP_LOGW(TAG,
"Could not open /dev/urandom, errno=%d", errno);
234 size_t read = fread(data, 1, len, fp);
236 ESP_LOGW(TAG,
"Not enough data from /dev/urandom");
242 #error "No random source available for this configuration." 249 return strcasecmp(a.c_str(), b.c_str()) == 0;
251 bool str_startswith(
const std::string &str,
const std::string &start) {
return str.rfind(start, 0) == 0; }
253 return str.rfind(end) == (str.size() - end.size());
256 return str.length() > length ? str.substr(0, length) : str;
259 const char *pos = strchr(str, ch);
260 return pos ==
nullptr ? std::string(str) : std::string(str, pos - str);
262 std::string
str_until(
const std::string &str,
char ch) {
return str.substr(0, str.find(ch)); }
267 result.resize(str.length());
268 std::transform(str.begin(), str.end(), result.begin(), [](
unsigned char ch) {
return fn(ch); });
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); }
275 result.resize(str.length());
276 std::transform(str.begin(), str.end(), result.begin(), ::tolower);
277 std::replace(result.begin(), result.end(),
' ',
'_');
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');
293 size_t out_length = vsnprintf(&str[0], len + 1, fmt, args);
296 if (out_length < len)
297 str.resize(out_length);
306 size_t length = vsnprintf(
nullptr, 0, fmt, args);
311 vsnprintf(&str[0], length + 1, fmt, args);
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') {
325 }
else if (*str >=
'A' && *str <=
'F') {
326 val = 10 + (*str -
'A');
327 }
else if (*str >=
'a' && *str <=
'f') {
328 val = 10 + (*str -
'a');
332 data[i >> 1] = !(i & 1) ? val << 4 : data[i >> 1] | val;
337 static char format_hex_char(uint8_t v) {
return v >= 10 ?
'a' + (v - 10) :
'0' + v; }
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);
349 static char format_hex_pretty_char(uint8_t v) {
return v >= 10 ?
'A' + (v - 10) :
'0' + v; }
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);
359 ret[3 * i + 2] =
'.';
362 return ret +
" (" +
to_string(length) +
")";
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);
378 ret[5 * i + 2] =
'.';
381 return ret +
" (" +
to_string(length) +
")";
387 if (on ==
nullptr && strcasecmp(str,
"on") == 0)
389 if (on !=
nullptr && strcasecmp(str, on) == 0)
391 if (off ==
nullptr && strcasecmp(str,
"off") == 0)
393 if (off !=
nullptr && strcasecmp(str, off) == 0)
395 if (strcasecmp(str,
"toggle") == 0)
402 if (accuracy_decimals < 0) {
403 auto multiplier = powf(10.0f, accuracy_decimals);
404 value = roundf(value * multiplier) / multiplier;
405 accuracy_decimals = 0;
408 snprintf(tmp,
sizeof(tmp),
"%.*f", accuracy_decimals, value);
409 return std::string(tmp);
415 sprintf(buf,
"%.5g", step);
417 std::string str{buf};
418 size_t dot_pos = str.find(
'.');
419 if (dot_pos == std::string::npos)
422 return str.length() - dot_pos - 1;
433 return powf(value, gamma);
441 return powf(value, 1 / gamma);
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;
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));
459 if (max_color_value == 0) {
462 saturation = delta / max_color_value;
465 value = max_color_value;
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;
473 if (0 <= hue_prime && hue_prime < 1) {
475 green = intermediate;
477 }
else if (1 <= hue_prime && hue_prime < 2) {
481 }
else if (2 <= hue_prime && hue_prime < 3) {
485 }
else if (3 <= hue_prime && hue_prime < 4) {
487 green = intermediate;
489 }
else if (4 <= hue_prime && hue_prime < 5) {
493 }
else if (5 <= hue_prime && hue_prime < 6) {
509 #if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST) 515 #elif defined(USE_ESP32) || defined(USE_LIBRETINY) 517 void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
518 bool Mutex::try_lock() {
return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
522 #if defined(USE_ESP8266) 525 #elif defined(USE_ESP32) || defined(USE_LIBRETINY) 530 #elif defined(USE_RP2040) 540 this->started_ =
true;
546 this->started_ =
false;
551 #if defined(USE_ESP32) 552 #if defined(CONFIG_SOC_IEEE802154_SUPPORTED) || defined(USE_ESP32_IGNORE_EFUSE_MAC_CRC) 559 esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48);
561 esp_efuse_mac_get_default(mac);
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);
574 return str_snprintf(
"%02x%02x%02x%02x%02x%02x", 12, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
579 return str_snprintf(
"%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
586 uint32_t start =
micros();
588 const uint32_t lag = 5000;
592 delay((us - lag) / 1000UL);
593 while (
micros() - start < us - lag)
596 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.
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...
uint8_t crc8(uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size 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.
void start()
Start running the loop continuously.
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.
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.