ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
bme680_bsec.cpp
Go to the documentation of this file.
1#include "bme680_bsec.h"
3#include "esphome/core/log.h"
4#include <string>
5
7#ifdef USE_BSEC
8static const char *const TAG = "bme680_bsec.sensor";
9
10static const std::string IAQ_ACCURACY_STATES[4] = {"Stabilizing", "Uncertain", "Calibrating", "Calibrated"};
11
12std::vector<BME680BSECComponent *>
13 BME680BSECComponent::instances; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
14uint8_t BME680BSECComponent::work_buffer_[BSEC_MAX_WORKBUFFER_SIZE] = {0};
15
17 uint8_t new_idx = BME680BSECComponent::instances.size();
18 BME680BSECComponent::instances.push_back(this);
19
20 this->bsec_state_data_valid_ = false;
21
22 // Initialize the bme680_ structure (passed-in to the bme680_* functions) and the BME680 device
23 this->bme680_.dev_id =
24 new_idx; // This is a "Place holder to store the id of the device structure" (see bme680_defs.h).
25 // This will be passed-in as first parameter to the next "read" and "write" function pointers.
26 // We currently use the index of the object in the BME680BSECComponent::instances vector to identify
27 // the different devices in the system.
28 this->bme680_.intf = BME680_I2C_INTF;
32 this->bme680_.amb_temp = 25;
33
34 this->bme680_status_ = bme680_init(&this->bme680_);
35 if (this->bme680_status_ != BME680_OK) {
36 this->mark_failed();
37 return;
38 }
39
40 // Initialize the BSEC library
41 if (this->reinit_bsec_lib_() != 0) {
42 this->mark_failed();
43 return;
44 }
45
46 // Load the BSEC library state from storage
47 this->load_state_();
48}
49
51 if (this->sample_rate_ == SAMPLE_RATE_ULP) {
53 const uint8_t config[] = {
54#include "config/generic_33v_300s_28d/bsec_iaq.txt"
55 };
56 this->bsec_status_ =
57 bsec_set_configuration(config, BSEC_MAX_PROPERTY_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
58 } else { // SUPPLY_VOLTAGE_1V8
59 const uint8_t config[] = {
60#include "config/generic_18v_300s_28d/bsec_iaq.txt"
61 };
62 this->bsec_status_ =
63 bsec_set_configuration(config, BSEC_MAX_PROPERTY_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
64 }
65 } else { // SAMPLE_RATE_LP
67 const uint8_t config[] = {
68#include "config/generic_33v_3s_28d/bsec_iaq.txt"
69 };
70 this->bsec_status_ =
71 bsec_set_configuration(config, BSEC_MAX_PROPERTY_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
72 } else { // SUPPLY_VOLTAGE_1V8
73 const uint8_t config[] = {
74#include "config/generic_18v_3s_28d/bsec_iaq.txt"
75 };
76 this->bsec_status_ =
77 bsec_set_configuration(config, BSEC_MAX_PROPERTY_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
78 }
79 }
80}
81
83 if (sample_rate == SAMPLE_RATE_DEFAULT) {
84 sample_rate = this->sample_rate_;
85 }
86 return sample_rate == SAMPLE_RATE_ULP ? BSEC_SAMPLE_RATE_ULP : BSEC_SAMPLE_RATE_LP;
87}
88
90 bsec_sensor_configuration_t virtual_sensors[BSEC_NUMBER_OUTPUTS];
91 int num_virtual_sensors = 0;
92
93 if (this->iaq_sensor_) {
94 virtual_sensors[num_virtual_sensors].sensor_id =
95 this->iaq_mode_ == IAQ_MODE_STATIC ? BSEC_OUTPUT_STATIC_IAQ : BSEC_OUTPUT_IAQ;
96 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
97 num_virtual_sensors++;
98 }
99
100 if (this->co2_equivalent_sensor_) {
101 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_CO2_EQUIVALENT;
102 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
103 num_virtual_sensors++;
104 }
105
107 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_BREATH_VOC_EQUIVALENT;
108 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
109 num_virtual_sensors++;
110 }
111
112 if (this->pressure_sensor_) {
113 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_RAW_PRESSURE;
114 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->pressure_sample_rate_);
115 num_virtual_sensors++;
116 }
117
118 if (this->gas_resistance_sensor_) {
119 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_RAW_GAS;
120 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
121 num_virtual_sensors++;
122 }
123
124 if (this->temperature_sensor_) {
125 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE;
126 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->temperature_sample_rate_);
127 num_virtual_sensors++;
128 }
129
130 if (this->humidity_sensor_) {
131 virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY;
132 virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->humidity_sample_rate_);
133 num_virtual_sensors++;
134 }
135
136 bsec_sensor_configuration_t sensor_settings[BSEC_MAX_PHYSICAL_SENSOR];
137 uint8_t num_sensor_settings = BSEC_MAX_PHYSICAL_SENSOR;
138 this->bsec_status_ =
139 bsec_update_subscription(virtual_sensors, num_virtual_sensors, sensor_settings, &num_sensor_settings);
140 ESP_LOGV(TAG, "%s: updating subscription for %d virtual sensors (out=%d sensors)", this->device_id_.c_str(),
141 num_virtual_sensors, num_sensor_settings);
142}
143
145 ESP_LOGCONFIG(TAG, "%s via BSEC:", this->device_id_.c_str());
146
147 bsec_version_t version;
148 bsec_get_version(&version);
149 ESP_LOGCONFIG(TAG, " BSEC Version: %d.%d.%d.%d", version.major, version.minor, version.major_bugfix,
150 version.minor_bugfix);
151
152 LOG_I2C_DEVICE(this);
153
154 if (this->is_failed()) {
155 ESP_LOGE(TAG, "Communication failed (BSEC Status: %d, BME680 Status: %d)", this->bsec_status_,
156 this->bme680_status_);
157 }
158
159 ESP_LOGCONFIG(TAG,
160 " Temperature Offset: %.2f\n"
161 " IAQ Mode: %s\n"
162 " Supply Voltage: %sV\n"
163 " Sample Rate: %s\n"
164 " State Save Interval: %ims",
165 this->temperature_offset_, this->iaq_mode_ == IAQ_MODE_STATIC ? "Static" : "Mobile",
166 this->supply_voltage_ == SUPPLY_VOLTAGE_3V3 ? "3.3" : "1.8",
167 BME680_BSEC_SAMPLE_RATE_LOG(this->sample_rate_), this->state_save_interval_ms_);
168
169 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
170 ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->temperature_sample_rate_));
171 LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
172 ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->pressure_sample_rate_));
173 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
174 ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->humidity_sample_rate_));
175 LOG_SENSOR(" ", "Gas Resistance", this->gas_resistance_sensor_);
176 LOG_SENSOR(" ", "IAQ", this->iaq_sensor_);
177 LOG_SENSOR(" ", "Numeric IAQ Accuracy", this->iaq_accuracy_sensor_);
178 LOG_TEXT_SENSOR(" ", "IAQ Accuracy", this->iaq_accuracy_text_sensor_);
179 LOG_SENSOR(" ", "CO2 Equivalent", this->co2_equivalent_sensor_);
180 LOG_SENSOR(" ", "Breath VOC Equivalent", this->breath_voc_equivalent_sensor_);
181}
182
184 this->run_();
185
187 this->status_set_error();
188 } else {
189 this->status_clear_error();
190 }
191 if (this->bsec_status_ > BSEC_OK || this->bme680_status_ > BME680_OK) {
192 this->status_set_warning();
193 } else {
194 this->status_clear_warning();
195 }
196
197 // Process a single action from the queue. These are primarily sensor state publishes
198 // that in totality take too long to send in a single call.
199 if (this->queue_.size()) {
200 auto action = std::move(this->queue_.front());
201 this->queue_.pop();
202 action();
203 }
204}
205
207 int64_t curr_time_ns = this->get_time_ns_();
208 if (curr_time_ns < this->next_call_ns_) {
209 return;
210 }
211
212 ESP_LOGV(TAG, "%s: Performing sensor run", this->device_id_.c_str());
213
214 // Restore BSEC library state
215 // The reinit_bsec_lib_ method is computationally expensive: it takes 1200รท2900 microseconds on a ESP32.
216 // It can be skipped entirely when there is only one device (since the BSEC library won't be shared)
217 if (BME680BSECComponent::instances.size() > 1) {
218 int res = this->reinit_bsec_lib_();
219 if (res != 0)
220 return;
221 }
222
223 this->bsec_status_ = bsec_sensor_control(curr_time_ns, &this->bme680_settings_);
224 if (this->bsec_status_ < BSEC_OK) {
225 ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC Error Code %d)", this->bsec_status_);
226 return;
227 }
228 this->next_call_ns_ = this->bme680_settings_.next_call;
229
230 if (this->bme680_settings_.trigger_measurement) {
231 this->bme680_.tph_sett.os_temp = this->bme680_settings_.temperature_oversampling;
232 this->bme680_.tph_sett.os_pres = this->bme680_settings_.pressure_oversampling;
233 this->bme680_.tph_sett.os_hum = this->bme680_settings_.humidity_oversampling;
234 this->bme680_.gas_sett.run_gas = this->bme680_settings_.run_gas;
235 this->bme680_.gas_sett.heatr_temp = this->bme680_settings_.heater_temperature;
236 this->bme680_.gas_sett.heatr_dur = this->bme680_settings_.heating_duration;
237 this->bme680_.power_mode = BME680_FORCED_MODE;
238 uint16_t desired_settings = BME680_OST_SEL | BME680_OSP_SEL | BME680_OSH_SEL | BME680_GAS_SENSOR_SEL;
239 this->bme680_status_ = bme680_set_sensor_settings(desired_settings, &this->bme680_);
240 if (this->bme680_status_ != BME680_OK) {
241 ESP_LOGW(TAG, "Failed to set sensor settings (BME680 Error Code %d)", this->bme680_status_);
242 return;
243 }
244
245 this->bme680_status_ = bme680_set_sensor_mode(&this->bme680_);
246 if (this->bme680_status_ != BME680_OK) {
247 ESP_LOGW(TAG, "Failed to set sensor mode (BME680 Error Code %d)", this->bme680_status_);
248 return;
249 }
250
251 uint16_t meas_dur = 0;
252 bme680_get_profile_dur(&meas_dur, &this->bme680_);
253
254 // Since we are about to go "out of scope" in the loop, take a snapshot of the state now so we can restore it later
255 // TODO: it would be interesting to see if this is really needed here, or if it's needed only after each
256 // bsec_do_steps() call
257 if (BME680BSECComponent::instances.size() > 1)
258 this->snapshot_state_();
259
260 ESP_LOGV(TAG, "Queueing read in %ums", meas_dur);
261 this->set_timeout("read", meas_dur, [this]() { this->read_(); });
262 } else {
263 ESP_LOGV(TAG, "Measurement not required");
264 this->read_();
265 }
266}
267
269 ESP_LOGV(TAG, "%s: Reading data", this->device_id_.c_str());
270 int64_t curr_time_ns = this->get_time_ns_();
271
272 if (this->bme680_settings_.trigger_measurement) {
273 uint32_t start = millis();
274 while (this->bme680_.power_mode != BME680_SLEEP_MODE) {
275 if (millis() - start > 50) {
276 ESP_LOGE(TAG, "Timeout waiting for BME680 to enter sleep mode");
277 return;
278 }
279 this->bme680_status_ = bme680_get_sensor_mode(&this->bme680_);
280 if (this->bme680_status_ != BME680_OK) {
281 ESP_LOGE(TAG, "Failed to get sensor mode (BME680 Error Code %d)", this->bme680_status_);
282 return;
283 }
284 }
285 }
286
287 if (!this->bme680_settings_.process_data) {
288 ESP_LOGV(TAG, "Data processing not required");
289 return;
290 }
291
292 struct bme680_field_data data;
293 this->bme680_status_ = bme680_get_sensor_data(&data, &this->bme680_);
294
295 if (this->bme680_status_ != BME680_OK) {
296 ESP_LOGW(TAG, "Failed to get sensor data (BME680 Error Code %d)", this->bme680_status_);
297 return;
298 }
299 if (!(data.status & BME680_NEW_DATA_MSK)) {
300 ESP_LOGD(TAG, "BME680 did not report new data");
301 return;
302 }
303
304 bsec_input_t inputs[BSEC_MAX_PHYSICAL_SENSOR]; // Temperature, Pressure, Humidity & Gas Resistance
305 uint8_t num_inputs = 0;
306
307 if (this->bme680_settings_.process_data & BSEC_PROCESS_TEMPERATURE) {
308 inputs[num_inputs].sensor_id = BSEC_INPUT_TEMPERATURE;
309 inputs[num_inputs].signal = data.temperature / 100.0f;
310 inputs[num_inputs].time_stamp = curr_time_ns;
311 num_inputs++;
312
313 // Temperature offset from the real temperature due to external heat sources
314 inputs[num_inputs].sensor_id = BSEC_INPUT_HEATSOURCE;
315 inputs[num_inputs].signal = this->temperature_offset_;
316 inputs[num_inputs].time_stamp = curr_time_ns;
317 num_inputs++;
318 }
319 if (this->bme680_settings_.process_data & BSEC_PROCESS_HUMIDITY) {
320 inputs[num_inputs].sensor_id = BSEC_INPUT_HUMIDITY;
321 inputs[num_inputs].signal = data.humidity / 1000.0f;
322 inputs[num_inputs].time_stamp = curr_time_ns;
323 num_inputs++;
324 }
325 if (this->bme680_settings_.process_data & BSEC_PROCESS_PRESSURE) {
326 inputs[num_inputs].sensor_id = BSEC_INPUT_PRESSURE;
327 inputs[num_inputs].signal = data.pressure;
328 inputs[num_inputs].time_stamp = curr_time_ns;
329 num_inputs++;
330 }
331 if (this->bme680_settings_.process_data & BSEC_PROCESS_GAS) {
332 if (data.status & BME680_GASM_VALID_MSK) {
333 inputs[num_inputs].sensor_id = BSEC_INPUT_GASRESISTOR;
334 inputs[num_inputs].signal = data.gas_resistance;
335 inputs[num_inputs].time_stamp = curr_time_ns;
336 num_inputs++;
337 } else {
338 ESP_LOGD(TAG, "BME680 did not report gas data");
339 }
340 }
341 if (num_inputs < 1) {
342 ESP_LOGD(TAG, "No signal inputs available for BSEC");
343 return;
344 }
345
346 // Restore BSEC library state
347 // The reinit_bsec_lib_ method is computationally expensive: it takes 1200รท2900 microseconds on a ESP32.
348 // It can be skipped entirely when there is only one device (since the BSEC library won't be shared)
350 int res = this->reinit_bsec_lib_();
351 if (res != 0)
352 return;
353 // Now that the BSEC library has been re-initialized, bsec_sensor_control *NEEDS* to be called in order to support
354 // multiple devices with a different set of enabled sensors (even if the bme680_settings_ data is not used)
355 this->bsec_status_ = bsec_sensor_control(curr_time_ns, &this->bme680_settings_);
356 if (this->bsec_status_ < BSEC_OK) {
357 ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC Error Code %d)", this->bsec_status_);
358 return;
359 }
360 }
361
362 bsec_output_t outputs[BSEC_NUMBER_OUTPUTS];
363 uint8_t num_outputs = BSEC_NUMBER_OUTPUTS;
364 this->bsec_status_ = bsec_do_steps(inputs, num_inputs, outputs, &num_outputs);
365 if (this->bsec_status_ != BSEC_OK) {
366 ESP_LOGW(TAG, "BSEC failed to process signals (BSEC Error Code %d)", this->bsec_status_);
367 return;
368 }
369 ESP_LOGV(TAG, "%s: after bsec_do_steps: num_inputs=%d num_outputs=%d", this->device_id_.c_str(), num_inputs,
370 num_outputs);
371
372 // Since we are about to go "out of scope" in the loop, take a snapshot of the state now so we can restore it later
374 this->snapshot_state_();
375
376 if (num_outputs < 1) {
377 ESP_LOGD(TAG, "No signal outputs provided by BSEC");
378 return;
379 }
380
381 this->publish_(outputs, num_outputs);
382}
383
384void BME680BSECComponent::publish_(const bsec_output_t *outputs, uint8_t num_outputs) {
385 ESP_LOGV(TAG, "%s: Queuing sensor state publish actions", this->device_id_.c_str());
386 for (uint8_t i = 0; i < num_outputs; i++) {
387 float signal = outputs[i].signal;
388 switch (outputs[i].sensor_id) {
389 case BSEC_OUTPUT_IAQ:
390 case BSEC_OUTPUT_STATIC_IAQ: {
391 uint8_t accuracy = std::min<uint8_t>(outputs[i].accuracy, std::size(IAQ_ACCURACY_STATES) - 1);
392 this->queue_push_([this, signal]() { this->publish_sensor_(this->iaq_sensor_, signal); });
393 this->queue_push_([this, accuracy]() {
394 this->publish_sensor_(this->iaq_accuracy_text_sensor_, IAQ_ACCURACY_STATES[accuracy]);
395 });
396 this->queue_push_([this, accuracy]() { this->publish_sensor_(this->iaq_accuracy_sensor_, accuracy, true); });
397
398 // Queue up an opportunity to save state
399 this->queue_push_([this, accuracy]() { this->save_state_(accuracy); });
400 } break;
401 case BSEC_OUTPUT_CO2_EQUIVALENT:
402 this->queue_push_([this, signal]() { this->publish_sensor_(this->co2_equivalent_sensor_, signal); });
403 break;
404 case BSEC_OUTPUT_BREATH_VOC_EQUIVALENT:
405 this->queue_push_([this, signal]() { this->publish_sensor_(this->breath_voc_equivalent_sensor_, signal); });
406 break;
407 case BSEC_OUTPUT_RAW_PRESSURE:
408 this->queue_push_([this, signal]() { this->publish_sensor_(this->pressure_sensor_, signal / 100.0f); });
409 break;
410 case BSEC_OUTPUT_RAW_GAS:
411 this->queue_push_([this, signal]() { this->publish_sensor_(this->gas_resistance_sensor_, signal); });
412 break;
413 case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE:
414 this->queue_push_([this, signal]() { this->publish_sensor_(this->temperature_sensor_, signal); });
415 break;
416 case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY:
417 this->queue_push_([this, signal]() { this->publish_sensor_(this->humidity_sensor_, signal); });
418 break;
419 }
420 }
421}
422
424 int64_t time_ms = millis();
425 if (this->last_time_ms_ > time_ms) {
427 }
428 this->last_time_ms_ = time_ms;
429
430 return (time_ms + ((int64_t) this->millis_overflow_counter_ << 32)) * INT64_C(1000000);
431}
432
433void BME680BSECComponent::publish_sensor_(sensor::Sensor *sensor, float value, bool change_only) {
434 if (!sensor || (change_only && sensor->has_state() && sensor->state == value)) {
435 return;
436 }
437 sensor->publish_state(value);
438}
439
440void BME680BSECComponent::publish_sensor_(text_sensor::TextSensor *sensor, const std::string &value) {
441 if (!sensor || (sensor->has_state() && sensor->state == value)) {
442 return;
443 }
444 sensor->publish_state(value);
445}
446
447// Communication function - read
448// First parameter is the "dev_id" member of our "bme680_" object, which is passed-back here as-is
449int8_t BME680BSECComponent::read_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len) {
450 BME680BSECComponent *inst = instances[devid];
451 // Use the I2CDevice::read_bytes method to perform the actual I2C register read
452 return inst->read_bytes(a_register, data, len) ? 0 : -1;
453}
454
455// Communication function - write
456// First parameter is the "dev_id" member of our "bme680_" object, which is passed-back here as-is
457int8_t BME680BSECComponent::write_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len) {
458 BME680BSECComponent *inst = instances[devid];
459 // Use the I2CDevice::write_bytes method to perform the actual I2C register write
460 return inst->write_bytes(a_register, data, len) ? 0 : -1;
461}
462
464 ESP_LOGV(TAG, "Delaying for %ums", period);
465 delay(period);
466}
467
468// Fetch the BSEC library state and save it in the bsec_state_data_ member (volatile memory)
469// Used to share the library when using more than one sensor
471 uint32_t num_serialized_state = BSEC_MAX_STATE_BLOB_SIZE;
472 this->bsec_status_ = bsec_get_state(0, this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_,
473 sizeof(this->work_buffer_), &num_serialized_state);
474 if (this->bsec_status_ != BSEC_OK) {
475 ESP_LOGW(TAG, "%s: Failed to fetch BSEC library state for snapshot (BSEC Error Code %d)", this->device_id_.c_str(),
476 this->bsec_status_);
477 return;
478 }
479 this->bsec_state_data_valid_ = true;
480}
481
482// Restores the BSEC library state from a snapshot in memory
483// Used to share the library when using more than one sensor
485 if (!this->bsec_state_data_valid_) {
486 ESP_LOGV(TAG, "%s: BSEC state data NOT valid, aborting restore_state_()", this->device_id_.c_str());
487 return;
488 }
489
490 this->bsec_status_ =
491 bsec_set_state(this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
492 if (this->bsec_status_ != BSEC_OK) {
493 ESP_LOGW(TAG, "Failed to restore BSEC library state (BSEC Error Code %d)", this->bsec_status_);
494 return;
495 }
496}
497
499 this->bsec_status_ = bsec_init();
500 if (this->bsec_status_ != BSEC_OK) {
501 this->mark_failed();
502 return -1;
503 }
504
505 this->set_config_();
506 if (this->bsec_status_ != BSEC_OK) {
507 this->mark_failed();
508 return -2;
509 }
510
511 this->restore_state_();
512
513 this->update_subscription_();
514 if (this->bsec_status_ != BSEC_OK) {
515 this->mark_failed();
516 return -3;
517 }
518
519 return 0;
520}
521
523 uint32_t hash = fnv1_hash_extend(fnv1_hash("bme680_bsec_state_"), this->device_id_);
524 this->bsec_state_ = global_preferences->make_preference<uint8_t[BSEC_MAX_STATE_BLOB_SIZE]>(hash, true);
525
526 if (!this->bsec_state_.load(&this->bsec_state_data_)) {
527 // No saved BSEC library state available
528 return;
529 }
530
531 ESP_LOGV(TAG, "%s: Loading BSEC library state", this->device_id_.c_str());
532 this->bsec_status_ =
533 bsec_set_state(this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
534 if (this->bsec_status_ != BSEC_OK) {
535 ESP_LOGW(TAG, "%s: Failed to load BSEC library state (BSEC Error Code %d)", this->device_id_.c_str(),
536 this->bsec_status_);
537 return;
538 }
539 // All OK: set the BSEC state data as valid
540 this->bsec_state_data_valid_ = true;
541 ESP_LOGI(TAG, "%s: Loaded BSEC library state", this->device_id_.c_str());
542}
543
544void BME680BSECComponent::save_state_(uint8_t accuracy) {
545 if (accuracy < 3 || (millis() - this->last_state_save_ms_ < this->state_save_interval_ms_)) {
546 return;
547 }
548 if (BME680BSECComponent::instances.size() <= 1) {
549 // When a single device is in use, no snapshot is taken regularly so one is taken now
550 // On multiple devices, a snapshot is taken at every loop, so there is no need to take one here
551 this->snapshot_state_();
552 }
553 if (!this->bsec_state_data_valid_)
554 return;
555
556 ESP_LOGV(TAG, "%s: Saving state", this->device_id_.c_str());
557
558 if (!this->bsec_state_.save(&this->bsec_state_data_)) {
559 ESP_LOGW(TAG, "Failed to save state");
560 return;
561 }
562 this->last_state_save_ms_ = millis();
563
564 ESP_LOGI(TAG, "Saved state");
565}
566#endif
567} // namespace esphome::bme680_bsec
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_error()
Definition component.h:312
void status_clear_warning()
Definition component.h:306
bool has_state() const
std::queue< std::function< void()> > queue_
static std::vector< BME680BSECComponent * > instances
Definition bme680_bsec.h:60
static int8_t read_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len)
static uint8_t work_buffer_[BSEC_MAX_WORKBUFFER_SIZE]
Definition bme680_bsec.h:96
void queue_push_(std::function< void()> &&f)
Definition bme680_bsec.h:94
float calc_sensor_sample_rate_(SampleRate sample_rate)
static int8_t write_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len)
uint8_t bsec_state_data_[BSEC_MAX_STATE_BLOB_SIZE]
void publish_(const bsec_output_t *outputs, uint8_t num_outputs)
void publish_sensor_(sensor::Sensor *sensor, float value, bool change_only=false)
text_sensor::TextSensor * iaq_accuracy_text_sensor_
static void delay_ms(uint32_t period)
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:251
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Compat APIs All methods below have been added for compatibility reasons.
Definition i2c.h:217
Base-class for all sensors.
Definition sensor.h:47
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
void publish_state(const std::string &state)
constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value)
Extend a FNV-1 hash with an integer (hashes each byte).
Definition helpers.h:789
std::string size_t len
uint16_t size
Definition helpers.cpp:25
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:161
void HOT delay(uint32_t ms)
Definition hal.cpp:82
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24