Helpers

esphomelib uses a bunch of helpers to make the library easier to use.

API Reference

helpers.h

Typedefs

using json_parse_t = std::function<void(JsonObject&)>

Callback function typedef for parsing JsonObjects.

using json_build_t = std::function<void(JsonObject&)>

Callback function typedef for building JsonObjects.

Enums

enum ParseOnOffState

Values:

PARSE_NONE = 0
PARSE_ON
PARSE_OFF
PARSE_TOGGLE

Functions

std::string get_mac_address()

Gets the MAC address as a string, this can be used as way to identify this ESP32.

void tick_status_led()
void feed_wdt()
std::string generate_hostname(const std::string &base)

Constructs a hostname by concatenating base, a hyphen, and the MAC address.

std::string sanitize_hostname(const std::string &hostname)

Sanitize the hostname by removing characters that are not in the whitelist and truncating it to 63 chars.

std::string truncate_string(const std::string &s, size_t length)

Truncate a string to a specific length.

bool is_empty(const IPAddress &address)

Checks whether the provided IPAddress is empty (is 0.0.0.0).

void reboot(const char *cause)

Force a shutdown (and reboot) of the ESP, calling any registered shutdown hooks.

void add_shutdown_hook(std::function<void(const char *)> &&f)

Add a shutdown callback.

void safe_reboot(const char *cause)

Create a safe shutdown (and reboot) of the ESP, calling any registered shutdown and safe shutdown hooks.

void run_shutdown_hooks(const char *cause)

Run shutdown hooks.

void add_safe_shutdown_hook(std::function<void(const char *)> &&f)

Add a safe shutdown callback that will be called if the device is shut down intentionally.

void run_safe_shutdown_hooks(const char *cause)

Run safe shutdown and force shutdown hooks.

std::string to_lowercase_underscore(std::string s)

Convert the string to lowercase_underscore.

const char *build_json(const json_build_t &f, size_t *length)

Build a JSON string with the provided json build function.

std::string build_json(const json_build_t &f)
void parse_json(const std::string &data, const json_parse_t &f)

Parse a JSON string and run the provided json parse function if it’s valid.

template <typename T>
T clamp(T min, T max, T val)

Clamp the value between min and max.

Return
val clamped in between min and max.
Template Parameters
  • T: The input/output typename.
Parameters
  • min: The minimum value.
  • max: The maximum value.
  • val: The value.

template <typename T>
T lerp(T start, T end, T completion)

Linearly interpolate between end start and end by completion.

Return
The linearly interpolated value.
Template Parameters
  • T: The input/output typename.
Parameters
  • start: The start value.
  • end: The end value.
  • completion: The completion. 0 is start value, 1 is end value.

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)

std::make_unique

uint32_t random_uint32()

Return a random 32 bit unsigned integer.

double random_double()

Returns a random double between 0 and 1.

Note: This function probably doesn’t provide a truly uniform distribution.

float random_float()

Returns a random float between 0 and 1. Essentially just casts random_double() to a float.

float gamma_correct(float value, float gamma)

Applies gamma correction with the provided gamma to value.

std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)

Create a string from a value and an accuracy in decimals.

std::string uint64_to_string(uint64_t num)

Convert a uint64_t to a hex string.

std::string uint32_to_string(uint32_t num)

Convert a uint32_t to a hex string.

std::string sanitize_string_whitelist(const std::string &s, const std::string &whitelist)

Sanitizes the input string with the whitelist.

uint8_t reverse_bits_8(uint8_t x)
uint16_t reverse_bits_16(uint16_t x)
uint32_t reverse_bits_32(uint32_t x)
void disable_interrupts()

Cross-platform method to disable interrupts.

Useful when you need to do some timing-dependent communication.

See
Do not forget to call enable_interrupts() again or otherwise things will go very wrong.

void enable_interrupts()

Cross-platform method to enable interrupts after they have been disabled.

uint8_t crc8(uint8_t *data, uint8_t len)

Calculate a crc8 of data with the provided data length.

ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr)
rmt_channel_t select_next_rmt_channel()
void delay_microseconds_accurate(uint32_t usec)

