ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
derivative_sensor.cpp
Go to the documentation of this file.
1#include "derivative_sensor.h"
2
3#include <cmath>
4
6#include "esphome/core/log.h"
7
9
10ESPHOME_LOG_TAG(TAG, "derivative");
11
12void DerivativeSensorBase::dump_config() { LOG_SENSOR("", "Derivative Sensor", this); }
13
14void DerivativeSensorBase::process_sensor_value_(float value, float ms_per_unit) {
15 // No valid reading: drop the baseline so a gap never yields a spike.
16 if (std::isnan(value)) {
17 this->last_value_ = NAN;
18 return;
19 }
20
22
23 if (std::isnan(this->last_value_)) {
24 this->last_value_ = value;
25 this->last_update_ = now;
26 return;
27 }
28
29 const uint32_t dt_ms = now - this->last_update_;
30 // Readings published within one component call share a timestamp: keep the older baseline.
31 if (dt_ms == 0)
32 return;
33
34 const float old_value = this->last_value_;
35 // Update before publishing: callbacks may feed back into this sensor.
36 this->last_value_ = value;
37 this->last_update_ = now;
38
39 this->publish_state((value - old_value) / dt_ms * ms_per_unit);
40}
41
42} // namespace esphome::derivative
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void process_sensor_value_(float value, float ms_per_unit)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
ESPHOME_LOG_TAG(TAG, "derivative")
uint32_t value
Definition hal.cpp:59
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t