ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
sen6x.cpp
Go to the documentation of this file.
1#include "sen6x.h"
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
5#include <cinttypes>
6#include <cmath>
7#include <iterator>
8
9namespace esphome::sen6x {
10
11ESPHOME_LOG_TAG(TAG, "sen6x");
12
13// Indexed by Sen6xType
14PROGMEM_STRING_TABLE(TypeStrings, "SEN62", "SEN63C", "SEN65", "SEN66", "SEN68", "SEN69C", "UNKNOWN");
15
16static SEN6XComponent::Sen6xType infer_type_from_product_name(const char *product_name) {
17 const int16_t type = progmem_string_table_find<TypeStrings>(product_name, strnlen(product_name, 32));
19}
20
21#ifdef SEN6X_STATUS_SENSOR_COUNT
22// Bit of the status register behind each kind; the CO2 error bit is 9 on SEN66 and 12 on SEN63C/SEN69C
23static uint8_t status_bit(Sen6xStatus status, SEN6XComponent::Sen6xType type) {
24 switch (status) {
26 return 4;
28 return 21;
30 return 6;
32 return 7;
34 return type == SEN6XComponent::SEN66 ? 9 : 12;
36 return 10;
38 return 11;
39 }
40 return 0;
41}
42#endif
43
44static constexpr uint8_t POLL_RETRIES = 24; // 24 attempts
45static constexpr uint32_t I2C_READ_DELAY = 20; // 20 ms to wait for I2C read to complete
46static constexpr uint32_t CMD_EXEC_DELAY = 20; // execution time of set commands (datasheet section 4.8)
47static constexpr uint32_t POLL_INTERVAL = 50; // 50 ms between poll attempts
48// Numeric timeout IDs. Each chain is sequential, so only one timeout per ID is active at a time.
49static constexpr uint32_t TIMEOUT_POLL = 1;
50static constexpr uint32_t TIMEOUT_SETUP_STEP = 2;
51static constexpr uint32_t TIMEOUT_STARTUP = 3;
52// Post-command wait times from the datasheet: start execution (4.8.1), stop execution (4.8.2),
53// fan cleaning (4.8.22), SHT heater (4.8.23), CO2 conditioning after start on SEN63C/SEN69C (4.8.1)
54static constexpr uint32_t START_MEASUREMENT_DELAY = 50;
55static constexpr uint32_t STOP_MEASUREMENT_DELAY = 1400;
56static constexpr uint32_t FAN_CLEANING_DELAY = 10000;
57static constexpr uint32_t SHT_HEATER_DELAY = 20000;
58static constexpr uint32_t CO2_CONDITIONING_DELAY = 24000;
59// Accepted range of a runtime pressure source, the same as the schema's ambient_pressure_compensation
60static constexpr float AMBIENT_PRESSURE_MIN_HPA = 700.0f;
61static constexpr float AMBIENT_PRESSURE_MAX_HPA = 1200.0f;
62static constexpr uint16_t SEN6X_CMD_GET_DATA_READY_STATUS = 0x0202;
63static constexpr uint16_t SEN6X_CMD_GET_FIRMWARE_VERSION = 0xD100;
64static constexpr uint16_t SEN6X_CMD_GET_PRODUCT_NAME = 0xD014;
65static constexpr uint16_t SEN6X_CMD_GET_SERIAL_NUMBER = 0xD033;
66static constexpr uint16_t SEN6X_CMD_READ_AND_CLEAR_DEVICE_STATUS = 0xD210;
67
68static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT = 0x0300; // SEN66 only!
69static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT_SEN62 = 0x04A3;
70static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT_SEN63C = 0x0471;
71static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT_SEN65 = 0x0446;
72static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT_SEN68 = 0x0467;
73static constexpr uint16_t SEN6X_CMD_READ_MEASUREMENT_SEN69C = 0x04B5;
74
75#ifdef USE_SEN6X_NUMBER_CONCENTRATION
76static constexpr uint16_t SEN6X_CMD_READ_NUMBER_CONCENTRATION = 0x0316;
77#endif
78static constexpr uint16_t SEN6X_CMD_START_MEASUREMENTS = 0x0021;
79static constexpr uint16_t SEN6X_CMD_STOP_MEASUREMENTS = 0x0104;
80static constexpr uint16_t SEN6X_CMD_START_FAN_CLEANING = 0x5607;
81static constexpr uint16_t SEN6X_CMD_ACTIVATE_SHT_HEATER = 0x6765;
82static constexpr uint16_t SEN6X_CMD_RESET = 0xD304;
83static constexpr uint16_t SEN6X_CMD_VOC_ALGORITHM_TUNING = 0x60D0;
84static constexpr uint16_t SEN6X_CMD_NOX_ALGORITHM_TUNING = 0x60E1;
85static constexpr uint16_t SEN6X_CMD_TEMPERATURE_COMPENSATION = 0x60B2;
86static constexpr uint16_t SEN6X_CMD_TEMPERATURE_ACCELERATION = 0x6100;
87static constexpr uint16_t SEN6X_CMD_CO2_AUTOMATIC_SELF_CAL = 0x6711;
88static constexpr uint16_t SEN6X_CMD_AMBIENT_PRESSURE = 0x6720;
89static constexpr uint16_t SEN6X_CMD_SENSOR_ALTITUDE = 0x6736;
90
91static inline void set_read_command_and_words(SEN6XComponent::Sen6xType type, uint16_t &read_cmd, uint8_t &read_words) {
92 read_cmd = SEN6X_CMD_READ_MEASUREMENT;
93 read_words = 9;
94 switch (type) {
95 case SEN6XComponent::SEN62:
96 read_cmd = SEN6X_CMD_READ_MEASUREMENT_SEN62;
97 read_words = 6;
98 break;
99 case SEN6XComponent::SEN63C:
100 read_cmd = SEN6X_CMD_READ_MEASUREMENT_SEN63C;
101 read_words = 7;
102 break;
103 case SEN6XComponent::SEN65:
104 read_cmd = SEN6X_CMD_READ_MEASUREMENT_SEN65;
105 read_words = 8;
106 break;
107 case SEN6XComponent::SEN66:
108 read_cmd = SEN6X_CMD_READ_MEASUREMENT;
109 read_words = 9;
110 break;
111 case SEN6XComponent::SEN68:
112 read_cmd = SEN6X_CMD_READ_MEASUREMENT_SEN68;
113 read_words = 9;
114 break;
115 case SEN6XComponent::SEN69C:
116 read_cmd = SEN6X_CMD_READ_MEASUREMENT_SEN69C;
117 read_words = 10;
118 break;
119 default:
120 break;
121 }
122}
123
125 ESP_LOGCONFIG(TAG, "Setting up sen6x...");
126
127 // the sensor needs 100 ms to enter the idle state
128 this->set_timeout(100, [this]() {
129 // Reset the sensor to ensure a clean state regardless of prior commands or power issues
130 if (!this->write_command(SEN6X_CMD_RESET)) {
131 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
132 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
133 return;
134 }
135
136 // After reset the sensor needs 100 ms to become ready
137 this->set_timeout(100, [this]() {
138 // Step 1: Read serial number (~25ms with I2C delay)
139 uint16_t raw_serial_number[16];
140 if (!this->get_register(SEN6X_CMD_GET_SERIAL_NUMBER, raw_serial_number, 16, 20)) {
141 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
142 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
143 return;
144 }
145 // The last byte of serial_number_ stays 0, so a full 32-byte serial is still terminated
146 memcpy(this->serial_number_, SEN6XComponent::sensirion_convert_to_string_in_place(raw_serial_number, 16),
147 sizeof(this->serial_number_) - 1);
148 ESP_LOGI(TAG, "Serial number: %s", this->serial_number_);
149
150 // Step 2: Read product name in next loop iteration
151 this->set_timeout(0, [this]() {
152 // One spare zero word so a full 32-byte name is still terminated
153 uint16_t raw_product_name[17]{};
154 if (!this->get_register(SEN6X_CMD_GET_PRODUCT_NAME, raw_product_name, 16, 20)) {
155 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
156 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
157 return;
158 }
159
160 const char *product_name = SEN6XComponent::sensirion_convert_to_string_in_place(raw_product_name, 16);
161
162 Sen6xType inferred_type = infer_type_from_product_name(product_name);
163 if (this->sen6x_type_ == UNKNOWN) {
164 this->sen6x_type_ = inferred_type;
165 if (inferred_type == UNKNOWN) {
166 ESP_LOGE(TAG, "Unknown product '%s'", product_name);
167 this->mark_failed();
168 return;
169 }
170 ESP_LOGD(TAG, "Type inferred from product: %s", product_name);
171 } else if (this->sen6x_type_ != inferred_type && inferred_type != UNKNOWN) {
172 ESP_LOGW(TAG, "Configured type (used) mismatches product '%s'", product_name);
173 }
174 ESP_LOGI(TAG, "Product: %s", product_name);
175
176 // Validate configured sensors against detected type and disable unsupported ones
177 const bool has_voc_nox = (this->sen6x_type_ == SEN65 || this->sen6x_type_ == SEN66 ||
178 this->sen6x_type_ == SEN68 || this->sen6x_type_ == SEN69C);
179 const bool has_co2 = (this->sen6x_type_ == SEN63C || this->sen6x_type_ == SEN66 || this->sen6x_type_ == SEN69C);
180 const bool has_hcho = (this->sen6x_type_ == SEN68 || this->sen6x_type_ == SEN69C);
181 if (this->voc_sensor_ && !has_voc_nox) {
182 ESP_LOGE(TAG, "VOC requires SEN65, SEN66, SEN68, or SEN69C");
183 this->voc_sensor_ = nullptr;
184 }
185 if (this->nox_sensor_ && !has_voc_nox) {
186 ESP_LOGE(TAG, "NOx requires SEN65, SEN66, SEN68, or SEN69C");
187 this->nox_sensor_ = nullptr;
188 }
189 if (this->co2_sensor_ && !has_co2) {
190 ESP_LOGE(TAG, "CO2 requires SEN63C, SEN66, or SEN69C");
191 this->co2_sensor_ = nullptr;
192 }
193 if (this->hcho_sensor_ && !has_hcho) {
194 ESP_LOGE(TAG, "Formaldehyde requires SEN68 or SEN69C");
195 this->hcho_sensor_ = nullptr;
196 }
197#ifdef SEN6X_STATUS_SENSOR_COUNT
198 // A status sensor for a feature this variant lacks is dropped like the measurement sensors above, so
199 // an empty table skips the status read; the kept ones learn their register bit here
200 size_t kept = 0;
201 for (auto entry : this->status_sensors_) {
202 if ((entry.status == Sen6xStatus::SEN6X_STATUS_GAS_ERROR && !has_voc_nox) ||
203 (entry.status == Sen6xStatus::SEN6X_STATUS_CO2_ERROR && !has_co2) ||
204 (entry.status == Sen6xStatus::SEN6X_STATUS_HCHO_ERROR && !has_hcho)) {
205 ESP_LOGE(TAG, "'%s' needs a variant with that feature", LOG_STR_ARG(entry.sensor->get_log_name()));
206 continue;
207 }
208 entry.bit = status_bit(entry.status, this->sen6x_type_);
209 this->status_sensors_[kept++] = entry;
210 }
211 this->status_sensors_.resize(kept);
212#endif
213
214 // Step 3: Read firmware version and start measurements in next loop iteration
215 this->set_timeout(0, [this]() {
216 uint16_t raw_firmware_version = 0;
217 if (!this->get_register(SEN6X_CMD_GET_FIRMWARE_VERSION, raw_firmware_version, 20)) {
218 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
219 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
220 return;
221 }
222 this->firmware_version_major_ = (raw_firmware_version >> 8) & 0xFF;
223 this->firmware_version_minor_ = raw_firmware_version & 0xFF;
224 ESP_LOGI(TAG, "Firmware: %u.%u", this->firmware_version_major_, this->firmware_version_minor_);
225
226 // Step 4: write configuration commands one at a time, then start measurements.
227 // Delay the first step so it doesn't run in the same loop tick as the read above.
228 this->set_timeout(TIMEOUT_SETUP_STEP, CMD_EXEC_DELAY, [this]() { this->run_next_setup_step_(); });
229 });
230 });
231 });
232 });
233}
234
235// One configuration write per invocation, spaced by CMD_EXEC_DELAY, then the start command.
236// These writes are optional, so a failure only warns and the chain carries on.
238 while (this->setup_step_index_ < SETUP_STEP_COUNT) {
239 if (this->write_setup_step_(static_cast<SetupStep>(this->setup_step_index_++))) {
240 this->set_timeout(TIMEOUT_SETUP_STEP, CMD_EXEC_DELAY, [this]() { this->run_next_setup_step_(); });
241 return;
242 }
243 }
244 this->finish_setup_();
245}
246
247// Returns false when the step has nothing to write: the setting is not configured, or setup()
248// disabled its sensor for this variant
250 switch (step) {
252 if (this->voc_sensor_ == nullptr || !this->voc_tuning_params_.has_value())
253 return false;
254 this->write_tuning_parameters_(SEN6X_CMD_VOC_ALGORITHM_TUNING, this->voc_tuning_params_.value());
255 return true;
257 if (this->nox_sensor_ == nullptr || !this->nox_tuning_params_.has_value())
258 return false;
259 this->write_tuning_parameters_(SEN6X_CMD_NOX_ALGORITHM_TUNING, this->nox_tuning_params_.value());
260 return true;
262 if (!this->temperature_compensation_.has_value())
263 return false;
265 return true;
267 if (!this->temperature_acceleration_.has_value())
268 return false;
270 return true;
272 if (this->co2_sensor_ == nullptr || !this->co2_asc_.has_value())
273 return false;
274 this->write_setup_register_(SEN6X_CMD_CO2_AUTOMATIC_SELF_CAL, this->co2_asc_.value() ? 1 : 0);
275 return true;
277 if (this->co2_sensor_ == nullptr || this->altitude_compensation_ == ALTITUDE_UNSET)
278 return false;
279 this->write_setup_register_(SEN6X_CMD_SENSOR_ALTITUDE, this->altitude_compensation_);
280 return true;
282 if (this->co2_sensor_ == nullptr || this->ambient_pressure_ == PRESSURE_UNSET)
283 return false;
285 return true;
286 default:
287 return false;
288 }
289}
290
292 // Word 4 selects compensation slot 0; other slots are not exposed
293 uint16_t params[4] = {static_cast<uint16_t>(compensation.offset),
294 static_cast<uint16_t>(compensation.normalized_offset_slope), compensation.time_constant, 0};
295 return this->write_config_words_(SEN6X_CMD_TEMPERATURE_COMPENSATION, params, 4);
296}
297
299 uint16_t params[4] = {acceleration.k, acceleration.p, acceleration.t1, acceleration.t2};
300 return this->write_config_words_(SEN6X_CMD_TEMPERATURE_ACCELERATION, params, 4);
301}
302
303bool SEN6XComponent::write_setup_register_(uint16_t i2c_command, uint16_t value) {
304 return this->write_config_words_(i2c_command, &value, 1);
305}
306
308 if (!this->write_command(SEN6X_CMD_START_MEASUREMENTS)) {
309 ESP_LOGE(TAG, "Write 0x%04X failed, error %d", SEN6X_CMD_START_MEASUREMENTS, this->last_error_);
310 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
311 return;
312 }
313
315 this->initialized_ = true;
316 ESP_LOGD(TAG, "Initialized");
317}
318
319// Writes one optional configuration command and reserves its execution time. A failure warns and
320// returns false, but does not stop setup: the sensor still measures with that setting left at its default.
321bool SEN6XComponent::write_config_words_(uint16_t i2c_command, const uint16_t *data, uint8_t len) {
322 if (!this->write_command(i2c_command, data, len)) {
323 ESP_LOGE(TAG, "Write 0x%04X failed, error %d", i2c_command, this->last_error_);
324 this->status_set_warning();
325 return false;
326 }
327 this->set_command_wait_(CMD_EXEC_DELAY);
328 return true;
329}
330
331bool SEN6XComponent::write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning) {
332 uint16_t params[6] = {tuning.index_offset,
336 tuning.std_initial,
337 tuning.gain_factor};
338 return this->write_config_words_(i2c_command, params, 6);
339}
340
341void SEN6XComponent::dump_config() {
342 ESP_LOGCONFIG(TAG,
343 "sen6x:\n"
344 " Type: %s\n"
345 " Serial: %s\n"
346 " Firmware: %u.%u\n"
347 " Address: 0x%02X\n"
348 " Startup delay: %" PRIu32 " ms",
349 LOG_STR_ARG(TypeStrings::get_log_str(this->sen6x_type_, TypeStrings::LAST_INDEX)), this->serial_number_,
351 LOG_UPDATE_INTERVAL(this);
352 if (this->temperature_compensation_.has_value()) {
353 const auto &comp = this->temperature_compensation_.value();
354 ESP_LOGCONFIG(TAG, " Temperature compensation: offset=%.2f slope=%.4f time_constant=%us", comp.offset / 200.0f,
355 comp.normalized_offset_slope / 10000.0f, comp.time_constant);
356 }
357 if (this->temperature_acceleration_.has_value()) {
358 const auto &accel = this->temperature_acceleration_.value();
359 ESP_LOGCONFIG(TAG, " Temperature acceleration: K=%.1f P=%.1f T1=%.1f T2=%.1f", accel.k / 10.0f, accel.p / 10.0f,
360 accel.t1 / 10.0f, accel.t2 / 10.0f);
361 }
362 // setup() clears co2_sensor_ once it detects a variant without CO2
363 if (this->co2_sensor_ != nullptr) {
364 if (this->co2_asc_.has_value()) {
365 ESP_LOGCONFIG(TAG, " CO2 automatic self-calibration: %s", ONOFF(this->co2_asc_.value()));
366 }
368 ESP_LOGCONFIG(TAG, " Altitude compensation: %u m", this->altitude_compensation_);
369 }
370 if (this->ambient_pressure_ != PRESSURE_UNSET) {
371 ESP_LOGCONFIG(TAG, " Ambient pressure compensation: %u hPa", this->ambient_pressure_);
372 }
373 if (this->ambient_pressure_source_sensor_ != nullptr) {
374 ESP_LOGCONFIG(TAG, " Ambient pressure compensation source: %s",
375 LOG_STR_ARG(this->ambient_pressure_source_sensor_->get_log_name()));
376 }
377 }
378 LOG_SENSOR(" ", "PM 1.0", this->pm_1_0_sensor_);
379 LOG_SENSOR(" ", "PM 2.5", this->pm_2_5_sensor_);
380 LOG_SENSOR(" ", "PM 4.0", this->pm_4_0_sensor_);
381 LOG_SENSOR(" ", "PM 10.0", this->pm_10_0_sensor_);
382#ifdef USE_SEN6X_NUMBER_CONCENTRATION
383 LOG_SENSOR(" ", "PMC 0.5", this->pmc_0_5_sensor_);
384 LOG_SENSOR(" ", "PMC 1.0", this->pmc_1_0_sensor_);
385 LOG_SENSOR(" ", "PMC 2.5", this->pmc_2_5_sensor_);
386 LOG_SENSOR(" ", "PMC 4.0", this->pmc_4_0_sensor_);
387 LOG_SENSOR(" ", "PMC 10.0", this->pmc_10_0_sensor_);
388#endif
389 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
390 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
391 LOG_SENSOR(" ", "VOC", this->voc_sensor_);
392 LOG_SENSOR(" ", "NOx", this->nox_sensor_);
393 LOG_SENSOR(" ", "HCHO", this->hcho_sensor_);
394 LOG_SENSOR(" ", "CO2", this->co2_sensor_);
395#ifdef SEN6X_STATUS_SENSOR_COUNT
396 for (const auto &entry : this->status_sensors_) {
397 LOG_BINARY_SENSOR(" ", "Device status", entry.sensor);
398 }
399#endif
400}
401
402void SEN6XComponent::update() {
403 if (!this->initialized_ || !this->measuring_) {
404 return;
405 }
406 // Cancel any in-flight polling from a previous update() cycle before touching the bus.
407 this->cancel_timeout(TIMEOUT_POLL);
408 // A command is still executing (an action moments ago): run this cycle once its window has passed
409 if (const uint32_t wait = this->command_wait_remaining_(); wait != 0) {
410 this->set_timeout(TIMEOUT_POLL, wait, [this]() { this->update(); });
411 return;
412 }
413
414 if (this->ambient_pressure_source_sensor_ != nullptr && this->co2_sensor_ != nullptr) {
415 this->update_ambient_pressure_compensation_(this->ambient_pressure_source_sensor_->state);
416 }
417
418 set_read_command_and_words(this->sen6x_type_, this->read_cmd_, this->read_words_);
419
420 // Polling uses chained timeouts to guarantee each I2C operation completes
421 // before the next begins. The flow is:
422 //
423 // read_device_status_()
424 // with status sensors: write_command (read and clear device status)
425 // -> timeout I2C_READ_DELAY -> parse_and_publish_device_status_()
426 // -> poll_data_ready_()
427 //
428 // poll_data_ready_()
429 // -> write_command (data ready status)
430 // -> timeout I2C_READ_DELAY
431 // -> read_data (check ready flag)
432 // -> if not ready: timeout POLL_INTERVAL -> poll_data_ready_() (retry)
433 // -> if ready: read_measurements_()
434 // -> write_command (read measurement)
435 // -> timeout I2C_READ_DELAY
436 // -> parse_and_publish_measurements_()
437 // -> with pmc_* sensors: read_number_concentration_()
438 // -> write_command (read number concentration)
439 // -> timeout I2C_READ_DELAY
440 // -> parse_and_publish_number_concentration_()
441 //
442 // All timeouts share a single ID (TIMEOUT_POLL) since only one is active
443 // at a time. cancel_timeout in update() stops any in-flight chain.
444 this->poll_retries_remaining_ = POLL_RETRIES;
445 this->read_device_status_();
446}
447
449 // stop_measurement() may have run from a publish callback while the chain was in flight
450 if (!this->measuring_)
451 return;
452 if (this->poll_retries_remaining_ == 0) {
453 this->status_set_warning();
454 ESP_LOGD(TAG, "Data not ready");
455 return;
456 }
457 // A set command (the pressure write above all) gets its execution time before the chain writes again
458 if (const uint32_t wait = this->command_wait_remaining_(); wait != 0) {
459 this->set_timeout(TIMEOUT_POLL, wait, [this]() { this->poll_data_ready_(); });
460 return;
461 }
462 ESP_LOGV(TAG, "Data ready polling attempt %u",
463 static_cast<unsigned>(POLL_RETRIES - this->poll_retries_remaining_ + 1));
465
466 if (!this->write_command(SEN6X_CMD_GET_DATA_READY_STATUS)) {
467 this->status_set_warning();
468 ESP_LOGD(TAG, "write data ready status error (%d)", this->last_error_);
469 return;
470 }
471
472 this->set_timeout(TIMEOUT_POLL, I2C_READ_DELAY, [this]() {
473 uint16_t raw_read_status;
474 if (!this->read_data(&raw_read_status, 1)) {
475 this->status_set_warning();
476 ESP_LOGD(TAG, "read data ready status error (%d)", this->last_error_);
477 return;
478 }
479
480 if ((raw_read_status & 0x0001) == 0) {
481 // Not ready yet; schedule next attempt after POLL_INTERVAL.
482 this->set_timeout(TIMEOUT_POLL, POLL_INTERVAL, [this]() { this->poll_data_ready_(); });
483 return;
484 }
485
486 this->read_measurements_();
487 });
488}
489
491 if (!this->write_command(this->read_cmd_)) {
492 this->status_set_warning();
493 ESP_LOGD(TAG, "Read measurement failed (%d)", this->last_error_);
494 return;
495 }
496
497 this->set_timeout(TIMEOUT_POLL, I2C_READ_DELAY, [this]() { this->parse_and_publish_measurements_(); });
498}
499
501 uint16_t measurements[10];
502
503 if (!this->read_data(measurements, this->read_words_)) {
504 this->status_set_warning();
505 ESP_LOGD(TAG, "Read data failed (%d)", this->last_error_);
506 return;
507 }
508 int8_t voc_index = -1;
509 int8_t nox_index = -1;
510 int8_t hcho_index = -1;
511 int8_t co2_index = -1;
512 bool co2_uint16 = false;
513 switch (this->sen6x_type_) {
514 case SEN62:
515 break;
516 case SEN63C:
517 co2_index = 6;
518 break;
519 case SEN65:
520 voc_index = 6;
521 nox_index = 7;
522 break;
523 case SEN66:
524 voc_index = 6;
525 nox_index = 7;
526 co2_index = 8;
527 co2_uint16 = true;
528 break;
529 case SEN68:
530 voc_index = 6;
531 nox_index = 7;
532 hcho_index = 8;
533 break;
534 case SEN69C:
535 voc_index = 6;
536 nox_index = 7;
537 hcho_index = 8;
538 co2_index = 9;
539 break;
540 default:
541 break;
542 }
543
544 float pm_1_0 = measurements[0] / 10.0f;
545 if (measurements[0] == 0xFFFF)
546 pm_1_0 = NAN;
547 float pm_2_5 = measurements[1] / 10.0f;
548 if (measurements[1] == 0xFFFF)
549 pm_2_5 = NAN;
550 float pm_4_0 = measurements[2] / 10.0f;
551 if (measurements[2] == 0xFFFF)
552 pm_4_0 = NAN;
553 float pm_10_0 = measurements[3] / 10.0f;
554 if (measurements[3] == 0xFFFF)
555 pm_10_0 = NAN;
556 float humidity = static_cast<int16_t>(measurements[4]) / 100.0f;
557 if (measurements[4] == 0x7FFF)
558 humidity = NAN;
559 float temperature = static_cast<int16_t>(measurements[5]) / 200.0f;
560 if (measurements[5] == 0x7FFF)
561 temperature = NAN;
562
563 float voc = NAN;
564 float nox = NAN;
565 float hcho = NAN;
566 float co2 = NAN;
567
568 if (voc_index >= 0) {
569 voc = static_cast<int16_t>(measurements[voc_index]) / 10.0f;
570 if (measurements[voc_index] == 0x7FFF)
571 voc = NAN;
572 }
573 if (nox_index >= 0) {
574 nox = static_cast<int16_t>(measurements[nox_index]) / 10.0f;
575 if (measurements[nox_index] == 0x7FFF)
576 nox = NAN;
577 }
578
579 if (hcho_index >= 0) {
580 const uint16_t hcho_raw = measurements[hcho_index];
581 hcho = hcho_raw / 10.0f;
582 if (hcho_raw == 0xFFFF)
583 hcho = NAN;
584 }
585
586 if (co2_index >= 0) {
587 if (co2_uint16) {
588 const uint16_t co2_raw = measurements[co2_index];
589 co2 = static_cast<float>(co2_raw);
590 if (co2_raw == 0xFFFF)
591 co2 = NAN;
592 } else {
593 const int16_t co2_raw = static_cast<int16_t>(measurements[co2_index]);
594 co2 = static_cast<float>(co2_raw);
595 if (co2_raw == 0x7FFF)
596 co2 = NAN;
597 }
598 }
599
600 if (!this->startup_complete_) {
601 ESP_LOGD(TAG, "Startup delay, ignoring values");
602 this->status_clear_warning();
603 return;
604 }
605
606 PUBLISH_STATE(this->pm_1_0_sensor_, pm_1_0);
607 PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
608 PUBLISH_STATE(this->pm_4_0_sensor_, pm_4_0);
609 PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
610 PUBLISH_STATE(this->temperature_sensor_, temperature);
611 PUBLISH_STATE(this->humidity_sensor_, humidity);
612 PUBLISH_STATE(this->voc_sensor_, voc);
613 PUBLISH_STATE(this->nox_sensor_, nox);
614 PUBLISH_STATE(this->hcho_sensor_, hcho);
615 PUBLISH_STATE(this->co2_sensor_, co2);
616
617#ifdef USE_SEN6X_NUMBER_CONCENTRATION
618 // The define says some device in the build has pmc sensors; this one may not
620 this->read_number_concentration_(); // the chain ends there, with the warning cleared
621 return;
622 }
623#endif
624 this->status_clear_warning();
625}
626
627// Reads the status register first, so the error sensors update even when the measurement read fails, then runs
628// the measurement poll chain. Read And Clear (0xD210) is used because error flags are sticky on the device;
629// clearing each cycle makes the sensors report whether a problem occurred since the last update.
631#ifdef SEN6X_STATUS_SENSOR_COUNT
632 if (!this->status_sensors_.empty()) {
633 // The pressure write in update() may still be executing; the device rejects commands until it is done
634 if (const uint32_t wait = this->command_wait_remaining_(); wait != 0) {
635 this->set_timeout(TIMEOUT_POLL, wait, [this]() { this->read_device_status_(); });
636 return;
637 }
638 if (this->write_command(SEN6X_CMD_READ_AND_CLEAR_DEVICE_STATUS)) {
639 this->set_timeout(TIMEOUT_POLL, I2C_READ_DELAY, [this]() { this->parse_and_publish_device_status_(); });
640 return;
641 }
642 ESP_LOGD(TAG, "Read device status failed (%d)", this->last_error_);
643 }
644#endif
645 this->poll_data_ready_();
646}
647
648#ifdef SEN6X_STATUS_SENSOR_COUNT
650 uint16_t words[2];
651 if (this->read_data(words, 2)) {
652 const uint32_t status = (static_cast<uint32_t>(words[0]) << 16) | words[1];
653 for (const auto &entry : this->status_sensors_)
654 entry.sensor->publish_state(((status >> entry.bit) & 1) != 0);
655 } else {
656 ESP_LOGD(TAG, "Read device status failed (%d)", this->last_error_);
657 }
658 this->poll_data_ready_();
659}
660#endif
661
662#ifdef USE_SEN6X_NUMBER_CONCENTRATION
664 return this->pmc_0_5_sensor_ != nullptr || this->pmc_1_0_sensor_ != nullptr || this->pmc_2_5_sensor_ != nullptr ||
665 this->pmc_4_0_sensor_ != nullptr || this->pmc_10_0_sensor_ != nullptr;
666}
667
669 if (!this->write_command(SEN6X_CMD_READ_NUMBER_CONCENTRATION)) {
670 this->status_set_warning();
671 ESP_LOGD(TAG, "Read number concentration failed (%d)", this->last_error_);
672 return;
673 }
674
675 this->set_timeout(TIMEOUT_POLL, I2C_READ_DELAY, [this]() { this->parse_and_publish_number_concentration_(); });
676}
677
679 sensor::Sensor *sensors[] = {this->pmc_0_5_sensor_, this->pmc_1_0_sensor_, this->pmc_2_5_sensor_,
680 this->pmc_4_0_sensor_, this->pmc_10_0_sensor_};
681 uint16_t measurements[std::size(sensors)];
682
683 if (!this->status_comm_result(this->read_data(measurements, std::size(measurements)))) {
684 ESP_LOGD(TAG, "Read data failed (%d)", this->last_error_);
685 return;
686 }
687
688 for (size_t i = 0; i < std::size(sensors); i++) {
689 PUBLISH_STATE(sensors[i], measurements[i] == 0xFFFF ? NAN : measurements[i] / 10.0f);
690 }
691}
692#endif
693
694void SEN6XComponent::write_ambient_pressure_(uint16_t pressure_hpa) {
695 if (this->write_setup_register_(SEN6X_CMD_AMBIENT_PRESSURE, pressure_hpa))
696 this->last_ambient_pressure_ = pressure_hpa;
697}
698
700 if (std::isnan(pressure_hpa))
701 return;
702 // Range-check before narrowing so out-of-unit sources (e.g. Pa) can't wrap into range
703 if (pressure_hpa < AMBIENT_PRESSURE_MIN_HPA || pressure_hpa > AMBIENT_PRESSURE_MAX_HPA) {
704 if (!this->pressure_range_warned_) {
705 ESP_LOGW(TAG, "Ambient pressure out of range: %.0f hPa", pressure_hpa);
706 this->pressure_range_warned_ = true;
707 }
708 return;
709 }
710 this->pressure_range_warned_ = false;
711 const auto value = static_cast<uint16_t>(lroundf(pressure_hpa));
712 if (value != this->last_ambient_pressure_)
714}
715
716// Time left in the previous command's execution or settling window, 0 once it has passed
718 const uint32_t elapsed = millis() - this->command_started_at_;
719 return elapsed < this->command_wait_ ? this->command_wait_ - elapsed : 0;
720}
721
723
725 this->command_started_at_ = millis();
726 this->command_wait_ = wait_ms;
727}
728
730 this->measuring_ = true;
731 this->set_command_wait_(START_MEASUREMENT_DELAY);
732 // SEN63C/SEN69C condition the CO2 sensor for 24 s after a start; block restarts until then
733 if (this->sen6x_type_ == SEN63C || this->sen6x_type_ == SEN69C) {
734 this->co2_started_at_ = millis();
735 this->co2_wait_ = CO2_CONDITIONING_DELAY;
736 }
737 // Values need the warm-up period again after every start
738 this->startup_complete_ = false;
739 this->set_timeout(TIMEOUT_STARTUP, this->startup_delay_ms_, [this]() { this->startup_complete_ = true; });
740}
741
742void SEN6XComponent::start_measurement() {
743 if (!this->initialized_ || this->measuring_)
744 return;
745 // The CO2 conditioning window only blocks restarting, not other commands
747 ESP_LOGW(TAG, "Device busy");
748 return;
749 }
750 if (!this->write_command(SEN6X_CMD_START_MEASUREMENTS)) {
751 this->status_set_warning();
752 ESP_LOGW(TAG, "Start measurement failed (%d)", this->last_error_);
753 return;
754 }
756}
757
758void SEN6XComponent::stop_measurement() {
759 if (!this->initialized_ || !this->measuring_)
760 return;
761 if (this->command_blocked_()) {
762 ESP_LOGW(TAG, "Device busy");
763 return;
764 }
765 // Stop any in-flight polling before the device goes idle
766 this->cancel_timeout(TIMEOUT_POLL);
767 if (!this->write_command(SEN6X_CMD_STOP_MEASUREMENTS)) {
768 this->status_set_warning();
769 ESP_LOGW(TAG, "Stop measurement failed (%d)", this->last_error_);
770 return;
771 }
772 this->measuring_ = false;
773 this->set_command_wait_(STOP_MEASUREMENT_DELAY);
774}
775
776void SEN6XComponent::start_fan_cleaning() {
777 if (!this->initialized_)
778 return;
779 // The device only accepts this command in idle mode (datasheet section 4.8.22)
780 if (this->measuring_) {
781 ESP_LOGW(TAG, "Fan cleaning requires idle mode; stop the measurement first");
782 return;
783 }
784 if (this->command_blocked_()) {
785 ESP_LOGW(TAG, "Device busy");
786 return;
787 }
788 if (!this->write_command(SEN6X_CMD_START_FAN_CLEANING)) {
789 this->status_set_warning();
790 ESP_LOGW(TAG, "Fan cleaning failed (%d)", this->last_error_);
791 return;
792 }
793 this->set_command_wait_(FAN_CLEANING_DELAY);
794}
795
796void SEN6XComponent::activate_sht_heater() {
797 if (!this->initialized_)
798 return;
799 // The device only accepts this command in idle mode (datasheet section 4.8.23)
800 if (this->measuring_) {
801 ESP_LOGW(TAG, "SHT heater requires idle mode; stop the measurement first");
802 return;
803 }
804 if (this->command_blocked_()) {
805 ESP_LOGW(TAG, "Device busy");
806 return;
807 }
808 if (!this->write_command(SEN6X_CMD_ACTIVATE_SHT_HEATER)) {
809 this->status_set_warning();
810 ESP_LOGW(TAG, "SHT heater failed (%d)", this->last_error_);
811 return;
812 }
813 this->set_command_wait_(SHT_HEATER_DELAY);
814}
815
816} // namespace esphome::sen6x
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
bool cancel_timeout(const char *name)
Cancel a timeout function.
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:309
uint8_t address_
store the address of the device on the bus
Definition i2c.h:327
void parse_and_publish_number_concentration_()
Definition sen6x.cpp:678
bool write_temperature_compensation_(const TemperatureCompensation &compensation)
Definition sen6x.cpp:291
optional< GasTuning > voc_tuning_params_
Definition sen6x.h:174
bool has_number_concentration_sensor_() const
Definition sen6x.cpp:663
StaticVector< StatusSensor, SEN6X_STATUS_SENSOR_COUNT > status_sensors_
Definition sen6x.h:172
optional< TemperatureAcceleration > temperature_acceleration_
Definition sen6x.h:176
void set_command_wait_(uint32_t wait_ms)
Definition sen6x.cpp:724
uint32_t command_wait_remaining_() const
Definition sen6x.cpp:717
bool write_setup_register_(uint16_t i2c_command, uint16_t value)
Definition sen6x.cpp:303
bool write_temperature_acceleration_(const TemperatureAcceleration &acceleration)
Definition sen6x.cpp:298
bool write_config_words_(uint16_t i2c_command, const uint16_t *data, uint8_t len)
Definition sen6x.cpp:321
bool write_setup_step_(SetupStep step)
Definition sen6x.cpp:249
optional< TemperatureCompensation > temperature_compensation_
Definition sen6x.h:177
optional< GasTuning > nox_tuning_params_
Definition sen6x.h:175
optional< bool > co2_asc_
Definition sen6x.h:190
bool write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning)
Definition sen6x.cpp:331
void write_ambient_pressure_(uint16_t pressure_hpa)
Definition sen6x.cpp:694
void update_ambient_pressure_compensation_(float pressure_hpa)
Definition sen6x.cpp:699
i2c::ErrorCode last_error_
last error code from I2C operation
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.
static const char * sensirion_convert_to_string_in_place(uint16_t *array, size_t length)
This function performs an in-place conversion of the provided buffer from uint16_t values to big endi...
Base-class for all sensors.
Definition sensor.h:48
uint8_t type
ESPHOME_LOG_TAG(TAG, "sen6x")
constexpr uint16_t ALTITUDE_UNSET
Definition sen6x.h:62
PROGMEM_STRING_TABLE(TypeStrings, "SEN62", "SEN63C", "SEN65", "SEN66", "SEN68", "SEN69C", "UNKNOWN")
constexpr uint16_t PRESSURE_UNSET
Definition sen6x.h:63
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
int16_t progmem_string_table_find(const char *value, size_t len)
The index of the string value (len bytes, in RAM) in a PROGMEM_STRING_TABLE, or -1 when it is not one...
Definition progmem.h:160
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
uint16_t learning_time_gain_hours
Definition sen6x.h:40
uint16_t learning_time_offset_hours
Definition sen6x.h:39
uint16_t gating_max_duration_minutes
Definition sen6x.h:41
uint16_t temperature
Definition sun_gtil2.cpp:12