Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 lines
15 KiB

  1. // -----------------------------------------------------------------------------
  2. // BME680 Sensor over I2C
  3. // Copyright (C) 2020 by Rui Marinho <ruipmarinho at gmail dot com>
  4. //
  5. // The BSEC software binaries and includes are only available for use after accepting its software
  6. // license agreement. By enabling this sensor integration, you are agreeing to the terms of the license
  7. // agreement available at the following URL:
  8. //
  9. // https://ae-bst.resource.bosch.com/media/_tech/media/bsec/2017-07-17_ClickThrough_License_Terms_Environmentalib_SW_CLEAN.pdf
  10. //
  11. // The Arduino wrapper and BME680 Sensor API used for this integration are licensed under the following terms:
  12. //
  13. // Copyright (c) 2020 Bosch Sensortec GmbH. All rights reserved.
  14. //
  15. // BSD-3-Clause
  16. //
  17. // Redistribution and use in source and binary forms, with or without
  18. // modification, are permitted provided that the following conditions are met:
  19. //
  20. // 1. Redistributions of source code must retain the above copyright
  21. // notice, this list of conditions and the following disclaimer.
  22. //
  23. // 2. Redistributions in binary form must reproduce the above copyright
  24. // notice, this list of conditions and the following disclaimer in the
  25. // documentation and/or other materials provided with the distribution.
  26. //
  27. // 3. Neither the name of the copyright holder nor the names of its
  28. // contributors may be used to endorse or promote products derived from
  29. // this software without specific prior written permission.
  30. //
  31. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  32. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  33. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  34. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  35. // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  36. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  37. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  38. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  39. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  41. // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  42. // POSSIBILITY OF SUCH DAMAGE.
  43. //
  44. // For more details, please refer to https://github.com/BoschSensortec/BSEC-Arduino-library.
  45. // -----------------------------------------------------------------------------
  46. #if SENSOR_SUPPORT && BME680_SUPPORT
  47. #pragma once
  48. #include "I2CSensor.h"
  49. #include <bsec.h>
  50. // Available configuration modes based on parameters:
  51. // voltage / maximum time between sensor calls / time considered
  52. // for background calibration.
  53. #define BME680_BSEC_CONFIG_GENERIC_18V_3S_4D 0
  54. #define BME680_BSEC_CONFIG_GENERIC_18V_3S_28D 1
  55. #define BME680_BSEC_CONFIG_GENERIC_18V_300S_4D 2
  56. #define BME680_BSEC_CONFIG_GENERIC_18V_300S_28D 3
  57. #define BME680_BSEC_CONFIG_GENERIC_33V_3S_4D 4
  58. #define BME680_BSEC_CONFIG_GENERIC_33V_3S_28D 5
  59. #define BME680_BSEC_CONFIG_GENERIC_33V_300S_4D 6
  60. #define BME680_BSEC_CONFIG_GENERIC_33V_300S_28D 7
  61. const uint8_t bsec_config_iaq[] = {
  62. #if BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_3S_4D
  63. #include <config/generic_18v_3s_28d/bsec_iaq.txt>
  64. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_3S_28D
  65. #include <config/generic_18v_300s_4d/bsec_iaq.txt>
  66. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D
  67. #include <config/generic_18v_300s_28d/bsec_iaq.txt>
  68. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_28D
  69. #include <config/generic_33v_3s_4d/bsec_iaq.txt>
  70. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_3S_4D
  71. #include <config/generic_33v_3s_28d/bsec_iaq.txt>
  72. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_3S_28D
  73. #include <config/generic_33v_300s_4d/bsec_iaq.txt>
  74. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_300S_4D
  75. #include <config/generic_33v_300s_28d/bsec_iaq.txt>
  76. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_300S_28D
  77. #include <config/generic_33v_3s_4d/bsec_iaq.txt>
  78. #endif
  79. };
  80. class BME680Sensor : public I2CSensor<> {
  81. public:
  82. // ---------------------------------------------------------------------
  83. // Public
  84. // ---------------------------------------------------------------------
  85. BME680Sensor() {
  86. _error = SENSOR_ERROR_OK;
  87. _sensor_id = SENSOR_BME680_ID;
  88. _count = 9;
  89. }
  90. // ---------------------------------------------------------------------
  91. // Sensor API
  92. // ---------------------------------------------------------------------
  93. void begin() {
  94. if (!_dirty) {
  95. return;
  96. }
  97. // I2C auto-discover
  98. unsigned char addresses[] = {BME680_I2C_ADDR_PRIMARY, BME680_I2C_ADDR_SECONDARY};
  99. _address = _begin_i2c(_address, sizeof(addresses), addresses);
  100. if (_address == 0) return;
  101. iaqSensor.begin(_address, Wire);
  102. DEBUG_MSG_P(PSTR("[BME680] BSEC library version v%u.%u.%u.%u\n"),
  103. iaqSensor.version.major,
  104. iaqSensor.version.minor,
  105. iaqSensor.version.major_bugfix,
  106. iaqSensor.version.minor_bugfix
  107. );
  108. if (!_isOk()) {
  109. _showSensorErrors();
  110. _error = SENSOR_ERROR_OTHER;
  111. return;
  112. }
  113. iaqSensor.setConfig(bsec_config_iaq);
  114. _loadState();
  115. float sampleRate;
  116. // BSEC configuration with 300s allows for the sensor to sleep for 300s
  117. // on the ULP mode in order to minimize power consumption.
  118. if (BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D ||
  119. BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D ||
  120. BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D) {
  121. sampleRate = BSEC_SAMPLE_RATE_ULP;
  122. } else {
  123. sampleRate = BSEC_SAMPLE_RATE_LP;
  124. }
  125. iaqSensor.updateSubscription(sensorList, 12, sampleRate);
  126. if (!_isOk()) {
  127. _showSensorErrors();
  128. _error = SENSOR_ERROR_OTHER;
  129. return;
  130. }
  131. _error = SENSOR_ERROR_OK;
  132. _ready = true;
  133. _dirty = false;
  134. }
  135. // Descriptive name of the sensor
  136. String description() {
  137. char buffer[21];
  138. snprintf(buffer, sizeof(buffer), "BME680 @ I2C (0x%02X)", _address);
  139. return String(buffer);
  140. }
  141. // Type for slot # index
  142. unsigned char type(unsigned char index) {
  143. if (index == 0) return MAGNITUDE_TEMPERATURE;
  144. if (index == 1) return MAGNITUDE_HUMIDITY;
  145. if (index == 2) return MAGNITUDE_PRESSURE;
  146. if (index == 3) return MAGNITUDE_RESISTANCE;
  147. if (index == 4) return MAGNITUDE_IAQ_ACCURACY;
  148. if (index == 5) return MAGNITUDE_IAQ;
  149. if (index == 6) return MAGNITUDE_IAQ_STATIC;
  150. if (index == 7) return MAGNITUDE_CO2;
  151. if (index == 8) return MAGNITUDE_VOC;
  152. return MAGNITUDE_NONE;
  153. }
  154. // The maximum allowed time between two `bsec_sensor_control` calls depends on
  155. // configuration profile `bsec_config_iaq` below.
  156. void tick() {
  157. if (iaqSensor.run()) {
  158. _rawTemperature = iaqSensor.rawTemperature;
  159. _rawHumidity = iaqSensor.rawHumidity;
  160. _temperature = iaqSensor.temperature;
  161. _humidity = iaqSensor.humidity;
  162. _pressure = iaqSensor.pressure / 100;
  163. _gasResistance = iaqSensor.gasResistance;
  164. _iaqAccuracy = iaqSensor.iaqAccuracy;
  165. _iaq = iaqSensor.iaq;
  166. _iaqStatic = iaqSensor.staticIaq;
  167. _co2Equivalent = iaqSensor.co2Equivalent;
  168. _breathVocEquivalent = iaqSensor.breathVocEquivalent;
  169. _saveState();
  170. _error = SENSOR_ERROR_OK;
  171. } else if (_isError()) {
  172. _error = SENSOR_ERROR_OTHER;
  173. }
  174. }
  175. // Ensure we show any possible issues with the sensor, post() is called regardless of sensor status() / error() codes
  176. void post() override {
  177. _showSensorErrors();
  178. }
  179. // Current value for slot # index
  180. double value(unsigned char index) {
  181. if (index == 0) return _temperature;
  182. if (index == 1) return _humidity;
  183. if (index == 2) return _pressure;
  184. if (index == 3) return _gasResistance;
  185. if (index == 4) return _iaqAccuracy;
  186. if (index == 5) return _iaq;
  187. if (index == 6) return _iaqStatic;
  188. if (index == 7) return _co2Equivalent;
  189. if (index == 8) return _breathVocEquivalent;
  190. return 0;
  191. }
  192. protected:
  193. void _loadState() {
  194. String storedState = getSetting("bsecState");
  195. if (!storedState.length()) {
  196. return;
  197. }
  198. DEBUG_MSG_P(PSTR("[BME680] Restoring previous state\n"));
  199. hexDecode(storedState.c_str(), storedState.length(), _bsecState, sizeof(_bsecState));
  200. iaqSensor.setState(_bsecState);
  201. _showSensorErrors();
  202. }
  203. void _saveState() {
  204. if (!BME680_STATE_SAVE_INTERVAL) return;
  205. static unsigned long last_millis = 0;
  206. if (_iaqAccuracy < 3 || (millis() - last_millis < BME680_STATE_SAVE_INTERVAL)) {
  207. return;
  208. }
  209. iaqSensor.getState(_bsecState);
  210. char storedState[BSEC_MAX_STATE_BLOB_SIZE * 2 + 1] = {0};
  211. hexEncode(_bsecState, BSEC_MAX_STATE_BLOB_SIZE, storedState, sizeof(storedState));
  212. setSetting("bsecState", storedState);
  213. last_millis = millis();
  214. }
  215. bool _isError() {
  216. return (iaqSensor.status < BSEC_OK) || (iaqSensor.bme680Status < BME680_OK);
  217. }
  218. bool _isOk() {
  219. return (iaqSensor.status == BSEC_OK) && (iaqSensor.bme680Status == BME680_OK);
  220. }
  221. void _showSensorErrors() {
  222. // see `enum { ... } bsec_library_return_t` values & description at:
  223. // BSEC Software Library/src/inc/bsec_datatypes.h
  224. if (iaqSensor.status != BSEC_OK) {
  225. if (iaqSensor.status < BSEC_OK) {
  226. DEBUG_MSG_P(PSTR("[BME680] BSEC error code (%d)\n"), iaqSensor.status);
  227. } else {
  228. DEBUG_MSG_P(PSTR("[BME680] BSEC warning code (%d)\n"), iaqSensor.status);
  229. }
  230. }
  231. // see `BME680_{W,E}_...` at:
  232. // BSEC Software Library/src/bme680/bme680_defs.h
  233. switch (iaqSensor.bme680Status) {
  234. case BME680_OK:
  235. break;
  236. case BME680_E_COM_FAIL:
  237. case BME680_E_DEV_NOT_FOUND:
  238. DEBUG_MSG_P(PSTR("[BME680] Communication error / device not found (%d)\n"), iaqSensor.bme680Status);
  239. case BME680_W_DEFINE_PWR_MODE:
  240. DEBUG_MSG_P(PSTR("[BME680] Power mode not defined (%d)\n"), iaqSensor.bme680Status);
  241. break;
  242. case BME680_W_NO_NEW_DATA:
  243. DEBUG_MSG_P(PSTR("[BME680] No new data (%d)\n"), iaqSensor.bme680Status);
  244. break;
  245. default:
  246. if (iaqSensor.bme680Status < BME680_OK) {
  247. DEBUG_MSG_P(PSTR("[BME680] Error code (%d)\n"), iaqSensor.bme680Status);
  248. } else {
  249. DEBUG_MSG_P(PSTR("[BME680] Warning code (%d)\n"), iaqSensor.bme680Status);
  250. }
  251. break;
  252. }
  253. }
  254. bsec_virtual_sensor_t sensorList[12] = {
  255. BSEC_OUTPUT_RAW_TEMPERATURE, // Unscaled (raw) temperature (ºC).
  256. BSEC_OUTPUT_RAW_PRESSURE, // Unscaled (raw) pressure (Pa).
  257. BSEC_OUTPUT_RAW_HUMIDITY, // Unscaled (raw) relative humidity (%).
  258. BSEC_OUTPUT_RAW_GAS, // Gas resistance (Ohm). The resistance value changes according to the
  259. // VOC concentration (the higher the concentration of reducing VOCs,
  260. // the lower the resistance and vice versa).
  261. BSEC_OUTPUT_IAQ, // Scaled Indoor Air Quality based on the recent sensor history, ideal
  262. // for mobile applications (e.g. carry-on devices). The scale ranges from
  263. // 0 (clean air) to 500 (heavily polluted air). The automatic background
  264. // calibration process ensures that consistent IAQ performance is achieved
  265. // after certain of days (depending on BSEC configuration - 4d or 28d).
  266. BSEC_OUTPUT_STATIC_IAQ, // Unscaled Indoor Air Quality, optimized for stationary applications
  267. // (e.g. fixed indoor devices).
  268. BSEC_OUTPUT_CO2_EQUIVALENT, // Estimate of CO2 measured in the air.
  269. BSEC_OUTPUT_BREATH_VOC_EQUIVALENT, // Breath VOC represents the most important compounds in an exhaled
  270. // breath of healthy humans.
  271. BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE, // Temperature compensated for the influence of sensor heater (ºC).
  272. BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY, // Relative humidity compensated for the influence of sensor heater (%).
  273. BSEC_OUTPUT_STABILIZATION_STATUS, // Indicates initial stabilization status of the gas sensor element:
  274. // ongoing (0) or finished (1).
  275. BSEC_OUTPUT_RUN_IN_STATUS, // Indicates power-on stabilization status of the gas sensor element:
  276. // ongoing (0) or finished (1).
  277. };
  278. float _breathVocEquivalent = 0.0f;
  279. float _co2Equivalent = 0.0f;
  280. float _gasResistance = 0.0f;
  281. float _humidity = 0.0f;
  282. float _iaq = 0.0f;
  283. float _pressure = 0.0f;
  284. float _rawHumidity = 0.0f;
  285. float _rawTemperature = 0.0f;
  286. float _temperature = 0.0f;
  287. uint8_t _bsecState[BSEC_MAX_STATE_BLOB_SIZE] = {0};
  288. uint8_t _iaqAccuracy = 0;
  289. float _iaqStatic = 0;
  290. Bsec iaqSensor;
  291. };
  292. #endif // SENSOR_SUPPORT && BME680_SUPPORT