ESPHome  2022.12.8
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 BME680BSECComponent *BME680BSECComponent::instance; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
14 
16  ESP_LOGCONFIG(TAG, "Setting up BME680 via BSEC...");
17  BME680BSECComponent::instance = this;
18 
19  this->bsec_status_ = bsec_init();
20  if (this->bsec_status_ != BSEC_OK) {
21  this->mark_failed();
22  return;
23  }
24 
25  this->bme680_.dev_id = this->address_;
26  this->bme680_.intf = BME680_I2C_INTF;
29  this->bme680_.delay_ms = BME680BSECComponent::delay_ms;
30  this->bme680_.amb_temp = 25;
31 
32  this->bme680_status_ = bme680_init(&this->bme680_);
33  if (this->bme680_status_ != BME680_OK) {
34  this->mark_failed();
35  return;
36  }
37 
38  if (this->sample_rate_ == SAMPLE_RATE_ULP) {
39  const uint8_t bsec_config[] = {
40 #include "config/generic_33v_300s_28d/bsec_iaq.txt"
41  };
42  this->set_config_(bsec_config);
43  } else {
44  const uint8_t bsec_config[] = {
45 #include "config/generic_33v_3s_28d/bsec_iaq.txt"
46  };
47  this->set_config_(bsec_config);
48  }
49  this->update_subscription_();
50  if (this->bsec_status_ != BSEC_OK) {
51  this->mark_failed();
52  return;
53  }
54 
55  this->load_state_();
56 }
57 
58 void BME680BSECComponent::set_config_(const uint8_t *config) {
59  uint8_t work_buffer[BSEC_MAX_WORKBUFFER_SIZE];
60  this->bsec_status_ = bsec_set_configuration(config, BSEC_MAX_PROPERTY_BLOB_SIZE, work_buffer, sizeof(work_buffer));
61 }
62 
64  if (sample_rate == SAMPLE_RATE_DEFAULT) {
65  sample_rate = this->sample_rate_;
66  }
67  return sample_rate == SAMPLE_RATE_ULP ? BSEC_SAMPLE_RATE_ULP : BSEC_SAMPLE_RATE_LP;
68 }
69 
71  bsec_sensor_configuration_t virtual_sensors[BSEC_NUMBER_OUTPUTS];
72  int num_virtual_sensors = 0;
73 
74  if (this->iaq_sensor_) {
75  virtual_sensors[num_virtual_sensors].sensor_id =
76  this->iaq_mode_ == IAQ_MODE_STATIC ? BSEC_OUTPUT_STATIC_IAQ : BSEC_OUTPUT_IAQ;
77  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
78  num_virtual_sensors++;
79  }
80 
81  if (this->co2_equivalent_sensor_) {
82  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_CO2_EQUIVALENT;
83  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
84  num_virtual_sensors++;
85  }
86 
88  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_BREATH_VOC_EQUIVALENT;
89  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
90  num_virtual_sensors++;
91  }
92 
93  if (this->pressure_sensor_) {
94  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_RAW_PRESSURE;
95  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->pressure_sample_rate_);
96  num_virtual_sensors++;
97  }
98 
99  if (this->gas_resistance_sensor_) {
100  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_RAW_GAS;
101  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(SAMPLE_RATE_DEFAULT);
102  num_virtual_sensors++;
103  }
104 
105  if (this->temperature_sensor_) {
106  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE;
107  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->temperature_sample_rate_);
108  num_virtual_sensors++;
109  }
110 
111  if (this->humidity_sensor_) {
112  virtual_sensors[num_virtual_sensors].sensor_id = BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY;
113  virtual_sensors[num_virtual_sensors].sample_rate = this->calc_sensor_sample_rate_(this->humidity_sample_rate_);
114  num_virtual_sensors++;
115  }
116 
117  bsec_sensor_configuration_t sensor_settings[BSEC_MAX_PHYSICAL_SENSOR];
118  uint8_t num_sensor_settings = BSEC_MAX_PHYSICAL_SENSOR;
119  this->bsec_status_ =
120  bsec_update_subscription(virtual_sensors, num_virtual_sensors, sensor_settings, &num_sensor_settings);
121 }
122 
124  ESP_LOGCONFIG(TAG, "BME680 via BSEC:");
125 
126  bsec_version_t version;
127  bsec_get_version(&version);
128  ESP_LOGCONFIG(TAG, " BSEC Version: %d.%d.%d.%d", version.major, version.minor, version.major_bugfix,
129  version.minor_bugfix);
130 
131  LOG_I2C_DEVICE(this);
132 
133  if (this->is_failed()) {
134  ESP_LOGE(TAG, "Communication failed (BSEC Status: %d, BME680 Status: %d)", this->bsec_status_,
135  this->bme680_status_);
136  }
137 
138  ESP_LOGCONFIG(TAG, " Temperature Offset: %.2f", this->temperature_offset_);
139  ESP_LOGCONFIG(TAG, " IAQ Mode: %s", this->iaq_mode_ == IAQ_MODE_STATIC ? "Static" : "Mobile");
140  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->sample_rate_));
141  ESP_LOGCONFIG(TAG, " State Save Interval: %ims", this->state_save_interval_ms_);
142 
143  LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
144  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->temperature_sample_rate_));
145  LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
146  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->pressure_sample_rate_));
147  LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
148  ESP_LOGCONFIG(TAG, " Sample Rate: %s", BME680_BSEC_SAMPLE_RATE_LOG(this->humidity_sample_rate_));
149  LOG_SENSOR(" ", "Gas Resistance", this->gas_resistance_sensor_);
150  LOG_SENSOR(" ", "IAQ", this->iaq_sensor_);
151  LOG_SENSOR(" ", "Numeric IAQ Accuracy", this->iaq_accuracy_sensor_);
152  LOG_TEXT_SENSOR(" ", "IAQ Accuracy", this->iaq_accuracy_text_sensor_);
153  LOG_SENSOR(" ", "CO2 Equivalent", this->co2_equivalent_sensor_);
154  LOG_SENSOR(" ", "Breath VOC Equivalent", this->breath_voc_equivalent_sensor_);
155 }
156 
158 
160  this->run_();
161 
162  if (this->bsec_status_ < BSEC_OK || this->bme680_status_ < BME680_OK) {
163  this->status_set_error();
164  } else {
165  this->status_clear_error();
166  }
167  if (this->bsec_status_ > BSEC_OK || this->bme680_status_ > BME680_OK) {
168  this->status_set_warning();
169  } else {
170  this->status_clear_warning();
171  }
172 
173  // Process a single action from the queue. These are primarily sensor state publishes
174  // that in totality take too long to send in a single call.
175  if (this->queue_.size()) {
176  auto action = std::move(this->queue_.front());
177  this->queue_.pop();
178  action();
179  }
180 }
181 
183  int64_t curr_time_ns = this->get_time_ns_();
184  if (curr_time_ns < this->next_call_ns_) {
185  return;
186  }
187 
188  ESP_LOGV(TAG, "Performing sensor run");
189 
190  bsec_bme_settings_t bme680_settings;
191  this->bsec_status_ = bsec_sensor_control(curr_time_ns, &bme680_settings);
192  if (this->bsec_status_ < BSEC_OK) {
193  ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC Error Code %d)", this->bsec_status_);
194  return;
195  }
196  this->next_call_ns_ = bme680_settings.next_call;
197 
198  if (bme680_settings.trigger_measurement) {
199  this->bme680_.tph_sett.os_temp = bme680_settings.temperature_oversampling;
200  this->bme680_.tph_sett.os_pres = bme680_settings.pressure_oversampling;
201  this->bme680_.tph_sett.os_hum = bme680_settings.humidity_oversampling;
202  this->bme680_.gas_sett.run_gas = bme680_settings.run_gas;
203  this->bme680_.gas_sett.heatr_temp = bme680_settings.heater_temperature;
204  this->bme680_.gas_sett.heatr_dur = bme680_settings.heating_duration;
205  this->bme680_.power_mode = BME680_FORCED_MODE;
206  uint16_t desired_settings = BME680_OST_SEL | BME680_OSP_SEL | BME680_OSH_SEL | BME680_GAS_SENSOR_SEL;
207  this->bme680_status_ = bme680_set_sensor_settings(desired_settings, &this->bme680_);
208  if (this->bme680_status_ != BME680_OK) {
209  ESP_LOGW(TAG, "Failed to set sensor settings (BME680 Error Code %d)", this->bme680_status_);
210  return;
211  }
212 
213  this->bme680_status_ = bme680_set_sensor_mode(&this->bme680_);
214  if (this->bme680_status_ != BME680_OK) {
215  ESP_LOGW(TAG, "Failed to set sensor mode (BME680 Error Code %d)", this->bme680_status_);
216  return;
217  }
218 
219  uint16_t meas_dur = 0;
220  bme680_get_profile_dur(&meas_dur, &this->bme680_);
221  ESP_LOGV(TAG, "Queueing read in %ums", meas_dur);
222  this->set_timeout("read", meas_dur,
223  [this, curr_time_ns, bme680_settings]() { this->read_(curr_time_ns, bme680_settings); });
224  } else {
225  ESP_LOGV(TAG, "Measurement not required");
226  this->read_(curr_time_ns, bme680_settings);
227  }
228 }
229 
230 void BME680BSECComponent::read_(int64_t trigger_time_ns, bsec_bme_settings_t bme680_settings) {
231  ESP_LOGV(TAG, "Reading data");
232 
233  if (bme680_settings.trigger_measurement) {
234  while (this->bme680_.power_mode != BME680_SLEEP_MODE) {
235  this->bme680_status_ = bme680_get_sensor_mode(&this->bme680_);
236  if (this->bme680_status_ != BME680_OK) {
237  ESP_LOGW(TAG, "Failed to get sensor mode (BME680 Error Code %d)", this->bme680_status_);
238  }
239  }
240  }
241 
242  if (!bme680_settings.process_data) {
243  ESP_LOGV(TAG, "Data processing not required");
244  return;
245  }
246 
247  struct bme680_field_data data;
248  this->bme680_status_ = bme680_get_sensor_data(&data, &this->bme680_);
249 
250  if (this->bme680_status_ != BME680_OK) {
251  ESP_LOGW(TAG, "Failed to get sensor data (BME680 Error Code %d)", this->bme680_status_);
252  return;
253  }
254  if (!(data.status & BME680_NEW_DATA_MSK)) {
255  ESP_LOGD(TAG, "BME680 did not report new data");
256  return;
257  }
258 
259  bsec_input_t inputs[BSEC_MAX_PHYSICAL_SENSOR]; // Temperature, Pressure, Humidity & Gas Resistance
260  uint8_t num_inputs = 0;
261 
262  if (bme680_settings.process_data & BSEC_PROCESS_TEMPERATURE) {
263  inputs[num_inputs].sensor_id = BSEC_INPUT_TEMPERATURE;
264  inputs[num_inputs].signal = data.temperature / 100.0f;
265  inputs[num_inputs].time_stamp = trigger_time_ns;
266  num_inputs++;
267 
268  // Temperature offset from the real temperature due to external heat sources
269  inputs[num_inputs].sensor_id = BSEC_INPUT_HEATSOURCE;
270  inputs[num_inputs].signal = this->temperature_offset_;
271  inputs[num_inputs].time_stamp = trigger_time_ns;
272  num_inputs++;
273  }
274  if (bme680_settings.process_data & BSEC_PROCESS_HUMIDITY) {
275  inputs[num_inputs].sensor_id = BSEC_INPUT_HUMIDITY;
276  inputs[num_inputs].signal = data.humidity / 1000.0f;
277  inputs[num_inputs].time_stamp = trigger_time_ns;
278  num_inputs++;
279  }
280  if (bme680_settings.process_data & BSEC_PROCESS_PRESSURE) {
281  inputs[num_inputs].sensor_id = BSEC_INPUT_PRESSURE;
282  inputs[num_inputs].signal = data.pressure;
283  inputs[num_inputs].time_stamp = trigger_time_ns;
284  num_inputs++;
285  }
286  if (bme680_settings.process_data & BSEC_PROCESS_GAS) {
287  if (data.status & BME680_GASM_VALID_MSK) {
288  inputs[num_inputs].sensor_id = BSEC_INPUT_GASRESISTOR;
289  inputs[num_inputs].signal = data.gas_resistance;
290  inputs[num_inputs].time_stamp = trigger_time_ns;
291  num_inputs++;
292  } else {
293  ESP_LOGD(TAG, "BME680 did not report gas data");
294  }
295  }
296  if (num_inputs < 1) {
297  ESP_LOGD(TAG, "No signal inputs available for BSEC");
298  return;
299  }
300 
301  bsec_output_t outputs[BSEC_NUMBER_OUTPUTS];
302  uint8_t num_outputs = BSEC_NUMBER_OUTPUTS;
303  this->bsec_status_ = bsec_do_steps(inputs, num_inputs, outputs, &num_outputs);
304  if (this->bsec_status_ != BSEC_OK) {
305  ESP_LOGW(TAG, "BSEC failed to process signals (BSEC Error Code %d)", this->bsec_status_);
306  return;
307  }
308  if (num_outputs < 1) {
309  ESP_LOGD(TAG, "No signal outputs provided by BSEC");
310  return;
311  }
312 
313  this->publish_(outputs, num_outputs);
314 }
315 
316 void BME680BSECComponent::publish_(const bsec_output_t *outputs, uint8_t num_outputs) {
317  ESP_LOGV(TAG, "Queuing sensor state publish actions");
318  for (uint8_t i = 0; i < num_outputs; i++) {
319  float signal = outputs[i].signal;
320  switch (outputs[i].sensor_id) {
321  case BSEC_OUTPUT_IAQ:
322  case BSEC_OUTPUT_STATIC_IAQ: {
323  uint8_t accuracy = outputs[i].accuracy;
324  this->queue_push_([this, signal]() { this->publish_sensor_(this->iaq_sensor_, signal); });
325  this->queue_push_([this, accuracy]() {
326  this->publish_sensor_(this->iaq_accuracy_text_sensor_, IAQ_ACCURACY_STATES[accuracy]);
327  });
328  this->queue_push_([this, accuracy]() { this->publish_sensor_(this->iaq_accuracy_sensor_, accuracy, true); });
329 
330  // Queue up an opportunity to save state
331  this->queue_push_([this, accuracy]() { this->save_state_(accuracy); });
332  } break;
333  case BSEC_OUTPUT_CO2_EQUIVALENT:
334  this->queue_push_([this, signal]() { this->publish_sensor_(this->co2_equivalent_sensor_, signal); });
335  break;
336  case BSEC_OUTPUT_BREATH_VOC_EQUIVALENT:
337  this->queue_push_([this, signal]() { this->publish_sensor_(this->breath_voc_equivalent_sensor_, signal); });
338  break;
339  case BSEC_OUTPUT_RAW_PRESSURE:
340  this->queue_push_([this, signal]() { this->publish_sensor_(this->pressure_sensor_, signal / 100.0f); });
341  break;
342  case BSEC_OUTPUT_RAW_GAS:
343  this->queue_push_([this, signal]() { this->publish_sensor_(this->gas_resistance_sensor_, signal); });
344  break;
345  case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE:
346  this->queue_push_([this, signal]() { this->publish_sensor_(this->temperature_sensor_, signal); });
347  break;
348  case BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY:
349  this->queue_push_([this, signal]() { this->publish_sensor_(this->humidity_sensor_, signal); });
350  break;
351  }
352  }
353 }
354 
356  int64_t time_ms = millis();
357  if (this->last_time_ms_ > time_ms) {
358  this->millis_overflow_counter_++;
359  }
360  this->last_time_ms_ = time_ms;
361 
362  return (time_ms + ((int64_t) this->millis_overflow_counter_ << 32)) * INT64_C(1000000);
363 }
364 
365 void BME680BSECComponent::publish_sensor_(sensor::Sensor *sensor, float value, bool change_only) {
366  if (!sensor || (change_only && sensor->has_state() && sensor->state == value)) {
367  return;
368  }
369  sensor->publish_state(value);
370 }
371 
372 void BME680BSECComponent::publish_sensor_(text_sensor::TextSensor *sensor, const std::string &value) {
373  if (!sensor || (sensor->has_state() && sensor->state == value)) {
374  return;
375  }
376  sensor->publish_state(value);
377 }
378 
379 int8_t BME680BSECComponent::read_bytes_wrapper(uint8_t address, uint8_t a_register, uint8_t *data, uint16_t len) {
380  return BME680BSECComponent::instance->read_bytes(a_register, data, len) ? 0 : -1;
381 }
382 
383 int8_t BME680BSECComponent::write_bytes_wrapper(uint8_t address, uint8_t a_register, uint8_t *data, uint16_t len) {
384  return BME680BSECComponent::instance->write_bytes(a_register, data, len) ? 0 : -1;
385 }
386 
387 void BME680BSECComponent::delay_ms(uint32_t period) {
388  ESP_LOGV(TAG, "Delaying for %ums", period);
389  delay(period);
390 }
391 
393  uint32_t hash = fnv1_hash("bme680_bsec_state_" + to_string(this->address_));
394  this->bsec_state_ = global_preferences->make_preference<uint8_t[BSEC_MAX_STATE_BLOB_SIZE]>(hash, true);
395 
396  uint8_t state[BSEC_MAX_STATE_BLOB_SIZE];
397  if (this->bsec_state_.load(&state)) {
398  ESP_LOGV(TAG, "Loading state");
399  uint8_t work_buffer[BSEC_MAX_WORKBUFFER_SIZE];
400  this->bsec_status_ = bsec_set_state(state, BSEC_MAX_STATE_BLOB_SIZE, work_buffer, sizeof(work_buffer));
401  if (this->bsec_status_ != BSEC_OK) {
402  ESP_LOGW(TAG, "Failed to load state (BSEC Error Code %d)", this->bsec_status_);
403  }
404  ESP_LOGI(TAG, "Loaded state");
405  }
406 }
407 
408 void BME680BSECComponent::save_state_(uint8_t accuracy) {
409  if (accuracy < 3 || (millis() - this->last_state_save_ms_ < this->state_save_interval_ms_)) {
410  return;
411  }
412 
413  ESP_LOGV(TAG, "Saving state");
414 
415  uint8_t state[BSEC_MAX_STATE_BLOB_SIZE];
416  uint8_t work_buffer[BSEC_MAX_STATE_BLOB_SIZE];
417  uint32_t num_serialized_state = BSEC_MAX_STATE_BLOB_SIZE;
418 
419  this->bsec_status_ =
420  bsec_get_state(0, state, BSEC_MAX_STATE_BLOB_SIZE, work_buffer, BSEC_MAX_STATE_BLOB_SIZE, &num_serialized_state);
421  if (this->bsec_status_ != BSEC_OK) {
422  ESP_LOGW(TAG, "Failed fetch state for save (BSEC Error Code %d)", this->bsec_status_);
423  return;
424  }
425 
426  if (!this->bsec_state_.save(&state)) {
427  ESP_LOGW(TAG, "Failed to save state");
428  return;
429  }
430  this->last_state_save_ms_ = millis();
431 
432  ESP_LOGI(TAG, "Saved state");
433 }
434 #endif
435 } // namespace bme680_bsec
436 } // namespace esphome
text_sensor::TextSensor * iaq_accuracy_text_sensor_
Definition: bme680_bsec.h:108
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:18
static int8_t write_bytes_wrapper(uint8_t address, uint8_t a_register, uint8_t *data, uint16_t len)
void queue_push_(std::function< void()> &&f)
Definition: bme680_bsec.h:79
void publish_(const bsec_output_t *outputs, uint8_t num_outputs)
static void delay_ms(uint32_t period)
float calc_sensor_sample_rate_(SampleRate sample_rate)
Definition: bme680_bsec.cpp:63
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:68
static BME680BSECComponent * instance
Definition: bme680_bsec.h:53
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Definition: i2c.h:68
void publish_state(const std::string &state)
Definition: text_sensor.cpp:12
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:26
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:135
void set_config_(const uint8_t *config)
Definition: bme680_bsec.cpp:58
static int8_t read_bytes_wrapper(uint8_t address, uint8_t a_register, uint8_t *data, uint16_t len)
ESPPreferences * global_preferences
void status_clear_warning()
Definition: component.cpp:149
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:72
void status_set_warning()
Definition: component.cpp:141
uint8_t address_
Definition: i2c.h:130
void status_clear_error()
Definition: component.cpp:150
void read_(int64_t trigger_time_ns, bsec_bme_settings_t bme680_settings)
std::string to_string(int value)
Definition: helpers.cpp:42
std::string size_t len
Definition: helpers.h:281
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:86
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:112
Definition: a4988.cpp:4
bool has_state() const
Return whether this sensor has gotten a full state (that passed through all filters) yet...
Definition: sensor.cpp:130
Base-class for all sensors.
Definition: sensor.h:50
void publish_sensor_(sensor::Sensor *sensor, float value, bool change_only=false)
std::queue< std::function< void()> > queue_
Definition: bme680_bsec.h:89
bool state
Definition: fan.h:34
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:27
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:109