ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
sgp30.cpp
Go to the documentation of this file.
1#include "sgp30.h"
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7#include <cinttypes>
8
9namespace esphome::sgp30 {
10
11ESPHOME_LOG_TAG(TAG, "sgp30");
12
13static const uint16_t SGP30_CMD_GET_SERIAL_ID = 0x3682;
14static const uint16_t SGP30_CMD_GET_FEATURESET = 0x202f;
15static const uint16_t SGP30_CMD_IAQ_INIT = 0x2003;
16static const uint16_t SGP30_CMD_MEASURE_IAQ = 0x2008;
17static const uint16_t SGP30_CMD_SET_ABSOLUTE_HUMIDITY = 0x2061;
18static const uint16_t SGP30_CMD_GET_IAQ_BASELINE = 0x2015;
19static const uint16_t SGP30_CMD_SET_IAQ_BASELINE = 0x201E;
20
21// Sensor baseline should first be relied on after 1H of operation,
22// if the sensor starts with a baseline value provided
24
25// Sensor baseline could first be relied on after 12H of operation,
26// if the sensor starts without any prior baseline value provided
28
29// Shortest time interval of 1H for storing baseline values.
30// Prevents wear of the flash because of too many write operations
32
33// Store anyway if the baseline difference exceeds the max storage diff value
35
37 // Serial Number identification
38 uint16_t raw_serial_number[3];
39 if (!this->get_register(SGP30_CMD_GET_SERIAL_ID, raw_serial_number, 3)) {
40 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
41 return;
42 }
43 this->serial_number_ = (static_cast<uint64_t>(raw_serial_number[0]) << 32) |
44 (static_cast<uint64_t>(raw_serial_number[1]) << 16) |
45 static_cast<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(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
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->mark_failed(LOG_STR("Unsupported ID"));
59 } else {
60 this->mark_failed(LOG_STR("Invalid ID"));
61 }
62 return;
63 }
64 ESP_LOGV(TAG, "Product version: 0x%0X", uint16_t(this->featureset_ & 0x1FF));
65
66 // Sensor initialization
67 if (!this->write_command(SGP30_CMD_IAQ_INIT)) {
68 this->mark_failed(LOG_STR("Measurement initialization failed"));
69 return;
70 }
71
72 // Hash with config hash, version, and serial number
73 // This ensures the baseline storage is cleared after OTA
74 // Serial numbers are unique to each sensor, so multiple sensors can be used without conflict
75 uint32_t hash = fnv1a_hash_extend(App.get_config_version_hash(), this->serial_number_);
77
78 if (this->store_baseline_ && this->pref_.load(&this->baselines_storage_)) {
79 ESP_LOGI(TAG, "Loaded eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", this->baselines_storage_.eco2,
83 }
84
85 // Initialize storage timestamp
87
88 // Sensor baseline reliability timer
89 if (this->eco2_baseline_ > 0 && this->tvoc_baseline_ > 0) {
92 } else {
94 }
95}
96
98 if ((this->required_warm_up_time_ == 0) || (std::floor(millis() / 1000) >= this->required_warm_up_time_)) {
99 // requirement for warm up is removed once the millis uptime surpasses the required warm_up_time
100 // this avoids the repetitive warm up when the millis uptime is rolled over every ~40 days
101 this->required_warm_up_time_ = 0;
102 return true;
103 }
104 return false;
105}
106
108 if (this->is_sensor_baseline_reliable_()) {
109 if (!this->write_command(SGP30_CMD_GET_IAQ_BASELINE)) {
110 ESP_LOGD(TAG, "Error getting baseline");
111 this->status_set_warning();
112 return;
113 }
114 this->set_timeout(50, [this]() {
115 uint16_t raw_data[2];
116 if (!this->read_data(raw_data, 2)) {
117 this->status_set_warning();
118 return;
119 }
120
121 uint16_t eco2baseline = (raw_data[0]);
122 uint16_t tvocbaseline = (raw_data[1]);
123
124 ESP_LOGI(TAG, "Baselines: eCO2: 0x%04X, TVOC: 0x%04X", eco2baseline, tvocbaseline);
125 if (eco2baseline != this->eco2_baseline_ || tvocbaseline != this->tvoc_baseline_) {
126 this->eco2_baseline_ = eco2baseline;
127 this->tvoc_baseline_ = tvocbaseline;
128 if (this->eco2_sensor_baseline_ != nullptr)
130 if (this->tvoc_sensor_baseline_ != nullptr)
132
133 // Store baselines after defined interval or if the difference between current and stored baseline becomes too
134 // much
135 if (this->store_baseline_ &&
136 (this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL ||
137 (uint32_t) abs(this->baselines_storage_.eco2 - this->eco2_baseline_) > MAXIMUM_STORAGE_DIFF ||
138 (uint32_t) abs(this->baselines_storage_.tvoc - this->tvoc_baseline_) > MAXIMUM_STORAGE_DIFF)) {
142 if (this->pref_.save(&this->baselines_storage_)) {
143 ESP_LOGI(TAG, "Store baselines: eCO2: 0x%04X, TVOC: 0x%04X", this->baselines_storage_.eco2,
144 this->baselines_storage_.tvoc);
145 } else {
146 ESP_LOGW(TAG, "Could not store eCO2 and TVOC baselines");
147 }
148 }
149 }
150 this->status_clear_warning();
151 });
152 } else {
153 ESP_LOGD(TAG, "Baseline reading not available for: %.0fs",
154 (this->required_warm_up_time_ - std::floor(millis() / 1000)));
155 }
156}
157
159 if (this->humidity_sensor_ == nullptr && this->temperature_sensor_ == nullptr)
160 return;
161 float humidity = NAN;
162 if (this->humidity_sensor_ != nullptr)
163 humidity = this->humidity_sensor_->state;
164 if (std::isnan(humidity) || humidity < 0.0f || humidity > 100.0f) {
165 ESP_LOGW(TAG, "Compensation not possible yet: bad humidity data");
166 return;
167 } else {
168 ESP_LOGD(TAG, "External compensation data received: Humidity %0.2f%%", humidity);
169 }
170 float temperature = NAN;
171 if (this->temperature_sensor_ != nullptr) {
172 temperature = float(this->temperature_sensor_->state);
173 }
174 if (std::isnan(temperature) || temperature < -40.0f || temperature > 85.0f) {
175 ESP_LOGW(TAG, "Compensation not possible yet: bad temperature value");
176 return;
177 } else {
178 ESP_LOGD(TAG, "External compensation data received: Temperature %0.2f°C", temperature);
179 }
180
181 float absolute_humidity;
182 if (temperature < 0) {
183 absolute_humidity =
184 216.67f *
185 ((humidity * 0.061121f * std::exp((23.036f - temperature / 333.7f) * (temperature / (279.82f + temperature)))) /
186 (273.15f + temperature));
187 } else {
188 absolute_humidity =
189 216.67f *
190 ((humidity * 0.061121f * std::exp((18.678f - temperature / 234.5f) * (temperature / (257.14f + temperature)))) /
191 (273.15f + temperature));
192 }
193 uint8_t data[4] = {
194 SGP30_CMD_SET_ABSOLUTE_HUMIDITY & 0xFF,
195 uint8_t(std::floor(absolute_humidity)), // humidity_full
196 uint8_t(std::floor((absolute_humidity - std::floor(absolute_humidity)) * 256)), // humidity_dec
197 0,
198 };
199 data[3] = crc8(&data[1], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
200 ESP_LOGD(TAG, "Calculated absolute humidity: %0.3f g/m³ (0x%04X)", absolute_humidity,
201 encode_uint16(data[1], data[2]));
202 if (!this->write_bytes(SGP30_CMD_SET_ABSOLUTE_HUMIDITY >> 8, data, 4)) {
203 ESP_LOGE(TAG, "Error sending compensation data");
204 }
205}
206
207void SGP30Component::write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline) {
208 uint8_t data[7];
209 data[0] = SGP30_CMD_SET_IAQ_BASELINE & 0xFF;
210 data[1] = tvoc_baseline >> 8;
211 data[2] = tvoc_baseline & 0xFF;
212 data[3] = crc8(&data[1], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
213 data[4] = eco2_baseline >> 8;
214 data[5] = eco2_baseline & 0xFF;
215 data[6] = crc8(&data[4], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
216 if (!this->write_bytes(SGP30_CMD_SET_IAQ_BASELINE >> 8, data, 7)) {
217 ESP_LOGE(TAG, "Error applying baselines: eCO2: 0x%04X, TVOC: 0x%04X", eco2_baseline, tvoc_baseline);
218 } else {
219 ESP_LOGI(TAG, "Initial baselines applied: eCO2: 0x%04X, TVOC: 0x%04X", eco2_baseline, tvoc_baseline);
220 }
221}
222
224 ESP_LOGCONFIG(TAG, "SGP30:");
225 LOG_I2C_DEVICE(this);
226 if (!this->is_failed()) {
227 ESP_LOGCONFIG(TAG, " Serial number: %" PRIu64, this->serial_number_);
228 if (this->eco2_baseline_ != 0x0000 && this->tvoc_baseline_ != 0x0000) {
229 ESP_LOGCONFIG(TAG,
230 " Baselines:\n"
231 " eCO2: 0x%04X\n"
232 " TVOC: 0x%04X",
233 this->eco2_baseline_, this->tvoc_baseline_);
234 } else {
235 ESP_LOGCONFIG(TAG, " Baselines not configured");
236 }
237 ESP_LOGCONFIG(TAG, " Warm up time: %" PRIu32 "s", this->required_warm_up_time_);
238 }
239 LOG_UPDATE_INTERVAL(this);
240 LOG_SENSOR(" ", "eCO2 sensor", this->eco2_sensor_);
241 LOG_SENSOR(" ", "TVOC sensor", this->tvoc_sensor_);
242 LOG_SENSOR(" ", "eCO2 baseline sensor", this->eco2_sensor_baseline_);
243 LOG_SENSOR(" ", "TVOC baseline sensor", this->tvoc_sensor_baseline_);
244 ESP_LOGCONFIG(TAG, "Store baseline: %s", YESNO(this->store_baseline_));
245 if (this->humidity_sensor_ != nullptr && this->temperature_sensor_ != nullptr) {
246 ESP_LOGCONFIG(TAG, " Compensation:");
247 LOG_SENSOR(" ", "Temperature source:", this->temperature_sensor_);
248 LOG_SENSOR(" ", "Humidity source:", this->humidity_sensor_);
249 } else {
250 ESP_LOGCONFIG(TAG, " Compensation: No source configured");
251 }
252}
253
255 if (!this->write_command(SGP30_CMD_MEASURE_IAQ)) {
256 this->status_set_warning();
257 return;
258 }
259 this->seconds_since_last_store_ += this->update_interval_ / 1000;
260 this->set_timeout(50, [this]() {
261 uint16_t raw_data[2];
262 if (!this->read_data(raw_data, 2)) {
263 this->status_set_warning();
264 return;
265 }
266
267 float eco2 = (raw_data[0]);
268 float tvoc = (raw_data[1]);
269
270 ESP_LOGV(TAG, "eCO2=%.1fppm TVOC=%.1fppb", eco2, tvoc);
271 if (this->eco2_sensor_ != nullptr)
272 this->eco2_sensor_->publish_state(eco2);
273 if (this->tvoc_sensor_ != nullptr)
274 this->tvoc_sensor_->publish_state(tvoc);
275
276 this->status_clear_warning();
277 this->send_env_data_();
278 this->read_iaq_baseline_();
279 });
280}
281
282} // namespace esphome::sgp30
uint32_t get_config_version_hash()
Get the config hash extended with ESPHome version.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:274
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:296
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:298
bool get_register(uint16_t command, uint16_t *data, uint8_t len, uint8_t delay=0)
get data words from I2C register.
bool write_command(T i2c_register)
Write a command to the I2C device.
bool read_data(uint16_t *data, uint8_t len)
Read data words from I2C device.
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:140
sensor::Sensor * eco2_sensor_baseline_
Definition sgp30.h:54
sensor::Sensor * temperature_sensor_
Definition sgp30.h:58
SGP30Baselines baselines_storage_
Definition sgp30.h:50
sensor::Sensor * tvoc_sensor_
Definition sgp30.h:53
sensor::Sensor * tvoc_sensor_baseline_
Definition sgp30.h:55
sensor::Sensor * humidity_sensor_
Input sensor for humidity and temperature compensation.
Definition sgp30.h:57
uint32_t seconds_since_last_store_
Definition sgp30.h:43
ESPPreferenceObject pref_
Definition sgp30.h:49
void write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline)
Definition sgp30.cpp:207
void dump_config() override
Definition sgp30.cpp:223
sensor::Sensor * eco2_sensor_
Definition sgp30.h:52
ESPHOME_LOG_TAG(TAG, "sgp30")
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITHOUT_BASELINE
Definition sgp30.cpp:27
const uint32_t SHORTEST_BASELINE_STORE_INTERVAL
Definition sgp30.cpp:31
const uint32_t MAXIMUM_STORAGE_DIFF
Definition sgp30.cpp:34
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITH_BASELINE_PROVIDED
Definition sgp30.cpp:23
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:950
ESPPreferences * global_preferences
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
Definition helpers.cpp:68
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:998
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
uint16_t temperature
Definition sun_gtil2.cpp:12