ESPHome 2026.8.0-dev
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 ESP_LOGCONFIG(TAG, " Extended Range: %s", this->extended_range_ ? "enabled" : "disabled");
28 if (this->pm_2_5_sensor_ != nullptr) {
29 ESP_LOGCONFIG(TAG, " PM2.5 Sensor: '%s'", this->pm_2_5_sensor_->get_name().c_str());
30 }
31 if (this->pm_10_0_sensor_ != nullptr) {
32 ESP_LOGCONFIG(TAG, " PM10 Sensor: '%s'", this->pm_10_0_sensor_->get_name().c_str());
33 }
34 LOG_SENSOR(" ", "AQI", this);
35}
36
38 if (std::isnan(this->pm_2_5_value_) || std::isnan(this->pm_10_0_value_)) {
39 return;
40 }
41
43 if (calculator == nullptr) {
44 ESP_LOGW(TAG, "Unknown AQI calculator type");
45 return;
46 }
47
48 uint16_t aqi = calculator->get_aqi(this->pm_2_5_value_, this->pm_10_0_value_, this->extended_range_);
49 this->publish_state(aqi);
50}
51
52} // namespace esphome::aqi
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
const StringRef & get_name() const
Definition entity_base.h:71
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:26
sensor::Sensor * pm_10_0_sensor_
Definition aqi_sensor.h:23
virtual uint16_t get_aqi(float pm2_5_value, float pm10_0_value, bool extended_range)=0
void add_on_state_callback(F &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition sensor.h:119
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68