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