Sensor

The sensor namespace contains all sensors.

See Application::register_sensor().

API Reference

Sensor

class Sensor : public Nameable

Base-class for all sensors.

A sensor has unit of measurement and can use publish_state to send out a new value with the specified accuracy.

Subclassed by sensor::EmptySensor< 1, ICON_FLASH, UNIT_A >, sensor::EmptySensor< 1, ICON_FLASH, UNIT_V >, sensor::EmptySensor< 3, ICON_FLASH, UNIT_V >, ESP32BLERSSISensor, sensor::EmptySensor< default_accuracy_decimals, default_icon, default_unit_of_measurement >, sensor::MQTTSubscribeSensor, sensor::PMSX003Sensor, sensor::PollingSensorComponent, sensor::RotaryEncoderSensor, sensor::TotalDailyEnergy, XiaomiSensor

Public Functions

Sensor(const std::string &name)
void set_unit_of_measurement(const std::string &unit_of_measurement)

Manually set the unit of measurement of this sensor.

By default the sensor’s default defined by unit_of_measurement() is used.

Parameters
  • unit_of_measurement: The unit of measurement, “” to disable.

void set_icon(const std::string &icon)

Manually set the icon of this sensor.

By default the sensor’s default defined by icon() is used.

Parameters
  • icon: The icon, for example “mdi:flash”. “” to disable.

void set_accuracy_decimals(int8_t accuracy_decimals)

Manually set the accuracy in decimals for this sensor.

By default, the sensor’s default defined by accuracy_decimals() is used.

Parameters
  • accuracy_decimals: The accuracy decimal that should be used.

void add_filter(Filter *filter)

Add a filter to the filter chain. Will be appended to the back.

void add_filters(const std::list<Filter *> &filters)

Add a list of vectors to the back of the filter chain.

This may look like:

sensor->add_filters({ LambdaFilter([&](float value) -> optional<float> { return 42/value; }), OffsetFilter(1), SlidingWindowMovingAverageFilter(15, 15), // average over last 15 values });

void set_filters(const std::list<Filter *> &filters)

Clear the filters and replace them by filters.

void clear_filters()

Clear the entire filter chain.

float get_value() const

Getter-syntax for .value. Please use .state instead.

float get_state() const

Getter-syntax for .state.

float get_raw_value() const

Getter-syntax for .raw_value. Please use .raw_state instead.

float get_raw_state() const

Getter-syntax for .raw_state.

int8_t get_accuracy_decimals()

Get the accuracy in decimals. Uses the manual override if specified or the default value instead.

std::string get_unit_of_measurement()

Get the unit of measurement. Uses the manual override if specified or the default value instead.

std::string get_icon()

Get the Home Assistant Icon. Uses the manual override if specified or the default value instead.

void publish_state(float state)

Publish a new state to the front-end.

First, the new state will be assigned to the raw_value. Then it’s passed through all filters until it finally lands in the .value member variable and a callback is issued.

Parameters
  • state: The state as a floating point number.

void push_new_value(float value)

Push a new value to the MQTT front-end.

Note: deprecated, please use publish_state.

void add_on_state_callback(std::function<void(float)> &&callback)

Add a callback that will be called every time a filtered value arrives.

void add_on_raw_state_callback(std::function<void(float)> &&callback)

Add a callback that will be called every time the sensor sends a raw value.

SensorStateTrigger *make_state_trigger()
SensorRawStateTrigger *make_raw_state_trigger()
ValueRangeTrigger *make_value_range_trigger()
bool has_state() const

Return whether this sensor has gotten a full state (that passed through all filters) yet.

std::string unique_id()

A unique ID for this sensor, empty for no unique id.

See unique ID requirements: https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements

Return
The unique id as a string.

uint32_t update_interval()

Return with which interval the sensor is polled. Return 0 for non-polling mode.

uint32_t calculate_expected_filter_update_interval()

Calculate the expected update interval for values that pass through all filters.

void send_state_to_frontend_internal_(float state)

Public Members

float please use sensor::Sensor::state
float please use sensor::Sensor::raw_state
float state

This member variable stores the last state that has passed through all filters.

On startup, when no state is available yet, this is NAN (not-a-number) and the validity can be checked using has_state().

This is exposed through a member variable for ease of use in esphomeyaml lambdas.

union sensor::Sensor::[anonymous] [anonymous]
float raw_state

This member variable stores the current raw state of the sensor.

Unlike .state, this will be updated immediately when publish_state is called.

union sensor::Sensor::[anonymous] [anonymous]

Protected Functions

std::string unit_of_measurement()

Override this to set the Home Assistant unit of measurement for this sensor.

Return “” to disable this feature.

Return
The icon of this sensor, for example “°C”.

std::string icon()

Override this to set the Home Assistant icon for this sensor.

Return “” to disable this feature.

Return
The icon of this sensor, for example “mdi:battery”.

int8_t accuracy_decimals()

Return the accuracy in decimals for this sensor.

Protected Attributes

CallbackManager<void(float)> raw_callback_

Storage for raw state callbacks.

CallbackManager<void(float)> callback_

Storage for filtered state callbacks.

optional<std::string> unit_of_measurement_

Override the unit of measurement.

optional<std::string> icon_
optional<int8_t> accuracy_decimals_

Override the icon advertised to Home Assistant, otherwise sensor’s icon will be used.

Override the accuracy in decimals, otherwise the sensor’s values will be used.

Filter *filter_list_ = {nullptr}

Store all active filters.

bool has_state_ = {false}
class PollingSensorComponent : public PollingComponent, public sensor::Sensor

Subclassed by sensor::ADCSensorComponent, sensor::BH1750Sensor, sensor::DutyCycleSensor, sensor::ESP32HallSensor, sensor::HX711Sensor, sensor::MAX6675Sensor, sensor::PulseCounterSensorComponent, sensor::TemplateSensor, sensor::TSL2561Sensor, sensor::UltrasonicSensorComponent, sensor::UptimeSensor, sensor::WiFiSignalSensor

Public Functions

PollingSensorComponent(const std::string &name, uint32_t update_interval)
uint32_t update_interval()

Return with which interval the sensor is polled. Return 0 for non-polling mode.

template <int8_t default_accuracy_decimals, const char * default_icon, const char * default_unit_of_measurement>
class EmptySensor : public sensor::Sensor

Subclassed by sensor::EmptyPollingParentSensor< 1, ICON_EMPTY, UNIT_C, DallasComponent >, sensor::EmptyPollingParentSensor< 1, ICON_EMPTY, UNIT_C, SHT3XDComponent >, sensor::EmptyPollingParentSensor< 1, ICON_WATER_PERCENT, UNIT_PERCENT, SHT3XDComponent >, sensor::EmptyPollingParentSensor< default_accuracy_decimals, default_icon, default_unit_of_measurement, ParentType >

Public Functions

EmptySensor(const std::string &name)
std::string unit_of_measurement()

Override this to set the Home Assistant unit of measurement for this sensor.

Return “” to disable this feature.

Return
The icon of this sensor, for example “°C”.

std::string icon()

Override this to set the Home Assistant icon for this sensor.

Return “” to disable this feature.

Return
The icon of this sensor, for example “mdi:battery”.

int8_t accuracy_decimals()

Return the accuracy in decimals for this sensor.

template <int8_t default_accuracy_decimals, const char * default_icon, const char * default_unit_of_measurement, class ParentType>
class EmptyPollingParentSensor : public sensor::EmptySensor<default_accuracy_decimals, default_icon, default_unit_of_measurement>

Public Functions

EmptyPollingParentSensor(const std::string &name, ParentType *parent)
uint32_t update_interval()

Return with which interval the sensor is polled. Return 0 for non-polling mode.

Protected Attributes

ParentType *parent_
const char sensor::ICON_EMPTY = ""
const char sensor::ICON_WATER_PERCENT = "mdi:water-percent"
const char sensor::ICON_GAUGE = "mdi:gauge"
const char sensor::ICON_FLASH = "mdi:flash"
const char sensor::ICON_SCREEN_ROTATION = "mdi:screen-rotation"
const char sensor::ICON_BRIEFCASE_DOWNLOAD = "mdi:briefcase-download"
const char sensor::UNIT_C = "°C"
const char sensor::UNIT_PERCENT = "%"
const char sensor::UNIT_HPA = "hPa"
const char sensor::UNIT_V = "V"
const char sensor::UNIT_DEGREES_PER_SECOND = "°/s"
const char sensor::UNIT_M_PER_S_SQUARED = "m/s²"

Filter

class Filter

Apply a filter to sensor values such as moving average.

This class is purposefully kept quite simple, since more complicated filters should really be done with the filter sensor in Home Assistant.

Subclassed by sensor::DebounceFilter, sensor::DeltaFilter, sensor::ExponentialMovingAverageFilter, sensor::FilterOutNANFilter, sensor::FilterOutValueFilter, sensor::HeartbeatFilter, sensor::LambdaFilter, sensor::MultiplyFilter, sensor::OffsetFilter, sensor::OrFilter, sensor::OrFilter::PhiNode, sensor::SlidingWindowMovingAverageFilter, sensor::ThrottleFilter, sensor::UniqueFilter

Public Functions

virtual optional<float> new_value(float value) = 0

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

void initialize(Sensor *parent, Filter *next)

Initialize this filter, please note this can be called more than once.

void input(float value)
uint32_t expected_interval(uint32_t input)

Return the amount of time that this filter is expected to take based on the input time interval.

uint32_t calculate_remaining_interval(uint32_t input)
void output(float value)

Protected Attributes

friend sensor::Filter::Sensor
friend sensor::Filter::MQTTSensorComponent
Filter *next_ = {nullptr}
Sensor *parent_ = {nullptr}
class SlidingWindowMovingAverageFilter : public sensor::Filter

Simple sliding window moving average filter.

Essentially just takes takes the average of the last window_size values and pushes them out every send_every.

Public Functions

SlidingWindowMovingAverageFilter(size_t window_size, size_t send_every, uint32_t send_first_at = 1)

Construct a SlidingWindowMovingAverageFilter.

Parameters
  • window_size: The number of values that should be averaged.
  • send_every: After how many sensor values should a new one be pushed out.
  • send_first_at: After how many values to forward the very first value. Defaults to the first value on startup being published on the first raw value, so with no filter applied. Must be less than or equal to send_every.

optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

size_t get_send_every() const
void set_send_every(size_t send_every)
size_t get_window_size() const
void set_window_size(size_t window_size)
uint32_t expected_interval(uint32_t input)

Return the amount of time that this filter is expected to take based on the input time interval.

Protected Attributes

SlidingWindowMovingAverage average_
size_t send_every_
size_t send_at_
class ExponentialMovingAverageFilter : public sensor::Filter

Simple exponential moving average filter.

Essentially just takes the average of the last few values using exponentially decaying weights. Use alpha to adjust decay rate.

Public Functions

ExponentialMovingAverageFilter(float alpha, size_t send_every)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

size_t get_send_every() const
void set_send_every(size_t send_every)
float get_alpha() const
void set_alpha(float alpha)
uint32_t expected_interval(uint32_t input)

Return the amount of time that this filter is expected to take based on the input time interval.

Protected Attributes

ExponentialMovingAverage average_
size_t send_every_
size_t send_at_
using sensor::lambda_filter_t = typedef std::function<optional<float>(float)>
class LambdaFilter : public sensor::Filter

This class allows for creation of simple template filters.

The constructor accepts a lambda of the form float -> optional<float>. It will be called with each new value in the filter chain and returns the modified value that shall be passed down the filter chain. Returning an empty Optional means that the value shall be discarded.

Public Functions

LambdaFilter(lambda_filter_t lambda_filter)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

const lambda_filter_t &get_lambda_filter() const
void set_lambda_filter(const lambda_filter_t &lambda_filter)

Protected Attributes

lambda_filter_t lambda_filter_
class OffsetFilter : public sensor::Filter

A simple filter that adds offset to each value it receives.

Public Functions

OffsetFilter(float offset)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

float offset_
class MultiplyFilter : public sensor::Filter

A simple filter that multiplies to each value it receives by multiplier.

Public Functions

MultiplyFilter(float multiplier)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

float multiplier_
class FilterOutValueFilter : public sensor::Filter

A simple filter that only forwards the filter chain if it doesn’t receive value_to_filter_out.

Public Functions

FilterOutValueFilter(float values_to_filter_out)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

float value_to_filter_out_
class FilterOutNANFilter : public sensor::Filter

A simple filter that only forwards the filter chain if it doesn’t receive nan.

Public Functions

optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

class ThrottleFilter : public sensor::Filter

Public Functions

ThrottleFilter(uint32_t min_time_between_inputs)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

uint32_t last_input_ = {0}
uint32_t min_time_between_inputs_
class HeartbeatFilter : public sensor::Filter, public Component

Public Functions

HeartbeatFilter(uint32_t time_period)
void setup()

Where the component’s initialization should happen.

Analogous to Arduino’s setup(). This method is guaranteed to only be called once. Defaults to doing nothing.

optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

uint32_t expected_interval(uint32_t input)

Return the amount of time that this filter is expected to take based on the input time interval.

float get_setup_priority() const

priority of setup().

higher -> executed earlier

Defaults to 0.

Return
The setup priority of this component

Protected Attributes

uint32_t time_period_
float last_input_
bool has_value_ = {false}
class DebounceFilter : public sensor::Filter, public Component

Public Functions

DebounceFilter(uint32_t time_period)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

float get_setup_priority() const

priority of setup().

higher -> executed earlier

Defaults to 0.

Return
The setup priority of this component

Protected Attributes

uint32_t time_period_
class DeltaFilter : public sensor::Filter

Public Functions

DeltaFilter(float min_delta)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

float min_delta_
float last_value_ = {NAN}
class OrFilter : public sensor::Filter

Public Functions

OrFilter(std::vector<Filter *> filters)
void initialize(Sensor *parent, Filter *next)

Initialize this filter, please note this can be called more than once.

uint32_t expected_interval(uint32_t input)

Return the amount of time that this filter is expected to take based on the input time interval.

optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

std::vector<Filter *> filters_
PhiNode phi_
class PhiNode : public sensor::Filter

Public Functions

PhiNode(OrFilter *parent)
optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

OrFilter *parent_
class UniqueFilter : public sensor::Filter

Public Functions

optional<float> new_value(float value)

This will be called every time the filter receives a new value.

It can return an empty optional to indicate that the filter chain should stop, otherwise the value in the filter will be passed down the chain.

Return
An optional float, the new value that should be pushed out.
Parameters
  • value: The new value.

Protected Attributes

float last_value_ = {NAN}

MQTTSensorComponent

class MQTTSensorComponent : public mqtt::MQTTComponent

Class that exposes sensors to the MQTT frontend.

Public Functions

MQTTSensorComponent(Sensor *sensor)

Construct this MQTTSensorComponent instance with the provided friendly_name and sensor.

Note the sensor is never stored and is only used for initializing some values of this class. If sensor is nullptr, then automatic initialization of these fields is disabled.

Parameters
  • sensor: The sensor, this can be null to disable automatic setup.

void set_expire_after(uint32_t expire_after)

Setup an expiry, 0 disables it.

void disable_expire_after()

Disable Home Assistant value expiry.

void send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config)

Send discovery info the Home Assistant, override this.

void setup()

Override setup.

void dump_config()
uint32_t get_expire_after() const

Get the expire_after in milliseconds used for Home Assistant discovery, first checks override.

void publish_state(float value)
void send_initial_state()
bool is_internal()

Protected Functions

std::string component_type() const

Override for MQTTComponent, returns “sensor”.

std::string friendly_name() const

Get the friendly name of this MQTT component.

std::string unique_id()

A unique ID for this MQTT component, empty for no unique id.

See unique ID requirements: https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements

Return
The unique id as a string.

Protected Attributes

Sensor *sensor_
optional<uint32_t> expire_after_