ESPHome  2022.9.2
demo_sensor.h
Go to the documentation of this file.
1 #pragma once
2 
4 #include "esphome/core/helpers.h"
6 
7 namespace esphome {
8 namespace demo {
9 
10 class DemoSensor : public sensor::Sensor, public PollingComponent {
11  public:
12  void update() override {
13  float val = random_float();
14  bool increasing = this->get_state_class() == sensor::STATE_CLASS_TOTAL_INCREASING;
15  if (increasing) {
16  float base = std::isnan(this->state) ? 0.0f : this->state;
17  this->publish_state(base + val * 10);
18  } else {
19  if (val < 0.1)
20  this->publish_state(NAN);
21  else
22  this->publish_state(val * 100);
23  }
24  }
25 };
26 
27 } // namespace demo
28 } // namespace esphome
This class simplifies creating components that periodically check a state.
Definition: component.h:266
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:133
void update() override
Definition: demo_sensor.h:12
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:72
StateClass get_state_class()
Get the state class, using the manual override if set.
Definition: sensor.cpp:62
Definition: a4988.cpp:4
uint32_t val
Definition: datatypes.h:85
Base-class for all sensors.
Definition: sensor.h:48
float random_float()
Return a random float between 0 and 1.
Definition: helpers.cpp:98