Variables

const char *HOSTNAME_CHARACTER_WHITELIST

The characters that are allowed in a hostname.

CallbackManager<void(const char *)> shutdown_hooks
CallbackManager<void(const char *)> safe_shutdown_hooks
rmt_channel_t next_rmt_channel
VectorJsonBuffer global_json_buffer
class SlidingWindowMovingAverage
#include <helpers.h>

Helper class that implements a sliding window moving average.

Public Functions

SlidingWindowMovingAverage(size_t max_size)

Create the SlidingWindowMovingAverage.

Parameters
  • max_size: The window size.

float next_value(float value)

Add value to the interval buffer.

Return
The new average.
Parameters
  • value: The value.

float calculate_average()

Return the average across the sliding window.

size_t get_max_size() const
void set_max_size(size_t max_size)

Protected Attributes

std::queue<float> queue_
size_t max_size_
float sum_
class ExponentialMovingAverage
#include <helpers.h>

Helper class that implements an exponential moving average.

Public Functions

ExponentialMovingAverage(float alpha)
float next_value(float value)
float calculate_average()
void set_alpha(float alpha)
float get_alpha() const

Protected Attributes

bool first_value_ = {true}
float alpha_
float accumulator_
template <typename... Ts>
template<>
class CallbackManager<void(Ts...)>
#include <helpers.h>

Simple helper class to allow having multiple subscribers to a signal.

Template Parameters
  • Ts: The arguments for the callback, wrapped in void().

Public Functions

void add(std::function<void(Ts...)> &&callback)

Add a callback to the internal callback list.

void call(Ts... args)

Call all callbacks in this manager.

Protected Attributes

std::vector<std::function<void(Ts...)>> callbacks_
template <typename T, typename X>
class TemplatableValue

Public Functions

TemplatableValue()
TemplatableValue(T const &value)
TemplatableValue(std::function<T(X)> f)
bool has_value()
T value(X x)

Protected Types

enum [anonymous]

Values:

EMPTY
VALUE
LAMBDA

Protected Attributes

TemplatableValue::[anonymous] type_
T value_
std::function<T(X)> f_
class VectorJsonBuffer : public ArduinoJson::Internals::JsonBufferBase<VectorJsonBuffer>

Public Functions

void *alloc(size_t bytes)
size_t size() const
void clear()
VectorJsonBuffer::String startString()

Protected Functions

void *do_alloc(size_t bytes)
void resize(size_t size)
void reserve(size_t size)

Protected Attributes

char *buffer_ = {nullptr}
size_t size_ = {0}
size_t capacity_ = {0}
std::vector<char *> free_blocks_
class String

Public Functions

String(VectorJsonBuffer *parent)
void append(char c) const
const char *c_str() const

Private Members

VectorJsonBuffer *parent_
uint32_t start_

optional.h

Functions

