22static const char *
const TAG =
"helpers";
24static const uint16_t CRC16_A001_LE_LUT_L[] = {0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
25 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440};
26static const uint16_t CRC16_A001_LE_LUT_H[] = {0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
27 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400};
30static const uint16_t CRC16_8408_LE_LUT_L[] = {0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
31 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7};
32static const uint16_t CRC16_8408_LE_LUT_H[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387,
33 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f};
36#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
37static const uint16_t CRC16_1021_BE_LUT_L[] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
38 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef};
39static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0x48c4, 0x5af5, 0x6ca6, 0x7e97,
40 0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
45uint8_t
crc8(
const uint8_t *data, uint8_t
len, uint8_t crc, uint8_t poly,
bool msb_first) {
46 while ((
len--) != 0u) {
47 uint8_t inbyte = *data++;
51 for (uint8_t i = 8; i != 0u; i--) {
53 crc = (crc << 1) ^ poly;
60 for (uint8_t i = 8; i != 0u; i--) {
61 bool mix = (crc ^ inbyte) & 0x01;
72uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t crc, uint16_t reverse_poly,
bool refin,
bool refout) {
74 if (reverse_poly == 0x8408) {
75 crc = crc16_le(refin ? crc : (crc ^ 0xffff), data,
len);
76 return refout ? crc : (crc ^ 0xffff);
83 if (reverse_poly == 0x8408) {
85 uint8_t combo = crc ^ (uint8_t) *data++;
86 crc = (crc >> 8) ^ CRC16_8408_LE_LUT_L[combo & 0x0F] ^ CRC16_8408_LE_LUT_H[combo >> 4];
91 if (reverse_poly == 0xa001) {
93 uint8_t combo = crc ^ (uint8_t) *data++;
94 crc = (crc >> 8) ^ CRC16_A001_LE_LUT_L[combo & 0x0F] ^ CRC16_A001_LE_LUT_H[combo >> 4];
99 for (uint8_t i = 0; i < 8; i++) {
101 crc = (crc >> 1) ^ reverse_poly;
109 return refout ? (crc ^ 0xffff) : crc;
112uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t crc, uint16_t poly,
bool refin,
bool refout) {
113#if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32S2)
114 if (poly == 0x1021) {
115 crc = crc16_be(refin ? crc : (crc ^ 0xffff), data,
len);
116 return refout ? crc : (crc ^ 0xffff);
122#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
123 if (poly == 0x1021) {
125 uint8_t combo = (crc >> 8) ^ *data++;
126 crc = (crc << 8) ^ CRC16_1021_BE_LUT_L[combo & 0x0F] ^ CRC16_1021_BE_LUT_H[combo >> 4];
131 crc ^= (((uint16_t) *data++) << 8);
132 for (uint8_t i = 0; i < 8; i++) {
134 crc = (crc << 1) ^ poly;
140#if !defined(USE_ESP32) || defined(USE_ESP32_VARIANT_ESP32S2)
143 return refout ? (crc ^ 0xffff) : crc;
147 uint32_t hash = 2166136261UL;
162 return strcasecmp(a.c_str(), b.c_str()) == 0;
164#if __cplusplus >= 202002L
165bool str_startswith(
const std::string &str,
const std::string &start) {
return str.starts_with(start); }
168bool str_startswith(
const std::string &str,
const std::string &start) {
return str.rfind(start, 0) == 0; }
170 return str.rfind(
end) == (str.size() -
end.size());
174 return str.length() >
length ? str.substr(0,
length) : str;
177 const char *pos = strchr(str, ch);
178 return pos ==
nullptr ? std::string(str) : std::string(str, pos - str);
180std::string
str_until(
const std::string &str,
char ch) {
return str.substr(0, str.find(ch)); }
185 result.resize(str.length());
186 std::transform(str.begin(), str.end(), result.begin(), [](
unsigned char ch) { return fn(ch); });
193 result.resize(str.length());
194 std::transform(str.begin(), str.end(), result.begin(), ::tolower);
195 std::replace(result.begin(), result.end(),
' ',
'_');
199 std::string out = str;
201 out.begin(), out.end(),
203 return c !=
'-' && c !=
'_' && (c <
'0' || c >
'9') && (c <
'a' || c >
'z') && (c <
'A' || c >
'Z');
214 size_t out_length = vsnprintf(&str[0],
len + 1, fmt, args);
217 if (out_length <
len)
218 str.resize(out_length);
227 size_t length = vsnprintf(
nullptr, 0, fmt, args);
232 vsnprintf(&str[0],
length + 1, fmt, args);
239static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
242 char buffer[MAX_NAME_WITH_SUFFIX_SIZE];
243 size_t name_len = name.size();
244 size_t total_len = name_len + 1 + suffix_len;
247 if (total_len >= MAX_NAME_WITH_SUFFIX_SIZE) {
251 name_len = MAX_NAME_WITH_SUFFIX_SIZE - suffix_len - 2;
252 total_len = name_len + 1 + suffix_len;
255 memcpy(buffer, name.c_str(), name_len);
256 buffer[name_len] = sep;
257 memcpy(buffer + name_len + 1, suffix_ptr, suffix_len);
258 buffer[total_len] =
'\0';
259 return std::string(buffer, total_len);
266 size_t chars = std::min(
length, 2 * count);
267 for (
size_t i = 2 * count - chars; i < 2 * count; i++, str++) {
268 if (*str >=
'0' && *str <=
'9') {
270 }
else if (*str >=
'A' && *str <=
'F') {
271 val = 10 + (*str -
'A');
272 }
else if (*str >=
'a' && *str <=
'f') {
273 val = 10 + (*str -
'a');
277 data[i >> 1] = !(i & 1) ?
val << 4 : data[i >> 1] |
val;
285 return std::string(buf);
291 for (
size_t i = 0; i <
length; i++) {
300static std::string format_hex_pretty_uint8(
const uint8_t *data,
size_t length,
char separator,
bool show_length) {
301 if (data ==
nullptr ||
length == 0)
304 uint8_t multiple = separator ? 3 : 2;
305 ret.resize(multiple *
length - (separator ? 1 : 0));
306 for (
size_t i = 0; i <
length; i++) {
309 if (separator && i !=
length - 1)
310 ret[multiple * i + 2] = separator;
312 if (show_length &&
length > 4)
313 return ret +
" (" + std::to_string(
length) +
")";
318 return format_hex_pretty_uint8(data,
length, separator, show_length);
320std::string
format_hex_pretty(
const std::vector<uint8_t> &data,
char separator,
bool show_length) {
325 if (data ==
nullptr ||
length == 0)
328 uint8_t multiple = separator ? 5 : 4;
329 ret.resize(multiple *
length - (separator ? 1 : 0));
330 for (
size_t i = 0; i <
length; i++) {
335 if (separator && i !=
length - 1)
336 ret[multiple * i + 4] = separator;
338 if (show_length &&
length > 4)
339 return ret +
" (" + std::to_string(
length) +
")";
342std::string
format_hex_pretty(
const std::vector<uint16_t> &data,
char separator,
bool show_length) {
346 return format_hex_pretty_uint8(
reinterpret_cast<const uint8_t *
>(data.data()), data.length(), separator, show_length);
351 result.resize(
length * 8);
352 for (
size_t byte_idx = 0; byte_idx <
length; byte_idx++) {
353 for (
size_t bit_idx = 0; bit_idx < 8; bit_idx++) {
354 result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) +
'0';
362 if (on ==
nullptr && strcasecmp(str,
"on") == 0)
364 if (on !=
nullptr && strcasecmp(str, on) == 0)
366 if (off ==
nullptr && strcasecmp(str,
"off") == 0)
368 if (off !=
nullptr && strcasecmp(str, off) == 0)
370 if (strcasecmp(str,
"toggle") == 0)
376static inline void normalize_accuracy_decimals(
float &value, int8_t &accuracy_decimals) {
377 if (accuracy_decimals < 0) {
378 auto multiplier = powf(10.0f, accuracy_decimals);
379 value = roundf(value * multiplier) / multiplier;
380 accuracy_decimals = 0;
385 normalize_accuracy_decimals(value, accuracy_decimals);
387 snprintf(tmp,
sizeof(tmp),
"%.*f", accuracy_decimals, value);
388 return std::string(tmp);
392 normalize_accuracy_decimals(value, accuracy_decimals);
396 if (unit_of_measurement.
empty()) {
397 snprintf(tmp,
sizeof(tmp),
"%.*f", accuracy_decimals, value);
399 snprintf(tmp,
sizeof(tmp),
"%.*f %s", accuracy_decimals, value, unit_of_measurement.
c_str());
401 return std::string(tmp);
407 snprintf(buf,
sizeof buf,
"%.5g", step);
409 std::string str{buf};
410 size_t dot_pos = str.find(
'.');
411 if (dot_pos == std::string::npos)
414 return str.length() - dot_pos - 1;
418static constexpr const char *BASE64_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
419 "abcdefghijklmnopqrstuvwxyz"
429static inline uint8_t base64_find_char(
char c) {
430 const char *pos = strchr(BASE64_CHARS, c);
431 return pos ? (pos - BASE64_CHARS) : 0;
434static inline bool is_base64(
char c) {
return (isalnum(c) || (c ==
'+') || (c ==
'/')); }
442 char char_array_3[3];
443 char char_array_4[4];
446 char_array_3[i++] = *(buf++);
448 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
449 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
450 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
451 char_array_4[3] = char_array_3[2] & 0x3f;
453 for (i = 0; (i < 4); i++)
454 ret += BASE64_CHARS[
static_cast<uint8_t
>(char_array_4[i])];
460 for (j = i; j < 3; j++)
461 char_array_3[j] =
'\0';
463 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
464 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
465 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
466 char_array_4[3] = char_array_3[2] & 0x3f;
468 for (j = 0; (j < i + 1); j++)
469 ret += BASE64_CHARS[
static_cast<uint8_t
>(char_array_4[j])];
478size_t base64_decode(
const std::string &encoded_string, uint8_t *buf,
size_t buf_len) {
479 std::vector<uint8_t> decoded =
base64_decode(encoded_string);
480 if (decoded.size() > buf_len) {
481 ESP_LOGW(TAG,
"Base64 decode: buffer too small, truncating");
482 decoded.resize(buf_len);
484 memcpy(buf, decoded.data(), decoded.size());
485 return decoded.size();
489 int in_len = encoded_string.size();
493 uint8_t char_array_4[4], char_array_3[3];
494 std::vector<uint8_t> ret;
499 while (in_len-- && (encoded_string[in] !=
'=') && is_base64(encoded_string[in])) {
500 char_array_4[i++] = encoded_string[in];
503 for (i = 0; i < 4; i++)
504 char_array_4[i] = base64_find_char(char_array_4[i]);
506 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
507 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
508 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
510 for (i = 0; (i < 3); i++)
511 ret.push_back(char_array_3[i]);
517 for (j = i; j < 4; j++)
520 for (j = 0; j < 4; j++)
521 char_array_4[j] = base64_find_char(char_array_4[j]);
523 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
524 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
525 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
527 for (j = 0; (j < i - 1); j++)
528 ret.push_back(char_array_3[j]);
542 return powf(value, gamma);
550 return powf(value, 1 / gamma);
553void rgb_to_hsv(
float red,
float green,
float blue,
int &hue,
float &saturation,
float &value) {
554 float max_color_value = std::max(std::max(red, green), blue);
555 float min_color_value = std::min(std::min(red, green), blue);
556 float delta = max_color_value - min_color_value;
560 }
else if (max_color_value == red) {
561 hue = int(fmod(((60 * ((green - blue) / delta)) + 360), 360));
562 }
else if (max_color_value == green) {
563 hue = int(fmod(((60 * ((blue - red) / delta)) + 120), 360));
564 }
else if (max_color_value == blue) {
565 hue = int(fmod(((60 * ((red - green) / delta)) + 240), 360));
568 if (max_color_value == 0) {
571 saturation = delta / max_color_value;
574 value = max_color_value;
576void hsv_to_rgb(
int hue,
float saturation,
float value,
float &red,
float &green,
float &blue) {
577 float chroma = value * saturation;
578 float hue_prime = fmod(hue / 60.0, 6);
579 float intermediate = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
580 float delta = value - chroma;
582 if (0 <= hue_prime && hue_prime < 1) {
584 green = intermediate;
586 }
else if (1 <= hue_prime && hue_prime < 2) {
590 }
else if (2 <= hue_prime && hue_prime < 3) {
594 }
else if (3 <= hue_prime && hue_prime < 4) {
596 green = intermediate;
598 }
else if (4 <= hue_prime && hue_prime < 5) {
602 }
else if (5 <= hue_prime && hue_prime < 6) {
637 return std::string(buf);
657 bool is_all_zeros =
true;
658 bool is_all_ones =
true;
660 for (uint8_t i = 0; i < 6; i++) {
662 is_all_zeros =
false;
664 if (mac[i] != 0xFF) {
668 return !(is_all_zeros || is_all_ones);
673 uint32_t start =
micros();
675 const uint32_t lag = 5000;
679 delay((us - lag) / 1000UL);
680 while (
micros() - start < us - lag)
683 while (
micros() - start < us)
void stop()
Stop running the loop continuously.
static bool is_high_frequency()
Check whether the loop is running continuously.
static uint8_t num_requests
void start()
Start running the loop continuously.
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr bool empty() const
Providing packet encoding functions for exchanging data with a remote host.
float random_float()
Return a random float between 0 and 1.
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
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.
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Create a string from a value and an accuracy in decimals.
char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing) This always uses uppercase (...
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
std::string make_name_with_suffix(const std::string &name, char sep, const char *suffix_ptr, size_t suffix_len)
Concatenate a name with a separator and suffix using an efficient stack-based approach.
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 format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
std::string value_accuracy_with_uom_to_string(float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Create a string from a value, an accuracy in decimals, and a unit of measurement.
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 fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
std::string str_snprintf(const char *fmt, size_t len,...)
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
uint32_t IRAM_ATTR HOT micros()
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
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.
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
std::string str_until(const char *str, char ch)
Extract the part of the string until either the first occurrence of the specified character,...
std::string format_mac_address_pretty(const uint8_t *mac)
std::string base64_encode(const std::vector< uint8_t > &buf)
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).
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
std::string str_sprintf(const char *fmt,...)
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
void IRAM_ATTR HOT delay(uint32_t ms)
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
void get_mac_address_into_buffer(std::span< char, 13 > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
ParseOnOffState
Return values for parse_on_off().
std::string str_ctype_transform(const std::string &str)
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.