ESPHome 2025.9.0
Loading...
Searching...
No Matches
helpers.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <cmath>
5#include <cstdint>
6#include <cstring>
7#include <functional>
8#include <iterator>
9#include <limits>
10#include <memory>
11#include <string>
12#include <type_traits>
13#include <vector>
14
16
17#ifdef USE_ESP8266
18#include <Esp.h>
19#endif
20
21#ifdef USE_RP2040
22#include <Arduino.h>
23#endif
24
25#ifdef USE_ESP32
26#include <esp_heap_caps.h>
27#endif
28
29#if defined(USE_ESP32)
30#include <freertos/FreeRTOS.h>
31#include <freertos/semphr.h>
32#elif defined(USE_LIBRETINY)
33#include <FreeRTOS.h>
34#include <semphr.h>
35#endif
36
37#ifdef USE_HOST
38#include <mutex>
39#endif
40
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))
45
46namespace esphome {
47
50
51// Keep "using" even after the removal of our backports, to avoid breaking existing code.
52using std::to_string;
53using std::is_trivially_copyable;
54using std::make_unique;
55using std::enable_if_t;
56using std::clamp;
57using std::is_invocable;
58#if __cpp_lib_bit_cast >= 201806
59using std::bit_cast;
60#else
62template<
63 typename To, typename From,
64 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
65 int> = 0>
66To bit_cast(const From &src) {
67 To dst;
68 memcpy(&dst, &src, sizeof(To));
69 return dst;
70}
71#endif
72
73// clang-format off
74inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
75// clang-format on
76
77// std::byteswap from C++23
78template<typename T> constexpr T byteswap(T n) {
79 T m;
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];
82 return m;
83}
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); }
92
94
97
99template<typename T, size_t N> class StaticVector {
100 public:
101 using value_type = T;
102 using iterator = typename std::array<T, N>::iterator;
103 using const_iterator = typename std::array<T, N>::const_iterator;
104 using reverse_iterator = std::reverse_iterator<iterator>;
105 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
106
107 private:
108 std::array<T, N> data_{};
109 size_t count_{0};
110
111 public:
112 // Minimal vector-compatible interface - only what we actually use
113 void push_back(const T &value) {
114 if (count_ < N) {
115 data_[count_++] = value;
116 }
117 }
118
119 size_t size() const { return count_; }
120 bool empty() const { return count_ == 0; }
121
122 T &operator[](size_t i) { return data_[i]; }
123 const T &operator[](size_t i) const { return data_[i]; }
124
125 // For range-based for loops
126 iterator begin() { return data_.begin(); }
127 iterator end() { return data_.begin() + count_; }
128 const_iterator begin() const { return data_.begin(); }
129 const_iterator end() const { return data_.begin() + count_; }
130
131 // Reverse iterators
136};
137
139
142
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;
146}
147
149uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
150
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);
156
158uint32_t fnv1_hash(const char *str);
159inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
160
162uint32_t random_uint32();
164float random_float();
166bool random_bytes(uint8_t *data, size_t len);
167
169
172
174constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
175 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
176}
178constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
179 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
180}
182constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
183 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
184 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
185}
186
188template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
189 T val = 0;
190 for (size_t i = 0; i < sizeof(T); i++) {
191 val <<= 8;
192 val |= bytes[i];
193 }
194 return val;
195}
197template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
198constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
199 return encode_value<T>(bytes.data());
200}
202template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
203constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
204 std::array<uint8_t, sizeof(T)> ret{};
205 for (size_t i = sizeof(T); i > 0; i--) {
206 ret[i - 1] = val & 0xFF;
207 val >>= 8;
208 }
209 return ret;
210}
211
213inline uint8_t reverse_bits(uint8_t x) {
214 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
215 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
216 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
217 return x;
218}
220inline uint16_t reverse_bits(uint16_t x) {
221 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
222}
224inline uint32_t reverse_bits(uint32_t x) {
225 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
226 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
227}
228
230template<typename T> constexpr T convert_big_endian(T val) {
231#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
232 return byteswap(val);
233#else
234 return val;
235#endif
236}
237
239template<typename T> constexpr T convert_little_endian(T val) {
240#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
241 return val;
242#else
243 return byteswap(val);
244#endif
245}
246
248
251
253bool str_equals_case_insensitive(const std::string &a, const std::string &b);
254
256bool str_startswith(const std::string &str, const std::string &start);
258bool str_endswith(const std::string &str, const std::string &end);
259
261std::string str_truncate(const std::string &str, size_t length);
262
265std::string str_until(const char *str, char ch);
267std::string str_until(const std::string &str, char ch);
268
270std::string str_lower_case(const std::string &str);
272std::string str_upper_case(const std::string &str);
274std::string str_snake_case(const std::string &str);
275
277std::string str_sanitize(const std::string &str);
278
280std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
281
283std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
284
286
289
291template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
292optional<T> parse_number(const char *str) {
293 char *end = nullptr;
294 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
295 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
296 return {};
297 return value;
298}
300template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
301optional<T> parse_number(const std::string &str) {
302 return parse_number<T>(str.c_str());
303}
305template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
306optional<T> parse_number(const char *str) {
307 char *end = nullptr;
308 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
309 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
310 return {};
311 return value;
312}
314template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
315optional<T> parse_number(const std::string &str) {
316 return parse_number<T>(str.c_str());
317}
319template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
320 char *end = nullptr;
321 float value = ::strtof(str, &end);
322 if (end == str || *end != '\0' || value == HUGE_VALF)
323 return {};
324 return value;
325}
327template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
328optional<T> parse_number(const std::string &str) {
329 return parse_number<T>(str.c_str());
330}
331
343size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
345inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
346 return parse_hex(str, strlen(str), data, count) == 2 * count;
347}
349inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
350 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
351}
353inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
354 data.resize(count);
355 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
356}
358inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
359 data.resize(count);
360 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
361}
367template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
368optional<T> parse_hex(const char *str, size_t len) {
369 T val = 0;
370 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
371 return {};
372 return convert_big_endian(val);
373}
375template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
376 return parse_hex<T>(str, strlen(str));
377}
379template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
380 return parse_hex<T>(str.c_str(), str.length());
381}
382
384inline char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
385
388inline char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
389
391inline void format_mac_addr_upper(const uint8_t *mac, char *output) {
392 for (size_t i = 0; i < 6; i++) {
393 uint8_t byte = mac[i];
394 output[i * 3] = format_hex_pretty_char(byte >> 4);
395 output[i * 3 + 1] = format_hex_pretty_char(byte & 0x0F);
396 if (i < 5)
397 output[i * 3 + 2] = ':';
398 }
399 output[17] = '\0';
400}
401
403inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
404 for (size_t i = 0; i < 6; i++) {
405 uint8_t byte = mac[i];
406 output[i * 2] = format_hex_char(byte >> 4);
407 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
408 }
409 output[12] = '\0';
410}
411
413std::string format_mac_address_pretty(const uint8_t mac[6]);
415std::string format_hex(const uint8_t *data, size_t length);
417std::string format_hex(const std::vector<uint8_t> &data);
419template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
421 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
422}
423template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
424 return format_hex(data.data(), data.size());
425}
426
452std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
453
474std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
475
497std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
498
519std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
520
541std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
542
566template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
567std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
569 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
570}
571
573std::string format_bin(const uint8_t *data, size_t length);
575template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
577 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
578}
579
588ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
589
591std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
592
594int8_t step_to_accuracy_decimals(float step);
595
596std::string base64_encode(const uint8_t *buf, size_t buf_len);
597std::string base64_encode(const std::vector<uint8_t> &buf);
598
599std::vector<uint8_t> base64_decode(const std::string &encoded_string);
600size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
601
603
606
608float gamma_correct(float value, float gamma);
610float gamma_uncorrect(float value, float gamma);
611
613void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
615void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
616
618
621
623constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
625constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
626
628
631
632template<typename... X> class CallbackManager;
633
638template<typename... Ts> class CallbackManager<void(Ts...)> {
639 public:
641 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
642
644 void call(Ts... args) {
645 for (auto &cb : this->callbacks_)
646 cb(args...);
647 }
648 size_t size() const { return this->callbacks_.size(); }
649
651 void operator()(Ts... args) { call(args...); }
652
653 protected:
654 std::vector<std::function<void(Ts...)>> callbacks_;
655};
656
658template<typename T> class Deduplicator {
659 public:
661 bool next(T value) {
662 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
663 return false;
664 }
665 this->has_value_ = true;
666 this->value_unknown_ = false;
667 this->last_value_ = value;
668 return true;
669 }
672 bool ret = !this->value_unknown_;
673 this->value_unknown_ = true;
674 return ret;
675 }
677 bool has_value() const { return this->has_value_; }
678
679 protected:
680 bool has_value_{false};
681 bool value_unknown_{false};
683};
684
686template<typename T> class Parented {
687 public:
689 Parented(T *parent) : parent_(parent) {}
690
692 T *get_parent() const { return parent_; }
694 void set_parent(T *parent) { parent_ = parent; }
695
696 protected:
697 T *parent_{nullptr};
698};
699
701
704
709class Mutex {
710 public:
711 Mutex();
712 Mutex(const Mutex &) = delete;
713 ~Mutex();
714 void lock();
715 bool try_lock();
716 void unlock();
717
718 Mutex &operator=(const Mutex &) = delete;
719
720 private:
721#if defined(USE_ESP32) || defined(USE_LIBRETINY)
722 SemaphoreHandle_t handle_;
723#else
724 // d-pointer to store private data on new platforms
725 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
726#endif
727};
728
734 public:
735 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
736 ~LockGuard() { mutex_.unlock(); }
737
738 private:
739 Mutex &mutex_;
740};
741
763 public:
766
767 protected:
768#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
769 uint32_t state_;
770#endif
771};
772
780class LwIPLock {
781 public:
782 LwIPLock();
783 ~LwIPLock();
784
785 // Delete copy constructor and copy assignment operator to prevent accidental copying
786 LwIPLock(const LwIPLock &) = delete;
787 LwIPLock &operator=(const LwIPLock &) = delete;
788};
789
796 public:
798 void start();
800 void stop();
801
803 static bool is_high_frequency();
804
805 protected:
806 bool started_{false};
807 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
808};
809
811void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
812
814std::string get_mac_address();
815
817std::string get_mac_address_pretty();
818
819#ifdef USE_ESP32
821void set_mac_address(uint8_t *mac);
822#endif
823
827
830bool mac_address_is_valid(const uint8_t *mac);
831
833void delay_microseconds_safe(uint32_t us);
834
836
839
848template<class T> class RAMAllocator {
849 public:
850 using value_type = T;
851
852 enum Flags {
853 NONE = 0, // Perform external allocation and fall back to internal memory
854 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
855 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
856 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
857 };
858
859 RAMAllocator() = default;
860 RAMAllocator(uint8_t flags) {
861 // default is both external and internal
863 if (flags != 0)
864 this->flags_ = flags;
865 }
866 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
867
868 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
869
870 T *allocate(size_t n, size_t manual_size) {
871 size_t size = n * manual_size;
872 T *ptr = nullptr;
873#ifdef USE_ESP32
874 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
875 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
876 }
877 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
878 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
879 }
880#else
881 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
882 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
883#endif
884 return ptr;
885 }
886
887 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
888
889 T *reallocate(T *p, size_t n, size_t manual_size) {
890 size_t size = n * manual_size;
891 T *ptr = nullptr;
892#ifdef USE_ESP32
893 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
894 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
895 }
896 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
897 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
898 }
899#else
900 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
901 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
902#endif
903 return ptr;
904 }
905
906 void deallocate(T *p, size_t n) {
907 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
908 }
909
913 size_t get_free_heap_size() const {
914#ifdef USE_ESP8266
915 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
916#elif defined(USE_ESP32)
917 auto max_internal =
918 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
919 auto max_external =
920 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
921 return max_internal + max_external;
922#elif defined(USE_RP2040)
923 return ::rp2040.getFreeHeap();
924#elif defined(USE_LIBRETINY)
925 return lt_heap_get_free();
926#else
927 return 100000;
928#endif
929 }
930
934 size_t get_max_free_block_size() const {
935#ifdef USE_ESP8266
936 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
937#elif defined(USE_ESP32)
938 auto max_internal =
939 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
940 auto max_external =
941 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
942 return std::max(max_internal, max_external);
943#else
944 return this->get_free_heap_size();
945#endif
946 }
947
948 private:
949 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
950};
951
952template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
953
955
958
963template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
968template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
969
971
974
975ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
976inline std::string hexencode(const uint8_t *data, uint32_t len) { return format_hex_pretty(data, len); }
977
978template<typename T>
979ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
980std::string hexencode(const T &data) {
981 return hexencode(data.data(), data.size());
982}
983
985
986} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:651
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:654
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:644
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:641
Helper class to deduplicate items in a series of values.
Definition helpers.h:658
bool next(T value)
Feeds the next item in the series to the deduplicator and returns false if this is a duplicate.
Definition helpers.h:661
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:677
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:671
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:795
void stop()
Stop running the loop continuously.
Definition helpers.cpp:582
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:588
void start()
Start running the loop continuously.
Definition helpers.cpp:576
Helper class to disable interrupts.
Definition helpers.h:762
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:733
LockGuard(Mutex &mutex)
Definition helpers.h:735
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:780
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:709
void unlock()
Definition helpers.cpp:27
bool try_lock()
Definition helpers.cpp:26
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:686
T * get_parent() const
Get the parent of this object.
Definition helpers.h:692
Parented(T *parent)
Definition helpers.h:689
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:694
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:848
RAMAllocator(uint8_t flags)
Definition helpers.h:860
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:889
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:913
T * reallocate(T *p, size_t n)
Definition helpers.h:887
void deallocate(T *p, size_t n)
Definition helpers.h:906
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:934
T * allocate(size_t n)
Definition helpers.h:868
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:866
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:870
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:99
const_reverse_iterator rend() const
Definition helpers.h:135
size_t size() const
Definition helpers.h:119
reverse_iterator rbegin()
Definition helpers.h:132
const T & operator[](size_t i) const
Definition helpers.h:123
reverse_iterator rend()
Definition helpers.h:133
void push_back(const T &value)
Definition helpers.h:113
bool empty() const
Definition helpers.h:120
const_reverse_iterator rbegin() const
Definition helpers.h:134
T & operator[](size_t i)
Definition helpers.h:122
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:105
typename std::array< T, N >::iterator iterator
Definition helpers.h:102
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:103
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:104
const_iterator end() const
Definition helpers.h:129
const_iterator begin() const
Definition helpers.h:128
struct @63::@64 __attribute__
mopeka_std_values val[4]
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1") inline std
Definition helpers.h:975
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:156
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition helpers.cpp:502
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:71
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:351
constexpr T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order.
Definition helpers.h:230
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 (...
Definition helpers.h:388
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition helpers.cpp:494
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:391
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:608
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:403
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:511
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:263
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:188
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:336
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition helpers.cpp:324
constexpr T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order.
Definition helpers.h:239
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:197
std::string size_t len
Definition helpers.h:280
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.
Definition helpers.h:178
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:93
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:239
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:145
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:292
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:598
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:207
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:91
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:362
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
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.
Definition helpers.cpp:625
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition helpers.cpp:189
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.
Definition helpers.cpp:292
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:160
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:175
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:257
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition helpers.cpp:394
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...
Definition helpers.h:188
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:534
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:111
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.
Definition helpers.h:182
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.
Definition helpers.cpp:44
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:623
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:221
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:174
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:73
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:164
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
Definition helpers.h:384
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:203
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:590
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:66
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:625
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:213
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition helpers.cpp:190
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).
Definition helpers.h:144
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:165
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
Definition helpers.h:963
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition helpers.cpp:436
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:581
@ PARSE_ON
Definition helpers.h:583
@ PARSE_TOGGLE
Definition helpers.h:585
@ PARSE_OFF
Definition helpers.h:584
@ PARSE_NONE
Definition helpers.h:582
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition helpers.cpp:172
uint8_t end[39]
Definition sun_gtil2.cpp:17
void byteswap()
uint16_t length
Definition tt21100.cpp:0
uint16_t x
Definition tt21100.cpp:5