ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
sen5x.cpp
Go to the documentation of this file.
1#include "sen5x.h"
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6#include <cinttypes>
7
8namespace esphome::sen5x {
9
10static const char *const TAG = "sen5x";
11
12static const uint16_t SEN5X_CMD_AUTO_CLEANING_INTERVAL = 0x8004;
13static const uint16_t SEN5X_CMD_GET_DATA_READY_STATUS = 0x0202;
14static const uint16_t SEN5X_CMD_GET_FIRMWARE_VERSION = 0xD100;
15static const uint16_t SEN5X_CMD_GET_PRODUCT_NAME = 0xD014;
16static const uint16_t SEN5X_CMD_GET_SERIAL_NUMBER = 0xD033;
17static const uint16_t SEN5X_CMD_NOX_ALGORITHM_TUNING = 0x60E1;
18static const uint16_t SEN5X_CMD_READ_MEASUREMENT = 0x03C4;
19static const uint16_t SEN5X_CMD_RHT_ACCELERATION_MODE = 0x60F7;
20static const uint16_t SEN5X_CMD_START_CLEANING_FAN = 0x5607;
21static const uint16_t SEN5X_CMD_START_MEASUREMENTS = 0x0021;
22static const uint16_t SEN5X_CMD_START_MEASUREMENTS_RHT_ONLY = 0x0037;
23static const uint16_t SEN5X_CMD_STOP_MEASUREMENTS = 0x3f86;
24static const uint16_t SEN5X_CMD_TEMPERATURE_COMPENSATION = 0x60B2;
25static const uint16_t SEN5X_CMD_VOC_ALGORITHM_STATE = 0x6181;
26static const uint16_t SEN5X_CMD_VOC_ALGORITHM_TUNING = 0x60D0;
27
28static const int8_t SEN5X_INDEX_SCALE_FACTOR = 10; // used for VOC and NOx index values
29static const int8_t SEN5X_MIN_INDEX_VALUE = 1 * SEN5X_INDEX_SCALE_FACTOR; // must be adjusted by the scale factor
30static const int16_t SEN5X_MAX_INDEX_VALUE = 500 * SEN5X_INDEX_SCALE_FACTOR; // must be adjusted by the scale factor
31
32static const LogString *type_to_string(Sen5xType type) {
33 switch (type) {
35 return LOG_STR("SEN50");
37 return LOG_STR("SEN54");
39 return LOG_STR("SEN55");
40 default:
41 return LOG_STR("UNKNOWN");
42 }
43}
44
45static const LogString *rht_accel_mode_to_string(RhtAccelerationMode mode) {
46 switch (mode) {
48 return LOG_STR("LOW");
50 return LOG_STR("MEDIUM");
52 return LOG_STR("HIGH");
53 default:
54 return LOG_STR("UNKNOWN");
55 }
56}
57
59 // the sensor needs 1000 ms to enter the idle state
60 this->set_timeout(1000, [this]() {
61 // Check if measurement is ready before reading the value
62 if (!this->write_command(SEN5X_CMD_GET_DATA_READY_STATUS)) {
63 ESP_LOGE(TAG, "Failed to write data ready status command");
64 this->mark_failed();
65 return;
66 }
67 delay(20); // per datasheet
68
69 uint16_t raw_read_status;
70 if (!this->read_data(raw_read_status)) {
71 ESP_LOGE(TAG, "Failed to read data ready status");
72 this->mark_failed();
73 return;
74 }
75
76 uint32_t stop_measurement_delay = 0;
77 // In order to query the device periodic measurement must be ceased
78 if (raw_read_status) {
79 ESP_LOGD(TAG, "Data is available; stopping periodic measurement");
80 if (!this->write_command(SEN5X_CMD_STOP_MEASUREMENTS)) {
81 ESP_LOGE(TAG, "Failed to stop measurements");
82 this->mark_failed();
83 return;
84 }
85 // According to the SEN5x datasheet the sensor will only respond to other commands after waiting 200 ms after
86 // issuing the stop_periodic_measurement command
87 stop_measurement_delay = 200;
88 }
89 this->set_timeout(stop_measurement_delay, [this]() {
90 // note: serial number register is actually 32-bytes long but we grab only the first 16-bytes,
91 // this appears to be all that Sensirion uses for serial numbers, this could change
92 uint16_t raw_serial_number[8];
93 if (!this->get_register(SEN5X_CMD_GET_SERIAL_NUMBER, raw_serial_number, 8, 20)) {
94 ESP_LOGE(TAG, "Failed to read serial number");
96 this->mark_failed();
97 return;
98 }
99 const char *serial_number = sensirion_convert_to_string_in_place(raw_serial_number, 8);
100 snprintf(this->serial_number_, sizeof(this->serial_number_), "%s", serial_number);
101 ESP_LOGV(TAG, "Serial number %s", this->serial_number_);
102
103 uint16_t raw_product_name[16];
104 Sen5xType detected_type = Sen5xType::UNKNOWN;
105 if (this->get_register(SEN5X_CMD_GET_PRODUCT_NAME, raw_product_name, 16, 20)) {
106 const char *product_name = sensirion_convert_to_string_in_place(raw_product_name, 16);
107 if (strncmp(product_name, "SEN50", 5) == 0) {
108 detected_type = Sen5xType::SEN50;
109 } else if (strncmp(product_name, "SEN54", 5) == 0) {
110 detected_type = Sen5xType::SEN54;
111 } else if (strncmp(product_name, "SEN55", 5) == 0) {
112 detected_type = Sen5xType::SEN55;
113 }
114 }
115
116 if (this->model_override_.has_value()) {
117 if (detected_type != this->model_override_.value()) {
118 ESP_LOGW(TAG, "Detected %s, using %s", LOG_STR_ARG(type_to_string(detected_type)),
119 LOG_STR_ARG(type_to_string(this->model_override_.value())));
120 }
121 this->type_ = this->model_override_.value();
122 } else if (detected_type == Sen5xType::UNKNOWN) {
125 this->mark_failed();
126 return;
127 } else {
128 this->type_ = detected_type;
129 }
130
131 ESP_LOGD(TAG, "Type: %s", LOG_STR_ARG(type_to_string(this->type_)));
132 if (this->humidity_sensor_ && this->type_ == Sen5xType::SEN50) {
133 ESP_LOGE(TAG, "Relative humidity requires a SEN54 or SEN55");
134 this->humidity_sensor_ = nullptr; // mark as not used
135 }
136 if (this->temperature_sensor_ && this->type_ == Sen5xType::SEN50) {
137 ESP_LOGE(TAG, "Temperature requires a SEN54 or SEN55");
138 this->temperature_sensor_ = nullptr; // mark as not used
139 }
140 if (this->voc_sensor_ && this->type_ == Sen5xType::SEN50) {
141 ESP_LOGE(TAG, "VOC requires a SEN54 or SEN55");
142 this->voc_sensor_ = nullptr; // mark as not used
143 }
144 if (this->nox_sensor_ && this->type_ != Sen5xType::SEN55) {
145 ESP_LOGE(TAG, "NOx requires a SEN55");
146 this->nox_sensor_ = nullptr; // mark as not used
147 }
148
149 if (!this->get_register(SEN5X_CMD_GET_FIRMWARE_VERSION, this->firmware_version_, 20)) {
150 ESP_LOGE(TAG, "Failed to read firmware version");
152 this->mark_failed();
153 return;
154 }
155 this->firmware_version_ >>= 8;
156 ESP_LOGV(TAG, "Firmware version %d", this->firmware_version_);
157
158 if (this->voc_sensor_ && this->store_baseline_) {
159 // Hash with serial number, serial numbers are unique, so multiple sensors can be used without conflict
160 uint32_t hash = fnv1a_hash(this->serial_number_);
161 this->pref_ = global_preferences->make_preference<uint16_t[4]>(hash, true);
163 if (this->pref_.load(&this->voc_baseline_state_)) {
164 if (!this->write_command(SEN5X_CMD_VOC_ALGORITHM_STATE, this->voc_baseline_state_, 4)) {
165 ESP_LOGE(TAG, "VOC Baseline State write to sensor failed");
166 } else {
167 ESP_LOGV(TAG, "VOC Baseline State loaded");
168 delay(20);
169 }
170 }
171 }
172 bool result;
173 if (this->auto_cleaning_interval_.has_value()) {
174 // override default value
175 result = this->write_command(SEN5X_CMD_AUTO_CLEANING_INTERVAL, this->auto_cleaning_interval_.value());
176 } else {
177 result = this->write_command(SEN5X_CMD_AUTO_CLEANING_INTERVAL);
178 }
179 if (result) {
180 delay(20);
181 uint16_t secs[2];
182 if (this->read_data(secs, 2)) {
183 this->auto_cleaning_interval_ = secs[0] << 16 | secs[1];
184 }
185 }
186 if (this->acceleration_mode_.has_value()) {
187 result = this->write_command(SEN5X_CMD_RHT_ACCELERATION_MODE, this->acceleration_mode_.value());
188 } else {
189 result = this->write_command(SEN5X_CMD_RHT_ACCELERATION_MODE);
190 }
191 if (!result) {
192 ESP_LOGE(TAG, "Failed to set rh/t acceleration mode");
194 this->mark_failed();
195 return;
196 }
197 delay(20);
198 if (!this->acceleration_mode_.has_value()) {
199 uint16_t mode;
200 if (this->read_data(mode)) {
202 } else {
203 ESP_LOGE(TAG, "Failed to read RHT Acceleration mode");
204 }
205 }
206 if (this->voc_tuning_params_.has_value()) {
207 this->write_tuning_parameters_(SEN5X_CMD_VOC_ALGORITHM_TUNING, this->voc_tuning_params_.value());
208 delay(20);
209 }
210 if (this->nox_tuning_params_.has_value()) {
211 this->write_tuning_parameters_(SEN5X_CMD_NOX_ALGORITHM_TUNING, this->nox_tuning_params_.value());
212 delay(20);
213 }
214
215 if (this->temperature_compensation_.has_value()) {
217 delay(20);
218 }
219
220 // Finally start sensor measurements
221 auto cmd = SEN5X_CMD_START_MEASUREMENTS_RHT_ONLY;
222 if (this->pm_1_0_sensor_ || this->pm_2_5_sensor_ || this->pm_4_0_sensor_ || this->pm_10_0_sensor_) {
223 // if any of the gas sensors are active we need a full measurement
224 cmd = SEN5X_CMD_START_MEASUREMENTS;
225 }
226
227 if (!this->write_command(cmd)) {
228 ESP_LOGE(TAG, "Error starting continuous measurements");
230 this->mark_failed();
231 return;
232 }
233 this->initialized_ = true;
234 });
235 });
236}
237
239 ESP_LOGCONFIG(TAG, "SEN5X:");
240 LOG_I2C_DEVICE(this);
241 if (this->is_failed()) {
242 switch (this->error_code_) {
244 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
245 break;
247 ESP_LOGW(TAG, "Measurement initialization failed");
248 break;
250 ESP_LOGW(TAG, "Unable to read serial ID");
251 break;
253 ESP_LOGW(TAG, "Unable to read product name");
254 break;
255 case FIRMWARE_FAILED:
256 ESP_LOGW(TAG, "Unable to read firmware version");
257 break;
258 default:
259 ESP_LOGW(TAG, "Unknown setup error");
260 break;
261 }
262 }
263 ESP_LOGCONFIG(TAG,
264 " Type: %s%s\n"
265 " Firmware version: %d\n"
266 " Serial number: %s",
267 LOG_STR_ARG(type_to_string(this->type_)),
268 this->model_override_.has_value() ? LOG_STR_LITERAL(" (overridden)") : LOG_STR_LITERAL(""),
269 this->firmware_version_, this->serial_number_);
270 if (this->auto_cleaning_interval_.has_value()) {
271 ESP_LOGCONFIG(TAG, " Auto cleaning interval: %" PRId32 "s", this->auto_cleaning_interval_.value());
272 }
273 if (this->acceleration_mode_.has_value()) {
274 ESP_LOGCONFIG(TAG, " RH/T acceleration mode: %s",
275 LOG_STR_ARG(rht_accel_mode_to_string(this->acceleration_mode_.value())));
276 }
277 if (this->voc_sensor_) {
278 char hex_buf[5 * 4];
279 format_hex_pretty_to(hex_buf, this->voc_baseline_state_, 4, 0);
280 ESP_LOGCONFIG(TAG,
281 " Store Baseline: %s\n"
282 " State: %s\n",
283 TRUEFALSE(this->store_baseline_), hex_buf);
284 }
285 LOG_UPDATE_INTERVAL(this);
286 LOG_SENSOR(" ", "PM 1.0", this->pm_1_0_sensor_);
287 LOG_SENSOR(" ", "PM 2.5", this->pm_2_5_sensor_);
288 LOG_SENSOR(" ", "PM 4.0", this->pm_4_0_sensor_);
289 LOG_SENSOR(" ", "PM 10.0", this->pm_10_0_sensor_);
290 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
291 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
292 LOG_SENSOR(" ", "VOC", this->voc_sensor_); // SEN54 and SEN55 only
293 LOG_SENSOR(" ", "NOx", this->nox_sensor_); // SEN55 only
294}
295
297 if (!this->initialized_) {
298 return;
299 }
300
301 if (!this->write_command(SEN5X_CMD_READ_MEASUREMENT)) {
302 this->status_set_warning();
303 ESP_LOGD(TAG, "Write error: read measurement (%d)", this->last_error_);
304 return;
305 }
306 this->set_timeout(20, [this]() {
307 uint16_t measurements[8];
308
309 if (!this->read_data(measurements, 8)) {
310 this->status_set_warning();
311 ESP_LOGD(TAG, "Read data error (%d)", this->last_error_);
312 return;
313 }
314
315 ESP_LOGVV(TAG, "pm_1_0 = 0x%.4x", measurements[0]);
316 float pm_1_0 = measurements[0] == UINT16_MAX ? NAN : measurements[0] / 10.0f;
317
318 ESP_LOGVV(TAG, "pm_2_5 = 0x%.4x", measurements[1]);
319 float pm_2_5 = measurements[1] == UINT16_MAX ? NAN : measurements[1] / 10.0f;
320
321 ESP_LOGVV(TAG, "pm_4_0 = 0x%.4x", measurements[2]);
322 float pm_4_0 = measurements[2] == UINT16_MAX ? NAN : measurements[2] / 10.0f;
323
324 ESP_LOGVV(TAG, "pm_10_0 = 0x%.4x", measurements[3]);
325 float pm_10_0 = measurements[3] == UINT16_MAX ? NAN : measurements[3] / 10.0f;
326
327 ESP_LOGVV(TAG, "humidity = 0x%.4x", measurements[4]);
328 float humidity = measurements[4] == INT16_MAX ? NAN : static_cast<int16_t>(measurements[4]) / 100.0f;
329
330 ESP_LOGVV(TAG, "temperature = 0x%.4x", measurements[5]);
331 float temperature = measurements[5] == INT16_MAX ? NAN : static_cast<int16_t>(measurements[5]) / 200.0f;
332
333 ESP_LOGVV(TAG, "voc = 0x%.4x", measurements[6]);
334 int16_t voc_idx = static_cast<int16_t>(measurements[6]);
335 float voc = (voc_idx < SEN5X_MIN_INDEX_VALUE || voc_idx > SEN5X_MAX_INDEX_VALUE)
336 ? NAN
337 : static_cast<float>(voc_idx) / 10.0f;
338
339 ESP_LOGVV(TAG, "nox = 0x%.4x", measurements[7]);
340 int16_t nox_idx = static_cast<int16_t>(measurements[7]);
341 float nox = (nox_idx < SEN5X_MIN_INDEX_VALUE || nox_idx > SEN5X_MAX_INDEX_VALUE)
342 ? NAN
343 : static_cast<float>(nox_idx) / 10.0f;
344
345 if (this->pm_1_0_sensor_ != nullptr) {
346 this->pm_1_0_sensor_->publish_state(pm_1_0);
347 }
348 if (this->pm_2_5_sensor_ != nullptr) {
349 this->pm_2_5_sensor_->publish_state(pm_2_5);
350 }
351 if (this->pm_4_0_sensor_ != nullptr) {
352 this->pm_4_0_sensor_->publish_state(pm_4_0);
353 }
354 if (this->pm_10_0_sensor_ != nullptr) {
355 this->pm_10_0_sensor_->publish_state(pm_10_0);
356 }
357 if (this->temperature_sensor_ != nullptr) {
358 this->temperature_sensor_->publish_state(temperature);
359 }
360 if (this->humidity_sensor_ != nullptr) {
361 this->humidity_sensor_->publish_state(humidity);
362 }
363 if (this->voc_sensor_ != nullptr) {
364 this->voc_sensor_->publish_state(voc);
365 }
366 if (this->nox_sensor_ != nullptr) {
367 this->nox_sensor_->publish_state(nox);
368 }
369
370 if (!this->voc_sensor_ || !this->store_baseline_ ||
371 (App.get_loop_component_start_time() - this->voc_baseline_time_) < SHORTEST_BASELINE_STORE_INTERVAL) {
372 this->status_clear_warning();
373 } else {
375 if (!this->write_command(SEN5X_CMD_VOC_ALGORITHM_STATE)) {
376 this->status_set_warning();
377 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
378 } else {
379 this->set_timeout(20, [this]() {
380 if (!this->read_data(this->voc_baseline_state_, 4)) {
381 this->status_set_warning();
382 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
383 } else {
384 if (this->pref_.save(&this->voc_baseline_state_)) {
385 ESP_LOGD(TAG, "VOC Baseline State saved");
386 }
387 this->status_clear_warning();
388 }
389 });
390 }
391 }
392 });
393}
394
395bool SEN5XComponent::write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning) {
396 uint16_t params[6];
397 params[0] = tuning.index_offset;
398 params[1] = tuning.learning_time_offset_hours;
399 params[2] = tuning.learning_time_gain_hours;
400 params[3] = tuning.gating_max_duration_minutes;
401 params[4] = tuning.std_initial;
402 params[5] = tuning.gain_factor;
403 auto result = write_command(i2c_command, params, 6);
404 if (!result) {
405 ESP_LOGE(TAG, "Set tuning parameters failed (command=%0xX, err=%d)", i2c_command, this->last_error_);
406 }
407 return result;
408}
409
411 uint16_t params[3];
412 params[0] = compensation.offset;
413 params[1] = compensation.normalized_offset_slope;
414 params[2] = compensation.time_constant;
415 if (!write_command(SEN5X_CMD_TEMPERATURE_COMPENSATION, params, 3)) {
416 ESP_LOGE(TAG, "Set temperature_compensation failed (%d)", this->last_error_);
417 return false;
418 }
419 return true;
420}
421
423 if (!write_command(SEN5X_CMD_START_CLEANING_FAN)) {
424 this->status_set_warning();
425 ESP_LOGE(TAG, "Start fan cleaning failed (%d)", this->last_error_);
426 return false;
427 } else {
428 ESP_LOGD(TAG, "Fan auto clean started");
429 }
430 return true;
431}
432
433} // namespace esphome::sen5x
BedjetMode mode
BedJet operating mode.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:272
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:289
optional< RhtAccelerationMode > acceleration_mode_
Definition sen5x.h:125
sensor::Sensor * pm_4_0_sensor_
Definition sen5x.h:116
void dump_config() override
Definition sen5x.cpp:238
ESPPreferenceObject pref_
Definition sen5x.h:131
bool write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning)
Definition sen5x.cpp:395
optional< Sen5xType > model_override_
Definition sen5x.h:130
sensor::Sensor * pm_2_5_sensor_
Definition sen5x.h:115
sensor::Sensor * temperature_sensor_
Definition sen5x.h:119
optional< uint32_t > auto_cleaning_interval_
Definition sen5x.h:126
sensor::Sensor * pm_1_0_sensor_
Definition sen5x.h:114
sensor::Sensor * voc_sensor_
Definition sen5x.h:121
optional< TemperatureCompensation > temperature_compensation_
Definition sen5x.h:129
sensor::Sensor * nox_sensor_
Definition sen5x.h:123
optional< GasTuning > voc_tuning_params_
Definition sen5x.h:127
sensor::Sensor * pm_10_0_sensor_
Definition sen5x.h:117
sensor::Sensor * humidity_sensor_
Definition sen5x.h:120
bool write_temperature_compensation_(const TemperatureCompensation &compensation)
Definition sen5x.cpp:410
optional< GasTuning > nox_tuning_params_
Definition sen5x.h:128
uint16_t voc_baseline_state_[4]
Definition sen5x.h:106
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...
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
uint16_t type
@ PRODUCT_NAME_FAILED
Definition sen5x.h:15
@ MEASUREMENT_INIT_FAILED
Definition sen5x.h:14
@ FIRMWARE_FAILED
Definition sen5x.h:16
@ SERIAL_NUMBER_IDENTIFICATION_FAILED
Definition sen5x.h:13
@ COMMUNICATION_FAILED
Definition sen5x.h:12
RhtAccelerationMode
Definition sen5x.h:20
@ LOW_ACCELERATION
Definition sen5x.h:21
@ HIGH_ACCELERATION
Definition sen5x.h:23
@ MEDIUM_ACCELERATION
Definition sen5x.h:22
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:340
ESPPreferences * global_preferences
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:848
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
uint16_t learning_time_gain_hours
Definition sen5x.h:31
uint16_t gating_max_duration_minutes
Definition sen5x.h:32
uint16_t learning_time_offset_hours
Definition sen5x.h:30
uint16_t temperature
Definition sun_gtil2.cpp:12
char serial_number[10]
Definition sun_gtil2.cpp:15