ESPHome  2025.2.0
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
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_ESP8266
15 #include <Esp.h>
16 #endif
17 
18 #ifdef USE_RP2040
19 #include <Arduino.h>
20 #endif
21 
22 #ifdef USE_ESP32
23 #include <esp_heap_caps.h>
24 #endif
25 
26 #if defined(USE_ESP32)
27 #include <freertos/FreeRTOS.h>
28 #include <freertos/semphr.h>
29 #elif defined(USE_LIBRETINY)
30 #include <FreeRTOS.h>
31 #include <semphr.h>
32 #endif
33 
34 #define HOT __attribute__((hot))
35 #define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
36 #define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
37 #define PACKED __attribute__((packed))
38 
39 // Various functions can be constexpr in C++14, but not in C++11 (because their body isn't just a return statement).
40 // Define a substitute constexpr keyword for those functions, until we can drop C++11 support.
41 #if __cplusplus >= 201402L
42 #define constexpr14 constexpr
43 #else
44 #define constexpr14 inline // constexpr implies inline
45 #endif
46 
47 namespace esphome {
48 
51 
52 // Backports for various STL features we like to use. Pull in the STL implementation wherever available, to avoid
53 // ambiguity and to provide a uniform API.
54 
55 // std::to_string() from C++11, available from libstdc++/g++ 8
56 // See https://github.com/espressif/esp-idf/issues/1445
57 #if _GLIBCXX_RELEASE >= 8
58 using std::to_string;
59 #else
60 std::string to_string(int value); // NOLINT
61 std::string to_string(long value); // NOLINT
62 std::string to_string(long long value); // NOLINT
63 std::string to_string(unsigned value); // NOLINT
64 std::string to_string(unsigned long value); // NOLINT
65 std::string to_string(unsigned long long value); // NOLINT
66 std::string to_string(float value);
67 std::string to_string(double value);
68 std::string to_string(long double value);
69 #endif
70 
71 // std::is_trivially_copyable from C++11, implemented in libstdc++/g++ 5.1 (but minor releases can't be detected)
72 #if _GLIBCXX_RELEASE >= 6
73 using std::is_trivially_copyable;
74 #else
75 // Implementing this is impossible without compiler intrinsics, so don't bother. Invalid usage will be detected on
76 // other variants that use a newer compiler anyway.
77 // NOLINTNEXTLINE(readability-identifier-naming)
78 template<typename T> struct is_trivially_copyable : public std::integral_constant<bool, true> {};
79 #endif
80 
81 // std::make_unique() from C++14
82 #if __cpp_lib_make_unique >= 201304
83 using std::make_unique;
84 #else
85 template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&...args) {
86  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
87 }
88 #endif
89 
90 // std::enable_if_t from C++14
91 #if __cplusplus >= 201402L
92 using std::enable_if_t;
93 #else
94 template<bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
95 #endif
96 
97 // std::clamp from C++17
98 #if __cpp_lib_clamp >= 201603
99 using std::clamp;
100 #else
101 template<typename T, typename Compare> constexpr const T &clamp(const T &v, const T &lo, const T &hi, Compare comp) {
102  return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
103 }
104 template<typename T> constexpr const T &clamp(const T &v, const T &lo, const T &hi) {
105  return clamp(v, lo, hi, std::less<T>{});
106 }
107 #endif
108 
109 // std::is_invocable from C++17
110 #if __cpp_lib_is_invocable >= 201703
111 using std::is_invocable;
112 #else
113 // https://stackoverflow.com/a/37161919/8924614
114 template<class T, class... Args> struct is_invocable { // NOLINT(readability-identifier-naming)
115  template<class U> static auto test(U *p) -> decltype((*p)(std::declval<Args>()...), void(), std::true_type());
116  template<class U> static auto test(...) -> decltype(std::false_type());
117  static constexpr auto value = decltype(test<T>(nullptr))::value; // NOLINT
118 };
119 #endif
120 
121 // std::bit_cast from C++20
122 #if __cpp_lib_bit_cast >= 201806
123 using std::bit_cast;
124 #else
125 template<
127  typename To, typename From,
129  int> = 0>
130 To bit_cast(const From &src) {
131  To dst;
132  memcpy(&dst, &src, sizeof(To));
133  return dst;
134 }
135 #endif
136 
137 // std::byteswap from C++23
138 template<typename T> constexpr14 T byteswap(T n) {
139  T m;
140  for (size_t i = 0; i < sizeof(T); i++)
141  reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
142  return m;
143 }
144 template<> constexpr14 uint8_t byteswap(uint8_t n) { return n; }
145 template<> constexpr14 uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
146 template<> constexpr14 uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
147 template<> constexpr14 uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
148 template<> constexpr14 int8_t byteswap(int8_t n) { return n; }
149 template<> constexpr14 int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
150 template<> constexpr14 int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
151 template<> constexpr14 int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
152 
154 
157 
159 float lerp(float completion, float start, float end);
160 
162 template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
163  return (value - min) * (max_out - min_out) / (max - min) + min_out;
164 }
165 
167 uint8_t crc8(const uint8_t *data, uint8_t len);
168 
170 uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
171  bool refin = false, bool refout = false);
172 uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
173  bool refout = false);
174 
176 uint32_t fnv1_hash(const std::string &str);
177 
179 uint32_t random_uint32();
181 float random_float();
183 bool random_bytes(uint8_t *data, size_t len);
184 
186 
189 
191 constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
192  return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
193 }
195 constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
196  return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
197  (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
198 }
200 constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
201  return ((static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3)));
202 }
203 
205 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
206 constexpr14 T encode_value(const uint8_t *bytes) {
207  T val = 0;
208  for (size_t i = 0; i < sizeof(T); i++) {
209  val <<= 8;
210  val |= bytes[i];
211  }
212  return val;
213 }
215 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
216 constexpr14 T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
217  return encode_value<T>(bytes.data());
218 }
220 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
221 constexpr14 std::array<uint8_t, sizeof(T)> decode_value(T val) {
222  std::array<uint8_t, sizeof(T)> ret{};
223  for (size_t i = sizeof(T); i > 0; i--) {
224  ret[i - 1] = val & 0xFF;
225  val >>= 8;
226  }
227  return ret;
228 }
229 
231 inline uint8_t reverse_bits(uint8_t x) {
232  x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
233  x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
234  x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
235  return x;
236 }
238 inline uint16_t reverse_bits(uint16_t x) {
239  return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
240 }
242 inline uint32_t reverse_bits(uint32_t x) {
243  return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
244  reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
245 }
246 
248 template<typename T> constexpr14 T convert_big_endian(T val) {
249 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
250  return byteswap(val);
251 #else
252  return val;
253 #endif
254 }
255 
257 template<typename T> constexpr14 T convert_little_endian(T val) {
258 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
259  return val;
260 #else
261  return byteswap(val);
262 #endif
263 }
264 
266 
269 
271 bool str_equals_case_insensitive(const std::string &a, const std::string &b);
272 
274 bool str_startswith(const std::string &str, const std::string &start);
276 bool str_endswith(const std::string &str, const std::string &end);
277 
279 inline std::string to_string(const std::string &val) { return val; }
280 
282 std::string str_truncate(const std::string &str, size_t length);
283 
286 std::string str_until(const char *str, char ch);
288 std::string str_until(const std::string &str, char ch);
289 
291 std::string str_lower_case(const std::string &str);
293 std::string str_upper_case(const std::string &str);
295 std::string str_snake_case(const std::string &str);
296 
298 std::string str_sanitize(const std::string &str);
299 
301 std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t len, ...);
302 
304 std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
305 
307 
310 
312 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
313 optional<T> parse_number(const char *str) {
314  char *end = nullptr;
315  unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
316  if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
317  return {};
318  return value;
319 }
321 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
322 optional<T> parse_number(const std::string &str) {
323  return parse_number<T>(str.c_str());
324 }
326 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
327 optional<T> parse_number(const char *str) {
328  char *end = nullptr;
329  signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
330  if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
331  return {};
332  return value;
333 }
335 template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
336 optional<T> parse_number(const std::string &str) {
337  return parse_number<T>(str.c_str());
338 }
340 template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
341  char *end = nullptr;
342  float value = ::strtof(str, &end);
343  if (end == str || *end != '\0' || value == HUGE_VALF)
344  return {};
345  return value;
346 }
348 template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
349 optional<T> parse_number(const std::string &str) {
350  return parse_number<T>(str.c_str());
351 }
352 
364 size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
366 inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
367  return parse_hex(str, strlen(str), data, count) == 2 * count;
368 }
370 inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
371  return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
372 }
374 inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
375  data.resize(count);
376  return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
377 }
379 inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
380  data.resize(count);
381  return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
382 }
388 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
389 optional<T> parse_hex(const char *str, size_t len) {
390  T val = 0;
391  if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
392  return {};
393  return convert_big_endian(val);
394 }
396 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
397  return parse_hex<T>(str, strlen(str));
398 }
400 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
401  return parse_hex<T>(str.c_str(), str.length());
402 }
403 
405 std::string format_hex(const uint8_t *data, size_t length);
407 std::string format_hex(const std::vector<uint8_t> &data);
409 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
410  val = convert_big_endian(val);
411  return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
412 }
413 template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
414  return format_hex(data.data(), data.size());
415 }
416 
418 std::string format_hex_pretty(const uint8_t *data, size_t length);
420 std::string format_hex_pretty(const uint16_t *data, size_t length);
422 std::string format_hex_pretty(const std::vector<uint8_t> &data);
424 std::string format_hex_pretty(const std::vector<uint16_t> &data);
426 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex_pretty(T val) {
427  val = convert_big_endian(val);
428  return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T));
429 }
430 
432 std::string format_bin(const uint8_t *data, size_t length);
434 template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
435  val = convert_big_endian(val);
436  return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
437 }
438 
445 };
447 ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
448 
450 std::string value_accuracy_to_string(float value, int8_t accuracy_decimals);
451 
453 int8_t step_to_accuracy_decimals(float step);
454 
455 std::string base64_encode(const uint8_t *buf, size_t buf_len);
456 std::string base64_encode(const std::vector<uint8_t> &buf);
457 
458 std::vector<uint8_t> base64_decode(const std::string &encoded_string);
459 size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
460 
462 
465 
467 float gamma_correct(float value, float gamma);
469 float gamma_uncorrect(float value, float gamma);
470 
472 void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
474 void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
475 
477 
480 
482 constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
484 constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
485 
487 
490 
491 template<typename... X> class CallbackManager;
492 
497 template<typename... Ts> class CallbackManager<void(Ts...)> {
498  public:
500  void add(std::function<void(Ts...)> &&callback) { this->callbacks_.push_back(std::move(callback)); }
501 
503  void call(Ts... args) {
504  for (auto &cb : this->callbacks_)
505  cb(args...);
506  }
507  size_t size() const { return this->callbacks_.size(); }
508 
510  void operator()(Ts... args) { call(args...); }
511 
512  protected:
513  std::vector<std::function<void(Ts...)>> callbacks_;
514 };
515 
517 template<typename T> class Deduplicator {
518  public:
520  bool next(T value) {
521  if (this->has_value_) {
522  if (this->last_value_ == value)
523  return false;
524  }
525  this->has_value_ = true;
526  this->last_value_ = value;
527  return true;
528  }
530  bool has_value() const { return this->has_value_; }
531 
532  protected:
533  bool has_value_{false};
534  T last_value_{};
535 };
536 
538 template<typename T> class Parented {
539  public:
540  Parented() {}
541  Parented(T *parent) : parent_(parent) {}
542 
544  T *get_parent() const { return parent_; }
546  void set_parent(T *parent) { parent_ = parent; }
547 
548  protected:
549  T *parent_{nullptr};
550 };
551 
553 
556 
561 class Mutex {
562  public:
563  Mutex();
564  Mutex(const Mutex &) = delete;
565  ~Mutex();
566  void lock();
567  bool try_lock();
568  void unlock();
569 
570  Mutex &operator=(const Mutex &) = delete;
571 
572  private:
573 #if defined(USE_ESP32) || defined(USE_LIBRETINY)
574  SemaphoreHandle_t handle_;
575 #else
576  // d-pointer to store private data on new platforms
577  void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
578 #endif
579 };
580 
585 class LockGuard {
586  public:
587  LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
588  ~LockGuard() { mutex_.unlock(); }
589 
590  private:
591  Mutex &mutex_;
592 };
593 
615  public:
616  InterruptLock();
617  ~InterruptLock();
618 
619  protected:
620 #if defined(USE_ESP8266) || defined(USE_RP2040)
621  uint32_t state_;
622 #endif
623 };
624 
631  public:
633  void start();
635  void stop();
636 
638  static bool is_high_frequency();
639 
640  protected:
641  bool started_{false};
642  static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
643 };
644 
646 void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
647 
649 std::string get_mac_address();
650 
652 std::string get_mac_address_pretty();
653 
654 #ifdef USE_ESP32
655 void set_mac_address(uint8_t *mac);
657 #endif
658 
662 
665 bool mac_address_is_valid(const uint8_t *mac);
666 
668 void delay_microseconds_safe(uint32_t us);
669 
671 
674 
683 template<class T> class RAMAllocator {
684  public:
685  using value_type = T;
686 
687  enum Flags {
688  NONE = 0, // Perform external allocation and fall back to internal memory
689  ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
690  ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
691  ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
692  };
693 
694  RAMAllocator() = default;
695  RAMAllocator(uint8_t flags) {
696  // default is both external and internal
697  flags &= ALLOC_INTERNAL | ALLOC_EXTERNAL;
698  if (flags != 0)
699  this->flags_ = flags;
700  }
701  template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
702 
703  T *allocate(size_t n) {
704  size_t size = n * sizeof(T);
705  T *ptr = nullptr;
706 #ifdef USE_ESP32
707  if (this->flags_ & Flags::ALLOC_EXTERNAL) {
708  ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
709  }
710  if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) {
711  ptr = static_cast<T *>(heap_caps_malloc(size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
712  }
713 #else
714  // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
715  ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
716 #endif
717  return ptr;
718  }
719 
720  void deallocate(T *p, size_t n) {
721  free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
722  }
723 
727  size_t get_free_heap_size() const {
728 #ifdef USE_ESP8266
729  return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
730 #elif defined(USE_ESP32)
731  auto max_internal =
732  this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
733  auto max_external =
734  this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
735  return max_internal + max_external;
736 #elif defined(USE_RP2040)
737  return ::rp2040.getFreeHeap();
738 #elif defined(USE_LIBRETINY)
739  return lt_heap_get_free();
740 #else
741  return 100000;
742 #endif
743  }
744 
748  size_t get_max_free_block_size() const {
749 #ifdef USE_ESP8266
750  return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
751 #elif defined(USE_ESP32)
752  auto max_internal =
753  this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
754  auto max_external =
755  this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
756  return std::max(max_internal, max_external);
757 #else
758  return this->get_free_heap_size();
759 #endif
760  }
761 
762  private:
763  uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
764 };
765 
766 template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
767 
769 
772 
777 template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
782 template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
783 
785 
788 
789 ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
790 inline std::string hexencode(const uint8_t *data, uint32_t len) { return format_hex_pretty(data, len); }
791 
792 template<typename T>
793 ESPDEPRECATED("hexencode() is deprecated, use format_hex_pretty() instead.", "2022.1")
794 std::string hexencode(const T &data) {
795  return hexencode(data.data(), data.size());
796 }
797 
799 
800 } // 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:603
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition: helpers.h:748
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition: helpers.cpp:293
std::string str_truncate(const std::string &str, size_t length)
Truncate a string to a specific length.
Definition: helpers.cpp:275
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition: helpers.cpp:153
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:436
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:373
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition: helpers.cpp:743
std::string str_upper_case(const std::string &str)
Convert the string to upper case.
Definition: helpers.cpp:292
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:361
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:342
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
Definition: helpers.cpp:409
bool next(T value)
Feeds the next item in the series to the deduplicator and returns whether this is a duplicate...
Definition: helpers.h:520
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition: helpers.cpp:197
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:278
Helper class to request loop() to be called as fast as possible.
Definition: helpers.h:630
typename std::enable_if< B, T >::type enable_if_t
Definition: helpers.h:94
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition: helpers.h:701
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:195
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
Definition: helpers.cpp:508
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:279
STL namespace.
T * allocate(size_t n)
Definition: helpers.h:703
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
Definition: helpers.h:777
std::vector< std::function< void(Ts...)> > callbacks_
Definition: helpers.h:513
float lerp(float completion, float start, float end)
Linearly interpolate between start and end by completion (between 0 and 1).
Definition: helpers.cpp:96
mopeka_std_values val[4]
void set_parent(T *parent)
Set the parent of this object.
Definition: helpers.h:546
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:774
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition: helpers.cpp:221
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:206
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:113
constexpr const T & clamp(const T &v, const T &lo, const T &hi, Compare comp)
Definition: helpers.h:101
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:421
void call(Ts... args)
Call all callbacks in this manager.
Definition: helpers.h:503
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition: helpers.h:231
ParseOnOffState
Return values for parse_on_off().
Definition: helpers.h:440
float gamma_correct(float value, float gamma)
Applies gamma correction of gamma to value.
Definition: helpers.cpp:563
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition: helpers.cpp:267
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition: helpers.h:482
std::string base64_encode(const std::vector< uint8_t > &buf)
Definition: helpers.cpp:466
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:313
uint8_t crc8(const uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum of data with size len using the CRC-8-Dallas/Maxim polynomial.
Definition: helpers.cpp:97
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:580
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition: helpers.cpp:291
std::string str_sprintf(const char *fmt,...)
Definition: helpers.cpp:324
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:221
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:248
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:727
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:200
uint8_t type
bool has_value() const
Returns whether this deduplicator has processed any items so far.
Definition: helpers.h:530
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition: helpers.cpp:268
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:191
RAMAllocator(uint8_t flags)
Definition: helpers.h:695
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition: helpers.cpp:740
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition: helpers.cpp:447
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:162
const uint32_t flags
Definition: stm32flash.h:85
Parented(T *parent)
Definition: helpers.h:541
void deallocate(T *p, size_t n)
Definition: helpers.h:720
LockGuard(Mutex &mutex)
Definition: helpers.h:587
T * get_parent() const
Get the parent of this object.
Definition: helpers.h:544
Helper class to disable interrupts.
Definition: helpers.h:614
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores...
Definition: helpers.cpp:300
std::string to_string(int value)
Definition: helpers.cpp:83
std::string size_t len
Definition: helpers.h:301
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:187
constexpr14 T byteswap(T n)
Definition: helpers.h:138
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition: helpers.cpp:757
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition: helpers.h:130
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:257
uint16_t length
Definition: tt21100.cpp:12
Helper class to deduplicate items in a series of values.
Definition: helpers.h:517
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void operator()(Ts... args)
Call all callbacks in this manager.
Definition: helpers.h:510
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:85
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition: helpers.cpp:733
void add(std::function< void(Ts...)> &&callback)
Add a callback to the list.
Definition: helpers.h:500
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition: helpers.h:484
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:310
An STL allocator that uses SPI or internal RAM.
Definition: helpers.h:683
float random_float()
Return a random float between 0 and 1.
Definition: helpers.cpp:219
Helper class to easily give an object a parent of type T.
Definition: helpers.h:538
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition: helpers.h:727
Helper class that wraps a mutex with a RAII-style API.
Definition: helpers.h:585
Mutex implementation, with API based on the unavailable std::mutex.
Definition: helpers.h:561
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition: helpers.cpp:263
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:689
constexpr const T & clamp(const T &v, const T &lo, const T &hi)
Definition: helpers.h:104
float gamma_uncorrect(float value, float gamma)
Reverts gamma correction of gamma to value.
Definition: helpers.cpp:571