ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
counter_sensor.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4
8
9namespace esphome::counter {
10
12class CounterSensor final : public sensor::Sensor, public Component {
13 public:
15 CounterSensor(bool restore, int64_t initial_value) : value_(initial_value), restore_(restore) {}
16
17 void setup() override;
18 void dump_config() override;
19 // restore value before `on_boot` automations run
20 float get_setup_priority() const override { return setup_priority::DATA + 50.0f; }
21
24 source->add_on_state_callback([this](float) { this->increment(); });
25 }
26
28 template<typename T> void count_true_from(T *source) {
29 source->add_on_state_callback([this](bool state) {
30 if (state)
31 this->increment();
32 });
33 }
34
35 void set_value(int64_t value);
37 void increment(int64_t amount = 1) {
38 this->set_value(static_cast<int64_t>(static_cast<uint64_t>(this->value_) + static_cast<uint64_t>(amount)));
39 }
40
41 protected:
43 int64_t value_;
45};
46
47} // namespace esphome::counter
A counter held as a 64-bit integer. The published sensor state is a float, so it is exact only up to ...
void increment(int64_t amount=1)
overflow on addition of signed numbers is undefined - use the well defined unsigned version
float get_setup_priority() const override
CounterSensor(bool restore, int64_t initial_value)
The counter starts at initial_value unless a stored value is restored.
void count_true_from(T *source)
Increment by one each time the given binary sensor changes to true.
void count_updates_from(sensor::Sensor *source)
Increment by one each time the given sensor publishes a state.
Base-class for all sensors.
Definition sensor.h:47
void add_on_state_callback(F &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition sensor.h:121
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:140
constexpr float DATA
For components that import data from directly connected sensors like DHT.
Definition component.h:45