ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
ads131m0x_sensor.cpp
Go to the documentation of this file.
1#include "ads131m0x_sensor.h"
2
3#ifdef USE_ESP32
4
5#include <cmath>
6
8#include "esphome/core/log.h"
10
11namespace esphome::ads131m0x {
12
13ESPHOME_LOG_TAG(TAG, "ads131m0x.sensor");
14
15// Extra time on top of two windows before a snapshot is considered stale
16static constexpr uint32_t STALE_MARGIN_MS = 1000;
17
18// Indexed by ADS131M0xSensorType; the last entry is the fallback for out-of-range values
19PROGMEM_STRING_TABLE(SensorTypeStrings, "rms", "mean", "unknown");
20
22 if (!this->parent_->is_healthy()) {
23 this->publish_state(NAN);
24 return;
25 }
26 const Snapshot snapshot = this->parent_->get_snapshot();
27 // The sampling task stamps windows with millis(), which can be later than the cached loop start time:
28 // a negative age is a fresh window, not an overflow.
29 const int32_t age_ms = static_cast<int32_t>(App.get_loop_component_start_time() - snapshot.timestamp_ms);
30 if (snapshot.sequence == 0 || age_ms > static_cast<int32_t>(2 * this->parent_->get_window_ms() + STALE_MARGIN_MS)) {
31 this->publish_state(NAN);
32 return;
33 }
34 this->publish_state(this->type_ == ADS131M0X_SENSOR_TYPE_MEAN ? snapshot.mean[this->channel_]
35 : snapshot.rms[this->channel_]);
36}
37
39 LOG_SENSOR("", "ADS131M0x Sensor", this);
40 ESP_LOGCONFIG(TAG,
41 " Channel: %u\n"
42 " Type: %s",
43 this->channel_, LOG_STR_ARG(SensorTypeStrings::get_log_str(this->type_)));
44}
45
46} // namespace esphome::ads131m0x
47
48#endif // USE_ESP32
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 publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
PROGMEM_STRING_TABLE(PowerModeStrings, "very low power", "low power", "high resolution", "unknown")
ESPHOME_LOG_TAG(TAG, "ads131m0x")
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
Result of one measurement window, in volts at the ADC input.
Definition ads131m0x.h:28
uint32_t sequence
Incremented with every completed window; 0 = no valid data.
Definition ads131m0x.h:31
std::array< float, MAX_CHANNELS > mean
Mean (DC) value.
Definition ads131m0x.h:30
std::array< float, MAX_CHANNELS > rms
RMS of the AC component (DC offset removed)
Definition ads131m0x.h:29
uint32_t timestamp_ms
millis() at the end of the window
Definition ads131m0x.h:32