ESPHome  2022.12.8
sgp30.cpp
Go to the documentation of this file.
1 #include "sgp30.h"
2 #include "esphome/core/hal.h"
3 #include "esphome/core/log.h"
5 #include <cinttypes>
6 
7 namespace esphome {
8 namespace sgp30 {
9 
10 static const char *const TAG = "sgp30";
11 
12 static const uint16_t SGP30_CMD_GET_SERIAL_ID = 0x3682;
13 static const uint16_t SGP30_CMD_GET_FEATURESET = 0x202f;
14 static const uint16_t SGP30_CMD_IAQ_INIT = 0x2003;
15 static const uint16_t SGP30_CMD_MEASURE_IAQ = 0x2008;
16 static const uint16_t SGP30_CMD_SET_ABSOLUTE_HUMIDITY = 0x2061;
17 static const uint16_t SGP30_CMD_GET_IAQ_BASELINE = 0x2015;
18 static const uint16_t SGP30_CMD_SET_IAQ_BASELINE = 0x201E;
19 
20 // Sensor baseline should first be relied on after 1H of operation,
21 // if the sensor starts with a baseline value provided
23 
24 // Sensor baseline could first be relied on after 12H of operation,
25 // if the sensor starts without any prior baseline value provided
27 
28 // Shortest time interval of 1H for storing baseline values.
29 // Prevents wear of the flash because of too many write operations
30 const uint32_t SHORTEST_BASELINE_STORE_INTERVAL = 3600;
31 
32 // Store anyway if the baseline difference exceeds the max storage diff value
33 const uint32_t MAXIMUM_STORAGE_DIFF = 50;
34 
36  ESP_LOGCONFIG(TAG, "Setting up SGP30...");
37 
38  // Serial Number identification
39  uint16_t raw_serial_number[3];
40  if (!this->get_register(SGP30_CMD_GET_SERIAL_ID, raw_serial_number, 3)) {
41  this->mark_failed();
42  return;
43  }
44  this->serial_number_ = (uint64_t(raw_serial_number[0]) << 24) | (uint64_t(raw_serial_number[1]) << 16) |
45  (uint64_t(raw_serial_number[2]));
46  ESP_LOGD(TAG, "Serial Number: %" PRIu64, this->serial_number_);
47 
48  // Featureset identification for future use
49  uint16_t raw_featureset;
50  if (!this->get_register(SGP30_CMD_GET_FEATURESET, raw_featureset)) {
51  this->mark_failed();
52  return;
53  }
54  this->featureset_ = raw_featureset;
55  if (uint16_t(this->featureset_ >> 12) != 0x0) {
56  if (uint16_t(this->featureset_ >> 12) == 0x1) {
57  // ID matching a different sensor: SGPC3
58  this->error_code_ = UNSUPPORTED_ID;
59  } else {
60  // Unknown ID
61  this->error_code_ = INVALID_ID;
62  }
63  this->mark_failed();
64  return;
65  }
66  ESP_LOGD(TAG, "Product version: 0x%0X", uint16_t(this->featureset_ & 0x1FF));
67 
68  // Sensor initialization
69  if (!this->write_command(SGP30_CMD_IAQ_INIT)) {
70  ESP_LOGE(TAG, "Sensor sgp30_iaq_init failed.");
71  this->error_code_ = MEASUREMENT_INIT_FAILED;
72  this->mark_failed();
73  return;
74  }
75 
76  // Hash with compilation time
77  // This ensures the baseline storage is cleared after OTA
78  uint32_t hash = fnv1_hash(App.get_compilation_time());
80 
81  if (this->pref_.load(&this->baselines_storage_)) {
82  ESP_LOGI(TAG, "Loaded eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", this->baselines_storage_.eco2,
86  }
87 
88  // Initialize storage timestamp
89  this->seconds_since_last_store_ = 0;
90 
91  // Sensor baseline reliability timer
92  if (this->eco2_baseline_ > 0 && this->tvoc_baseline_ > 0) {
95  } else {
97  }
98 }
99 
101  if ((this->required_warm_up_time_ == 0) || (std::floor(millis() / 1000) >= this->required_warm_up_time_)) {
102  // requirement for warm up is removed once the millis uptime surpasses the required warm_up_time
103  // this avoids the repetitive warm up when the millis uptime is rolled over every ~40 days
104  this->required_warm_up_time_ = 0;
105  return true;
106  }
107  return false;
108 }
109 
111  if (this->is_sensor_baseline_reliable_()) {
112  if (!this->write_command(SGP30_CMD_GET_IAQ_BASELINE)) {
113  ESP_LOGD(TAG, "Error getting baseline");
114  this->status_set_warning();
115  return;
116  }
117  this->set_timeout(50, [this]() {
118  uint16_t raw_data[2];
119  if (!this->read_data(raw_data, 2)) {
120  this->status_set_warning();
121  return;
122  }
123 
124  uint16_t eco2baseline = (raw_data[0]);
125  uint16_t tvocbaseline = (raw_data[1]);
126 
127  ESP_LOGI(TAG, "Current eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", eco2baseline, tvocbaseline);
128  if (eco2baseline != this->eco2_baseline_ || tvocbaseline != this->tvoc_baseline_) {
129  this->eco2_baseline_ = eco2baseline;
130  this->tvoc_baseline_ = tvocbaseline;
131  if (this->eco2_sensor_baseline_ != nullptr)
133  if (this->tvoc_sensor_baseline_ != nullptr)
135 
136  // Store baselines after defined interval or if the difference between current and stored baseline becomes too
137  // much
138  if (this->store_baseline_ &&
139  (this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL ||
140  (uint32_t) abs(this->baselines_storage_.eco2 - this->eco2_baseline_) > MAXIMUM_STORAGE_DIFF ||
141  (uint32_t) abs(this->baselines_storage_.tvoc - this->tvoc_baseline_) > MAXIMUM_STORAGE_DIFF)) {
142  this->seconds_since_last_store_ = 0;
143  this->baselines_storage_.eco2 = this->eco2_baseline_;
144  this->baselines_storage_.tvoc = this->tvoc_baseline_;
145  if (this->pref_.save(&this->baselines_storage_)) {
146  ESP_LOGI(TAG, "Store eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", this->baselines_storage_.eco2,
147  this->baselines_storage_.tvoc);
148  } else {
149  ESP_LOGW(TAG, "Could not store eCO2 and TVOC baselines");
150  }
151  }
152  }
153  this->status_clear_warning();
154  });
155  } else {
156  ESP_LOGD(TAG, "Baseline reading not available for: %.0fs",
157  (this->required_warm_up_time_ - std::floor(millis() / 1000)));
158  }
159 }
160 
162  if (this->humidity_sensor_ == nullptr && this->temperature_sensor_ == nullptr)
163  return;
164  float humidity = NAN;
165  if (this->humidity_sensor_ != nullptr)
166  humidity = this->humidity_sensor_->state;
167  if (std::isnan(humidity) || humidity < 0.0f || humidity > 100.0f) {
168  ESP_LOGW(TAG, "Compensation not possible yet: bad humidity data.");
169  return;
170  } else {
171  ESP_LOGD(TAG, "External compensation data received: Humidity %0.2f%%", humidity);
172  }
173  float temperature = NAN;
174  if (this->temperature_sensor_ != nullptr) {
175  temperature = float(this->temperature_sensor_->state);
176  }
177  if (std::isnan(temperature) || temperature < -40.0f || temperature > 85.0f) {
178  ESP_LOGW(TAG, "Compensation not possible yet: bad temperature value data.");
179  return;
180  } else {
181  ESP_LOGD(TAG, "External compensation data received: Temperature %0.2f°C", temperature);
182  }
183 
184  float absolute_humidity =
185  216.7f * (((humidity / 100) * 6.112f * std::exp((17.62f * temperature) / (243.12f + temperature))) /
186  (273.15f + temperature));
187  uint8_t humidity_full = uint8_t(std::floor(absolute_humidity));
188  uint8_t humidity_dec = uint8_t(std::floor((absolute_humidity - std::floor(absolute_humidity)) * 256));
189  ESP_LOGD(TAG, "Calculated Absolute humidity: %0.3f g/m³ (0x%04X)", absolute_humidity,
190  uint16_t(uint16_t(humidity_full) << 8 | uint16_t(humidity_dec)));
191  uint8_t crc = sht_crc_(humidity_full, humidity_dec);
192  uint8_t data[4];
193  data[0] = SGP30_CMD_SET_ABSOLUTE_HUMIDITY & 0xFF;
194  data[1] = humidity_full;
195  data[2] = humidity_dec;
196  data[3] = crc;
197  if (!this->write_bytes(SGP30_CMD_SET_ABSOLUTE_HUMIDITY >> 8, data, 4)) {
198  ESP_LOGE(TAG, "Error sending compensation data.");
199  }
200 }
201 
202 void SGP30Component::write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline) {
203  uint8_t data[7];
204  data[0] = SGP30_CMD_SET_IAQ_BASELINE & 0xFF;
205  data[1] = tvoc_baseline >> 8;
206  data[2] = tvoc_baseline & 0xFF;
207  data[3] = sht_crc_(data[1], data[2]);
208  data[4] = eco2_baseline >> 8;
209  data[5] = eco2_baseline & 0xFF;
210  data[6] = sht_crc_(data[4], data[5]);
211  if (!this->write_bytes(SGP30_CMD_SET_IAQ_BASELINE >> 8, data, 7)) {
212  ESP_LOGE(TAG, "Error applying eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", eco2_baseline, tvoc_baseline);
213  } else {
214  ESP_LOGI(TAG, "Initial baselines applied successfully! eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", eco2_baseline,
215  tvoc_baseline);
216  }
217 }
218 
220  ESP_LOGCONFIG(TAG, "SGP30:");
221  LOG_I2C_DEVICE(this);
222  if (this->is_failed()) {
223  switch (this->error_code_) {
225  ESP_LOGW(TAG, "Communication failed! Is the sensor connected?");
226  break;
228  ESP_LOGW(TAG, "Measurement Initialization failed!");
229  break;
230  case INVALID_ID:
231  ESP_LOGW(TAG, "Sensor reported an invalid ID. Is this an SGP30?");
232  break;
233  case UNSUPPORTED_ID:
234  ESP_LOGW(TAG, "Sensor reported an unsupported ID (SGPC3).");
235  break;
236  default:
237  ESP_LOGW(TAG, "Unknown setup error!");
238  break;
239  }
240  } else {
241  ESP_LOGCONFIG(TAG, " Serial number: %" PRIu64, this->serial_number_);
242  if (this->eco2_baseline_ != 0x0000 && this->tvoc_baseline_ != 0x0000) {
243  ESP_LOGCONFIG(TAG, " Baseline:");
244  ESP_LOGCONFIG(TAG, " eCO2 Baseline: 0x%04X", this->eco2_baseline_);
245  ESP_LOGCONFIG(TAG, " TVOC Baseline: 0x%04X", this->tvoc_baseline_);
246  } else {
247  ESP_LOGCONFIG(TAG, " Baseline: No baseline configured");
248  }
249  ESP_LOGCONFIG(TAG, " Warm up time: %us", this->required_warm_up_time_);
250  }
251  LOG_UPDATE_INTERVAL(this);
252  LOG_SENSOR(" ", "eCO2 sensor", this->eco2_sensor_);
253  LOG_SENSOR(" ", "TVOC sensor", this->tvoc_sensor_);
254  LOG_SENSOR(" ", "eCO2 baseline sensor", this->eco2_sensor_baseline_);
255  LOG_SENSOR(" ", "TVOC baseline sensor", this->tvoc_sensor_baseline_);
256  ESP_LOGCONFIG(TAG, "Store baseline: %s", YESNO(this->store_baseline_));
257  if (this->humidity_sensor_ != nullptr && this->temperature_sensor_ != nullptr) {
258  ESP_LOGCONFIG(TAG, " Compensation:");
259  LOG_SENSOR(" ", "Temperature Source:", this->temperature_sensor_);
260  LOG_SENSOR(" ", "Humidity Source:", this->humidity_sensor_);
261  } else {
262  ESP_LOGCONFIG(TAG, " Compensation: No source configured");
263  }
264 }
265 
267  if (!this->write_command(SGP30_CMD_MEASURE_IAQ)) {
268  this->status_set_warning();
269  return;
270  }
271  this->seconds_since_last_store_ += this->update_interval_ / 1000;
272  this->set_timeout(50, [this]() {
273  uint16_t raw_data[2];
274  if (!this->read_data(raw_data, 2)) {
275  this->status_set_warning();
276  return;
277  }
278 
279  float eco2 = (raw_data[0]);
280  float tvoc = (raw_data[1]);
281 
282  ESP_LOGD(TAG, "Got eCO2=%.1fppm TVOC=%.1fppb", eco2, tvoc);
283  if (this->eco2_sensor_ != nullptr)
284  this->eco2_sensor_->publish_state(eco2);
285  if (this->tvoc_sensor_ != nullptr)
286  this->tvoc_sensor_->publish_state(tvoc);
287 
288  if (this->get_update_interval() != 1000) {
289  ESP_LOGW(TAG, "Update interval for SGP30 sensor must be set to 1s for optimized readout");
290  }
291 
292  this->status_clear_warning();
293  this->send_env_data_();
294  this->read_iaq_baseline_();
295  });
296 }
297 
298 } // namespace sgp30
299 } // namespace esphome
uint32_t seconds_since_last_store_
Definition: sgp30.h:43
bool write_command(T i2c_register)
Write a command to the i2c device.
Definition: i2c_sensirion.h:82
sensor::Sensor * tvoc_sensor_
Definition: sgp30.h:56
void write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline)
Definition: sgp30.cpp:202
sensor::Sensor * eco2_sensor_baseline_
Definition: sgp30.h:57
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:68
float temperature
Definition: qmp6988.h:71
sensor::Sensor * eco2_sensor_
Definition: sgp30.h:55
bool read_data(uint16_t *data, uint8_t len)
Read data words from i2c device.
uint8_t sht_crc_(uint16_t data)
8-bit CRC checksum that is transmitted after each data word for read and write operation ...
sensor::Sensor * tvoc_sensor_baseline_
Definition: sgp30.h:58
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:26
sensor::Sensor * humidity_sensor_
Input sensor for humidity and temperature compensation.
Definition: sgp30.h:64
bool save(const T *src)
Definition: preferences.h:21
SGP30Baselines baselines_storage_
Definition: sgp30.h:44
sensor::Sensor * temperature_sensor_
Definition: sgp30.h:65
ESPPreferenceObject pref_
Definition: sgp30.h:45
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:135
const uint32_t SHORTEST_BASELINE_STORE_INTERVAL
Definition: sgp30.cpp:30
ESPPreferences * global_preferences
void status_clear_warning()
Definition: component.cpp:149
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:72
Application App
Global storage of Application pointer - only one Application can exist.
uint32_t required_warm_up_time_
Definition: sgp30.h:42
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITHOUT_BASELINE
Definition: sgp30.cpp:26
void status_set_warning()
Definition: component.cpp:141
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
Definition: component.cpp:191
void setup() override
Definition: sgp30.cpp:35
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITH_BASELINE_PROVIDED
Definition: sgp30.cpp:22
const std::string & get_compilation_time() const
Definition: application.h:139
const uint32_t MAXIMUM_STORAGE_DIFF
Definition: sgp30.cpp:33
bool get_register(uint16_t command, uint16_t *data, uint8_t len, uint8_t delay=0)
get data words from i2c register.
Definition: i2c_sensirion.h:43
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:86
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:112
Definition: a4988.cpp:4
void dump_config() override
Definition: sgp30.cpp:219
void update() override
Definition: sgp30.cpp:266
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:109