ESPHome  2024.10.2
aqi_calculator.h
Go to the documentation of this file.
1 #pragma once
2 
4 // https://www.airnow.gov/sites/default/files/2020-05/aqi-technical-assistance-document-sept2018.pdf
5 
6 namespace esphome {
7 namespace hm3301 {
8 
10  public:
11  uint16_t get_aqi(uint16_t pm2_5_value, uint16_t pm10_0_value) override {
12  int pm2_5_index = calculate_index_(pm2_5_value, pm2_5_calculation_grid_);
13  int pm10_0_index = calculate_index_(pm10_0_value, pm10_0_calculation_grid_);
14 
15  return (pm2_5_index < pm10_0_index) ? pm10_0_index : pm2_5_index;
16  }
17 
18  protected:
19  static const int AMOUNT_OF_LEVELS = 7;
20 
21  int index_grid_[AMOUNT_OF_LEVELS][2] = {{0, 50}, {51, 100}, {101, 150}, {151, 200},
22  {201, 300}, {301, 400}, {401, 500}};
23 
24  int pm2_5_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 12}, {13, 35}, {36, 55}, {56, 150},
25  {151, 250}, {251, 350}, {351, 500}};
26 
27  int pm10_0_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 54}, {55, 154}, {155, 254}, {255, 354},
28  {355, 424}, {425, 504}, {505, 604}};
29 
30  int calculate_index_(uint16_t value, int array[AMOUNT_OF_LEVELS][2]) {
31  int grid_index = get_grid_index_(value, array);
32  int aqi_lo = index_grid_[grid_index][0];
33  int aqi_hi = index_grid_[grid_index][1];
34  int conc_lo = array[grid_index][0];
35  int conc_hi = array[grid_index][1];
36 
37  return (value - conc_lo) * (aqi_hi - aqi_lo) / (conc_hi - conc_lo) + aqi_lo;
38  }
39 
40  int get_grid_index_(uint16_t value, int array[AMOUNT_OF_LEVELS][2]) {
41  for (int i = 0; i < AMOUNT_OF_LEVELS; i++) {
42  if (value >= array[i][0] && value <= array[i][1]) {
43  return i;
44  }
45  }
46  return -1;
47  }
48 };
49 
50 } // namespace hm3301
51 } // namespace esphome
int pm10_0_calculation_grid_[AMOUNT_OF_LEVELS][2]
int pm2_5_calculation_grid_[AMOUNT_OF_LEVELS][2]
int get_grid_index_(uint16_t value, int array[AMOUNT_OF_LEVELS][2])
int calculate_index_(uint16_t value, int array[AMOUNT_OF_LEVELS][2])
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
int index_grid_[AMOUNT_OF_LEVELS][2]
static const int AMOUNT_OF_LEVELS
uint16_t get_aqi(uint16_t pm2_5_value, uint16_t pm10_0_value) override