ESPHome 2026.1.0b1
Loading...
Searching...
No Matches
aqi_sensor.cpp
Go to the documentation of this file.
1#include "aqi_sensor.h"
2#include "esphome/core/log.h"
3
4namespace esphome::aqi {
5
6static const char *const TAG = "aqi";
7
9 if (this->pm_2_5_sensor_ != nullptr) {
10 this->pm_2_5_sensor_->add_on_state_callback([this](float value) {
11 this->pm_2_5_value_ = value;
12 // Defer calculation to avoid double-publishing if both sensors update in the same loop
13 this->defer("update", [this]() { this->calculate_aqi_(); });
14 });
15 }
16 if (this->pm_10_0_sensor_ != nullptr) {
17 this->pm_10_0_sensor_->add_on_state_callback([this](float value) {
18 this->pm_10_0_value_ = value;
19 this->defer("update", [this]() { this->calculate_aqi_(); });
20 });
21 }
22}
23
25 ESP_LOGCONFIG(TAG, "AQI Sensor:");
26 ESP_LOGCONFIG(TAG, " Calculation Type: %s", this->aqi_calc_type_ == AQI_TYPE ? "AQI" : "CAQI");
27 if (this->pm_2_5_sensor_ != nullptr) {
28 ESP_LOGCONFIG(TAG, " PM2.5 Sensor: '%s'", this->pm_2_5_sensor_->get_name().c_str());
29 }
30 if (this->pm_10_0_sensor_ != nullptr) {
31 ESP_LOGCONFIG(TAG, " PM10 Sensor: '%s'", this->pm_10_0_sensor_->get_name().c_str());
32 }
33 LOG_SENSOR(" ", "AQI", this);
34}
35
37 if (std::isnan(this->pm_2_5_value_) || std::isnan(this->pm_10_0_value_)) {
38 return;
39 }
40
42 if (calculator == nullptr) {
43 ESP_LOGW(TAG, "Unknown AQI calculator type");
44 return;
45 }
46
47 uint16_t aqi = calculator->get_aqi(this->pm_2_5_value_, this->pm_10_0_value_);
48 this->publish_state(aqi);
49}
50
51} // namespace esphome::aqi
ESPDEPRECATED("Use const char* overload instead. Removed in 2026.7.0", "2026.1.0") void defer(const std voi defer)(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Definition component.h:492
const StringRef & get_name() const
constexpr const char * c_str() const
Definition string_ref.h:73
AbstractAQICalculator * get_calculator(AQICalculatorType type)
AQICalculatorType aqi_calc_type_
Definition aqi_sensor.h:24
sensor::Sensor * pm_2_5_sensor_
Definition aqi_sensor.h:22
void setup() override
Definition aqi_sensor.cpp:8
void dump_config() override
AQICalculatorFactory aqi_calculator_factory_
Definition aqi_sensor.h:25
sensor::Sensor * pm_10_0_sensor_
Definition aqi_sensor.h:23
virtual uint16_t get_aqi(float pm2_5_value, float pm10_0_value)=0
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:76
void add_on_state_callback(std::function< void(float)> &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition sensor.cpp:89