26#include <esp_heap_caps.h>
30#include <freertos/FreeRTOS.h>
31#include <freertos/semphr.h>
32#elif defined(USE_LIBRETINY)
41#define HOT __attribute__((hot))
42#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
43#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
44#define PACKED __attribute__((packed))
53using std::is_trivially_copyable;
54using std::make_unique;
55using std::enable_if_t;
57using std::is_invocable;
58#if __cpp_lib_bit_cast >= 201806
63 typename To,
typename From,
64 enable_if_t<
sizeof(To) ==
sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
68 memcpy(&dst, &src,
sizeof(To));
74inline float lerp(
float completion,
float start,
float end) =
delete;
78template<
typename T>
constexpr T
byteswap(T n) {
80 for (
size_t i = 0; i <
sizeof(T); i++)
81 reinterpret_cast<uint8_t *
>(&
m)[i] =
reinterpret_cast<uint8_t *
>(&n)[
sizeof(T) - 1 - i];
84template<>
constexpr uint8_t
byteswap(uint8_t n) {
return n; }
85template<>
constexpr uint16_t
byteswap(uint16_t n) {
return __builtin_bswap16(n); }
86template<>
constexpr uint32_t
byteswap(uint32_t n) {
return __builtin_bswap32(n); }
87template<>
constexpr uint64_t
byteswap(uint64_t n) {
return __builtin_bswap64(n); }
88template<>
constexpr int8_t
byteswap(int8_t n) {
return n; }
89template<>
constexpr int16_t
byteswap(int16_t n) {
return __builtin_bswap16(n); }
90template<>
constexpr int32_t
byteswap(int32_t n) {
return __builtin_bswap32(n); }
91template<>
constexpr int64_t
byteswap(int64_t n) {
return __builtin_bswap64(n); }
102 using iterator =
typename std::array<T, N>::iterator;
108 std::array<T, N> data_{};
115 data_[count_++] = value;
119 size_t size()
const {
return count_; }
120 bool empty()
const {
return count_ == 0; }
144template<
typename T,
typename U> T
remap(U value, U min, U max, T min_out, T max_out) {
145 return (value - min) * (max_out - min_out) / (max - min) + min_out;
149uint8_t
crc8(
const uint8_t *data, uint8_t
len);
152uint16_t
crc16(
const uint8_t *data, uint16_t
len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
153 bool refin =
false,
bool refout =
false);
154uint16_t
crc16be(
const uint8_t *data, uint16_t
len, uint16_t crc = 0, uint16_t poly = 0x1021,
bool refin =
false,
155 bool refout =
false);
158uint32_t
fnv1_hash(
const std::string &str);
174 return (
static_cast<uint16_t
>(msb) << 8) | (
static_cast<uint16_t
>(lsb));
177constexpr uint32_t
encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
178 return (
static_cast<uint32_t
>(byte1) << 16) | (
static_cast<uint32_t
>(byte2) << 8) | (
static_cast<uint32_t
>(byte3));
181constexpr uint32_t
encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
182 return (
static_cast<uint32_t
>(byte1) << 24) | (
static_cast<uint32_t
>(byte2) << 16) |
183 (
static_cast<uint32_t
>(byte3) << 8) | (
static_cast<uint32_t
>(byte4));
187template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
constexpr T
encode_value(
const uint8_t *bytes) {
189 for (
size_t i = 0; i <
sizeof(T); i++) {
196template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
201template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
203 std::array<uint8_t,
sizeof(T)> ret{};
204 for (
size_t i =
sizeof(T); i > 0; i--) {
205 ret[i - 1] =
val & 0xFF;
213 x = ((
x & 0xAA) >> 1) | ((
x & 0x55) << 1);
214 x = ((
x & 0xCC) >> 2) | ((
x & 0x33) << 2);
215 x = ((
x & 0xF0) >> 4) | ((
x & 0x0F) << 4);
224 return (
reverse_bits(
static_cast<uint16_t
>(
x & 0xFFFF)) << 16) |
230#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
239#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
255bool str_startswith(
const std::string &str,
const std::string &start);
264std::string
str_until(
const char *str,
char ch);
266std::string
str_until(
const std::string &str,
char ch);
290template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value),
int> = 0>
293 unsigned long value = ::strtoul(str, &
end, 10);
294 if (
end == str || *
end !=
'\0' || value > std::numeric_limits<T>::max())
299template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
unsigned<T>::value),
int> = 0>
304template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
signed<T>::value),
int> = 0>
307 signed long value = ::strtol(str, &
end, 10);
308 if (
end == str || *
end !=
'\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
313template<
typename T, enable_if_t<(std::is_
integral<T>::value && std::is_
signed<T>::value),
int> = 0>
318template<
typename T, enable_if_t<(std::is_same<T,
float>::value),
int> = 0> optional<T>
parse_number(
const char *str) {
320 float value = ::strtof(str, &
end);
321 if (
end == str || *
end !=
'\0' || value == HUGE_VALF)
326template<
typename T, enable_if_t<(std::is_same<T,
float>::value),
int> = 0>
342size_t parse_hex(
const char *str,
size_t len, uint8_t *data,
size_t count);
344inline bool parse_hex(
const char *str, uint8_t *data,
size_t count) {
345 return parse_hex(str, strlen(str), data, count) == 2 * count;
348inline bool parse_hex(
const std::string &str, uint8_t *data,
size_t count) {
349 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
352inline bool parse_hex(
const char *str, std::vector<uint8_t> &data,
size_t count) {
354 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
357inline bool parse_hex(
const std::string &str, std::vector<uint8_t> &data,
size_t count) {
359 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
366template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
369 if (
len > 2 *
sizeof(T) ||
parse_hex(str,
len,
reinterpret_cast<uint8_t *
>(&
val),
sizeof(T)) == 0)
378template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
optional<T> parse_hex(
const std::string &str) {
387std::string
format_hex(
const std::vector<uint8_t> &data);
389template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0> std::string
format_hex(T
val) {
391 return format_hex(
reinterpret_cast<uint8_t *
>(&
val),
sizeof(T));
393template<std::
size_t N> std::string
format_hex(
const std::array<uint8_t, N> &data) {
422std::string
format_hex_pretty(
const uint8_t *data,
size_t length,
char separator =
'.',
bool show_length =
true);
444std::string
format_hex_pretty(
const uint16_t *data,
size_t length,
char separator =
'.',
bool show_length =
true);
467std::string
format_hex_pretty(
const std::vector<uint8_t> &data,
char separator =
'.',
bool show_length =
true);
489std::string
format_hex_pretty(
const std::vector<uint16_t> &data,
char separator =
'.',
bool show_length =
true);
511std::string
format_hex_pretty(
const std::string &data,
char separator =
'.',
bool show_length =
true);
536template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0>
545template<typename T, enable_if_t<std::is_unsigned<T>::value,
int> = 0> std::string
format_bin(T
val) {
547 return format_bin(
reinterpret_cast<uint8_t *
>(&
val),
sizeof(T));
566std::string
base64_encode(
const uint8_t *buf,
size_t buf_len);
569std::vector<uint8_t>
base64_decode(
const std::string &encoded_string);
570size_t base64_decode(std::string
const &encoded_string, uint8_t *buf,
size_t buf_len);
583void rgb_to_hsv(
float red,
float green,
float blue,
int &hue,
float &saturation,
float &value);
585void hsv_to_rgb(
int hue,
float saturation,
float value,
float &red,
float &green,
float &blue);
611 void add(std::function<
void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
615 for (
auto &cb : this->callbacks_)
618 size_t size()
const {
return this->callbacks_.size(); }
691#if defined(USE_ESP32) || defined(USE_LIBRETINY)
692 SemaphoreHandle_t handle_;
738#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
834 this->flags_ = flags;
841 size_t size = n * manual_size;
845 ptr =
static_cast<T *
>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
848 ptr =
static_cast<T *
>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
852 ptr =
static_cast<T *
>(malloc(size));
860 size_t size = n * manual_size;
864 ptr =
static_cast<T *
>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
867 ptr =
static_cast<T *
>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
871 ptr =
static_cast<T *
>(realloc(p, size));
885 return ESP.getFreeHeap();
886#elif defined(USE_ESP32)
888 this->flags_ &
ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
890 this->flags_ &
ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
891 return max_internal + max_external;
892#elif defined(USE_RP2040)
893 return ::rp2040.getFreeHeap();
894#elif defined(USE_LIBRETINY)
895 return lt_heap_get_free();
906 return ESP.getMaxFreeBlockSize();
907#elif defined(USE_ESP32)
909 this->flags_ &
ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
911 this->flags_ &
ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
912 return std::max(max_internal, max_external);
933template<typename T, enable_if_t<!std::is_pointer<T>::value,
int> = 0> T
id(T value) {
return value; }
938template<typename T, enable_if_t<std::is_pointer<T *>::value,
int> = 0> T &
id(T *value) {
return *value; }
945ESPDEPRECATED(
"hexencode() is deprecated, use format_hex_pretty() instead.",
"2022.1")
949ESPDEPRECATED(
"hexencode() is deprecated, use format_hex_pretty() instead.",
"2022.1")
950std::
string hexencode(const T &data) {
951 return hexencode(data.data(), data.size());
void operator()(Ts... args)
Call all callbacks in this manager.
std::vector< std::function< void(Ts...)> > callbacks_
void call(Ts... args)
Call all callbacks in this manager.
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Helper class to deduplicate items in a series of values.
bool next(T value)
Feeds the next item in the series to the deduplicator and returns false if this is a duplicate.
bool has_value() const
Returns true if this deduplicator has processed any items.
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Helper class to request loop() to be called as fast as possible.
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.
Helper class to disable interrupts.
Helper class that wraps a mutex with a RAII-style API.
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
T * get_parent() const
Get the parent of this object.
void set_parent(T *parent)
Set the parent of this object.
An STL allocator that uses SPI or internal RAM.
RAMAllocator(uint8_t flags)
T * reallocate(T *p, size_t n, size_t manual_size)
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
T * reallocate(T *p, size_t n)
void deallocate(T *p, size_t n)
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
constexpr RAMAllocator(const RAMAllocator< U > &other)
T * allocate(size_t n, size_t manual_size)
Minimal static vector - saves memory by avoiding std::vector overhead.
const_reverse_iterator rend() const
reverse_iterator rbegin()
const T & operator[](size_t i) const
void push_back(const T &value)
const_reverse_iterator rbegin() const
std::reverse_iterator< const_iterator > const_reverse_iterator
typename std::array< T, N >::iterator iterator
typename std::array< T, N >::const_iterator const_iterator
std::reverse_iterator< iterator > reverse_iterator
const_iterator end() const
const_iterator begin() const
struct @67::@68 __attribute__
Providing packet encoding functions for exchanging data with a remote host.
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
uint8_t crc8(const uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size len using the CRC-8-Dallas/Maxim polynomial.
ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1") inline std
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.
constexpr T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order.
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
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.
constexpr T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order.
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
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.
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
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,...)
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.
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)
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
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)
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
std::string str_sprintf(const char *fmt,...)
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
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.
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
float lerp(float completion, float start, float end)=delete
T remap(U value, U min, U max, T min_out, T max_out)
Remap value from the range (min, max) to (min_out, max_out).
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
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_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.