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