ESPHome 2026.11.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
6ESPHOME_LOG_TAG(TAG, "aqi");
7
8static constexpr uint32_t CALCULATE_DEFER_ID = 0;
9
11 if (this->pm_2_5_sensor_ != nullptr) {
12 this->pm_2_5_sensor_->add_on_state_callback([this](float value) {
13 this->pm_2_5_value_ = value;
14 // Defer calculation to avoid double-publishing if both sensors update in the same loop
15 this->defer(CALCULATE_DEFER_ID, [this]() { this->calculate_aqi_(); });
16 });
17 }
18 if (this->pm_10_0_sensor_ != nullptr) {
19 this->pm_10_0_sensor_->add_on_state_callback([this](float value) {
20 this->pm_10_0_value_ = value;
21 this->defer(CALCULATE_DEFER_ID, [this]() { this->calculate_aqi_(); });
22 });
23 }
24}
25
27 ESP_LOGCONFIG(TAG, "AQI Sensor:");
28 ESP_LOGCONFIG(TAG, " Calculation Type: %s",
29 this->aqi_calc_type_ == AQI_TYPE ? LOG_STR_LITERAL("AQI") : LOG_STR_LITERAL("CAQI"));
30 ESP_LOGCONFIG(TAG, " Extended Range: %s",
31 this->extended_range_ ? LOG_STR_LITERAL("enabled") : LOG_STR_LITERAL("disabled"));
32 if (this->pm_2_5_sensor_ != nullptr) {
33 ESP_LOGCONFIG(TAG, " PM2.5 Sensor: '%s'", this->pm_2_5_sensor_->get_name().c_str());
34 }
35 if (this->pm_10_0_sensor_ != nullptr) {
36 ESP_LOGCONFIG(TAG, " PM10 Sensor: '%s'", this->pm_10_0_sensor_->get_name().c_str());
37 }
38 LOG_SENSOR(" ", "AQI", this);
39}
40
42 if (std::isnan(this->pm_2_5_value_) || std::isnan(this->pm_10_0_value_)) {
43 return;
44 }
45
47 if (calculator == nullptr) {
48 ESP_LOGW(TAG, "Unknown AQI calculator type");
49 return;
50 }
51
52 uint16_t aqi = calculator->get_aqi(this->pm_2_5_value_, this->pm_10_0_value_, this->extended_range_);
53 this->publish_state(aqi);
54}
55
56} // 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:78
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
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:121
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
ESPHOME_LOG_TAG(TAG, "aqi")
static void uint32_t