ESPHome 2025.10.0-dev
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; }
85#ifdef USE_LIBRETINY
86// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
87template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
88template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
89template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
90template<> inline int8_t byteswap(int8_t n) { return n; }
91template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
92template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
93template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
94#else
95template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
96template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
97template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
98template<> constexpr int8_t byteswap(int8_t n) { return n; }
99template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
100template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
101template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
102#endif
103
105
108
110template<typename T, size_t N> class StaticVector {
111 public:
112 using value_type = T;
113 using iterator = typename std::array<T, N>::iterator;
114 using const_iterator = typename std::array<T, N>::const_iterator;
115 using reverse_iterator = std::reverse_iterator<iterator>;
116 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
117
118 private:
119 std::array<T, N> data_{};
120 size_t count_{0};
121
122 public:
123 // Minimal vector-compatible interface - only what we actually use
124 void push_back(const T &value) {
125 if (count_ < N) {
126 data_[count_++] = value;
127 }
128 }
129
130 size_t size() const { return count_; }
131 bool empty() const { return count_ == 0; }
132
133 T &operator[](size_t i) { return data_[i]; }
134 const T &operator[](size_t i) const { return data_[i]; }
135
136 // For range-based for loops
137 iterator begin() { return data_.begin(); }
138 iterator end() { return data_.begin() + count_; }
139 const_iterator begin() const { return data_.begin(); }
140 const_iterator end() const { return data_.begin() + count_; }
141
142 // Reverse iterators
147};
148
150
153
155template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
156 return (value - min) * (max_out - min_out) / (max - min) + min_out;
157}
158
160uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
161
163uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
164 bool refin = false, bool refout = false);
165uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
166 bool refout = false);
167
169uint32_t fnv1_hash(const char *str);
170inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
171
173uint32_t random_uint32();
175float random_float();
177bool random_bytes(uint8_t *data, size_t len);
178
180
183
185constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
186 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
187}
189constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
190 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
191}
193constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
194 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
195 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
196}
197
199template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
200 T val = 0;
201 for (size_t i = 0; i < sizeof(T); i++) {
202 val <<= 8;
203 val |= bytes[i];
204 }
205 return val;
206}
208template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
209constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
210 return encode_value<T>(bytes.data());
211}
213template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
214constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
215 std::array<uint8_t, sizeof(T)> ret{};
216 for (size_t i = sizeof(T); i > 0; i--) {
217 ret[i - 1] = val & 0xFF;
218 val >>= 8;
219 }
220 return ret;
221}
222
224inline uint8_t reverse_bits(uint8_t x) {
225 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
226 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
227 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
228 return x;
229}
231inline uint16_t reverse_bits(uint16_t x) {
232 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
233}
235inline uint32_t reverse_bits(uint32_t x) {
236 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
237 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
238}
239
241template<typename T> constexpr T convert_big_endian(T val) {
242#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
243 return byteswap(val);
244#else
245 return val;
246#endif
247}
248
250template<typename T> constexpr T convert_little_endian(T val) {
251#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
252 return val;
253#else
254 return byteswap(val);
255#endif
256}
257
259
262
264bool str_equals_case_insensitive(const std::string &a, const std::string &b);
265
267bool str_startswith(const std::string &str, const std::string &start);
269bool str_endswith(const std::string &str, const std::string &end);
270
272std::string str_truncate(const std::string &str, size_t length);
273
276std::string str_until(const char *str, char ch);
278std::string str_until(const std::string &str, char ch);
279
281std::string str_lower_case(const std::string &str);
283std::string str_upper_case(const std::string &str);
285std::string str_snake_case(const std::string &str);
286
288std::string str_sanitize(const std::string &str);
289
291std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
292
294std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
295
297
300
302template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
303optional<T> parse_number(const char *str) {
304 char *end = nullptr;
305 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
306 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
307 return {};
308 return value;
309}
311template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
312optional<T> parse_number(const std::string &str) {
313 return parse_number<T>(str.c_str());
314}
316template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
317optional<T> parse_number(const char *str) {
318 char *end = nullptr;
319 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
320 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
321 return {};
322 return value;
323}
325template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
326optional<T> parse_number(const std::string &str) {
327 return parse_number<T>(str.c_str());
328}
330template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
331 char *end = nullptr;
332 float value = ::strtof(str, &end);
333 if (end == str || *end != '\0' || value == HUGE_VALF)
334 return {};
335 return value;
336}
338template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
339optional<T> parse_number(const std::string &str) {
340 return parse_number<T>(str.c_str());
341}
342
354size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
356inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
357 return parse_hex(str, strlen(str), data, count) == 2 * count;
358}
360inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
361 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
362}
364inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
365 data.resize(count);
366 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
367}
369inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
370 data.resize(count);
371 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
372}
378template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
379optional<T> parse_hex(const char *str, size_t len) {
380 T val = 0;
381 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
382 return {};
383 return convert_big_endian(val);
384}
386template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
387 return parse_hex<T>(str, strlen(str));
388}
390template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
391 return parse_hex<T>(str.c_str(), str.length());
392}
393
395inline char format_hex_char(uint8_t v) { return v >= 10 ? 'a' + (v - 10) : '0' + v; }
396
399inline char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; }
400
402inline void format_mac_addr_upper(const uint8_t *mac, char *output) {
403 for (size_t i = 0; i < 6; i++) {
404 uint8_t byte = mac[i];
405 output[i * 3] = format_hex_pretty_char(byte >> 4);
406 output[i * 3 + 1] = format_hex_pretty_char(byte & 0x0F);
407 if (i < 5)
408 output[i * 3 + 2] = ':';
409 }
410 output[17] = '\0';
411}
412
414inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
415 for (size_t i = 0; i < 6; i++) {
416 uint8_t byte = mac[i];
417 output[i * 2] = format_hex_char(byte >> 4);
418 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
419 }
420 output[12] = '\0';
421}
422
424std::string format_mac_address_pretty(const uint8_t mac[6]);
426std::string format_hex(const uint8_t *data, size_t length);
428std::string format_hex(const std::vector<uint8_t> &data);
430template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
432 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
433}
434template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
435 return format_hex(data.data(), data.size());
436}
437
463std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true);
464
485std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true);
486
508std::string format_hex_pretty(const std::vector<uint8_t> &data, char separator = '.', bool show_length = true);
509
530std::string format_hex_pretty(const std::vector<uint16_t> &data, char separator = '.', bool show_length = true);
531
552std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true);
553
577template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
578std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
580 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
581}
582
584std::string format_bin(const uint8_t *data, size_t length);
586template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
588 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
589}
590
599ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
600
602std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
603
605int8_t step_to_accuracy_decimals(float step);
606
607std::string base64_encode(const uint8_t *buf, size_t buf_len);
608std::string base64_encode(const std::vector<uint8_t> &buf);
609
610std::vector<uint8_t> base64_decode(const std::string &encoded_string);
611size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
612
614
617
619float gamma_correct(float value, float gamma);
621float gamma_uncorrect(float value, float gamma);
622
624void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
626void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
627
629
632
634constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
636constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
637
639
642
643template<typename... X> class CallbackManager;
644
649template<typename... Ts> class CallbackManager<void(Ts...)> {
650 public:
652 void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
653
655 void call(Ts... args) {
656 for (auto &cb : this->callbacks_)
657 cb(args...);
658 }
659 size_t size() const { return this->callbacks_.size(); }
660
662 void operator()(Ts... args) { call(args...); }
663
664 protected:
665 std::vector<std::function<void(Ts...)>> callbacks_;
666};
667
669template<typename T> class Deduplicator {
670 public:
672 bool next(T value) {
673 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
674 return false;
675 }
676 this->has_value_ = true;
677 this->value_unknown_ = false;
678 this->last_value_ = value;
679 return true;
680 }
683 bool ret = !this->value_unknown_;
684 this->value_unknown_ = true;
685 return ret;
686 }
688 bool has_value() const { return this->has_value_; }
689
690 protected:
691 bool has_value_{false};
692 bool value_unknown_{false};
694};
695
697template<typename T> class Parented {
698 public:
700 Parented(T *parent) : parent_(parent) {}
701
703 T *get_parent() const { return parent_; }
705 void set_parent(T *parent) { parent_ = parent; }
706
707 protected:
708 T *parent_{nullptr};
709};
710
712
715
720class Mutex {
721 public:
722 Mutex();
723 Mutex(const Mutex &) = delete;
724 ~Mutex();
725 void lock();
726 bool try_lock();
727 void unlock();
728
729 Mutex &operator=(const Mutex &) = delete;
730
731 private:
732#if defined(USE_ESP32) || defined(USE_LIBRETINY)
733 SemaphoreHandle_t handle_;
734#else
735 // d-pointer to store private data on new platforms
736 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
737#endif
738};
739
745 public:
746 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
747 ~LockGuard() { mutex_.unlock(); }
748
749 private:
750 Mutex &mutex_;
751};
752
774 public:
777
778 protected:
779#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_ZEPHYR)
780 uint32_t state_;
781#endif
782};
783
791class LwIPLock {
792 public:
793 LwIPLock();
794 ~LwIPLock();
795
796 // Delete copy constructor and copy assignment operator to prevent accidental copying
797 LwIPLock(const LwIPLock &) = delete;
798 LwIPLock &operator=(const LwIPLock &) = delete;
799};
800
807 public:
809 void start();
811 void stop();
812
814 static bool is_high_frequency();
815
816 protected:
817 bool started_{false};
818 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
819};
820
822void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
823
825std::string get_mac_address();
826
828std::string get_mac_address_pretty();
829
830#ifdef USE_ESP32
832void set_mac_address(uint8_t *mac);
833#endif
834
838
841bool mac_address_is_valid(const uint8_t *mac);
842
844void delay_microseconds_safe(uint32_t us);
845
847
850
859template<class T> class RAMAllocator {
860 public:
861 using value_type = T;
862
863 enum Flags {
864 NONE = 0, // Perform external allocation and fall back to internal memory
865 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
866 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
867 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
868 };
869
870 RAMAllocator() = default;
872 // default is both external and internal
874 if (flags != 0)
875 this->flags_ = flags;
876 }
877 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
878
879 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
880
881 T *allocate(size_t n, size_t manual_size) {
882 size_t size = n * manual_size;
883 T *ptr = nullptr;
884#ifdef USE_ESP32
885 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
886 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
887 }
888 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
889 ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
890 }
891#else
892 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
893 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
894#endif
895 return ptr;
896 }
897
898 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
899
900 T *reallocate(T *p, size_t n, size_t manual_size) {
901 size_t size = n * manual_size;
902 T *ptr = nullptr;
903#ifdef USE_ESP32
904 if (this->flags_ & Flags::ALLOC_EXTERNAL) {
905 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
906 }
907 if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
908 ptr = static_cast<T *>(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
909 }
910#else
911 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
912 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
913#endif
914 return ptr;
915 }
916
917 void deallocate(T *p, size_t n) {
918 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
919 }
920
924 size_t get_free_heap_size() const {
925#ifdef USE_ESP8266
926 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
927#elif defined(USE_ESP32)
928 auto max_internal =
929 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
930 auto max_external =
931 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
932 return max_internal + max_external;
933#elif defined(USE_RP2040)
934 return ::rp2040.getFreeHeap();
935#elif defined(USE_LIBRETINY)
936 return lt_heap_get_free();
937#else
938 return 100000;
939#endif
940 }
941
945 size_t get_max_free_block_size() const {
946#ifdef USE_ESP8266
947 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
948#elif defined(USE_ESP32)
949 auto max_internal =
950 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
951 auto max_external =
952 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
953 return std::max(max_internal, max_external);
954#else
955 return this->get_free_heap_size();
956#endif
957 }
958
959 private:
960 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
961};
962
963template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
964
966
969
974template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
979template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
980
982
985
986ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
987inline std::string hexencode(const uint8_t *data, uint32_t len) { return format_hex_pretty(data, len); }
988
989template<typename T>
990ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
991std::string hexencode(const T &data) {
992 return hexencode(data.data(), data.size());
993}
994
996
997} // namespace esphome
uint8_t m
Definition bl0906.h:1
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:662
std::vector< std::function< void(Ts...)> > callbacks_
Definition helpers.h:665
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:655
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition helpers.h:652
Helper class to deduplicate items in a series of values.
Definition helpers.h:669
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:672
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:688
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:682
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:806
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:773
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:744
LockGuard(Mutex &mutex)
Definition helpers.h:746
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:791
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:720
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:697
T * get_parent() const
Get the parent of this object.
Definition helpers.h:703
Parented(T *parent)
Definition helpers.h:700
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:705
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:859
RAMAllocator(uint8_t flags)
Definition helpers.h:871
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:900
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:924
T * reallocate(T *p, size_t n)
Definition helpers.h:898
void deallocate(T *p, size_t n)
Definition helpers.h:917
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:945
T * allocate(size_t n)
Definition helpers.h:879
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:877
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:881
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:110
const_reverse_iterator rend() const
Definition helpers.h:146
size_t size() const
Definition helpers.h:130
reverse_iterator rbegin()
Definition helpers.h:143
const T & operator[](size_t i) const
Definition helpers.h:134
reverse_iterator rend()
Definition helpers.h:144
void push_back(const T &value)
Definition helpers.h:124
bool empty() const
Definition helpers.h:131
const_reverse_iterator rbegin() const
Definition helpers.h:145
T & operator[](size_t i)
Definition helpers.h:133
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:116
typename std::array< T, N >::iterator iterator
Definition helpers.h:113
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:114
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:115
const_iterator end() const
Definition helpers.h:140
const_iterator begin() const
Definition helpers.h:139
struct @63::@64 __attribute__
uint16_t flags
uint16_t id
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:986
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:241
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:399
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:402
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:414
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:250
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:291
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:189
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:303
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:199
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:193
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:634
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:185
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:395
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:214
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:636
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:224
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:155
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:165
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:592
@ PARSE_ON
Definition helpers.h:594
@ PARSE_TOGGLE
Definition helpers.h:596
@ PARSE_OFF
Definition helpers.h:595
@ PARSE_NONE
Definition helpers.h:593
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