const nullopt_t nullopt(( nullopt_t::init ()))
template <typename T, typename U>
bool operator==(optional<T> const &x, optional<U> const &y)
template <typename T, typename U>
bool operator!=(optional<T> const &x, optional<U> const &y)
template <typename T, typename U>
bool operator<(optional<T> const &x, optional<U> const &y)
template <typename T, typename U>
bool operator>(optional<T> const &x, optional<U> const &y)
template <typename T, typename U>
bool operator<=(optional<T> const &x, optional<U> const &y)
template <typename T, typename U>
bool operator>=(optional<T> const &x, optional<U> const &y)
template <typename T>
bool operator==(optional<T> const &x, nullopt_t)
template <typename T>
bool operator==(nullopt_t, optional<T> const &x)
template <typename T>
bool operator!=(optional<T> const &x, nullopt_t)
template <typename T>
bool operator!=(nullopt_t, optional<T> const &x)
template <typename T>
bool operator<(optional<T> const&, nullopt_t)
template <typename T>
bool operator<(nullopt_t, optional<T> const &x)
template <typename T>
bool operator<=(optional<T> const &x, nullopt_t)
template <typename T>
bool operator<=(nullopt_t, optional<T> const&)
template <typename T>
bool operator>(optional<T> const &x, nullopt_t)
template <typename T>
bool operator>(nullopt_t, optional<T> const&)
template <typename T>
bool operator>=(optional<T> const&, nullopt_t)
template <typename T>
bool operator>=(nullopt_t, optional<T> const &x)
template <typename T, typename U>
bool operator==(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator==(U const &v, optional<T> const &x)
template <typename T, typename U>
bool operator!=(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator!=(U const &v, optional<T> const &x)
template <typename T, typename U>
bool operator<(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator<(U const &v, optional<T> const &x)
template <typename T, typename U>
bool operator<=(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator<=(U const &v, optional<T> const &x)
template <typename T, typename U>
bool operator>(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator>(U const &v, optional<T> const &x)
template <typename T, typename U>
bool operator>=(optional<T> const &x, U const &v)
template <typename T, typename U>
bool operator>=(U const &v, optional<T> const &x)
template <typename T>
void swap(optional<T> &x, optional<T> &y)
template <typename T>
optional<T> make_optional(T const &v)
struct nullopt_t

Public Functions

nullopt_t(init)
template <typename T>
class optional

Public Types

typedef T value_type

Public Functions

optional()
optional(nullopt_t)
optional(T const &arg)
template <class U>
optional(optional<U> const &other)
optional &operator=(nullopt_t)
template <class U>
optional &operator=(optional<U> const &other)
void swap(optional &rhs)
value_type const *operator->() const
value_type *operator->()
value_type const &operator*() const
value_type &operator*()
operator safe_bool() const
bool has_value() const
value_type const &value() const
value_type &value()
template <class U>
value_type value_or(U const &v) const
void reset()

Private Types

template<>
typedef void (optional::*safe_bool)() const

Private Functions

void this_type_does_not_support_comparisons() const
template <typename V>
void initialize(V const &value)

Private Members

bool has_value_
value_type value_

ESPPreferences

class ESPPreferences

Public Functions

ESPPreferences()
void begin(const std::string &name)
ESPPreferenceObject make_preference(size_t length, uint32_t type)
template <typename T>
ESPPreferenceObject make_preference(uint32_t type)
template <typename T>
ESPPreferenceObject make_preference(uint32_t type, const std::string &str)
void prevent_write(bool prevent)

On the ESP8266, we can’t override the first 128 bytes during OTA uploads as the eboot parameters are stored there.

Writing there during an OTA upload would invalidate applying the new firmware. During normal operation, we use this part of the RTC user memory, but stop writing to it during OTA uploads.

Parameters
  • prevent: Whether to prevent writing to the first 32 words of RTC user memory.

bool is_prevent_write()

Protected Attributes

friend ESPPreferences::ESPPreferenceObject
uint32_t current_offset_
Preferences preferences_
bool prevent_write_ = {false}
class ESPPreferenceObject

Public Functions

ESPPreferenceObject()
ESPPreferenceObject(size_t rtc_offset, size_t length, uint32_t type)
template <typename T>
bool save(T *src)
template <typename T>
bool load(T *dest)
bool is_initialized() const

Protected Functions

bool save_()
bool load_()
bool save_internal_()
bool load_internal_()
uint32_t calculate_crc_() const

Protected Attributes

size_t rtc_offset_
size_t length_words_
uint32_t type_
uint32_t *data_
ESPPreferences global_preferences

esphal.h

This header should be used whenever you want to access some digitalRead, digitalWrite, … methods.

class GPIOPin

A high-level abstraction class that can expose a pin together with useful options like pinMode.

Set the parameters for this at construction time and use setup() to apply them. The inverted parameter will automatically invert the input/output for you.

Use read_value() and write_value() to use digitalRead() and digitalWrite(), respectively.

Subclassed by GPIOInputPin, GPIOOutputPin

Public Functions

GPIOPin(uint8_t pin, uint8_t mode, bool inverted = false)

Construct the GPIOPin instance.

Parameters
  • pin: The GPIO pin number of this instance.
  • mode: The Arduino pinMode that this pin should be put into at setup().
  • inverted: Whether all digitalRead/digitalWrite calls should be inverted.

GPIOPin *copy() const
virtual void setup()

Setup the pin mode.

bool ICACHE_RAM_ATTR HOT GPIOPin::digital_read()

Read the binary value from this pin using digitalRead (and inverts automatically).

void ICACHE_RAM_ATTR HOT GPIOPin::digital_write(bool value)

Write the binary value to this pin using digitalWrite (and inverts automatically).

void ICACHE_RAM_ATTR HOT GPIOPin::pin_mode(uint8_t mode)

Set the pin mode.

uint8_t get_pin() const

Get the GPIO pin number.

const char *get_pin_mode_name() const
uint8_t get_mode() const

Get the pinMode of this pin.

bool is_inverted() const

Return whether this pin shall be treated as inverted. (for example active-low)

Protected Attributes

const uint8_t pin_
const uint8_t mode_
volatile uint32_t *const gpio_clear_
volatile uint32_t *const gpio_set_
volatile uint32_t *const gpio_read_
const uint32_t gpio_mask_
const bool inverted_
class GPIOOutputPin : public GPIOPin

Basically just a GPIOPin, but defaults to OUTPUT pinMode.

Note that theoretically you can still assign an INPUT pinMode to this - we intentionally don’t check this.

The constructor also allows for easy usage because of it’s lack of “explicit” constructor.

Subclassed by io::PCF8574GPIOOutputPin

Public Functions

GPIOOutputPin(uint8_t pin, uint8_t mode = OUTPUT, bool inverted = false)
class GPIOInputPin : public GPIOPin

Basically just a GPIOPin, but defaults to INPUT pinMode.

Note that theoretically you can still assign an OUTPUT pinMode to this - we intentionally don’t check this.

The constructor also allows for easy usage because of it’s lack of “explicit” constructor.

Subclassed by io::PCF8574GPIOInputPin

Public Functions

GPIOInputPin(uint8_t pin, uint8_t mode = INPUT, bool inverted = false)

ESPOneWire

esphomelib has its own implementation of OneWire, because the implementation in the Arduino libraries seems to have lots of timing issues with the ESP8266/ESP32. That’s why ESPOneWire was created.

class ESPOneWire

This is esphomelib’s own (minimal) implementation of 1-Wire that improves timing for ESP boards.

It’s more or less the same as Arduino’s internal library but uses some fancy C++ and 64 bit unsigned integers to make our lives easier.

Public Functions

ESPOneWire(GPIOPin *pin)

Construct a OneWire instance for the specified pin. There should only exist one instance per pin.

bool HOT ESPOneWire::reset()

Reset the bus, should be done before all write operations.

Takes approximately 1ms.

Return
Whether the operation was successful.

void HOT ESPOneWire::write_bit(bool bit)

Write a single bit to the bus, takes about 70µs.

bool HOT ESPOneWire::read_bit()

Read a single bit from the bus, takes about 70µs.

void write8(uint8_t val)

Write a word to the bus. LSB first.

void write64(uint64_t val)

Write a 64 bit unsigned integer to the bus. LSB first.

void skip()

Write a command to the bus that addresses all devices by skipping the ROM.

uint8_t read8()

Read an 8 bit word from the bus.

uint64_t read64()

Read an 64-bit unsigned integer from the bus.

void select(uint64_t address)

Select a specific address on the bus for the following command.

void reset_search()

Reset the device search.

uint64_t HOT ESPOneWire::search()

Search for a 1-Wire device on the bus. Returns 0 if all devices have been found.

std::vector<uint64_t> search_vec()

Helper that wraps search in a std::vector.

GPIOPin *get_pin()

Protected Functions

uint8_t *rom_number8_()

Helper to get the internal 64-bit unsigned rom number as a 8-bit integer pointer.

Protected Attributes

GPIOPin *pin_
uint8_t last_discrepancy_ = {0}
uint8_t last_family_discrepancy_ = {0}
bool last_device_flag_ = {false}
uint64_t rom_number = {0}

defines.h