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.

344 lines
14 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 <Arduino.h>
  49. #include <bsec.h>
  50. #include "I2CSensor.h"
  51. // Available configuration modes based on parameters:
  52. // voltage / maximum time between sensor calls / time considered
  53. // for background calibration.
  54. #define BME680_BSEC_CONFIG_GENERIC_18V_3S_4D 0
  55. #define BME680_BSEC_CONFIG_GENERIC_18V_3S_28D 1
  56. #define BME680_BSEC_CONFIG_GENERIC_18V_300S_4D 2
  57. #define BME680_BSEC_CONFIG_GENERIC_18V_300S_28D 3
  58. #define BME680_BSEC_CONFIG_GENERIC_33V_3S_4D 4
  59. #define BME680_BSEC_CONFIG_GENERIC_33V_3S_28D 5
  60. #define BME680_BSEC_CONFIG_GENERIC_33V_300S_4D 6
  61. #define BME680_BSEC_CONFIG_GENERIC_33V_300S_28D 7
  62. const uint8_t bsec_config_iaq[] = {
  63. #if BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_3S_4D
  64. #include <config/generic_18v_3s_28d/bsec_iaq.txt>
  65. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_3S_28D
  66. #include <config/generic_18v_300s_4d/bsec_iaq.txt>
  67. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D
  68. #include <config/generic_18v_300s_28d/bsec_iaq.txt>
  69. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_28D
  70. #include <config/generic_33v_3s_4d/bsec_iaq.txt>
  71. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_3S_4D
  72. #include <config/generic_33v_3s_28d/bsec_iaq.txt>
  73. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_3S_28D
  74. #include <config/generic_33v_300s_4d/bsec_iaq.txt>
  75. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_300S_4D
  76. #include <config/generic_33v_300s_28d/bsec_iaq.txt>
  77. #elif BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_33V_300S_28D
  78. #include <config/generic_33v_3s_4d/bsec_iaq.txt>
  79. #endif
  80. };
  81. class BME680Sensor : public I2CSensor<> {
  82. public:
  83. // ---------------------------------------------------------------------
  84. // Public
  85. // ---------------------------------------------------------------------
  86. BME680Sensor() {
  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. #if SENSOR_DEBUG
  103. DEBUG_MSG("[BME680] BSEC library version v%u.%u.%u.%u\n",
  104. iaqSensor.version.major,
  105. iaqSensor.version.minor,
  106. iaqSensor.version.major_bugfix,
  107. iaqSensor.version.minor_bugfix
  108. );
  109. #endif
  110. if (!_isSensorOk()) {
  111. _error = SENSOR_ERROR_OTHER;
  112. return;
  113. }
  114. iaqSensor.setConfig(bsec_config_iaq);
  115. _loadState();
  116. float sampleRate;
  117. // BSEC configuration with 300s allows for the sensor to sleep for 300s
  118. // on the ULP mode in order to minimize power consumption.
  119. if (BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D ||
  120. BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D ||
  121. BME680_BSEC_CONFIG == BME680_BSEC_CONFIG_GENERIC_18V_300S_4D) {
  122. sampleRate = BSEC_SAMPLE_RATE_ULP;
  123. } else {
  124. sampleRate = BSEC_SAMPLE_RATE_LP;
  125. }
  126. iaqSensor.updateSubscription(sensorList, 12, sampleRate);
  127. if (!_isSensorOk()) {
  128. _error = SENSOR_ERROR_OTHER;
  129. return;
  130. }
  131. _ready = true;
  132. _dirty = false;
  133. }
  134. // Descriptive name of the sensor
  135. String description() {
  136. char buffer[21];
  137. snprintf(buffer, sizeof(buffer), "BME680 @ I2C (0x%02X)", _address);
  138. return String(buffer);
  139. }
  140. // Type for slot # index
  141. unsigned char type(unsigned char index) {
  142. if (index == 0) return MAGNITUDE_TEMPERATURE;
  143. if (index == 1) return MAGNITUDE_HUMIDITY;
  144. if (index == 2) return MAGNITUDE_PRESSURE;
  145. if (index == 3) return MAGNITUDE_RESISTANCE;
  146. if (index == 4) return MAGNITUDE_IAQ_ACCURACY;
  147. if (index == 5) return MAGNITUDE_IAQ;
  148. if (index == 6) return MAGNITUDE_IAQ_STATIC;
  149. if (index == 7) return MAGNITUDE_CO2;
  150. if (index == 8) return MAGNITUDE_VOC;
  151. return MAGNITUDE_NONE;
  152. }
  153. void _loadState() {
  154. String storedState = getSetting("bsecState");
  155. if (storedState.length() == 0) {
  156. #if SENSOR_DEBUG
  157. DEBUG_MSG("[BME680] Previous state not found\n");
  158. #endif
  159. return;
  160. }
  161. hexDecode(storedState.c_str(), storedState.length(), _bsecState, sizeof(_bsecState));
  162. iaqSensor.setState(_bsecState);
  163. #if SENSOR_DEBUG
  164. DEBUG_MSG("[BME680] Loaded previous state %s\n", storedState.c_str());
  165. #endif
  166. }
  167. void _saveState() {
  168. if (BME680_STATE_SAVE_INTERVAL == 0) {
  169. return;
  170. }
  171. static unsigned long last_millis = 0;
  172. if (_iaqAccuracy < 3 || (millis() - last_millis < BME680_STATE_SAVE_INTERVAL)) {
  173. return;
  174. }
  175. iaqSensor.getState(_bsecState);
  176. char storedState[BSEC_MAX_STATE_BLOB_SIZE * 2 + 1] = {0};
  177. hexEncode(_bsecState, BSEC_MAX_STATE_BLOB_SIZE, storedState, sizeof(storedState));
  178. setSetting("bsecState", storedState);
  179. last_millis = millis();
  180. }
  181. // The maximum allowed time between two `bsec_sensor_control` calls depends on
  182. // configuration profile `bsec_config_iaq` below.
  183. void tick() {
  184. _error = SENSOR_ERROR_OK;
  185. if (!_isSensorOk()) {
  186. _error = SENSOR_ERROR_OTHER;
  187. return;
  188. }
  189. if (iaqSensor.run()) {
  190. _rawTemperature = iaqSensor.rawTemperature;
  191. _rawHumidity = iaqSensor.rawHumidity;
  192. _temperature = iaqSensor.temperature;
  193. _humidity = iaqSensor.humidity;
  194. _pressure = iaqSensor.pressure / 100;
  195. _gasResistance = iaqSensor.gasResistance;
  196. _iaqAccuracy = iaqSensor.iaqAccuracy;
  197. _iaq = iaqSensor.iaq;
  198. _iaqStatic = iaqSensor.staticIaq;
  199. _co2Equivalent = iaqSensor.co2Equivalent;
  200. _breathVocEquivalent = iaqSensor.breathVocEquivalent;
  201. _saveState();
  202. }
  203. }
  204. // Current value for slot # index
  205. double value(unsigned char index) {
  206. if (index == 0) return _temperature;
  207. if (index == 1) return _humidity;
  208. if (index == 2) return _pressure;
  209. if (index == 3) return _gasResistance;
  210. if (index == 4) return _iaqAccuracy;
  211. if (index == 5) return _iaq;
  212. if (index == 6) return _iaqStatic;
  213. if (index == 7) return _co2Equivalent;
  214. if (index == 8) return _breathVocEquivalent;
  215. return 0;
  216. }
  217. protected:
  218. bool _isSensorOk() {
  219. if (iaqSensor.status == BSEC_OK && iaqSensor.bme680Status == BME680_OK) {
  220. return true;
  221. }
  222. #if SENSOR_DEBUG
  223. if (iaqSensor.status != BSEC_OK) {
  224. if (iaqSensor.status < BSEC_OK) {
  225. DEBUG_MSG("[BME680] BSEC error code %d\n", iaqSensor.status);
  226. } else {
  227. DEBUG_MSG("[BME680] BSEC warning code %d\n", iaqSensor.status);
  228. }
  229. }
  230. #endif
  231. #if SENSOR_DEBUG
  232. if (iaqSensor.bme680Status != BME680_OK) {
  233. if (iaqSensor.bme680Status < BME680_OK) {
  234. DEBUG_MSG("[BME680] Error code %d\n", iaqSensor.bme680Status);
  235. } else {
  236. DEBUG_MSG("[BME680] Warning code %d\n", iaqSensor.bme680Status);
  237. }
  238. }
  239. #endif
  240. return false;
  241. }
  242. bsec_virtual_sensor_t sensorList[12] = {
  243. BSEC_OUTPUT_RAW_TEMPERATURE, // Unscaled (raw) temperature (ºC).
  244. BSEC_OUTPUT_RAW_PRESSURE, // Unscaled (raw) pressure (Pa).
  245. BSEC_OUTPUT_RAW_HUMIDITY, // Unscaled (raw) relative humidity (%).
  246. BSEC_OUTPUT_RAW_GAS, // Gas resistance (Ohm). The resistance value changes according to the
  247. // VOC concentration (the higher the concentration of reducing VOCs,
  248. // the lower the resistance and vice versa).
  249. BSEC_OUTPUT_IAQ, // Scaled Indoor Air Quality based on the recent sensor history, ideal
  250. // for mobile applications (e.g. carry-on devices). The scale ranges from
  251. // 0 (clean air) to 500 (heavily polluted air). The automatic background
  252. // calibration process ensures that consistent IAQ performance is achieved
  253. // after certain of days (depending on BSEC configuration - 4d or 28d).
  254. BSEC_OUTPUT_STATIC_IAQ, // Unscaled Indoor Air Quality, optimized for stationary applications
  255. // (e.g. fixed indoor devices).
  256. BSEC_OUTPUT_CO2_EQUIVALENT, // Estimate of CO2 measured in the air.
  257. BSEC_OUTPUT_BREATH_VOC_EQUIVALENT, // Breath VOC represents the most important compounds in an exhaled
  258. // breath of healthy humans.
  259. BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE, // Temperature compensated for the influence of sensor heater (ºC).
  260. BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY, // Relative humidity compensated for the influence of sensor heater (%).
  261. BSEC_OUTPUT_STABILIZATION_STATUS, // Indicates initial stabilization status of the gas sensor element:
  262. // ongoing (0) or finished (1).
  263. BSEC_OUTPUT_RUN_IN_STATUS, // Indicates power-on stabilization status of the gas sensor element:
  264. // ongoing (0) or finished (1).
  265. };
  266. float _breathVocEquivalent = 0.0f;
  267. float _co2Equivalent = 0.0f;
  268. float _gasResistance = 0.0f;
  269. float _humidity = 0.0f;
  270. float _iaq = 0.0f;
  271. float _pressure = 0.0f;
  272. float _rawHumidity = 0.0f;
  273. float _rawTemperature = 0.0f;
  274. float _temperature = 0.0f;
  275. uint8_t _bsecState[BSEC_MAX_STATE_BLOB_SIZE] = {0};
  276. uint8_t _iaqAccuracy = 0;
  277. float _iaqStatic = 0;
  278. Bsec iaqSensor;
  279. };
  280. #endif // SENSOR_SUPPORT && BME680_SUPPORT