ESPHome  2024.10.2
bme680_bsec.cpp
Go to the documentation of this file.
1 #include "bme680_bsec.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/helpers.h"
4 #include <string>
5 
6 namespace esphome {
7 namespace bme680_bsec {
8 #ifdef USE_BSEC
9 static const char *const TAG = "bme680_bsec.sensor";
10 
11 static const std::string IAQ_ACCURACY_STATES[4] = {"Stabilizing", "Uncertain", "Calibrating", "Calibrated"};
12 
13 std::vector<BME680BSECComponent *>
14  BME680BSECComponent::instances; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
15 uint8_t BME680BSECComponent::work_buffer_[BSEC_MAX_WORKBUFFER_SIZE] = {0};
16 
18  ESP_LOGCONFIG(TAG, "Setting up BME680(%s) via BSEC...", 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;
34  this->bme680_.delay_ms = BME680BSECComponent::delay_ms;
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) {
55  if (this->supply_voltage_ == SUPPLY_VOLTAGE_3V3) {
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
69  if (this->supply_voltage_ == SUPPLY_VOLTAGE_3V3) {
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 
109  if (this->breath_voc_equivalent_sensor_) {
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, " Temperature Offset: %.2f", this->temperature_offset_);
163  ESP_LOGCONFIG(TAG, " IAQ Mode: %s", this->iaq_mode_ == IAQ_MODE_STATIC ? "Static" : "Mobile");
164  ESP_LOGCONFIG(TAG, " Supply Voltage: %sV", this->supply_voltage_ == SUPPLY_VOLTAGE_3V3 ? "3.3" : "1.8");
165  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->sample_rate_));
166  ESP_LOGCONFIG(TAG, " State Save Interval: %ims", this->state_save_interval_ms_);
167 
168  LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
169  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->temperature_sample_rate_));
170  LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
171  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->pressure_sample_rate_));
172  LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
173  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->humidity_sample_rate_));
174  LOG_SENSOR(" ", "Gas Resistance", this->gas_resistance_sensor_);
175  LOG_SENSOR(" ", "IAQ", this->iaq_sensor_);
176  LOG_SENSOR(" ", "Numeric IAQ Accuracy", this->iaq_accuracy_sensor_);
177  LOG_TEXT_SENSOR(" ", "IAQ Accuracy", this->iaq_accuracy_text_sensor_);
178  LOG_SENSOR(" ", "CO2 Equivalent", this->co2_equivalent_sensor_);
179  LOG_SENSOR(" ", "Breath VOC Equivalent", this->breath_voc_equivalent_sensor_);
180 }
181 
183 
185  this->run_();
186 
187  if (this->bsec_status_ < BSEC_OK || this->bme680_status_ < BME680_OK) {
188  this->status_set_error();
189  } else {
190  this->status_clear_error();
191  }
192  if (this->bsec_status_ > BSEC_OK || this->bme680_status_ > BME680_OK) {
193  this->status_set_warning();
194  } else {
195  this->status_clear_warning();
196  }
197 
198  // Process a single action from the queue. These are primarily sensor state publishes
199  // that in totality take too long to send in a single call.
200  if (this->queue_.size()) {
201  auto action = std::move(this->queue_.front());
202  this->queue_.pop();
203  action();
204  }
205 }
206 
208  int64_t curr_time_ns = this->get_time_ns_();
209  if (curr_time_ns < this->next_call_ns_) {
210  return;
211  }
212 
213  ESP_LOGV(TAG, "%s: Performing sensor run", this->device_id_.c_str());
214 
215  // Restore BSEC library state
216  // The reinit_bsec_lib_ method is computationally expensive: it takes 1200รท2900 microseconds on a ESP32.
217  // It can be skipped entirely when there is only one device (since the BSEC library won't be shared)
218  if (BME680BSECComponent::instances.size() > 1) {
219  int res = this->reinit_bsec_lib_();
220  if (res != 0)
221  return;
222  }
223 
224  this->bsec_status_ = bsec_sensor_control(curr_time_ns, &this->bme680_settings_);
225  if (this->bsec_status_ < BSEC_OK) {
226  ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC Error Code %d)", this->bsec_status_);
227  return;
228  }
229  this->next_call_ns_ = this->bme680_settings_.next_call;
230 
231  if (this->bme680_settings_.trigger_measurement) {
232  this->bme680_.tph_sett.os_temp = this->bme680_settings_.temperature_oversampling;
233  this->bme680_.tph_sett.os_pres = this->bme680_settings_.pressure_oversampling;
234  this->bme680_.tph_sett.os_hum = this->bme680_settings_.humidity_oversampling;
235  this->bme680_.gas_sett.run_gas = this->bme680_settings_.run_gas;
236  this->bme680_.gas_sett.heatr_temp = this->bme680_settings_.heater_temperature;
237  this->bme680_.gas_sett.heatr_dur = this->bme680_settings_.heating_duration;
238  this->bme680_.power_mode = BME680_FORCED_MODE;
239  uint16_t desired_settings = BME680_OST_SEL | BME680_OSP_SEL | BME680_OSH_SEL | BME680_GAS_SENSOR_SEL;
240  this->bme680_status_ = bme680_set_sensor_settings(desired_settings, &this->bme680_);
241  if (this->bme680_status_ != BME680_OK) {
242  ESP_LOGW(TAG, "Failed to set sensor settings (BME680 Error Code %d)", this->bme680_status_);
243  return;
244  }
245 
246  this->bme680_status_ = bme680_set_sensor_mode(&this->bme680_);
247  if (this->bme680_status_ != BME680_OK) {
248  ESP_LOGW(TAG, "Failed to set sensor mode (BME680 Error Code %d)", this->bme680_status_);
249  return;
250  }
251 
252  uint16_t meas_dur = 0;
253  bme680_get_profile_dur(&meas_dur, &this->bme680_);
254 
255  // 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
256  // TODO: it would be interesting to see if this is really needed here, or if it's needed only after each
257  // bsec_do_steps() call
258  if (BME680BSECComponent::instances.size() > 1)
259  this->snapshot_state_();
260 
261  ESP_LOGV(TAG, "Queueing read in %ums", meas_dur);
262  this->set_timeout("read", meas_dur, [this]() { this->read_(); });
263  } else {
264  ESP_LOGV(TAG, "Measurement not required");
265  this->read_();
266  }
267 }
268 
270  ESP_LOGV(TAG, "%s: Reading data", this->device_id_.c_str());
271  int64_t curr_time_ns = this->get_time_ns_();
272 
273  if (this->bme680_settings_.trigger_measurement) {
274  while (this->bme680_.power_mode != BME680_SLEEP_MODE) {
275  this->bme680_status_ = bme680_get_sensor_mode(&this->bme680_);
276  if (this->bme680_status_ != BME680_OK) {
277  ESP_LOGW(TAG, "Failed to get sensor mode (BME680 Error Code %d)", this->bme680_status_);
278  }
279  }
280  }
281 
282  if (!this->bme680_settings_.process_data) {
283  ESP_LOGV(TAG, "Data processing not required");
284  return;
285  }
286 
287  struct bme680_field_data data;
288  this->bme680_status_ = bme680_get_sensor_data(&data, &this->bme680_);
289 
290  if (this->bme680_status_ != BME680_OK) {
291  ESP_LOGW(TAG, "Failed to get sensor data (BME680 Error Code %d)", this->bme680_status_);
292  return;
293  }
294  if (!(data.status & BME680_NEW_DATA_MSK)) {
295  ESP_LOGD(TAG, "BME680 did not report new data");
296  return;
297  }
298 
299  bsec_input_t inputs[BSEC_MAX_PHYSICAL_SENSOR]; // Temperature, Pressure, Humidity & Gas Resistance
300  uint8_t num_inputs = 0;
301 
302  if (this->bme680_settings_.process_data & BSEC_PROCESS_TEMPERATURE) {
303  inputs[num_inputs].sensor_id = BSEC_INPUT_TEMPERATURE;
304  inputs[num_inputs].signal = data.temperature / 100.0f;
305  inputs[num_inputs].time_stamp = curr_time_ns;
306  num_inputs++;
307 
308  // Temperature offset from the real temperature due to external heat sources
309  inputs[num_inputs].sensor_id = BSEC_INPUT_HEATSOURCE;
310  inputs[num_inputs].signal = this->temperature_offset_;
311  inputs[num_inputs].time_stamp = curr_time_ns;
312  num_inputs++;
313  }
314  if (this->bme680_settings_.process_data & BSEC_PROCESS_HUMIDITY) {
315  inputs[num_inputs].sensor_id = BSEC_INPUT_HUMIDITY;
316  inputs[num_inputs].signal = data.humidity / 1000.0f;
317  inputs[num_inputs].time_stamp = curr_time_ns;
318  num_inputs++;
319  }
320  if (this->bme680_settings_.process_data & BSEC_PROCESS_PRESSURE) {
321  inputs[num_inputs].sensor_id = BSEC_INPUT_PRESSURE;
322  inputs[num_inputs].signal = data.pressure;
323  inputs[num_inputs].time_stamp = curr_time_ns;
324  num_inputs++;
325  }
326  if (this->bme680_settings_.process_data & BSEC_PROCESS_GAS) {
327  if (data.status & BME680_GASM_VALID_MSK) {
328  inputs[num_inputs].sensor_id = BSEC_INPUT_GASRESISTOR;
329  inputs[num_inputs].signal = data.gas_resistance;
330  inputs[num_inputs].time_stamp = curr_time_ns;
331  num_inputs++;
332  } else {
333  ESP_LOGD(TAG, "BME680 did not report gas data");
334  }
335  }
336  if (num_inputs < 1) {
337  ESP_LOGD(TAG, "No signal inputs available for BSEC");
338  return;
339  }
340 
341  // Restore BSEC library state
342  // The reinit_bsec_lib_ method is computationally expensive: it takes 1200รท2900 microseconds on a ESP32.
343  // It can be skipped entirely when there is only one device (since the BSEC library won't be shared)
344  if (BME680BSECComponent::instances.size() > 1) {
345  int res = this->reinit_bsec_lib_();
346  if (res != 0)
347  return;
348  // Now that the BSEC library has been re-initialized, bsec_sensor_control *NEEDS* to be called in order to support
349  // multiple devices with a different set of enabled sensors (even if the bme680_settings_ data is not used)
350  this->bsec_status_ = bsec_sensor_control(curr_time_ns, &this->bme680_settings_);
351  if (this->bsec_status_ < BSEC_OK) {
352  ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC Error Code %d)", this->bsec_status_);
353  return;
354  }
355  }
356 
357  bsec_output_t outputs[BSEC_NUMBER_OUTPUTS];
358  uint8_t num_outputs = BSEC_NUMBER_OUTPUTS;
359  this->bsec_status_ = bsec_do_steps(inputs, num_inputs, outputs, &num_outputs);
360  if (this->bsec_status_ != BSEC_OK) {
361  ESP_LOGW(TAG, "BSEC failed to process signals (BSEC Error Code %d)", this->bsec_status_);
362  return;
363  }
364  ESP_LOGV(TAG, "%s: after bsec_do_steps: num_inputs=%d num_outputs=%d", this->device_id_.c_str(), num_inputs,
365  num_outputs);
366 
367  // 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
368  if (BME680BSECComponent::instances.size() > 1)
369  this->snapshot_state_();
370 
371  if (num_outputs < 1) {
372  ESP_LOGD(TAG, "No signal outputs provided by BSEC");
373  return;
374  }
375 
376  this->publish_(outputs, num_outputs);
377 }
378 
379 void BME680BSECComponent::publish_(const bsec_output_t *outputs, uint8_t num_outputs) {
380  ESP_LOGV(TAG, "%s: Queuing sensor state publish actions", this->device_id_.c_str());
381  for (uint8_t i = 0; i < num_outputs; i++) {
382  float signal = outputs[i].signal;
383  switch (outputs[i].sensor_id) {
384  case BSEC_OUTPUT_IAQ:
385  case BSEC_OUTPUT_STATIC_IAQ: {
386  uint8_t accuracy = outputs[i].accuracy;
387  this->queue_push_([this, signal]() { this->publish_sensor_(this->iaq_sensor_, signal); });
388  this->queue_push_([this, accuracy]() {
389  this->publish_sensor_(this->iaq_accuracy_text_sensor_, IAQ_ACCURACY_STATES[accuracy]);
390  });
391  this->queue_push_([this, accuracy]() { this->publish_sensor_(this->iaq_accuracy_sensor_, accuracy, true); });
392 
393  // Queue up an opportunity to save state
394  this->queue_push_([this, accuracy]() { this->save_state_(accuracy); });
395  } break;
396  case BSEC_OUTPUT_CO2_EQUIVALENT:
397  this->queue_push_([this, signal]() { this->publish_sensor_(this->co2_equivalent_sensor_, signal); });
398  break;
399  case BSEC_OUTPUT_BREATH_VOC_EQUIVALENT:
400  this->queue_push_([this, signal]() { this->publish_sensor_(this->breath_voc_equivalent_sensor_, signal); });
401  break;
402  case BSEC_OUTPUT_RAW_PRESSURE:
403  this->queue_push_([this, signal]() { this->publish_sensor_(this->pressure_sensor_, signal / 100.0f); });
404  break;
405  case BSEC_OUTPUT_RAW_GAS:
406  this->queue_push_([this, signal]() { this->publish_sensor_(this->gas_resistance_sensor_, signal); });
407  break;
408  case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE:
409  this->queue_push_([this, signal]() { this->publish_sensor_(this->temperature_sensor_, signal); });
410  break;
411  case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY:
412  this->queue_push_([this, signal]() { this->publish_sensor_(this->humidity_sensor_, signal); });
413  break;
414  }
415  }
416 }
417 
419  int64_t time_ms = millis();
420  if (this->last_time_ms_ > time_ms) {
421  this->millis_overflow_counter_++;
422  }
423  this->last_time_ms_ = time_ms;
424 
425  return (time_ms + ((int64_t) this->millis_overflow_counter_ << 32)) * INT64_C(1000000);
426 }
427 
428 void BME680BSECComponent::publish_sensor_(sensor::Sensor *sensor, float value, bool change_only) {
429  if (!sensor || (change_only && sensor->has_state() && sensor->state == value)) {
430  return;
431  }
432  sensor->publish_state(value);
433 }
434 
436  if (!sensor || (sensor->has_state() && sensor->state == value)) {
437  return;
438  }
439  sensor->publish_state(value);
440 }
441 
442 // Communication function - read
443 // First parameter is the "dev_id" member of our "bme680_" object, which is passed-back here as-is
444 int8_t BME680BSECComponent::read_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len) {
445  BME680BSECComponent *inst = instances[devid];
446  // Use the I2CDevice::read_bytes method to perform the actual I2C register read
447  return inst->read_bytes(a_register, data, len) ? 0 : -1;
448 }
449 
450 // Communication function - write
451 // First parameter is the "dev_id" member of our "bme680_" object, which is passed-back here as-is
452 int8_t BME680BSECComponent::write_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len) {
453  BME680BSECComponent *inst = instances[devid];
454  // Use the I2CDevice::write_bytes method to perform the actual I2C register write
455  return inst->write_bytes(a_register, data, len) ? 0 : -1;
456 }
457 
458 void BME680BSECComponent::delay_ms(uint32_t period) {
459  ESP_LOGV(TAG, "Delaying for %ums", period);
460  delay(period);
461 }
462 
463 // Fetch the BSEC library state and save it in the bsec_state_data_ member (volatile memory)
464 // Used to share the library when using more than one sensor
466  uint32_t num_serialized_state = BSEC_MAX_STATE_BLOB_SIZE;
467  this->bsec_status_ = bsec_get_state(0, this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_,
468  sizeof(this->work_buffer_), &num_serialized_state);
469  if (this->bsec_status_ != BSEC_OK) {
470  ESP_LOGW(TAG, "%s: Failed to fetch BSEC library state for snapshot (BSEC Error Code %d)", this->device_id_.c_str(),
471  this->bsec_status_);
472  return;
473  }
474  this->bsec_state_data_valid_ = true;
475 }
476 
477 // Restores the BSEC library state from a snapshot in memory
478 // Used to share the library when using more than one sensor
480  if (!this->bsec_state_data_valid_) {
481  ESP_LOGV(TAG, "%s: BSEC state data NOT valid, aborting restore_state_()", this->device_id_.c_str());
482  return;
483  }
484 
485  this->bsec_status_ =
486  bsec_set_state(this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
487  if (this->bsec_status_ != BSEC_OK) {
488  ESP_LOGW(TAG, "Failed to restore BSEC library state (BSEC Error Code %d)", this->bsec_status_);
489  return;
490  }
491 }
492 
494  this->bsec_status_ = bsec_init();
495  if (this->bsec_status_ != BSEC_OK) {
496  this->mark_failed();
497  return -1;
498  }
499 
500  this->set_config_();
501  if (this->bsec_status_ != BSEC_OK) {
502  this->mark_failed();
503  return -2;
504  }
505 
506  this->restore_state_();
507 
508  this->update_subscription_();
509  if (this->bsec_status_ != BSEC_OK) {
510  this->mark_failed();
511  return -3;
512  }
513 
514  return 0;
515 }
516 
518  uint32_t hash = fnv1_hash("bme680_bsec_state_" + this->device_id_);
519  this->bsec_state_ = global_preferences->make_preference<uint8_t[BSEC_MAX_STATE_BLOB_SIZE]>(hash, true);
520 
521  if (!this->bsec_state_.load(&this->bsec_state_data_)) {
522  // No saved BSEC library state available
523  return;
524  }
525 
526  ESP_LOGV(TAG, "%s: Loading BSEC library state", this->device_id_.c_str());
527  this->bsec_status_ =
528  bsec_set_state(this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
529  if (this->bsec_status_ != BSEC_OK) {
530  ESP_LOGW(TAG, "%s: Failed to load BSEC library state (BSEC Error Code %d)", this->device_id_.c_str(),
531  this->bsec_status_);
532  return;
533  }
534  // All OK: set the BSEC state data as valid
535  this->bsec_state_data_valid_ = true;
536  ESP_LOGI(TAG, "%s: Loaded BSEC library state", this->device_id_.c_str());
537 }
538 
539 void BME680BSECComponent::save_state_(uint8_t accuracy) {
540  if (accuracy < 3 || (millis() - this->last_state_save_ms_ < this->state_save_interval_ms_)) {
541  return;
542  }
543  if (BME680BSECComponent::instances.size() <= 1) {
544  // When a single device is in use, no snapshot is taken regularly so one is taken now
545  // On multiple devices, a snapshot is taken at every loop, so there is no need to take one here
546  this->snapshot_state_();
547  }
548  if (!this->bsec_state_data_valid_)
549  return;
550 
551  ESP_LOGV(TAG, "%s: Saving state", this->device_id_.c_str());
552 
553  if (!this->bsec_state_.save(&this->bsec_state_data_)) {
554  ESP_LOGW(TAG, "Failed to save state");
555  return;
556  }
557  this->last_state_save_ms_ = millis();
558 
559  ESP_LOGI(TAG, "Saved state");
560 }
561 #endif
562 } // namespace bme680_bsec
563 } // namespace esphome
text_sensor::TextSensor * iaq_accuracy_text_sensor_
Definition: bme680_bsec.h:130
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
void status_set_warning(const char *message="unspecified")
Definition: component.cpp:151
void queue_push_(std::function< void()> &&f)
Definition: bme680_bsec.h:95
void publish_(const bsec_output_t *outputs, uint8_t num_outputs)
bool is_failed() const
Definition: component.cpp:143
static void delay_ms(uint32_t period)
float calc_sensor_sample_rate_(SampleRate sample_rate)
Definition: bme680_bsec.cpp:85
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:69
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:212
static int8_t read_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len)
void publish_state(const std::string &state)
Definition: text_sensor.cpp:9
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
uint8_t bsec_state_data_[BSEC_MAX_STATE_BLOB_SIZE]
Definition: bme680_bsec.h:109
bool save(const T *src)
Definition: preferences.h:21
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:131
void status_set_error(const char *message="unspecified")
Definition: component.cpp:159
ESPPreferences * global_preferences
void status_clear_warning()
Definition: component.cpp:166
static std::vector< BME680BSECComponent * > instances
Definition: bme680_bsec.h:60
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
void status_clear_error()
Definition: component.cpp:172
std::string size_t len
Definition: helpers.h:292
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
static int8_t write_bytes_wrapper(uint8_t devid, uint8_t a_register, uint8_t *data, uint16_t len)
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:182
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
bool has_state() const
Return whether this sensor has gotten a full state (that passed through all filters) yet...
Definition: sensor.cpp:97
static uint8_t work_buffer_[BSEC_MAX_WORKBUFFER_SIZE]
Definition: bme680_bsec.h:97
Base-class for all sensors.
Definition: sensor.h:57
void publish_sensor_(sensor::Sensor *sensor, float value, bool change_only=false)
std::queue< std::function< void()> > queue_
Definition: bme680_bsec.h:106
esphome::sensor::Sensor * sensor
Definition: statsd.h:37
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:248