ESPHome 2025.9.0
Loading...
Searching...
No Matches
sen5x.cpp
Go to the documentation of this file.
1#include "sen5x.h"
2#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
5#include <cinttypes>
6
7namespace esphome {
8namespace 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 *rht_accel_mode_to_string(RhtAccelerationMode mode) {
33 switch (mode) {
35 return LOG_STR("LOW");
37 return LOG_STR("MEDIUM");
39 return LOG_STR("HIGH");
40 default:
41 return LOG_STR("UNKNOWN");
42 }
43}
44
46 // the sensor needs 1000 ms to enter the idle state
47 this->set_timeout(1000, [this]() {
48 // Check if measurement is ready before reading the value
49 if (!this->write_command(SEN5X_CMD_GET_DATA_READY_STATUS)) {
50 ESP_LOGE(TAG, "Failed to write data ready status command");
51 this->mark_failed();
52 return;
53 }
54 delay(20); // per datasheet
55
56 uint16_t raw_read_status;
57 if (!this->read_data(raw_read_status)) {
58 ESP_LOGE(TAG, "Failed to read data ready status");
59 this->mark_failed();
60 return;
61 }
62
63 uint32_t stop_measurement_delay = 0;
64 // In order to query the device periodic measurement must be ceased
65 if (raw_read_status) {
66 ESP_LOGD(TAG, "Data is available; stopping periodic measurement");
67 if (!this->write_command(SEN5X_CMD_STOP_MEASUREMENTS)) {
68 ESP_LOGE(TAG, "Failed to stop measurements");
69 this->mark_failed();
70 return;
71 }
72 // According to the SEN5x datasheet the sensor will only respond to other commands after waiting 200 ms after
73 // issuing the stop_periodic_measurement command
74 stop_measurement_delay = 200;
75 }
76 this->set_timeout(stop_measurement_delay, [this]() {
77 uint16_t raw_serial_number[3];
78 if (!this->get_register(SEN5X_CMD_GET_SERIAL_NUMBER, raw_serial_number, 3, 20)) {
79 ESP_LOGE(TAG, "Failed to read serial number");
81 this->mark_failed();
82 return;
83 }
84 this->serial_number_[0] = static_cast<bool>(uint16_t(raw_serial_number[0]) & 0xFF);
85 this->serial_number_[1] = static_cast<uint16_t>(raw_serial_number[0] & 0xFF);
86 this->serial_number_[2] = static_cast<uint16_t>(raw_serial_number[1] >> 8);
87 ESP_LOGV(TAG, "Serial number %02d.%02d.%02d", this->serial_number_[0], this->serial_number_[1],
88 this->serial_number_[2]);
89
90 uint16_t raw_product_name[16];
91 if (!this->get_register(SEN5X_CMD_GET_PRODUCT_NAME, raw_product_name, 16, 20)) {
92 ESP_LOGE(TAG, "Failed to read product name");
94 this->mark_failed();
95 return;
96 }
97 // 2 ASCII bytes are encoded in an int
98 const uint16_t *current_int = raw_product_name;
99 char current_char;
100 uint8_t max = 16;
101 do {
102 // first char
103 current_char = *current_int >> 8;
104 if (current_char) {
105 this->product_name_.push_back(current_char);
106 // second char
107 current_char = *current_int & 0xFF;
108 if (current_char) {
109 this->product_name_.push_back(current_char);
110 }
111 }
112 current_int++;
113 } while (current_char && --max);
114
115 Sen5xType sen5x_type = UNKNOWN;
116 if (this->product_name_ == "SEN50") {
117 sen5x_type = SEN50;
118 } else {
119 if (this->product_name_ == "SEN54") {
120 sen5x_type = SEN54;
121 } else {
122 if (this->product_name_ == "SEN55") {
123 sen5x_type = SEN55;
124 }
125 }
126 ESP_LOGD(TAG, "Product name: %s", this->product_name_.c_str());
127 }
128 if (this->humidity_sensor_ && sen5x_type == SEN50) {
129 ESP_LOGE(TAG, "Relative humidity requires a SEN54 or SEN55");
130 this->humidity_sensor_ = nullptr; // mark as not used
131 }
132 if (this->temperature_sensor_ && sen5x_type == SEN50) {
133 ESP_LOGE(TAG, "Temperature requires a SEN54 or SEN55");
134 this->temperature_sensor_ = nullptr; // mark as not used
135 }
136 if (this->voc_sensor_ && sen5x_type == SEN50) {
137 ESP_LOGE(TAG, "VOC requires a SEN54 or SEN55");
138 this->voc_sensor_ = nullptr; // mark as not used
139 }
140 if (this->nox_sensor_ && sen5x_type != SEN55) {
141 ESP_LOGE(TAG, "NOx requires a SEN55");
142 this->nox_sensor_ = nullptr; // mark as not used
143 }
144
145 if (!this->get_register(SEN5X_CMD_GET_FIRMWARE_VERSION, this->firmware_version_, 20)) {
146 ESP_LOGE(TAG, "Failed to read firmware version");
148 this->mark_failed();
149 return;
150 }
151 this->firmware_version_ >>= 8;
152 ESP_LOGV(TAG, "Firmware version %d", this->firmware_version_);
153
154 if (this->voc_sensor_ && this->store_baseline_) {
155 uint32_t combined_serial =
156 encode_uint24(this->serial_number_[0], this->serial_number_[1], this->serial_number_[2]);
157 // Hash with compilation time and serial number
158 // This ensures the baseline storage is cleared after OTA
159 // Serial numbers are unique to each sensor, so mulitple sensors can be used without conflict
160 uint32_t hash = fnv1_hash(App.get_compilation_time() + std::to_string(combined_serial));
162
163 if (this->pref_.load(&this->voc_baselines_storage_)) {
164 ESP_LOGI(TAG, "Loaded VOC baseline state0: 0x%04" PRIX32 ", state1: 0x%04" PRIX32,
165 this->voc_baselines_storage_.state0, this->voc_baselines_storage_.state1);
166 }
167
168 // Initialize storage timestamp
170
171 if (this->voc_baselines_storage_.state0 > 0 && this->voc_baselines_storage_.state1 > 0) {
172 ESP_LOGI(TAG, "Setting VOC baseline from save state0: 0x%04" PRIX32 ", state1: 0x%04" PRIX32,
173 this->voc_baselines_storage_.state0, this->voc_baselines_storage_.state1);
174 uint16_t states[4];
175
176 states[0] = this->voc_baselines_storage_.state0 >> 16;
177 states[1] = this->voc_baselines_storage_.state0 & 0xFFFF;
178 states[2] = this->voc_baselines_storage_.state1 >> 16;
179 states[3] = this->voc_baselines_storage_.state1 & 0xFFFF;
180
181 if (!this->write_command(SEN5X_CMD_VOC_ALGORITHM_STATE, states, 4)) {
182 ESP_LOGE(TAG, "Failed to set VOC baseline from saved state");
183 }
184 }
185 }
186 bool result;
188 // override default value
189 result = write_command(SEN5X_CMD_AUTO_CLEANING_INTERVAL, this->auto_cleaning_interval_.value());
190 } else {
191 result = write_command(SEN5X_CMD_AUTO_CLEANING_INTERVAL);
192 }
193 if (result) {
194 delay(20);
195 uint16_t secs[2];
196 if (this->read_data(secs, 2)) {
197 this->auto_cleaning_interval_ = secs[0] << 16 | secs[1];
198 }
199 }
200 if (this->acceleration_mode_.has_value()) {
201 result = this->write_command(SEN5X_CMD_RHT_ACCELERATION_MODE, this->acceleration_mode_.value());
202 } else {
203 result = this->write_command(SEN5X_CMD_RHT_ACCELERATION_MODE);
204 }
205 if (!result) {
206 ESP_LOGE(TAG, "Failed to set rh/t acceleration mode");
208 this->mark_failed();
209 return;
210 }
211 delay(20);
212 if (!this->acceleration_mode_.has_value()) {
213 uint16_t mode;
214 if (this->read_data(mode)) {
216 } else {
217 ESP_LOGE(TAG, "Failed to read RHT Acceleration mode");
218 }
219 }
220 if (this->voc_tuning_params_.has_value()) {
221 this->write_tuning_parameters_(SEN5X_CMD_VOC_ALGORITHM_TUNING, this->voc_tuning_params_.value());
222 delay(20);
223 }
224 if (this->nox_tuning_params_.has_value()) {
225 this->write_tuning_parameters_(SEN5X_CMD_NOX_ALGORITHM_TUNING, this->nox_tuning_params_.value());
226 delay(20);
227 }
228
229 if (this->temperature_compensation_.has_value()) {
231 delay(20);
232 }
233
234 // Finally start sensor measurements
235 auto cmd = SEN5X_CMD_START_MEASUREMENTS_RHT_ONLY;
236 if (this->pm_1_0_sensor_ || this->pm_2_5_sensor_ || this->pm_4_0_sensor_ || this->pm_10_0_sensor_) {
237 // if any of the gas sensors are active we need a full measurement
238 cmd = SEN5X_CMD_START_MEASUREMENTS;
239 }
240
241 if (!this->write_command(cmd)) {
242 ESP_LOGE(TAG, "Error starting continuous measurements");
244 this->mark_failed();
245 return;
246 }
247 this->initialized_ = true;
248 });
249 });
250}
251
253 ESP_LOGCONFIG(TAG, "SEN5X:");
254 LOG_I2C_DEVICE(this);
255 if (this->is_failed()) {
256 switch (this->error_code_) {
258 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
259 break;
261 ESP_LOGW(TAG, "Measurement initialization failed");
262 break;
264 ESP_LOGW(TAG, "Unable to read serial ID");
265 break;
267 ESP_LOGW(TAG, "Unable to read product name");
268 break;
269 case FIRMWARE_FAILED:
270 ESP_LOGW(TAG, "Unable to read firmware version");
271 break;
272 default:
273 ESP_LOGW(TAG, "Unknown setup error");
274 break;
275 }
276 }
277 ESP_LOGCONFIG(TAG,
278 " Product name: %s\n"
279 " Firmware version: %d\n"
280 " Serial number %02d.%02d.%02d",
281 this->product_name_.c_str(), this->firmware_version_, this->serial_number_[0], this->serial_number_[1],
282 this->serial_number_[2]);
284 ESP_LOGCONFIG(TAG, " Auto cleaning interval: %" PRId32 "s", this->auto_cleaning_interval_.value());
285 }
286 if (this->acceleration_mode_.has_value()) {
287 ESP_LOGCONFIG(TAG, " RH/T acceleration mode: %s",
288 LOG_STR_ARG(rht_accel_mode_to_string(this->acceleration_mode_.value())));
289 }
290 LOG_UPDATE_INTERVAL(this);
291 LOG_SENSOR(" ", "PM 1.0", this->pm_1_0_sensor_);
292 LOG_SENSOR(" ", "PM 2.5", this->pm_2_5_sensor_);
293 LOG_SENSOR(" ", "PM 4.0", this->pm_4_0_sensor_);
294 LOG_SENSOR(" ", "PM 10.0", this->pm_10_0_sensor_);
295 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
296 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
297 LOG_SENSOR(" ", "VOC", this->voc_sensor_); // SEN54 and SEN55 only
298 LOG_SENSOR(" ", "NOx", this->nox_sensor_); // SEN55 only
299}
300
302 if (!this->initialized_) {
303 return;
304 }
305
306 // Store baselines after defined interval or if the difference between current and stored baseline becomes too
307 // much
308 if (this->store_baseline_ && this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL) {
309 if (this->write_command(SEN5X_CMD_VOC_ALGORITHM_STATE)) {
310 // run it a bit later to avoid adding a delay here
311 this->set_timeout(550, [this]() {
312 uint16_t states[4];
313 if (this->read_data(states, 4)) {
314 uint32_t state0 = states[0] << 16 | states[1];
315 uint32_t state1 = states[2] << 16 | states[3];
316 if ((uint32_t) std::abs(static_cast<int32_t>(this->voc_baselines_storage_.state0 - state0)) >
317 MAXIMUM_STORAGE_DIFF ||
318 (uint32_t) std::abs(static_cast<int32_t>(this->voc_baselines_storage_.state1 - state1)) >
319 MAXIMUM_STORAGE_DIFF) {
321 this->voc_baselines_storage_.state0 = state0;
322 this->voc_baselines_storage_.state1 = state1;
323
324 if (this->pref_.save(&this->voc_baselines_storage_)) {
325 ESP_LOGI(TAG, "Stored VOC baseline state0: 0x%04" PRIX32 ", state1: 0x%04" PRIX32,
326 this->voc_baselines_storage_.state0, this->voc_baselines_storage_.state1);
327 } else {
328 ESP_LOGW(TAG, "Could not store VOC baselines");
329 }
330 }
331 }
332 });
333 }
334 }
335
336 if (!this->write_command(SEN5X_CMD_READ_MEASUREMENT)) {
337 this->status_set_warning();
338 ESP_LOGD(TAG, "Write error: read measurement (%d)", this->last_error_);
339 return;
340 }
341 this->set_timeout(20, [this]() {
342 uint16_t measurements[8];
343
344 if (!this->read_data(measurements, 8)) {
345 this->status_set_warning();
346 ESP_LOGD(TAG, "Read data error (%d)", this->last_error_);
347 return;
348 }
349
350 ESP_LOGVV(TAG, "pm_1_0 = 0x%.4x", measurements[0]);
351 float pm_1_0 = measurements[0] == UINT16_MAX ? NAN : measurements[0] / 10.0f;
352
353 ESP_LOGVV(TAG, "pm_2_5 = 0x%.4x", measurements[1]);
354 float pm_2_5 = measurements[1] == UINT16_MAX ? NAN : measurements[1] / 10.0f;
355
356 ESP_LOGVV(TAG, "pm_4_0 = 0x%.4x", measurements[2]);
357 float pm_4_0 = measurements[2] == UINT16_MAX ? NAN : measurements[2] / 10.0f;
358
359 ESP_LOGVV(TAG, "pm_10_0 = 0x%.4x", measurements[3]);
360 float pm_10_0 = measurements[3] == UINT16_MAX ? NAN : measurements[3] / 10.0f;
361
362 ESP_LOGVV(TAG, "humidity = 0x%.4x", measurements[4]);
363 float humidity = measurements[4] == INT16_MAX ? NAN : static_cast<int16_t>(measurements[4]) / 100.0f;
364
365 ESP_LOGVV(TAG, "temperature = 0x%.4x", measurements[5]);
366 float temperature = measurements[5] == INT16_MAX ? NAN : static_cast<int16_t>(measurements[5]) / 200.0f;
367
368 ESP_LOGVV(TAG, "voc = 0x%.4x", measurements[6]);
369 int16_t voc_idx = static_cast<int16_t>(measurements[6]);
370 float voc = (voc_idx < SEN5X_MIN_INDEX_VALUE || voc_idx > SEN5X_MAX_INDEX_VALUE)
371 ? NAN
372 : static_cast<float>(voc_idx) / 10.0f;
373
374 ESP_LOGVV(TAG, "nox = 0x%.4x", measurements[7]);
375 int16_t nox_idx = static_cast<int16_t>(measurements[7]);
376 float nox = (nox_idx < SEN5X_MIN_INDEX_VALUE || nox_idx > SEN5X_MAX_INDEX_VALUE)
377 ? NAN
378 : static_cast<float>(nox_idx) / 10.0f;
379
380 if (this->pm_1_0_sensor_ != nullptr) {
381 this->pm_1_0_sensor_->publish_state(pm_1_0);
382 }
383 if (this->pm_2_5_sensor_ != nullptr) {
384 this->pm_2_5_sensor_->publish_state(pm_2_5);
385 }
386 if (this->pm_4_0_sensor_ != nullptr) {
387 this->pm_4_0_sensor_->publish_state(pm_4_0);
388 }
389 if (this->pm_10_0_sensor_ != nullptr) {
390 this->pm_10_0_sensor_->publish_state(pm_10_0);
391 }
392 if (this->temperature_sensor_ != nullptr) {
393 this->temperature_sensor_->publish_state(temperature);
394 }
395 if (this->humidity_sensor_ != nullptr) {
396 this->humidity_sensor_->publish_state(humidity);
397 }
398 if (this->voc_sensor_ != nullptr) {
399 this->voc_sensor_->publish_state(voc);
400 }
401 if (this->nox_sensor_ != nullptr) {
402 this->nox_sensor_->publish_state(nox);
403 }
404 this->status_clear_warning();
405 });
406}
407
408bool SEN5XComponent::write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning) {
409 uint16_t params[6];
410 params[0] = tuning.index_offset;
411 params[1] = tuning.learning_time_offset_hours;
412 params[2] = tuning.learning_time_gain_hours;
413 params[3] = tuning.gating_max_duration_minutes;
414 params[4] = tuning.std_initial;
415 params[5] = tuning.gain_factor;
416 auto result = write_command(i2c_command, params, 6);
417 if (!result) {
418 ESP_LOGE(TAG, "Set tuning parameters failed (command=%0xX, err=%d)", i2c_command, this->last_error_);
419 }
420 return result;
421}
422
424 uint16_t params[3];
425 params[0] = compensation.offset;
426 params[1] = compensation.normalized_offset_slope;
427 params[2] = compensation.time_constant;
428 if (!write_command(SEN5X_CMD_TEMPERATURE_COMPENSATION, params, 3)) {
429 ESP_LOGE(TAG, "Set temperature_compensation failed (%d)", this->last_error_);
430 return false;
431 }
432 return true;
433}
434
436 if (!write_command(SEN5X_CMD_START_CLEANING_FAN)) {
437 this->status_set_warning();
438 ESP_LOGE(TAG, "Start fan cleaning failed (%d)", this->last_error_);
439 return false;
440 } else {
441 ESP_LOGD(TAG, "Fan auto clean started");
442 }
443 return true;
444}
445
446} // namespace sen5x
447} // namespace esphome
BedjetMode mode
BedJet operating mode.
std::string get_compilation_time() const
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
bool save(const T *src)
Definition preferences.h:21
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
optional< RhtAccelerationMode > acceleration_mode_
Definition sen5x.h:128
sensor::Sensor * pm_4_0_sensor_
Definition sen5x.h:119
void dump_config() override
Definition sen5x.cpp:252
ESPPreferenceObject pref_
Definition sen5x.h:133
bool write_tuning_parameters_(uint16_t i2c_command, const GasTuning &tuning)
Definition sen5x.cpp:408
sensor::Sensor * pm_2_5_sensor_
Definition sen5x.h:118
sensor::Sensor * temperature_sensor_
Definition sen5x.h:122
optional< uint32_t > auto_cleaning_interval_
Definition sen5x.h:129
sensor::Sensor * pm_1_0_sensor_
Definition sen5x.h:117
sensor::Sensor * voc_sensor_
Definition sen5x.h:124
optional< TemperatureCompensation > temperature_compensation_
Definition sen5x.h:132
sensor::Sensor * nox_sensor_
Definition sen5x.h:126
optional< GasTuning > voc_tuning_params_
Definition sen5x.h:130
sensor::Sensor * pm_10_0_sensor_
Definition sen5x.h:120
Sen5xBaselines voc_baselines_storage_
Definition sen5x.h:135
sensor::Sensor * humidity_sensor_
Definition sen5x.h:123
bool write_temperature_compensation_(const TemperatureCompensation &compensation)
Definition sen5x.cpp:423
optional< GasTuning > nox_tuning_params_
Definition sen5x.h:131
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.
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:73
@ PRODUCT_NAME_FAILED
Definition sen5x.h:16
@ MEASUREMENT_INIT_FAILED
Definition sen5x.h:15
@ FIRMWARE_FAILED
Definition sen5x.h:17
@ SERIAL_NUMBER_IDENTIFICATION_FAILED
Definition sen5x.h:14
@ COMMUNICATION_FAILED
Definition sen5x.h:13
RhtAccelerationMode
Definition sen5x.h:21
@ LOW_ACCELERATION
Definition sen5x.h:22
@ HIGH_ACCELERATION
Definition sen5x.h:24
@ MEDIUM_ACCELERATION
Definition sen5x.h:23
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:178
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:145
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t learning_time_gain_hours
Definition sen5x.h:35
uint16_t gating_max_duration_minutes
Definition sen5x.h:36
uint16_t learning_time_offset_hours
Definition sen5x.h:34
uint16_t temperature
Definition sun_gtil2.cpp:12