ESPHome 2026.5.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 {
10namespace sgp30 {
11
12static const char *const TAG = "sgp30";
13
14static const uint16_t SGP30_CMD_GET_SERIAL_ID = 0x3682;
15static const uint16_t SGP30_CMD_GET_FEATURESET = 0x202f;
16static const uint16_t SGP30_CMD_IAQ_INIT = 0x2003;
17static const uint16_t SGP30_CMD_MEASURE_IAQ = 0x2008;
18static const uint16_t SGP30_CMD_SET_ABSOLUTE_HUMIDITY = 0x2061;
19static const uint16_t SGP30_CMD_GET_IAQ_BASELINE = 0x2015;
20static const uint16_t SGP30_CMD_SET_IAQ_BASELINE = 0x201E;
21
22// Sensor baseline should first be relied on after 1H of operation,
23// if the sensor starts with a baseline value provided
25
26// Sensor baseline could first be relied on after 12H of operation,
27// if the sensor starts without any prior baseline value provided
29
30// Shortest time interval of 1H for storing baseline values.
31// Prevents wear of the flash because of too many write operations
33
34// Store anyway if the baseline difference exceeds the max storage diff value
36
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_ = (static_cast<uint64_t>(raw_serial_number[0]) << 32) |
45 (static_cast<uint64_t>(raw_serial_number[1]) << 16) |
46 static_cast<uint64_t>(raw_serial_number[2]);
47 ESP_LOGD(TAG, "Serial number: %" PRIu64, this->serial_number_);
48
49 // Featureset identification for future use
50 uint16_t raw_featureset;
51 if (!this->get_register(SGP30_CMD_GET_FEATURESET, raw_featureset)) {
52 this->mark_failed();
53 return;
54 }
55 this->featureset_ = raw_featureset;
56 if (uint16_t(this->featureset_ >> 12) != 0x0) {
57 if (uint16_t(this->featureset_ >> 12) == 0x1) {
58 // ID matching a different sensor: SGPC3
59 this->error_code_ = UNSUPPORTED_ID;
60 } else {
61 // Unknown ID
62 this->error_code_ = INVALID_ID;
63 }
64 this->mark_failed();
65 return;
66 }
67 ESP_LOGV(TAG, "Product version: 0x%0X", uint16_t(this->featureset_ & 0x1FF));
68
69 // Sensor initialization
70 if (!this->write_command(SGP30_CMD_IAQ_INIT)) {
71 ESP_LOGE(TAG, "sgp30_iaq_init failed");
72 this->error_code_ = MEASUREMENT_INIT_FAILED;
73 this->mark_failed();
74 return;
75 }
76
77 // Hash with config hash, version, and serial number
78 // This ensures the baseline storage is cleared after OTA
79 // Serial numbers are unique to each sensor, so multiple sensors can be used without conflict
80 uint32_t hash = fnv1a_hash_extend(App.get_config_version_hash(), this->serial_number_);
82
83 if (this->store_baseline_ && this->pref_.load(&this->baselines_storage_)) {
84 ESP_LOGI(TAG, "Loaded eCO2 baseline: 0x%04X, TVOC baseline: 0x%04X", this->baselines_storage_.eco2,
88 }
89
90 // Initialize storage timestamp
92
93 // Sensor baseline reliability timer
94 if (this->eco2_baseline_ > 0 && this->tvoc_baseline_ > 0) {
97 } else {
99 }
100}
101
103 if ((this->required_warm_up_time_ == 0) || (std::floor(millis() / 1000) >= this->required_warm_up_time_)) {
104 // requirement for warm up is removed once the millis uptime surpasses the required warm_up_time
105 // this avoids the repetitive warm up when the millis uptime is rolled over every ~40 days
106 this->required_warm_up_time_ = 0;
107 return true;
108 }
109 return false;
110}
111
113 if (this->is_sensor_baseline_reliable_()) {
114 if (!this->write_command(SGP30_CMD_GET_IAQ_BASELINE)) {
115 ESP_LOGD(TAG, "Error getting baseline");
116 this->status_set_warning();
117 return;
118 }
119 this->set_timeout(50, [this]() {
120 uint16_t raw_data[2];
121 if (!this->read_data(raw_data, 2)) {
122 this->status_set_warning();
123 return;
124 }
125
126 uint16_t eco2baseline = (raw_data[0]);
127 uint16_t tvocbaseline = (raw_data[1]);
128
129 ESP_LOGI(TAG, "Baselines: eCO2: 0x%04X, TVOC: 0x%04X", eco2baseline, tvocbaseline);
130 if (eco2baseline != this->eco2_baseline_ || tvocbaseline != this->tvoc_baseline_) {
131 this->eco2_baseline_ = eco2baseline;
132 this->tvoc_baseline_ = tvocbaseline;
133 if (this->eco2_sensor_baseline_ != nullptr)
135 if (this->tvoc_sensor_baseline_ != nullptr)
137
138 // Store baselines after defined interval or if the difference between current and stored baseline becomes too
139 // much
140 if (this->store_baseline_ &&
141 (this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL ||
142 (uint32_t) abs(this->baselines_storage_.eco2 - this->eco2_baseline_) > MAXIMUM_STORAGE_DIFF ||
143 (uint32_t) abs(this->baselines_storage_.tvoc - this->tvoc_baseline_) > MAXIMUM_STORAGE_DIFF)) {
147 if (this->pref_.save(&this->baselines_storage_)) {
148 ESP_LOGI(TAG, "Store baselines: eCO2: 0x%04X, TVOC: 0x%04X", this->baselines_storage_.eco2,
149 this->baselines_storage_.tvoc);
150 } else {
151 ESP_LOGW(TAG, "Could not store eCO2 and TVOC baselines");
152 }
153 }
154 }
155 this->status_clear_warning();
156 });
157 } else {
158 ESP_LOGD(TAG, "Baseline reading not available for: %.0fs",
159 (this->required_warm_up_time_ - std::floor(millis() / 1000)));
160 }
161}
162
164 if (this->humidity_sensor_ == nullptr && this->temperature_sensor_ == nullptr)
165 return;
166 float humidity = NAN;
167 if (this->humidity_sensor_ != nullptr)
168 humidity = this->humidity_sensor_->state;
169 if (std::isnan(humidity) || humidity < 0.0f || humidity > 100.0f) {
170 ESP_LOGW(TAG, "Compensation not possible yet: bad humidity data");
171 return;
172 } else {
173 ESP_LOGD(TAG, "External compensation data received: Humidity %0.2f%%", humidity);
174 }
175 float temperature = NAN;
176 if (this->temperature_sensor_ != nullptr) {
177 temperature = float(this->temperature_sensor_->state);
178 }
179 if (std::isnan(temperature) || temperature < -40.0f || temperature > 85.0f) {
180 ESP_LOGW(TAG, "Compensation not possible yet: bad temperature value");
181 return;
182 } else {
183 ESP_LOGD(TAG, "External compensation data received: Temperature %0.2f°C", temperature);
184 }
185
186 float absolute_humidity;
187 if (temperature < 0) {
188 absolute_humidity =
189 216.67f *
190 ((humidity * 0.061121f * std::exp((23.036f - temperature / 333.7f) * (temperature / (279.82f + temperature)))) /
191 (273.15f + temperature));
192 } else {
193 absolute_humidity =
194 216.67f *
195 ((humidity * 0.061121f * std::exp((18.678f - temperature / 234.5f) * (temperature / (257.14f + temperature)))) /
196 (273.15f + temperature));
197 }
198 uint8_t data[4] = {
199 SGP30_CMD_SET_ABSOLUTE_HUMIDITY & 0xFF,
200 uint8_t(std::floor(absolute_humidity)), // humidity_full
201 uint8_t(std::floor((absolute_humidity - std::floor(absolute_humidity)) * 256)), // humidity_dec
202 0,
203 };
204 data[3] = crc8(&data[1], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
205 ESP_LOGD(TAG, "Calculated absolute humidity: %0.3f g/m³ (0x%04X)", absolute_humidity,
206 encode_uint16(data[1], data[2]));
207 if (!this->write_bytes(SGP30_CMD_SET_ABSOLUTE_HUMIDITY >> 8, data, 4)) {
208 ESP_LOGE(TAG, "Error sending compensation data");
209 }
210}
211
212void SGP30Component::write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline) {
213 uint8_t data[7];
214 data[0] = SGP30_CMD_SET_IAQ_BASELINE & 0xFF;
215 data[1] = tvoc_baseline >> 8;
216 data[2] = tvoc_baseline & 0xFF;
217 data[3] = crc8(&data[1], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
218 data[4] = eco2_baseline >> 8;
219 data[5] = eco2_baseline & 0xFF;
220 data[6] = crc8(&data[4], 2, 0xFF, sensirion_common::CRC_POLYNOMIAL, true);
221 if (!this->write_bytes(SGP30_CMD_SET_IAQ_BASELINE >> 8, data, 7)) {
222 ESP_LOGE(TAG, "Error applying baselines: eCO2: 0x%04X, TVOC: 0x%04X", eco2_baseline, tvoc_baseline);
223 } else {
224 ESP_LOGI(TAG, "Initial baselines applied: eCO2: 0x%04X, TVOC: 0x%04X", eco2_baseline, tvoc_baseline);
225 }
226}
227
229 ESP_LOGCONFIG(TAG, "SGP30:");
230 LOG_I2C_DEVICE(this);
231 if (this->is_failed()) {
232 switch (this->error_code_) {
234 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
235 break;
237 ESP_LOGW(TAG, "Measurement Initialization failed");
238 break;
239 case INVALID_ID:
240 ESP_LOGW(TAG, "Invalid ID");
241 break;
242 case UNSUPPORTED_ID:
243 ESP_LOGW(TAG, "Unsupported ID");
244 break;
245 default:
246 ESP_LOGW(TAG, "Unknown setup error");
247 break;
248 }
249 } else {
250 ESP_LOGCONFIG(TAG, " Serial number: %" PRIu64, this->serial_number_);
251 if (this->eco2_baseline_ != 0x0000 && this->tvoc_baseline_ != 0x0000) {
252 ESP_LOGCONFIG(TAG,
253 " Baselines:\n"
254 " eCO2: 0x%04X\n"
255 " TVOC: 0x%04X",
256 this->eco2_baseline_, this->tvoc_baseline_);
257 } else {
258 ESP_LOGCONFIG(TAG, " Baselines not configured");
259 }
260 ESP_LOGCONFIG(TAG, " Warm up time: %" PRIu32 "s", this->required_warm_up_time_);
261 }
262 LOG_UPDATE_INTERVAL(this);
263 LOG_SENSOR(" ", "eCO2 sensor", this->eco2_sensor_);
264 LOG_SENSOR(" ", "TVOC sensor", this->tvoc_sensor_);
265 LOG_SENSOR(" ", "eCO2 baseline sensor", this->eco2_sensor_baseline_);
266 LOG_SENSOR(" ", "TVOC baseline sensor", this->tvoc_sensor_baseline_);
267 ESP_LOGCONFIG(TAG, "Store baseline: %s", YESNO(this->store_baseline_));
268 if (this->humidity_sensor_ != nullptr && this->temperature_sensor_ != nullptr) {
269 ESP_LOGCONFIG(TAG, " Compensation:");
270 LOG_SENSOR(" ", "Temperature source:", this->temperature_sensor_);
271 LOG_SENSOR(" ", "Humidity source:", this->humidity_sensor_);
272 } else {
273 ESP_LOGCONFIG(TAG, " Compensation: No source configured");
274 }
275}
276
278 if (!this->write_command(SGP30_CMD_MEASURE_IAQ)) {
279 this->status_set_warning();
280 return;
281 }
282 this->seconds_since_last_store_ += this->update_interval_ / 1000;
283 this->set_timeout(50, [this]() {
284 uint16_t raw_data[2];
285 if (!this->read_data(raw_data, 2)) {
286 this->status_set_warning();
287 return;
288 }
289
290 float eco2 = (raw_data[0]);
291 float tvoc = (raw_data[1]);
292
293 ESP_LOGV(TAG, "eCO2=%.1fppm TVOC=%.1fppb", eco2, tvoc);
294 if (this->eco2_sensor_ != nullptr)
295 this->eco2_sensor_->publish_state(eco2);
296 if (this->tvoc_sensor_ != nullptr)
297 this->tvoc_sensor_->publish_state(tvoc);
298
299 this->status_clear_warning();
300 this->send_env_data_();
301 this->read_iaq_baseline_();
302 });
303}
304
305} // namespace sgp30
306} // namespace esphome
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:284
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:510
void status_clear_warning()
Definition component.h:306
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:251
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:68
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:138
sensor::Sensor * eco2_sensor_baseline_
Definition sgp30.h:63
sensor::Sensor * temperature_sensor_
Definition sgp30.h:67
SGP30Baselines baselines_storage_
Definition sgp30.h:59
sensor::Sensor * tvoc_sensor_
Definition sgp30.h:62
sensor::Sensor * tvoc_sensor_baseline_
Definition sgp30.h:64
sensor::Sensor * humidity_sensor_
Input sensor for humidity and temperature compensation.
Definition sgp30.h:66
uint32_t seconds_since_last_store_
Definition sgp30.h:44
ESPPreferenceObject pref_
Definition sgp30.h:58
void write_iaq_baseline_(uint16_t eco2_baseline, uint16_t tvoc_baseline)
Definition sgp30.cpp:212
void dump_config() override
Definition sgp30.cpp:228
sensor::Sensor * eco2_sensor_
Definition sgp30.h:61
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITHOUT_BASELINE
Definition sgp30.cpp:28
const uint32_t SHORTEST_BASELINE_STORE_INTERVAL
Definition sgp30.cpp:32
const uint32_t MAXIMUM_STORAGE_DIFF
Definition sgp30.cpp:35
const uint32_t IAQ_BASELINE_WARM_UP_SECONDS_WITH_BASELINE_PROVIDED
Definition sgp30.cpp:24
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:799
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:59
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:881
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:26
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