ESPHome  2024.11.3
helpers.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <cmath>
4 #include <cstring>
5 #include <functional>
6 #include <memory>
7 #include <string>
8 #include <type_traits>
9 #include <vector>
10 #include <limits>
11 
12 #include "esphome/core/optional.h"
13 
14 #ifdef USE_ESP32
15 #include <esp_heap_caps.h>
16 #endif
17 
18 #if defined(USE_ESP32)
19 #include <freertos/FreeRTOS.h>
20 #include <freertos/semphr.h>
21 #elif defined(USE_LIBRETINY)
22 #include <FreeRTOS.h>
23 #include <semphr.h>
24 #endif
25 
26 #define HOT __attribute__((hot))
27 #define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
28 #define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
29 #define PACKED __attribute__((packed))
30 
31 // Various functions can be constexpr in C++14, but not in C++11 (because their body isn't just a return statement).
32 // Define a substitute constexpr keyword for those functions, until we can drop C++11 support.
33 #if __cplusplus >= 201402L
34 #define constexpr14 constexpr
35 #else
36 #define constexpr14 inline // constexpr implies inline
37 #endif
38 
39 namespace esphome {
40 
43 
44 // Backports for various STL features we like to use. Pull in the STL implementation wherever available, to avoid
45 // ambiguity and to provide a uniform API.
46 
47 // std::to_string() from C++11, available from libstdc++/g++ 8
48 // See https://github.com/espressif/esp-idf/issues/1445
49 #if _GLIBCXX_RELEASE >= 8
50 using std::to_string;
51 #else
52 std::string to_string(int value); // NOLINT
53 std::string to_string(long value); // NOLINT
54 std::string to_string(long long value); // NOLINT
55 std::string to_string(unsigned value); // NOLINT
56 std::string to_string(unsigned long value); // NOLINT
57 std::string to_string(unsigned long long value); // NOLINT
58 std::string to_string(float value);
59 std::string to_string(double value);
60 std::string to_string(long double value);
61 #endif
62 
63 // std::is_trivially_copyable from C++11, implemented in libstdc++/g++ 5.1 (but minor releases can't be detected)
64 #if _GLIBCXX_RELEASE >= 6
65 using std::is_trivially_copyable;
66 #else
67 // Implementing this is impossible without compiler intrinsics, so don't bother. Invalid usage will be detected on
68 // other variants that use a newer compiler anyway.
69 // NOLINTNEXTLINE(readability-identifier-naming)
70 template<typename T> struct is_trivially_copyable : public std::integral_constant<bool, true> {};
71 #endif
72 
73 // std::make_unique() from C++14
74 #if __cpp_lib_make_unique >= 201304
75 using std::make_unique;
76 #else
77 template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&...args) {
78  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
79 }
80 #endif
81 
82 // std::enable_if_t from C++14
83 #if __cplusplus >= 201402L
84 using std::enable_if_t;
85 #else
86 template<bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
87 #endif
88 
89 // std::clamp from C++17
90 #if __cpp_lib_clamp >= 201603
91 using std::clamp;
92 #else
93 template<typename T, typename Compare> constexpr const T &clamp(const T &v, const T &lo, const T &hi, Compare comp) {
94  return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
95 }
96 template<typename T> constexpr const T &clamp(const T &v, const T &lo, const T &hi) {
97  return clamp(v, lo, hi, std::less<T>{});
98 }
99 #endif
100 
101 // std::is_invocable from C++17
102 #if __cpp_lib_is_invocable >= 201703
103 using std::is_invocable;
104 #else
105 // https://stackoverflow.com/a/37161919/8924614
106 template<class T, class... Args> struct is_invocable { // NOLINT(readability-identifier-naming)
107  template<class U> static auto test(U *p) -> decltype((*p)(std::declval<Args>()...), void(), std::true_type());
108  template<class U> static auto test(...) -> decltype(std::false_type());
109  static constexpr auto value = decltype(test<T>(nullptr))::value; // NOLINT
110 };
111 #endif
112 
113 // std::bit_cast from C++20
114 #if __cpp_lib_bit_cast >= 201806
115 using std::bit_cast;
116 #else
117 template<
119  typename To, typename From,
121  int> = 0>
122 To bit_cast(const From &src) {
123  To dst;
124  memcpy(&dst, &src, sizeof(To));
125  return dst;
126 }
127 #endif
128 
129 // std::byteswap from C++23
130 template<typename T> constexpr14 T byteswap(T n) {
131  T m;
132  for (size_t i = 0; i < sizeof(T); i++)
133  reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
134  return m;
135 }
136 template<> constexpr14 uint8_t byteswap(uint8_t n) { return n; }
137 template<> constexpr14 uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
138 template<> constexpr14 uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
139 template<> constexpr14 uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
140 template<> constexpr14 int8_t byteswap(int8_t n) { return n; }
141 template<> constexpr14 int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
142 template<> constexpr14 int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
143 template<> constexpr14 int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
144 
146 
149 
151 float lerp(float completion, float start, float end);
152 
154 template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
155  return (value - min) * (max_out - min_out) / (max - min) + min_out;
156 }
157 
159 uint8_t crc8(const uint8_t *data, uint8_t len);
160 
162 uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
163  bool refin = false, bool refout = false);
164 uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
165  bool refout = false);
166 
168 uint32_t fnv1_hash(const std::string &str);
169 
171 uint32_t random_uint32();
173 float random_float();
175 bool random_bytes(uint8_t *data, size_t len);
176 
178 
181 
183 constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
184  return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
185 }
187 constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
188  return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
189  (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
190 }
192 constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
193  return ((static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3)));
194 }
195 
197 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
198 constexpr14 T encode_value(const uint8_t *bytes) {
199  T val = 0;
200  for (size_t i = 0; i < sizeof(T); i++) {
201  val <<= 8;
202  val |= bytes[i];
203  }
204  return val;
205 }
207 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
208 constexpr14 T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
209  return encode_value<T>(bytes.data());
210 }
212 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
213 constexpr14 std::array<uint8_t, sizeof(T)> decode_value(T val) {
214  std::array<uint8_t, sizeof(T)> ret{};
215  for (size_t i = sizeof(T); i > 0; i--) {
216  ret[i - 1] = val & 0xFF;
217  val >>= 8;
218  }
219  return ret;
220 }
221 
223 inline uint8_t reverse_bits(uint8_t x) {
224  x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
225  x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
226  x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
227  return x;
228 }
230 inline uint16_t reverse_bits(uint16_t x) {
231  return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
232 }
234 inline uint32_t reverse_bits(uint32_t x) {
235  return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
236  reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
237 }
238 
240 template<typename T> constexpr14 T convert_big_endian(T val) {
241 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
242  return byteswap(val);
243 #else
244  return val;
245 #endif
246 }
247 
249 template<typename T> constexpr14 T convert_little_endian(T val) {
250 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
251  return val;
252 #else
253  return byteswap(val);
254 #endif
255 }
256 
258 
261 
263 bool str_equals_case_insensitive(const std::string &a, const std::string &b);
264 
266 bool str_startswith(const std::string &str, const std::string &start);
268 bool str_endswith(const std::string &str, const std::string &end);
269 
271 inline std::string to_string(const std::string &val) { return val; }
272 
274 std::string str_truncate(const std::string &str, size_t length);
275 
278 std::string str_until(const char *str, char ch);
280 std::string str_until(const std::string &str, char ch);
281 
283 std::string str_lower_case(const std::string &str);
285 std::string str_upper_case(const std::string &str);
287 std::string str_snake_case(const std::string &str);
288 
290 std::string str_sanitize(const std::string &str);
291 
293 std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
294 
296 std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
297 
299 
302 
304 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
305 optional<T> parse_number(const char *str) {
306  char *end = nullptr;
307  unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
308  if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
309  return {};
310  return value;
311 }
313 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
314 optional<T> parse_number(const std::string &str) {
315  return parse_number<T>(str.c_str());
316 }
318 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
319 optional<T> parse_number(const char *str) {
320  char *end = nullptr;
321  signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
322  if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
323  return {};
324  return value;
325 }
327 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
328 optional<T> parse_number(const std::string &str) {
329  return parse_number<T>(str.c_str());
330 }
332 template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
333  char *end = nullptr;
334  float value = ::strtof(str, &end);
335  if (end == str || *end != '\0' || value == HUGE_VALF)
336  return {};
337  return value;
338 }
340 template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
341 optional<T> parse_number(const std::string &str) {
342  return parse_number<T>(str.c_str());
343 }
344 
356 size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
358 inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
359  return parse_hex(str, strlen(str), data, count) == 2 * count;
360 }
362 inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
363  return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
364 }
366 inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
367  data.resize(count);
368  return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
369 }
371 inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
372  data.resize(count);
373  return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
374 }
380 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
381 optional<T> parse_hex(const char *str, size_t len) {
382  T val = 0;
383  if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
384  return {};
385  return convert_big_endian(val);
386 }
388 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
389  return parse_hex<T>(str, strlen(str));
390 }
392 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
393  return parse_hex<T>(str.c_str(), str.length());
394 }
395 
397 std::string format_hex(const uint8_t *data, size_t length);
399 std::string format_hex(const std::vector<uint8_t> &data);
401 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
402  val = convert_big_endian(val);
403  return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
404 }
405 template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
406  return format_hex(data.data(), data.size());
407 }
408 
410 std::string format_hex_pretty(const uint8_t *data, size_t length);
412 std::string format_hex_pretty(const uint16_t *data, size_t length);
414 std::string format_hex_pretty(const std::vector<uint8_t> &data);
416 std::string format_hex_pretty(const std::vector<uint16_t> &data);
418 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex_pretty(T val) {
419  val = convert_big_endian(val);
420  return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T));
421 }
422 
424 std::string format_bin(const uint8_t *data, size_t length);
426 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
427  val = convert_big_endian(val);
428  return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
429 }
430 
437 };
439 ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
440 
442 std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
443 
445 int8_t step_to_accuracy_decimals(float step);
446 
447 std::string base64_encode(const uint8_t *buf, size_t buf_len);
448 std::string base64_encode(const std::vector<uint8_t> &buf);
449 
450 std::vector<uint8_t> base64_decode(const std::string &encoded_string);
451 size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
452 
454 
457 
459 float gamma_correct(float value, float gamma);
461 float gamma_uncorrect(float value, float gamma);
462 
464 void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
466 void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
467 
469 
472 
474 constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
476 constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
477 
479 
482 
483 template<typename... X> class CallbackManager;
484 
489 template<typename... Ts> class CallbackManager<void(Ts...)> {
490  public:
492  void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
493 
495  void call(Ts... args) {
496  for (auto &cb : this->callbacks_)
497  cb(args...);
498  }
499  size_t size() const { return this->callbacks_.size(); }
500 
502  void operator()(Ts... args) { call(args...); }
503 
504  protected:
505  std::vector<std::function<void(Ts...)>> callbacks_;
506 };
507 
509 template<typename T> class Deduplicator {
510  public:
512  bool next(T value) {
513  if (this->has_value_) {
514  if (this->last_value_ == value)
515  return false;
516  }
517  this->has_value_ = true;
518  this->last_value_ = value;
519  return true;
520  }
522  bool has_value() const { return this->has_value_; }
523 
524  protected:
525  bool has_value_{false};
526  T last_value_{};
527 };
528 
530 template<typename T> class Parented {
531  public:
532  Parented() {}
533  Parented(T *parent) : parent_(parent) {}
534 
536  T *get_parent() const { return parent_; }
538  void set_parent(T *parent) { parent_ = parent; }
539 
540  protected:
541  T *parent_{nullptr};
542 };
543 
545 
548 
553 class Mutex {
554  public:
555  Mutex();
556  Mutex(const Mutex &) = delete;
557  ~Mutex();
558  void lock();
559  bool try_lock();
560  void unlock();
561 
562  Mutex &operator=(const Mutex &) = delete;
563 
564  private:
565 #if defined(USE_ESP32) || defined(USE_LIBRETINY)
566  SemaphoreHandle_t handle_;
567 #else
568  void *handle_; // d-pointer to store private data on new platforms
569 #endif
570 };
571 
576 class LockGuard {
577  public:
578  LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
579  ~LockGuard() { mutex_.unlock(); }
580 
581  private:
582  Mutex &mutex_;
583 };
584 
606  public:
607  InterruptLock();
608  ~InterruptLock();
609 
610  protected:
611 #if defined(USE_ESP8266) || defined(USE_RP2040)
612  uint32_t state_;
613 #endif
614 };
615 
622  public:
624  void start();
626  void stop();
627 
629  static bool is_high_frequency();
630 
631  protected:
632  bool started_{false};
633  static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
634 };
635 
637 void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
638 
640 std::string get_mac_address();
641 
643 std::string get_mac_address_pretty();
644 
645 #ifdef USE_ESP32
646 void set_mac_address(uint8_t *mac);
648 #endif
649 
653 
656 bool mac_address_is_valid(const uint8_t *mac);
657 
659 void delay_microseconds_safe(uint32_t us);
660 
662 
665 
674 template<class T> class RAMAllocator {
675  public:
676  using value_type = T;
677 
678  enum Flags {
679  NONE = 0, // Perform external allocation and fall back to internal memory
680  ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
681  ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
682  ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
683  };
684 
685  RAMAllocator() = default;
686  RAMAllocator(uint8_t flags) : flags_{flags} {}
687  template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
688 
689  T *allocate(size_t n) {
690  size_t size = n * sizeof(T);
691  T *ptr = nullptr;
692 #ifdef USE_ESP32
693  // External allocation by default or if explicitely requested
694  if ((this->flags_ & Flags::ALLOC_EXTERNAL) || ((this->flags_ & Flags::ALLOC_INTERNAL) == 0)) {
695  ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
696  }
697  // Fallback to internal allocation if explicitely requested or no flag is specified
698  if (ptr == nullptr && ((this->flags_ & Flags::ALLOC_INTERNAL) || (this->flags_ & Flags::ALLOC_EXTERNAL) == 0)) {
699  ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
700  }
701 #else
702  // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
703  ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
704 #endif
705  return ptr;
706  }
707 
708  void deallocate(T *p, size_t n) {
709  free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
710  }
711 
712  private:
713  uint8_t flags_{Flags::ALLOW_FAILURE};
714 };
715 
716 template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
717 
719 
722 
727 template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
732 template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
733 
735 
738 
739 ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
740 inline std::string hexencode(const uint8_t *data, uint32_t len) { return format_hex_pretty(data, len); }
741 
742 template<typename T>
743 ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
744 std::string hexencode(const T &data) {
745  return hexencode(data.data(), data.size());
746 }
747 
749 
750 } // namespace esphome
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:594
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition: helpers.cpp:284
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition: helpers.cpp:266
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition: helpers.cpp:149
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:427
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:364
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition: helpers.cpp:734
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition: helpers.cpp:283
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:352
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:333
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition: helpers.cpp:400
bool next(T value)
Feeds the next item in the series to the deduplicator and returns whether this is a duplicate...
Definition: helpers.h:512
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition: helpers.cpp:193
uint16_t x
Definition: tt21100.cpp:17
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:269
Helper class to request loop() to be called as fast as possible.
Definition: helpers.h:621
typename std::enable_if< B, T >::type enable_if_t
Definition: helpers.h:86
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition: helpers.h:687
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:187
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition: helpers.cpp:499
std::string to_string(const std::string &val)
Convert the value to a string (added as extra overload so that to_string() can be used on all stringi...
Definition: helpers.h:271
STL namespace.
T * allocate(size_t n)
Definition: helpers.h:689
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
Definition: helpers.h:727
std::vector< std::function< void(Ts...)> > callbacks_
Definition: helpers.h:505
float lerp(float completion, float start, float end)
Linearly interpolate between start and end by completion (between 0 and 1).
Definition: helpers.cpp:94
mopeka_std_values val[4]
void set_parent(T *parent)
Set the parent of this object.
Definition: helpers.h:538
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait...
Definition: helpers.cpp:765
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition: helpers.cpp:217
constexpr14 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:198
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:111
constexpr const T & clamp(const T &v, const T &lo, const T &hi, Compare comp)
Definition: helpers.h:93
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:412
void call(Ts... args)
Call all callbacks in this manager.
Definition: helpers.h:495
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition: helpers.h:223
ParseOnOffState
Return values for parse_on_off().
Definition: helpers.h:432
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition: helpers.cpp:554
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition: helpers.cpp:262
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition: helpers.h:474
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition: helpers.cpp:457
ESPDEPRECATED("Use Color::BLACK instead of COLOR_BLACK", "v1.21") extern const Color COLOR_BLACK
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition: helpers.h:305
uint8_t crc8(const uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size len.
Definition: helpers.cpp:95
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:571
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition: helpers.cpp:282
std::string str_sprintf(const char *fmt,...)
Definition: helpers.cpp:315
constexpr14 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:213
constexpr14 T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order...
Definition: helpers.h:240
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:718
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:192
uint8_t type
bool has_value() const
Returns whether this deduplicator has processed any items so far.
Definition: helpers.h:522
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition: helpers.cpp:263
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:183
RAMAllocator(uint8_t flags)
Definition: helpers.h:686
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition: helpers.cpp:731
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition: helpers.cpp:438
enum esphome::EntityCategory __attribute__
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:154
const uint32_t flags
Definition: stm32flash.h:85
Parented(T *parent)
Definition: helpers.h:533
void deallocate(T *p, size_t n)
Definition: helpers.h:708
LockGuard(Mutex &mutex)
Definition: helpers.h:578
T * get_parent() const
Get the parent of this object.
Definition: helpers.h:536
Helper class to disable interrupts.
Definition: helpers.h:605
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores...
Definition: helpers.cpp:291
std::string to_string(int value)
Definition: helpers.cpp:81
std::string size_t len
Definition: helpers.h:293
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:183
constexpr14 T byteswap(T n)
Definition: helpers.h:130
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition: helpers.cpp:748
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition: helpers.h:122
constexpr14 T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order...
Definition: helpers.h:249
uint16_t length
Definition: tt21100.cpp:12
Helper class to deduplicate items in a series of values.
Definition: helpers.h:509
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void operator()(Ts... args)
Call all callbacks in this manager.
Definition: helpers.h:502
num_t cb(num_t x)
Definition: sun.cpp:31
std::vector< uint8_t > bytes
Definition: sml_parser.h:12
uint8_t m
Definition: bl0906.h:208
uint8_t end[39]
Definition: sun_gtil2.cpp:31
std::unique_ptr< T > make_unique(Args &&...args)
Definition: helpers.h:77
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition: helpers.cpp:724
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition: helpers.h:492
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition: helpers.h:476
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:301
An STL allocator that uses SPI or internal RAM.
Definition: helpers.h:674
float random_float()
Return a random float between 0 and 1.
Definition: helpers.cpp:215
Helper class to easily give an object a parent of type T.
Definition: helpers.h:530
Helper class that wraps a mutex with a RAII-style API.
Definition: helpers.h:576
Mutex implementation, with API based on the unavailable std::mutex.
Definition: helpers.h:553
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition: helpers.cpp:259
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:680
constexpr const T & clamp(const T &v, const T &lo, const T &hi)
Definition: helpers.h:96
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition: helpers.cpp:562