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.

2902 lines
85 KiB

3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
7 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
6 years ago
7 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "sensor.h"
  6. #if SENSOR_SUPPORT
  7. #include "api.h"
  8. #include "domoticz.h"
  9. #include "i2c.h"
  10. #include "mqtt.h"
  11. #include "ntp.h"
  12. #include "relay.h"
  13. #include "terminal.h"
  14. #include "thingspeak.h"
  15. #include "rtcmem.h"
  16. #include "ws.h"
  17. #include <cfloat>
  18. #include <cmath>
  19. #include <limits>
  20. #include <vector>
  21. //--------------------------------------------------------------------------------
  22. // TODO: namespace { ... } ? sensor ctors need to work though
  23. #include "filters/LastFilter.h"
  24. #include "filters/MaxFilter.h"
  25. #include "filters/MedianFilter.h"
  26. #include "filters/MovingAverageFilter.h"
  27. #include "filters/SumFilter.h"
  28. #include "sensors/BaseSensor.h"
  29. #include "sensors/BaseEmonSensor.h"
  30. #include "sensors/BaseAnalogSensor.h"
  31. #if AM2320_SUPPORT
  32. #include "sensors/AM2320Sensor.h"
  33. #endif
  34. #if ANALOG_SUPPORT
  35. #include "sensors/AnalogSensor.h"
  36. #endif
  37. #if BH1750_SUPPORT
  38. #include "sensors/BH1750Sensor.h"
  39. #endif
  40. #if BMP180_SUPPORT
  41. #include "sensors/BMP180Sensor.h"
  42. #endif
  43. #if BMX280_SUPPORT
  44. #include "sensors/BMX280Sensor.h"
  45. #endif
  46. #if BME680_SUPPORT
  47. #include "sensors/BME680Sensor.h"
  48. #endif
  49. #if CSE7766_SUPPORT
  50. #include "sensors/CSE7766Sensor.h"
  51. #endif
  52. #if DALLAS_SUPPORT
  53. #include "sensors/DallasSensor.h"
  54. #endif
  55. #if DHT_SUPPORT
  56. #include "sensors/DHTSensor.h"
  57. #endif
  58. #if DIGITAL_SUPPORT
  59. #include "sensors/DigitalSensor.h"
  60. #endif
  61. #if ECH1560_SUPPORT
  62. #include "sensors/ECH1560Sensor.h"
  63. #endif
  64. #if EMON_ADC121_SUPPORT
  65. #include "sensors/EmonADC121Sensor.h"
  66. #endif
  67. #if EMON_ADS1X15_SUPPORT
  68. #include "sensors/EmonADS1X15Sensor.h"
  69. #endif
  70. #if EMON_ANALOG_SUPPORT
  71. #include "sensors/EmonAnalogSensor.h"
  72. #endif
  73. #if EVENTS_SUPPORT
  74. #include "sensors/EventSensor.h"
  75. #endif
  76. #if EZOPH_SUPPORT
  77. #include "sensors/EZOPHSensor.h"
  78. #endif
  79. #if GEIGER_SUPPORT
  80. #include "sensors/GeigerSensor.h"
  81. #endif
  82. #if GUVAS12SD_SUPPORT
  83. #include "sensors/GUVAS12SDSensor.h"
  84. #endif
  85. #if HLW8012_SUPPORT
  86. #include "sensors/HLW8012Sensor.h"
  87. #endif
  88. #if LDR_SUPPORT
  89. #include "sensors/LDRSensor.h"
  90. #endif
  91. #if MAX6675_SUPPORT
  92. #include "sensors/MAX6675Sensor.h"
  93. #endif
  94. #if MICS2710_SUPPORT
  95. #include "sensors/MICS2710Sensor.h"
  96. #endif
  97. #if MICS5525_SUPPORT
  98. #include "sensors/MICS5525Sensor.h"
  99. #endif
  100. #if MHZ19_SUPPORT
  101. #include "sensors/MHZ19Sensor.h"
  102. #endif
  103. #if NTC_SUPPORT
  104. #include "sensors/NTCSensor.h"
  105. #endif
  106. #if SDS011_SUPPORT
  107. #include "sensors/SDS011Sensor.h"
  108. #endif
  109. #if SENSEAIR_SUPPORT
  110. #include "sensors/SenseAirSensor.h"
  111. #endif
  112. #if PMSX003_SUPPORT
  113. #include "sensors/PMSX003Sensor.h"
  114. #endif
  115. #if PULSEMETER_SUPPORT
  116. #include "sensors/PulseMeterSensor.h"
  117. #endif
  118. #if PZEM004T_SUPPORT
  119. #include "sensors/PZEM004TSensor.h"
  120. #endif
  121. #if SHT3X_I2C_SUPPORT
  122. #include "sensors/SHT3XI2CSensor.h"
  123. #endif
  124. #if SI7021_SUPPORT
  125. #include "sensors/SI7021Sensor.h"
  126. #endif
  127. #if SONAR_SUPPORT
  128. #include "sensors/SonarSensor.h"
  129. #endif
  130. #if T6613_SUPPORT
  131. #include "sensors/T6613Sensor.h"
  132. #endif
  133. #if TMP3X_SUPPORT
  134. #include "sensors/TMP3XSensor.h"
  135. #endif
  136. #if V9261F_SUPPORT
  137. #include "sensors/V9261FSensor.h"
  138. #endif
  139. #if VEML6075_SUPPORT
  140. #include "sensors/VEML6075Sensor.h"
  141. #endif
  142. #if VL53L1X_SUPPORT
  143. #include "sensors/VL53L1XSensor.h"
  144. #endif
  145. #if ADE7953_SUPPORT
  146. #include "sensors/ADE7953Sensor.h"
  147. #endif
  148. #if SI1145_SUPPORT
  149. #include "sensors/SI1145Sensor.h"
  150. #endif
  151. #if HDC1080_SUPPORT
  152. #include "sensors/HDC1080Sensor.h"
  153. #endif
  154. #if PZEM004TV30_SUPPORT
  155. // TODO: this is temporary, until we have external API giving us swserial stream objects
  156. #include <SoftwareSerial.h>
  157. #include "sensors/PZEM004TV30Sensor.h"
  158. #endif
  159. //--------------------------------------------------------------------------------
  160. struct sensor_magnitude_t {
  161. private:
  162. constexpr static double _unset = std::numeric_limits<double>::quiet_NaN();
  163. static unsigned char _counts[MAGNITUDE_MAX];
  164. sensor_magnitude_t& operator=(const sensor_magnitude_t&) = default;
  165. void move(sensor_magnitude_t&& other) noexcept {
  166. *this = other;
  167. other.filter = nullptr;
  168. }
  169. public:
  170. static unsigned char counts(unsigned char type) {
  171. return _counts[type];
  172. }
  173. sensor_magnitude_t() = delete;
  174. sensor_magnitude_t(const sensor_magnitude_t&) = delete;
  175. sensor_magnitude_t(sensor_magnitude_t&& other) noexcept {
  176. *this = other;
  177. other.filter = nullptr;
  178. }
  179. sensor_magnitude_t& operator=(sensor_magnitude_t&& other) noexcept {
  180. move(std::move(other));
  181. return *this;
  182. }
  183. ~sensor_magnitude_t() noexcept {
  184. delete filter;
  185. }
  186. sensor_magnitude_t(unsigned char slot, unsigned char index_local, unsigned char type, sensor::Unit units, BaseSensor* sensor);
  187. BaseSensor * sensor { nullptr }; // Sensor object
  188. BaseFilter * filter { nullptr }; // Filter object
  189. unsigned char slot { 0u }; // Sensor slot # taken by the magnitude, used to access the measurement
  190. unsigned char type { MAGNITUDE_NONE }; // Type of measurement, returned by the BaseSensor::type(slot)
  191. unsigned char index_local { 0u }; // N'th magnitude of it's type, local to the sensor
  192. unsigned char index_global { 0u }; // ... and across all of the active sensors
  193. sensor::Unit units { sensor::Unit::None }; // Units of measurement
  194. unsigned char decimals { 0u }; // Number of decimals in textual representation
  195. double last { _unset }; // Last raw value from sensor (unfiltered)
  196. double reported { _unset }; // Last reported value
  197. double min_change { 0.0 }; // Minimum value change to report
  198. double max_change { 0.0 }; // Maximum value change to report
  199. double correction { 0.0 }; // Value correction (applied when processing)
  200. double zero_threshold { _unset }; // Reset value to zero when below threshold (applied when reading)
  201. };
  202. static_assert(
  203. std::is_nothrow_move_constructible<sensor_magnitude_t>::value,
  204. "std::vector<sensor_magnitude_t> should be able to work with resize()"
  205. );
  206. static_assert(
  207. !std::is_copy_constructible<sensor_magnitude_t>::value,
  208. "std::vector<sensor_magnitude_t> should only use move ctor"
  209. );
  210. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX] = {0};
  211. namespace sensor {
  212. // Base units
  213. // TODO: implement through a single class and allow direct access to the ::value
  214. KWh::KWh() :
  215. value(0)
  216. {}
  217. KWh::KWh(uint32_t value) :
  218. value(value)
  219. {}
  220. Ws::Ws() :
  221. value(0)
  222. {}
  223. Ws::Ws(uint32_t value) :
  224. value(value)
  225. {}
  226. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  227. Energy::Energy(KWh kwh, Ws ws) :
  228. kwh(kwh)
  229. {
  230. *this += ws;
  231. }
  232. Energy::Energy(KWh kwh) :
  233. kwh(kwh),
  234. ws()
  235. {}
  236. Energy::Energy(Ws ws) :
  237. kwh()
  238. {
  239. *this += ws;
  240. }
  241. Energy::Energy(double raw) {
  242. *this = raw;
  243. }
  244. Energy& Energy::operator =(double raw) {
  245. double _wh;
  246. kwh = modf(raw, &_wh);
  247. ws = _wh * 3600.0;
  248. return *this;
  249. }
  250. Energy& Energy::operator +=(Ws _ws) {
  251. while (_ws.value >= KwhMultiplier) {
  252. _ws.value -= KwhMultiplier;
  253. ++kwh.value;
  254. }
  255. ws.value += _ws.value;
  256. while (ws.value >= KwhMultiplier) {
  257. ws.value -= KwhMultiplier;
  258. ++kwh.value;
  259. }
  260. return *this;
  261. }
  262. Energy Energy::operator +(Ws watt_s) {
  263. Energy result(*this);
  264. result += watt_s;
  265. return result;
  266. }
  267. Energy::operator bool() {
  268. return (kwh.value > 0) && (ws.value > 0);
  269. }
  270. Ws Energy::asWs() {
  271. auto _kwh = kwh.value;
  272. while (_kwh >= KwhLimit) {
  273. _kwh -= KwhLimit;
  274. }
  275. return (_kwh * KwhMultiplier) + ws.value;
  276. }
  277. double Energy::asDouble() {
  278. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  279. }
  280. void Energy::reset() {
  281. kwh.value = 0;
  282. ws.value = 0;
  283. }
  284. } // namespace sensor
  285. // -----------------------------------------------------------------------------
  286. // Configuration
  287. // -----------------------------------------------------------------------------
  288. constexpr double _magnitudeCorrection(unsigned char type) {
  289. return (
  290. (MAGNITUDE_TEMPERATURE == type) ? (SENSOR_TEMPERATURE_CORRECTION) :
  291. (MAGNITUDE_HUMIDITY == type) ? (SENSOR_HUMIDITY_CORRECTION) :
  292. (MAGNITUDE_LUX == type) ? (SENSOR_LUX_CORRECTION) :
  293. (MAGNITUDE_PRESSURE == type) ? (SENSOR_PRESSURE_CORRECTION) :
  294. 0.0
  295. );
  296. }
  297. constexpr bool _magnitudeCanUseCorrection(unsigned char type) {
  298. return (
  299. (MAGNITUDE_TEMPERATURE == type) ? (true) :
  300. (MAGNITUDE_HUMIDITY == type) ? (true) :
  301. (MAGNITUDE_LUX == type) ? (true) :
  302. (MAGNITUDE_PRESSURE == type) ? (true) :
  303. false
  304. );
  305. }
  306. // -----------------------------------------------------------------------------
  307. // Energy persistence
  308. // -----------------------------------------------------------------------------
  309. std::vector<unsigned char> _sensor_save_count;
  310. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  311. bool _sensorIsEmon(BaseSensor* sensor) {
  312. return sensor->type() & sensor::type::Emon;
  313. }
  314. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  315. return sensor::Energy {
  316. sensor::KWh { Rtcmem->energy[index].kwh },
  317. sensor::Ws { Rtcmem->energy[index].ws }
  318. };
  319. }
  320. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  321. Rtcmem->energy[index].kwh = source.kwh.value;
  322. Rtcmem->energy[index].ws = source.ws.value;
  323. }
  324. sensor::Energy _sensorParseEnergy(const String& value) {
  325. sensor::Energy result;
  326. if (!value.length()) {
  327. return result;
  328. }
  329. const char* p { value.c_str() };
  330. char* endp { nullptr };
  331. auto kwh = strtoul(p, &endp, 10);
  332. if (!endp || (endp == p)) {
  333. return result;
  334. }
  335. result.kwh = kwh;
  336. const char* plus { strchr(p, '+') };
  337. if (!plus) {
  338. return result;
  339. }
  340. p = plus + 1;
  341. if (*p == '\0') {
  342. return result;
  343. }
  344. auto ws = strtoul(p, &endp, 10);
  345. if (!endp || (endp == p)) {
  346. return result;
  347. }
  348. result.ws = ws;
  349. return result;
  350. }
  351. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  352. if (!payload || !strlen(payload)) return;
  353. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  354. auto energy = _sensorParseEnergy(payload);
  355. sensor->resetEnergy(magnitude.index_local, energy);
  356. }
  357. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const String& payload) {
  358. _sensorApiResetEnergy(magnitude, payload.c_str());
  359. }
  360. sensor::Energy _sensorEnergyTotal(unsigned char index) {
  361. sensor::Energy result;
  362. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  363. result = _sensorRtcmemLoadEnergy(index);
  364. } else {
  365. result = _sensorParseEnergy(getSetting({"eneTotal", index}));
  366. }
  367. return result;
  368. }
  369. sensor::Energy sensorEnergyTotal() {
  370. return _sensorEnergyTotal(0);
  371. }
  372. void _sensorResetEnergyTotal(unsigned char index) {
  373. delSetting({"eneTotal", index});
  374. delSetting({"eneTime", index});
  375. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  376. Rtcmem->energy[index].kwh = 0;
  377. Rtcmem->energy[index].ws = 0;
  378. }
  379. }
  380. void _magnitudeSaveEnergyTotal(sensor_magnitude_t& magnitude, bool persistent) {
  381. if (magnitude.type != MAGNITUDE_ENERGY) return;
  382. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  383. const auto energy = sensor->totalEnergy();
  384. // Always save to RTCMEM
  385. if (magnitude.index_global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  386. _sensorRtcmemSaveEnergy(magnitude.index_global, energy);
  387. }
  388. // Save to EEPROM every '_sensor_save_every' readings
  389. // Format is `<kwh>+<ws>`, value without `+` is treated as `<ws>`
  390. if (persistent && _sensor_save_every) {
  391. _sensor_save_count[magnitude.index_global] =
  392. (_sensor_save_count[magnitude.index_global] + 1) % _sensor_save_every;
  393. if (0 == _sensor_save_count[magnitude.index_global]) {
  394. const String total = String(energy.kwh.value) + "+" + String(energy.ws.value);
  395. setSetting({"eneTotal", magnitude.index_global}, total);
  396. #if NTP_SUPPORT
  397. if (ntpSynced()) setSetting({"eneTime", magnitude.index_global}, ntpDateTime());
  398. #endif
  399. }
  400. }
  401. }
  402. // ---------------------------------------------------------------------------
  403. std::vector<BaseSensor *> _sensors;
  404. std::vector<sensor_magnitude_t> _magnitudes;
  405. bool _sensors_ready = false;
  406. bool _sensor_realtime = API_REAL_TIME_VALUES;
  407. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  408. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  409. // ---------------------------------------------------------------------------
  410. using MagnitudeReadHandlers = std::forward_list<MagnitudeReadHandler>;
  411. MagnitudeReadHandlers _magnitude_read_handlers;
  412. void sensorSetMagnitudeRead(MagnitudeReadHandler handler) {
  413. _magnitude_read_handlers.push_front(handler);
  414. }
  415. MagnitudeReadHandlers _magnitude_report_handlers;
  416. void sensorSetMagnitudeReport(MagnitudeReadHandler handler) {
  417. _magnitude_report_handlers.push_front(handler);
  418. }
  419. // -----------------------------------------------------------------------------
  420. // Private
  421. // -----------------------------------------------------------------------------
  422. BaseFilter* _magnitudeCreateFilter(unsigned char type, size_t size) {
  423. BaseFilter* filter { nullptr };
  424. switch (type) {
  425. case MAGNITUDE_IAQ:
  426. case MAGNITUDE_IAQ_STATIC:
  427. case MAGNITUDE_ENERGY:
  428. filter = new LastFilter();
  429. break;
  430. case MAGNITUDE_COUNT:
  431. case MAGNITUDE_GEIGER_CPM:
  432. case MAGNITUDE_GEIGER_SIEVERT:
  433. case MAGNITUDE_ENERGY_DELTA:
  434. filter = new SumFilter();
  435. break;
  436. case MAGNITUDE_EVENT:
  437. case MAGNITUDE_DIGITAL:
  438. filter = new MaxFilter();
  439. break;
  440. default:
  441. filter = new MedianFilter();
  442. break;
  443. }
  444. filter->resize(size);
  445. return filter;
  446. }
  447. sensor_magnitude_t::sensor_magnitude_t(unsigned char slot_, unsigned char index_local_, unsigned char type_, sensor::Unit units_, BaseSensor* sensor_) :
  448. sensor(sensor_),
  449. filter(_magnitudeCreateFilter(type_, _sensor_report_every)),
  450. slot(slot_),
  451. type(type_),
  452. index_local(index_local_),
  453. index_global(_counts[type]),
  454. units(units_)
  455. {
  456. ++_counts[type];
  457. }
  458. // Hardcoded decimals for each magnitude
  459. unsigned char _sensorUnitDecimals(sensor::Unit unit) {
  460. switch (unit) {
  461. case sensor::Unit::Celcius:
  462. case sensor::Unit::Farenheit:
  463. return 1;
  464. case sensor::Unit::Percentage:
  465. return 0;
  466. case sensor::Unit::Hectopascal:
  467. return 2;
  468. case sensor::Unit::Ampere:
  469. return 3;
  470. case sensor::Unit::Volt:
  471. return 0;
  472. case sensor::Unit::Watt:
  473. case sensor::Unit::Voltampere:
  474. case sensor::Unit::VoltampereReactive:
  475. return 0;
  476. case sensor::Unit::Kilowatt:
  477. case sensor::Unit::Kilovoltampere:
  478. case sensor::Unit::KilovoltampereReactive:
  479. return 3;
  480. case sensor::Unit::KilowattHour:
  481. return 3;
  482. case sensor::Unit::WattSecond:
  483. return 0;
  484. case sensor::Unit::CountsPerMinute:
  485. case sensor::Unit::MicrosievertPerHour:
  486. return 4;
  487. case sensor::Unit::Meter:
  488. return 3;
  489. case sensor::Unit::Hertz:
  490. return 1;
  491. case sensor::Unit::UltravioletIndex:
  492. return 3;
  493. case sensor::Unit::Ph:
  494. return 3;
  495. case sensor::Unit::None:
  496. default:
  497. return 0;
  498. }
  499. }
  500. String magnitudeTopic(unsigned char type) {
  501. const __FlashStringHelper* result = nullptr;
  502. switch (type) {
  503. case MAGNITUDE_TEMPERATURE:
  504. result = F("temperature");
  505. break;
  506. case MAGNITUDE_HUMIDITY:
  507. result = F("humidity");
  508. break;
  509. case MAGNITUDE_PRESSURE:
  510. result = F("pressure");
  511. break;
  512. case MAGNITUDE_CURRENT:
  513. result = F("current");
  514. break;
  515. case MAGNITUDE_VOLTAGE:
  516. result = F("voltage");
  517. break;
  518. case MAGNITUDE_POWER_ACTIVE:
  519. result = F("power");
  520. break;
  521. case MAGNITUDE_POWER_APPARENT:
  522. result = F("apparent");
  523. break;
  524. case MAGNITUDE_POWER_REACTIVE:
  525. result = F("reactive");
  526. break;
  527. case MAGNITUDE_POWER_FACTOR:
  528. result = F("factor");
  529. break;
  530. case MAGNITUDE_ENERGY:
  531. result = F("energy");
  532. break;
  533. case MAGNITUDE_ENERGY_DELTA:
  534. result = F("energy_delta");
  535. break;
  536. case MAGNITUDE_ANALOG:
  537. result = F("analog");
  538. break;
  539. case MAGNITUDE_DIGITAL:
  540. result = F("digital");
  541. break;
  542. case MAGNITUDE_EVENT:
  543. result = F("event");
  544. break;
  545. case MAGNITUDE_PM1dot0:
  546. result = F("pm1dot0");
  547. break;
  548. case MAGNITUDE_PM2dot5:
  549. result = F("pm2dot5");
  550. break;
  551. case MAGNITUDE_PM10:
  552. result = F("pm10");
  553. break;
  554. case MAGNITUDE_CO2:
  555. result = F("co2");
  556. break;
  557. case MAGNITUDE_VOC:
  558. result = F("voc");
  559. break;
  560. case MAGNITUDE_IAQ:
  561. result = F("iaq");
  562. break;
  563. case MAGNITUDE_IAQ_ACCURACY:
  564. result = F("iaq_accuracy");
  565. break;
  566. case MAGNITUDE_IAQ_STATIC:
  567. result = F("iaq_static");
  568. break;
  569. case MAGNITUDE_LUX:
  570. result = F("lux");
  571. break;
  572. case MAGNITUDE_UVA:
  573. result = F("uva");
  574. break;
  575. case MAGNITUDE_UVB:
  576. result = F("uvb");
  577. break;
  578. case MAGNITUDE_UVI:
  579. result = F("uvi");
  580. break;
  581. case MAGNITUDE_DISTANCE:
  582. result = F("distance");
  583. break;
  584. case MAGNITUDE_HCHO:
  585. result = F("hcho");
  586. break;
  587. case MAGNITUDE_GEIGER_CPM:
  588. result = F("ldr_cpm"); // local dose rate [Counts per minute]
  589. break;
  590. case MAGNITUDE_GEIGER_SIEVERT:
  591. result = F("ldr_uSvh"); // local dose rate [µSievert per hour]
  592. break;
  593. case MAGNITUDE_COUNT:
  594. result = F("count");
  595. break;
  596. case MAGNITUDE_NO2:
  597. result = F("no2");
  598. break;
  599. case MAGNITUDE_CO:
  600. result = F("co");
  601. break;
  602. case MAGNITUDE_RESISTANCE:
  603. result = F("resistance");
  604. break;
  605. case MAGNITUDE_PH:
  606. result = F("ph");
  607. break;
  608. case MAGNITUDE_FREQUENCY:
  609. result = F("frequency");
  610. break;
  611. case MAGNITUDE_NONE:
  612. default:
  613. result = F("unknown");
  614. break;
  615. }
  616. return String(result);
  617. }
  618. String _magnitudeTopic(const sensor_magnitude_t& magnitude) {
  619. return magnitudeTopic(magnitude.type);
  620. }
  621. String _magnitudeUnits(const sensor_magnitude_t& magnitude) {
  622. const __FlashStringHelper* result = nullptr;
  623. switch (magnitude.units) {
  624. case sensor::Unit::Farenheit:
  625. result = F("°F");
  626. break;
  627. case sensor::Unit::Celcius:
  628. result = F("°C");
  629. break;
  630. case sensor::Unit::Percentage:
  631. result = F("%");
  632. break;
  633. case sensor::Unit::Hectopascal:
  634. result = F("hPa");
  635. break;
  636. case sensor::Unit::Ampere:
  637. result = F("A");
  638. break;
  639. case sensor::Unit::Volt:
  640. result = F("V");
  641. break;
  642. case sensor::Unit::Watt:
  643. result = F("W");
  644. break;
  645. case sensor::Unit::Kilowatt:
  646. result = F("kW");
  647. break;
  648. case sensor::Unit::Voltampere:
  649. result = F("VA");
  650. break;
  651. case sensor::Unit::Kilovoltampere:
  652. result = F("kVA");
  653. break;
  654. case sensor::Unit::VoltampereReactive:
  655. result = F("VAR");
  656. break;
  657. case sensor::Unit::KilovoltampereReactive:
  658. result = F("kVAR");
  659. break;
  660. case sensor::Unit::Joule:
  661. //aka case sensor::Unit::WattSecond:
  662. result = F("J");
  663. break;
  664. case sensor::Unit::KilowattHour:
  665. result = F("kWh");
  666. break;
  667. case sensor::Unit::MicrogrammPerCubicMeter:
  668. result = F("µg/m³");
  669. break;
  670. case sensor::Unit::PartsPerMillion:
  671. result = F("ppm");
  672. break;
  673. case sensor::Unit::Lux:
  674. result = F("lux");
  675. break;
  676. case sensor::Unit::Ohm:
  677. result = F("ohm");
  678. break;
  679. case sensor::Unit::MilligrammPerCubicMeter:
  680. result = F("mg/m³");
  681. break;
  682. case sensor::Unit::CountsPerMinute:
  683. result = F("cpm");
  684. break;
  685. case sensor::Unit::MicrosievertPerHour:
  686. result = F("µSv/h");
  687. break;
  688. case sensor::Unit::Meter:
  689. result = F("m");
  690. break;
  691. case sensor::Unit::Hertz:
  692. result = F("Hz");
  693. break;
  694. case sensor::Unit::None:
  695. default:
  696. result = F("");
  697. break;
  698. }
  699. return String(result);
  700. }
  701. String magnitudeUnits(unsigned char index) {
  702. if (index >= magnitudeCount()) return String();
  703. return _magnitudeUnits(_magnitudes[index]);
  704. }
  705. // Choose unit based on type of magnitude we use
  706. sensor::Unit _magnitudeUnitFilter(const sensor_magnitude_t& magnitude, sensor::Unit updated) {
  707. auto result = magnitude.units;
  708. switch (magnitude.type) {
  709. case MAGNITUDE_TEMPERATURE: {
  710. switch (updated) {
  711. case sensor::Unit::Celcius:
  712. case sensor::Unit::Farenheit:
  713. case sensor::Unit::Kelvin:
  714. result = updated;
  715. break;
  716. default:
  717. break;
  718. }
  719. break;
  720. }
  721. case MAGNITUDE_POWER_ACTIVE: {
  722. switch (updated) {
  723. case sensor::Unit::Kilowatt:
  724. case sensor::Unit::Watt:
  725. result = updated;
  726. break;
  727. default:
  728. break;
  729. }
  730. break;
  731. }
  732. case MAGNITUDE_ENERGY: {
  733. switch (updated) {
  734. case sensor::Unit::KilowattHour:
  735. case sensor::Unit::Joule:
  736. result = updated;
  737. break;
  738. default:
  739. break;
  740. }
  741. break;
  742. }
  743. default:
  744. result = updated;
  745. break;
  746. }
  747. return result;
  748. };
  749. double _magnitudeProcess(const sensor_magnitude_t& magnitude, double value) {
  750. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  751. switch (magnitude.sensor->units(magnitude.slot)) {
  752. case sensor::Unit::Celcius:
  753. if (magnitude.units == sensor::Unit::Farenheit) {
  754. value = (value * 1.8) + 32.0;
  755. } else if (magnitude.units == sensor::Unit::Kelvin) {
  756. value = value + 273.15;
  757. }
  758. break;
  759. case sensor::Unit::Percentage:
  760. value = constrain(value, 0.0, 100.0);
  761. break;
  762. case sensor::Unit::Watt:
  763. case sensor::Unit::Voltampere:
  764. case sensor::Unit::VoltampereReactive:
  765. if ((magnitude.units == sensor::Unit::Kilowatt)
  766. || (magnitude.units == sensor::Unit::Kilovoltampere)
  767. || (magnitude.units == sensor::Unit::KilovoltampereReactive)) {
  768. value = value / 1.0e+3;
  769. }
  770. break;
  771. case sensor::Unit::KilowattHour:
  772. // TODO: we may end up with inf at some point?
  773. if (magnitude.units == sensor::Unit::Joule) {
  774. value = value * 3.6e+6;
  775. }
  776. break;
  777. default:
  778. break;
  779. }
  780. value = value + magnitude.correction;
  781. return roundTo(value, magnitude.decimals);
  782. }
  783. String _magnitudeDescription(const sensor_magnitude_t& magnitude) {
  784. return magnitude.sensor->description(magnitude.slot);
  785. }
  786. // -----------------------------------------------------------------------------
  787. // do `callback(type)` for each present magnitude
  788. template<typename T>
  789. void _magnitudeForEachCounted(T callback) {
  790. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  791. if (sensor_magnitude_t::counts(type)) {
  792. callback(type);
  793. }
  794. }
  795. }
  796. // check if `callback(type)` returns `true` at least once
  797. template<typename T>
  798. bool _magnitudeForEachCountedCheck(T callback) {
  799. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  800. if (sensor_magnitude_t::counts(type) && callback(type)) {
  801. return true;
  802. }
  803. }
  804. return false;
  805. }
  806. // do `callback(type)` for each error type
  807. template<typename T>
  808. void _sensorForEachError(T callback) {
  809. for (unsigned char error = SENSOR_ERROR_OK; error < SENSOR_ERROR_MAX; ++error) {
  810. callback(error);
  811. }
  812. }
  813. const char * const _magnitudeSettingsPrefix(unsigned char type) {
  814. switch (type) {
  815. case MAGNITUDE_TEMPERATURE: return "tmp";
  816. case MAGNITUDE_HUMIDITY: return "hum";
  817. case MAGNITUDE_PRESSURE: return "press";
  818. case MAGNITUDE_CURRENT: return "curr";
  819. case MAGNITUDE_VOLTAGE: return "volt";
  820. case MAGNITUDE_POWER_ACTIVE: return "pwrP";
  821. case MAGNITUDE_POWER_APPARENT: return "pwrQ";
  822. case MAGNITUDE_POWER_REACTIVE: return "pwrModS";
  823. case MAGNITUDE_POWER_FACTOR: return "pwrPF";
  824. case MAGNITUDE_ENERGY: return "ene";
  825. case MAGNITUDE_ENERGY_DELTA: return "eneDelta";
  826. case MAGNITUDE_ANALOG: return "analog";
  827. case MAGNITUDE_DIGITAL: return "digital";
  828. case MAGNITUDE_EVENT: return "event";
  829. case MAGNITUDE_PM1dot0: return "pm1dot0";
  830. case MAGNITUDE_PM2dot5: return "pm1dot5";
  831. case MAGNITUDE_PM10: return "pm10";
  832. case MAGNITUDE_CO2: return "co2";
  833. case MAGNITUDE_VOC: return "voc";
  834. case MAGNITUDE_IAQ: return "iaq";
  835. case MAGNITUDE_IAQ_ACCURACY: return "iaqAccuracy";
  836. case MAGNITUDE_IAQ_STATIC: return "iaqStatic";
  837. case MAGNITUDE_LUX: return "lux";
  838. case MAGNITUDE_UVA: return "uva";
  839. case MAGNITUDE_UVB: return "uvb";
  840. case MAGNITUDE_UVI: return "uvi";
  841. case MAGNITUDE_DISTANCE: return "distance";
  842. case MAGNITUDE_HCHO: return "hcho";
  843. case MAGNITUDE_GEIGER_CPM: return "gcpm";
  844. case MAGNITUDE_GEIGER_SIEVERT: return "gsiev";
  845. case MAGNITUDE_COUNT: return "count";
  846. case MAGNITUDE_NO2: return "no2";
  847. case MAGNITUDE_CO: return "co";
  848. case MAGNITUDE_RESISTANCE: return "res";
  849. case MAGNITUDE_PH: return "ph";
  850. case MAGNITUDE_FREQUENCY: return "freq";
  851. default: return nullptr;
  852. }
  853. }
  854. template <typename T>
  855. String _magnitudeSettingsKey(sensor_magnitude_t& magnitude, T&& suffix) {
  856. return String(_magnitudeSettingsPrefix(magnitude.type)) + suffix;
  857. }
  858. bool _sensorMatchKeyPrefix(const char * key) {
  859. if (strncmp(key, "sns", 3) == 0) return true;
  860. if (strncmp(key, "pwr", 3) == 0) return true;
  861. return _magnitudeForEachCountedCheck([key](unsigned char type) {
  862. const char* const prefix { _magnitudeSettingsPrefix(type) };
  863. return (strncmp(prefix, key, strlen(prefix)) == 0);
  864. });
  865. }
  866. const String _sensorQueryDefault(const String& key) {
  867. auto get_defaults = [](unsigned char type, BaseSensor* ptr) -> String {
  868. if (!ptr) return String();
  869. auto* sensor = static_cast<BaseEmonSensor*>(ptr);
  870. switch (type) {
  871. case MAGNITUDE_CURRENT:
  872. return String(sensor->defaultCurrentRatio());
  873. case MAGNITUDE_VOLTAGE:
  874. return String(sensor->defaultVoltageRatio());
  875. case MAGNITUDE_POWER_ACTIVE:
  876. return String(sensor->defaultPowerRatio());
  877. case MAGNITUDE_ENERGY:
  878. return String(sensor->defaultEnergyRatio());
  879. default:
  880. return String();
  881. }
  882. };
  883. auto magnitude_key = [](const sensor_magnitude_t& magnitude) -> SettingsKey {
  884. switch (magnitude.type) {
  885. case MAGNITUDE_CURRENT:
  886. return {"pwrRatioC", magnitude.index_global};
  887. case MAGNITUDE_VOLTAGE:
  888. return {"pwrRatioV", magnitude.index_global};
  889. case MAGNITUDE_POWER_ACTIVE:
  890. return {"pwrRatioP", magnitude.index_global};
  891. case MAGNITUDE_ENERGY:
  892. return {"pwrRatioE", magnitude.index_global};
  893. default:
  894. return "";
  895. }
  896. };
  897. unsigned char type = MAGNITUDE_NONE;
  898. BaseSensor* target = nullptr;
  899. for (auto& magnitude : _magnitudes) {
  900. switch (magnitude.type) {
  901. case MAGNITUDE_CURRENT:
  902. case MAGNITUDE_VOLTAGE:
  903. case MAGNITUDE_POWER_ACTIVE:
  904. case MAGNITUDE_ENERGY: {
  905. auto ratioKey(magnitude_key(magnitude));
  906. if (ratioKey == key) {
  907. target = magnitude.sensor;
  908. type = magnitude.type;
  909. goto return_defaults;
  910. }
  911. break;
  912. }
  913. default:
  914. break;
  915. }
  916. }
  917. return_defaults:
  918. return get_defaults(type, target);
  919. }
  920. #if WEB_SUPPORT
  921. bool _sensorWebSocketOnKeyCheck(const char* key, JsonVariant&) {
  922. return _sensorMatchKeyPrefix(key);
  923. }
  924. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  925. void sensorWebSocketMagnitudes(JsonObject& root, const String& prefix) {
  926. // ws produces flat list <prefix>Magnitudes
  927. const String ws_name = prefix + "Magnitudes";
  928. // config uses <prefix>Magnitude<index> (cut 's')
  929. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  930. JsonObject& list = root.createNestedObject(ws_name);
  931. list["size"] = magnitudeCount();
  932. JsonArray& type = list.createNestedArray("type");
  933. JsonArray& index = list.createNestedArray("index");
  934. JsonArray& idx = list.createNestedArray("idx");
  935. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  936. type.add(magnitudeType(i));
  937. index.add(magnitudeIndex(i));
  938. idx.add(getSetting({conf_name, i}, 0));
  939. }
  940. }
  941. String sensorError(unsigned char error) {
  942. const __FlashStringHelper* result = nullptr;
  943. switch (error) {
  944. case SENSOR_ERROR_OK:
  945. result = F("OK");
  946. break;
  947. case SENSOR_ERROR_OUT_OF_RANGE:
  948. result = F("Out of Range");
  949. break;
  950. case SENSOR_ERROR_WARM_UP:
  951. result = F("Warming Up");
  952. break;
  953. case SENSOR_ERROR_TIMEOUT:
  954. result = F("Timeout");
  955. break;
  956. case SENSOR_ERROR_UNKNOWN_ID:
  957. result = F("Unknown ID");
  958. break;
  959. case SENSOR_ERROR_CRC:
  960. result = F("CRC / Data Error");
  961. break;
  962. case SENSOR_ERROR_I2C:
  963. result = F("I2C Error");
  964. break;
  965. case SENSOR_ERROR_GPIO_USED:
  966. result = F("GPIO Already Used");
  967. break;
  968. case SENSOR_ERROR_CALIBRATION:
  969. result = F("Calibration Error");
  970. break;
  971. default:
  972. case SENSOR_ERROR_OTHER:
  973. result = F("Other / Unknown Error");
  974. break;
  975. }
  976. return result;
  977. }
  978. String magnitudeName(unsigned char type) {
  979. const __FlashStringHelper* result = nullptr;
  980. switch (type) {
  981. case MAGNITUDE_TEMPERATURE:
  982. result = F("Temperature");
  983. break;
  984. case MAGNITUDE_HUMIDITY:
  985. result = F("Humidity");
  986. break;
  987. case MAGNITUDE_PRESSURE:
  988. result = F("Pressure");
  989. break;
  990. case MAGNITUDE_CURRENT:
  991. result = F("Current");
  992. break;
  993. case MAGNITUDE_VOLTAGE:
  994. result = F("Voltage");
  995. break;
  996. case MAGNITUDE_POWER_ACTIVE:
  997. result = F("Active Power");
  998. break;
  999. case MAGNITUDE_POWER_APPARENT:
  1000. result = F("Apparent Power");
  1001. break;
  1002. case MAGNITUDE_POWER_REACTIVE:
  1003. result = F("Reactive Power");
  1004. break;
  1005. case MAGNITUDE_POWER_FACTOR:
  1006. result = F("Power Factor");
  1007. break;
  1008. case MAGNITUDE_ENERGY:
  1009. result = F("Energy");
  1010. break;
  1011. case MAGNITUDE_ENERGY_DELTA:
  1012. result = F("Energy (delta)");
  1013. break;
  1014. case MAGNITUDE_ANALOG:
  1015. result = F("Analog");
  1016. break;
  1017. case MAGNITUDE_DIGITAL:
  1018. result = F("Digital");
  1019. break;
  1020. case MAGNITUDE_EVENT:
  1021. result = F("Event");
  1022. break;
  1023. case MAGNITUDE_PM1dot0:
  1024. result = F("PM1.0");
  1025. break;
  1026. case MAGNITUDE_PM2dot5:
  1027. result = F("PM2.5");
  1028. break;
  1029. case MAGNITUDE_PM10:
  1030. result = F("PM10");
  1031. break;
  1032. case MAGNITUDE_CO2:
  1033. result = F("CO2");
  1034. break;
  1035. case MAGNITUDE_VOC:
  1036. result = F("VOC");
  1037. break;
  1038. case MAGNITUDE_IAQ_STATIC:
  1039. result = F("IAQ (Static)");
  1040. break;
  1041. case MAGNITUDE_IAQ:
  1042. result = F("IAQ");
  1043. break;
  1044. case MAGNITUDE_IAQ_ACCURACY:
  1045. result = F("IAQ Accuracy");
  1046. break;
  1047. case MAGNITUDE_LUX:
  1048. result = F("Lux");
  1049. break;
  1050. case MAGNITUDE_UVA:
  1051. result = F("UVA");
  1052. break;
  1053. case MAGNITUDE_UVB:
  1054. result = F("UVB");
  1055. break;
  1056. case MAGNITUDE_UVI:
  1057. result = F("UVI");
  1058. break;
  1059. case MAGNITUDE_DISTANCE:
  1060. result = F("Distance");
  1061. break;
  1062. case MAGNITUDE_HCHO:
  1063. result = F("HCHO");
  1064. break;
  1065. case MAGNITUDE_GEIGER_CPM:
  1066. case MAGNITUDE_GEIGER_SIEVERT:
  1067. result = F("Local Dose Rate");
  1068. break;
  1069. case MAGNITUDE_COUNT:
  1070. result = F("Count");
  1071. break;
  1072. case MAGNITUDE_NO2:
  1073. result = F("NO2");
  1074. break;
  1075. case MAGNITUDE_CO:
  1076. result = F("CO");
  1077. break;
  1078. case MAGNITUDE_RESISTANCE:
  1079. result = F("Resistance");
  1080. break;
  1081. case MAGNITUDE_PH:
  1082. result = F("pH");
  1083. break;
  1084. case MAGNITUDE_FREQUENCY:
  1085. result = F("Frequency");
  1086. break;
  1087. case MAGNITUDE_NONE:
  1088. default:
  1089. break;
  1090. }
  1091. return String(result);
  1092. }
  1093. void _sensorWebSocketOnVisible(JsonObject& root) {
  1094. root["snsVisible"] = 1;
  1095. // prepare available magnitude types
  1096. JsonArray& magnitudes = root.createNestedArray("snsMagnitudes");
  1097. _magnitudeForEachCounted([&magnitudes](unsigned char type) {
  1098. JsonArray& tuple = magnitudes.createNestedArray();
  1099. tuple.add(type);
  1100. tuple.add(_magnitudeSettingsPrefix(type));
  1101. tuple.add(magnitudeName(type));
  1102. });
  1103. // and available error types
  1104. JsonArray& errors = root.createNestedArray("snsErrors");
  1105. _sensorForEachError([&errors](unsigned char error) {
  1106. JsonArray& tuple = errors.createNestedArray();
  1107. tuple.add(error);
  1108. tuple.add(sensorError(error));
  1109. });
  1110. }
  1111. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  1112. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  1113. uint8_t size = 0;
  1114. JsonArray& index = magnitudes.createNestedArray("index");
  1115. JsonArray& type = magnitudes.createNestedArray("type");
  1116. JsonArray& units = magnitudes.createNestedArray("units");
  1117. JsonArray& description = magnitudes.createNestedArray("description");
  1118. for (auto& magnitude : _magnitudes) {
  1119. // TODO: we don't display event for some reason?
  1120. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1121. ++size;
  1122. index.add<uint8_t>(magnitude.index_global);
  1123. type.add<uint8_t>(magnitude.type);
  1124. units.add(_magnitudeUnits(magnitude));
  1125. description.add(_magnitudeDescription(magnitude));
  1126. }
  1127. magnitudes["size"] = size;
  1128. }
  1129. void _sensorWebSocketSendData(JsonObject& root) {
  1130. char buffer[64];
  1131. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  1132. uint8_t size = 0;
  1133. JsonArray& value = magnitudes.createNestedArray("value");
  1134. JsonArray& error = magnitudes.createNestedArray("error");
  1135. #if NTP_SUPPORT
  1136. JsonArray& info = magnitudes.createNestedArray("info");
  1137. #endif
  1138. for (auto& magnitude : _magnitudes) {
  1139. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1140. ++size;
  1141. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  1142. value.add(buffer);
  1143. error.add(magnitude.sensor->error());
  1144. #if NTP_SUPPORT
  1145. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  1146. String string = F("Last saved: ");
  1147. string += getSetting({"eneTime", magnitude.index_global}, F("(unknown)"));
  1148. info.add(string);
  1149. } else {
  1150. info.add((uint8_t)0);
  1151. }
  1152. #endif
  1153. }
  1154. magnitudes["size"] = size;
  1155. }
  1156. void _sensorWebSocketOnConnected(JsonObject& root) {
  1157. for (auto* sensor [[gnu::unused]] : _sensors) {
  1158. if (_sensorIsEmon(sensor)) {
  1159. root["emonVisible"] = 1;
  1160. root["pwrVisible"] = 1;
  1161. }
  1162. #if EMON_ANALOG_SUPPORT
  1163. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  1164. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  1165. }
  1166. #endif
  1167. #if HLW8012_SUPPORT
  1168. if (sensor->getID() == SENSOR_HLW8012_ID) {
  1169. root["hlwVisible"] = 1;
  1170. }
  1171. #endif
  1172. #if CSE7766_SUPPORT
  1173. if (sensor->getID() == SENSOR_CSE7766_ID) {
  1174. root["cseVisible"] = 1;
  1175. }
  1176. #endif
  1177. #if PZEM004T_SUPPORT || PZEM004TV30_SUPPORT
  1178. switch (sensor->getID()) {
  1179. case SENSOR_PZEM004T_ID:
  1180. case SENSOR_PZEM004TV30_ID:
  1181. root["pzemVisible"] = 1;
  1182. break;
  1183. default:
  1184. break;
  1185. }
  1186. #endif
  1187. #if PULSEMETER_SUPPORT
  1188. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  1189. root["pmVisible"] = 1;
  1190. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  1191. }
  1192. #endif
  1193. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1194. switch (sensor->getID()) {
  1195. case SENSOR_MICS2710_ID:
  1196. case SENSOR_MICS5525_ID:
  1197. root["micsVisible"] = 1;
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. #endif
  1203. }
  1204. if (magnitudeCount()) {
  1205. root["snsRead"] = _sensor_read_interval / 1000;
  1206. root["snsReport"] = _sensor_report_every;
  1207. root["snsSave"] = _sensor_save_every;
  1208. _sensorWebSocketMagnitudesConfig(root);
  1209. }
  1210. }
  1211. #endif // WEB_SUPPORT
  1212. #if API_SUPPORT
  1213. String _sensorApiMagnitudeName(sensor_magnitude_t& magnitude) {
  1214. String name = magnitudeTopic(magnitude.type);
  1215. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) name = name + "/" + String(magnitude.index_global);
  1216. return name;
  1217. }
  1218. bool _sensorApiTryParseMagnitudeIndex(const char* p, unsigned char type, unsigned char& magnitude_index) {
  1219. char* endp { nullptr };
  1220. const unsigned long result { strtoul(p, &endp, 10) };
  1221. if ((endp == p) || (*endp != '\0') || (result >= sensor_magnitude_t::counts(type))) {
  1222. DEBUG_MSG_P(PSTR("[SENSOR] Invalid magnitude ID (%s)\n"), p);
  1223. return false;
  1224. }
  1225. magnitude_index = result;
  1226. return true;
  1227. }
  1228. template <typename T>
  1229. bool _sensorApiTryHandle(ApiRequest& request, unsigned char type, T&& callback) {
  1230. unsigned char index { 0u };
  1231. if (request.wildcards()) {
  1232. auto index_param = request.wildcard(0);
  1233. if (!_sensorApiTryParseMagnitudeIndex(index_param.c_str(), type, index)) {
  1234. return false;
  1235. }
  1236. }
  1237. for (auto& magnitude : _magnitudes) {
  1238. if ((type == magnitude.type) && (index == magnitude.index_global)) {
  1239. callback(magnitude);
  1240. return true;
  1241. }
  1242. }
  1243. return false;
  1244. }
  1245. void _sensorApiSetup() {
  1246. apiRegister(F("magnitudes"),
  1247. [](ApiRequest&, JsonObject& root) {
  1248. JsonArray& magnitudes = root.createNestedArray("magnitudes");
  1249. for (auto& magnitude : _magnitudes) {
  1250. JsonArray& data = magnitudes.createNestedArray();
  1251. data.add(_sensorApiMagnitudeName(magnitude));
  1252. data.add(magnitude.last);
  1253. data.add(magnitude.reported);
  1254. }
  1255. return true;
  1256. },
  1257. nullptr
  1258. );
  1259. _magnitudeForEachCounted([](unsigned char type) {
  1260. String pattern = magnitudeTopic(type);
  1261. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(type) > 1)) {
  1262. pattern += "/+";
  1263. }
  1264. ApiBasicHandler get {
  1265. [type](ApiRequest& request) {
  1266. return _sensorApiTryHandle(request, type, [&](const sensor_magnitude_t& magnitude) {
  1267. char buffer[64] { 0 };
  1268. dtostrf(
  1269. _sensor_realtime ? magnitude.last : magnitude.reported,
  1270. 1, magnitude.decimals,
  1271. buffer
  1272. );
  1273. request.send(String(buffer));
  1274. return true;
  1275. });
  1276. }
  1277. };
  1278. ApiBasicHandler put { nullptr };
  1279. if (type == MAGNITUDE_ENERGY) {
  1280. put = [](ApiRequest& request) {
  1281. return _sensorApiTryHandle(request, MAGNITUDE_ENERGY, [&](const sensor_magnitude_t& magnitude) {
  1282. _sensorApiResetEnergy(magnitude, request.param(F("value")));
  1283. });
  1284. };
  1285. }
  1286. apiRegister(pattern, std::move(get), std::move(put));
  1287. });
  1288. }
  1289. #endif // API_SUPPORT == 1
  1290. #if MQTT_SUPPORT
  1291. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  1292. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  1293. switch (type) {
  1294. case MQTT_MESSAGE_EVENT: {
  1295. String t = mqttMagnitude((char *) topic);
  1296. if (!t.startsWith(energy_topic)) break;
  1297. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  1298. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  1299. for (auto& magnitude : _magnitudes) {
  1300. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  1301. if (index != magnitude.index_global) continue;
  1302. _sensorApiResetEnergy(magnitude, payload);
  1303. break;
  1304. }
  1305. }
  1306. case MQTT_CONNECT_EVENT: {
  1307. for (auto& magnitude : _magnitudes) {
  1308. if (MAGNITUDE_ENERGY == magnitude.type) {
  1309. const String topic = energy_topic + "/+";
  1310. mqttSubscribe(topic.c_str());
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. case MQTT_DISCONNECT_EVENT:
  1316. default:
  1317. break;
  1318. }
  1319. }
  1320. #endif // MQTT_SUPPORT == 1
  1321. #if TERMINAL_SUPPORT
  1322. void _sensorInitCommands() {
  1323. terminalRegisterCommand(F("MAGNITUDES"), [](const terminal::CommandContext&) {
  1324. char last[64];
  1325. char reported[64];
  1326. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1327. auto& magnitude = _magnitudes.at(index);
  1328. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  1329. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  1330. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  1331. index,
  1332. magnitudeTopic(magnitude.type).c_str(),
  1333. magnitude.index_global,
  1334. _magnitudeDescription(magnitude).c_str(),
  1335. last, reported
  1336. );
  1337. }
  1338. terminalOK();
  1339. });
  1340. }
  1341. #endif // TERMINAL_SUPPORT == 1
  1342. void _sensorTick() {
  1343. for (auto* sensor : _sensors) {
  1344. sensor->tick();
  1345. }
  1346. }
  1347. void _sensorPre() {
  1348. for (auto* sensor : _sensors) {
  1349. sensor->pre();
  1350. if (!sensor->status()) {
  1351. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  1352. sensor->description().c_str(),
  1353. sensor->error()
  1354. );
  1355. }
  1356. }
  1357. }
  1358. void _sensorPost() {
  1359. for (auto* sensor : _sensors) {
  1360. sensor->post();
  1361. }
  1362. }
  1363. // -----------------------------------------------------------------------------
  1364. // Sensor initialization
  1365. // -----------------------------------------------------------------------------
  1366. void _sensorLoad() {
  1367. /*
  1368. This is temporal, in the future sensors will be initialized based on
  1369. soft configuration (data stored in EEPROM config) so you will be able
  1370. to define and configure new sensors on the fly
  1371. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  1372. loaded and initialized here. If you want to add new sensors of the same type
  1373. just duplicate the block and change the arguments for the set* methods.
  1374. For example, how to add a second DHT sensor:
  1375. #if DHT_SUPPORT
  1376. {
  1377. DHTSensor * sensor = new DHTSensor();
  1378. sensor->setGPIO(DHT2_PIN);
  1379. sensor->setType(DHT2_TYPE);
  1380. _sensors.push_back(sensor);
  1381. }
  1382. #endif
  1383. DHT2_PIN and DHT2_TYPE should be globally accessible:
  1384. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1385. - in custom.h, as `#define ...`
  1386. */
  1387. #if AM2320_SUPPORT
  1388. {
  1389. AM2320Sensor * sensor = new AM2320Sensor();
  1390. sensor->setAddress(AM2320_ADDRESS);
  1391. _sensors.push_back(sensor);
  1392. }
  1393. #endif
  1394. #if ANALOG_SUPPORT
  1395. {
  1396. AnalogSensor * sensor = new AnalogSensor();
  1397. sensor->setSamples(ANALOG_SAMPLES);
  1398. sensor->setDelay(ANALOG_DELAY);
  1399. //CICM For analog scaling
  1400. sensor->setFactor(ANALOG_FACTOR);
  1401. sensor->setOffset(ANALOG_OFFSET);
  1402. _sensors.push_back(sensor);
  1403. }
  1404. #endif
  1405. #if BH1750_SUPPORT
  1406. {
  1407. BH1750Sensor * sensor = new BH1750Sensor();
  1408. sensor->setAddress(BH1750_ADDRESS);
  1409. sensor->setMode(BH1750_MODE);
  1410. _sensors.push_back(sensor);
  1411. }
  1412. #endif
  1413. #if BMP180_SUPPORT
  1414. {
  1415. BMP180Sensor * sensor = new BMP180Sensor();
  1416. sensor->setAddress(BMP180_ADDRESS);
  1417. _sensors.push_back(sensor);
  1418. }
  1419. #endif
  1420. #if BMX280_SUPPORT
  1421. {
  1422. // Support up to two sensors with full auto-discovery.
  1423. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1424. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1425. // otherwise choose the other unnamed sensor address
  1426. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  1427. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1428. const decltype(first) address_map[2] { first, second };
  1429. for (unsigned char n=0; n < number; ++n) {
  1430. BMX280Sensor * sensor = new BMX280Sensor();
  1431. sensor->setAddress(address_map[n]);
  1432. _sensors.push_back(sensor);
  1433. }
  1434. }
  1435. #endif
  1436. #if BME680_SUPPORT
  1437. {
  1438. BME680Sensor * sensor = new BME680Sensor();
  1439. sensor->setAddress(BME680_I2C_ADDRESS);
  1440. _sensors.push_back(sensor);
  1441. }
  1442. #endif
  1443. #if CSE7766_SUPPORT
  1444. {
  1445. CSE7766Sensor * sensor = new CSE7766Sensor();
  1446. sensor->setRX(CSE7766_RX_PIN);
  1447. _sensors.push_back(sensor);
  1448. }
  1449. #endif
  1450. #if DALLAS_SUPPORT
  1451. {
  1452. DallasSensor * sensor = new DallasSensor();
  1453. sensor->setGPIO(DALLAS_PIN);
  1454. _sensors.push_back(sensor);
  1455. }
  1456. #endif
  1457. #if DHT_SUPPORT
  1458. {
  1459. DHTSensor * sensor = new DHTSensor();
  1460. sensor->setGPIO(DHT_PIN);
  1461. sensor->setType(DHT_TYPE);
  1462. _sensors.push_back(sensor);
  1463. }
  1464. #endif
  1465. #if DIGITAL_SUPPORT
  1466. {
  1467. auto getPin = [](unsigned char index) -> int {
  1468. switch (index) {
  1469. case 0: return DIGITAL1_PIN;
  1470. case 1: return DIGITAL2_PIN;
  1471. case 2: return DIGITAL3_PIN;
  1472. case 3: return DIGITAL4_PIN;
  1473. case 4: return DIGITAL5_PIN;
  1474. case 5: return DIGITAL6_PIN;
  1475. case 6: return DIGITAL7_PIN;
  1476. case 7: return DIGITAL8_PIN;
  1477. default: return GPIO_NONE;
  1478. }
  1479. };
  1480. auto getDefaultState = [](unsigned char index) -> int {
  1481. switch (index) {
  1482. case 0: return DIGITAL1_DEFAULT_STATE;
  1483. case 1: return DIGITAL2_DEFAULT_STATE;
  1484. case 2: return DIGITAL3_DEFAULT_STATE;
  1485. case 3: return DIGITAL4_DEFAULT_STATE;
  1486. case 4: return DIGITAL5_DEFAULT_STATE;
  1487. case 5: return DIGITAL6_DEFAULT_STATE;
  1488. case 6: return DIGITAL7_DEFAULT_STATE;
  1489. case 7: return DIGITAL8_DEFAULT_STATE;
  1490. default: return 1;
  1491. }
  1492. };
  1493. auto getMode = [](unsigned char index) -> int {
  1494. switch (index) {
  1495. case 0: return DIGITAL1_PIN_MODE;
  1496. case 1: return DIGITAL2_PIN_MODE;
  1497. case 2: return DIGITAL3_PIN_MODE;
  1498. case 3: return DIGITAL4_PIN_MODE;
  1499. case 4: return DIGITAL5_PIN_MODE;
  1500. case 5: return DIGITAL6_PIN_MODE;
  1501. case 6: return DIGITAL7_PIN_MODE;
  1502. case 7: return DIGITAL8_PIN_MODE;
  1503. default: return INPUT_PULLUP;
  1504. }
  1505. };
  1506. auto pins = gpioPins();
  1507. for (unsigned char index = 0; index < pins; ++index) {
  1508. const auto pin = getPin(index);
  1509. if (pin == GPIO_NONE) break;
  1510. DigitalSensor * sensor = new DigitalSensor();
  1511. sensor->setGPIO(pin);
  1512. sensor->setMode(getMode(index));
  1513. sensor->setDefault(getDefaultState(index));
  1514. _sensors.push_back(sensor);
  1515. }
  1516. }
  1517. #endif
  1518. #if ECH1560_SUPPORT
  1519. {
  1520. ECH1560Sensor * sensor = new ECH1560Sensor();
  1521. sensor->setCLK(ECH1560_CLK_PIN);
  1522. sensor->setMISO(ECH1560_MISO_PIN);
  1523. sensor->setInverted(ECH1560_INVERTED);
  1524. _sensors.push_back(sensor);
  1525. }
  1526. #endif
  1527. #if EMON_ADC121_SUPPORT
  1528. {
  1529. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1530. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1531. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1532. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1533. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1534. _sensors.push_back(sensor);
  1535. }
  1536. #endif
  1537. #if EMON_ADS1X15_SUPPORT
  1538. {
  1539. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  1540. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  1541. sensor->setType(EMON_ADS1X15_TYPE);
  1542. sensor->setMask(EMON_ADS1X15_MASK);
  1543. sensor->setGain(EMON_ADS1X15_GAIN);
  1544. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1545. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1546. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  1547. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  1548. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  1549. _sensors.push_back(sensor);
  1550. }
  1551. #endif
  1552. #if EMON_ANALOG_SUPPORT
  1553. {
  1554. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  1555. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1556. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1557. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1558. _sensors.push_back(sensor);
  1559. }
  1560. #endif
  1561. #if EVENTS_SUPPORT
  1562. {
  1563. auto getPin = [](unsigned char index) -> int {
  1564. switch (index) {
  1565. case 0: return EVENTS1_PIN;
  1566. case 1: return EVENTS2_PIN;
  1567. case 2: return EVENTS3_PIN;
  1568. case 3: return EVENTS4_PIN;
  1569. case 4: return EVENTS5_PIN;
  1570. case 5: return EVENTS6_PIN;
  1571. case 6: return EVENTS7_PIN;
  1572. case 7: return EVENTS8_PIN;
  1573. default: return GPIO_NONE;
  1574. }
  1575. };
  1576. auto getMode = [](unsigned char index) -> int {
  1577. switch (index) {
  1578. case 0: return EVENTS1_PIN_MODE;
  1579. case 1: return EVENTS2_PIN_MODE;
  1580. case 2: return EVENTS3_PIN_MODE;
  1581. case 3: return EVENTS4_PIN_MODE;
  1582. case 4: return EVENTS5_PIN_MODE;
  1583. case 5: return EVENTS6_PIN_MODE;
  1584. case 6: return EVENTS7_PIN_MODE;
  1585. case 7: return EVENTS8_PIN_MODE;
  1586. default: return INPUT;
  1587. }
  1588. };
  1589. auto getDebounce = [](unsigned char index) -> unsigned long {
  1590. switch (index) {
  1591. case 0: return EVENTS1_DEBOUNCE;
  1592. case 1: return EVENTS2_DEBOUNCE;
  1593. case 2: return EVENTS3_DEBOUNCE;
  1594. case 3: return EVENTS4_DEBOUNCE;
  1595. case 4: return EVENTS5_DEBOUNCE;
  1596. case 5: return EVENTS6_DEBOUNCE;
  1597. case 6: return EVENTS7_DEBOUNCE;
  1598. case 7: return EVENTS8_DEBOUNCE;
  1599. default: return 50;
  1600. }
  1601. };
  1602. auto getIsrMode = [](unsigned char index) -> int {
  1603. switch (index) {
  1604. case 0: return EVENTS1_INTERRUPT_MODE;
  1605. case 1: return EVENTS2_INTERRUPT_MODE;
  1606. case 2: return EVENTS3_INTERRUPT_MODE;
  1607. case 3: return EVENTS4_INTERRUPT_MODE;
  1608. case 4: return EVENTS5_INTERRUPT_MODE;
  1609. case 5: return EVENTS6_INTERRUPT_MODE;
  1610. case 6: return EVENTS7_INTERRUPT_MODE;
  1611. case 7: return EVENTS8_INTERRUPT_MODE;
  1612. default: return RISING;
  1613. }
  1614. };
  1615. auto pins = gpioPins();
  1616. for (unsigned char index = 0; index < pins; ++index) {
  1617. const auto pin = getPin(index);
  1618. if (pin == GPIO_NONE) break;
  1619. EventSensor * sensor = new EventSensor();
  1620. sensor->setGPIO(pin);
  1621. sensor->setPinMode(getMode(index));
  1622. sensor->setDebounceTime(getDebounce(index));
  1623. sensor->setInterruptMode(getIsrMode(index));
  1624. _sensors.push_back(sensor);
  1625. }
  1626. }
  1627. #endif
  1628. #if GEIGER_SUPPORT
  1629. {
  1630. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1631. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1632. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1633. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1634. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1635. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1636. _sensors.push_back(sensor);
  1637. }
  1638. #endif
  1639. #if GUVAS12SD_SUPPORT
  1640. {
  1641. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1642. sensor->setGPIO(GUVAS12SD_PIN);
  1643. _sensors.push_back(sensor);
  1644. }
  1645. #endif
  1646. #if SONAR_SUPPORT
  1647. {
  1648. SonarSensor * sensor = new SonarSensor();
  1649. sensor->setEcho(SONAR_ECHO);
  1650. sensor->setIterations(SONAR_ITERATIONS);
  1651. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1652. sensor->setTrigger(SONAR_TRIGGER);
  1653. _sensors.push_back(sensor);
  1654. }
  1655. #endif
  1656. #if HLW8012_SUPPORT
  1657. {
  1658. HLW8012Sensor * sensor = new HLW8012Sensor();
  1659. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1660. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1661. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1662. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1663. _sensors.push_back(sensor);
  1664. }
  1665. #endif
  1666. #if LDR_SUPPORT
  1667. {
  1668. LDRSensor * sensor = new LDRSensor();
  1669. sensor->setSamples(LDR_SAMPLES);
  1670. sensor->setDelay(LDR_DELAY);
  1671. sensor->setType(LDR_TYPE);
  1672. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1673. sensor->setResistor(LDR_RESISTOR);
  1674. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1675. _sensors.push_back(sensor);
  1676. }
  1677. #endif
  1678. #if MHZ19_SUPPORT
  1679. {
  1680. MHZ19Sensor * sensor = new MHZ19Sensor();
  1681. sensor->setRX(MHZ19_RX_PIN);
  1682. sensor->setTX(MHZ19_TX_PIN);
  1683. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1684. _sensors.push_back(sensor);
  1685. }
  1686. #endif
  1687. #if MICS2710_SUPPORT
  1688. {
  1689. MICS2710Sensor * sensor = new MICS2710Sensor();
  1690. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1691. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1692. sensor->setR0(MICS2710_R0);
  1693. sensor->setRL(MICS2710_RL);
  1694. sensor->setRS(0);
  1695. _sensors.push_back(sensor);
  1696. }
  1697. #endif
  1698. #if MICS5525_SUPPORT
  1699. {
  1700. MICS5525Sensor * sensor = new MICS5525Sensor();
  1701. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1702. sensor->setR0(MICS5525_R0);
  1703. sensor->setRL(MICS5525_RL);
  1704. sensor->setRS(0);
  1705. _sensors.push_back(sensor);
  1706. }
  1707. #endif
  1708. #if NTC_SUPPORT
  1709. {
  1710. NTCSensor * sensor = new NTCSensor();
  1711. sensor->setSamples(NTC_SAMPLES);
  1712. sensor->setDelay(NTC_DELAY);
  1713. sensor->setUpstreamResistor(NTC_R_UP);
  1714. sensor->setDownstreamResistor(NTC_R_DOWN);
  1715. sensor->setBeta(NTC_BETA);
  1716. sensor->setR0(NTC_R0);
  1717. sensor->setT0(NTC_T0);
  1718. _sensors.push_back(sensor);
  1719. }
  1720. #endif
  1721. #if PMSX003_SUPPORT
  1722. {
  1723. PMSX003Sensor * sensor = new PMSX003Sensor();
  1724. #if PMS_USE_SOFT
  1725. sensor->setRX(PMS_RX_PIN);
  1726. sensor->setTX(PMS_TX_PIN);
  1727. #else
  1728. sensor->setSerial(& PMS_HW_PORT);
  1729. #endif
  1730. sensor->setType(PMS_TYPE);
  1731. _sensors.push_back(sensor);
  1732. }
  1733. #endif
  1734. #if PULSEMETER_SUPPORT
  1735. {
  1736. PulseMeterSensor * sensor = new PulseMeterSensor();
  1737. sensor->setGPIO(PULSEMETER_PIN);
  1738. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1739. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1740. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1741. _sensors.push_back(sensor);
  1742. }
  1743. #endif
  1744. #if PZEM004T_SUPPORT
  1745. {
  1746. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1747. if (!addresses.length()) {
  1748. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1749. return;
  1750. }
  1751. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1752. sensor->setAddresses(addresses.c_str());
  1753. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1754. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1755. if (!getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1756. sensor->setSerial(& PZEM004T_HW_PORT);
  1757. }
  1758. _sensors.push_back(sensor);
  1759. #if TERMINAL_SUPPORT
  1760. pzem004tInitCommands();
  1761. #endif
  1762. }
  1763. #endif
  1764. #if SENSEAIR_SUPPORT
  1765. {
  1766. SenseAirSensor * sensor = new SenseAirSensor();
  1767. sensor->setRX(SENSEAIR_RX_PIN);
  1768. sensor->setTX(SENSEAIR_TX_PIN);
  1769. _sensors.push_back(sensor);
  1770. }
  1771. #endif
  1772. #if SDS011_SUPPORT
  1773. {
  1774. SDS011Sensor * sensor = new SDS011Sensor();
  1775. sensor->setRX(SDS011_RX_PIN);
  1776. sensor->setTX(SDS011_TX_PIN);
  1777. _sensors.push_back(sensor);
  1778. }
  1779. #endif
  1780. #if SHT3X_I2C_SUPPORT
  1781. {
  1782. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1783. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1784. _sensors.push_back(sensor);
  1785. }
  1786. #endif
  1787. #if SI7021_SUPPORT
  1788. {
  1789. SI7021Sensor * sensor = new SI7021Sensor();
  1790. sensor->setAddress(SI7021_ADDRESS);
  1791. _sensors.push_back(sensor);
  1792. }
  1793. #endif
  1794. #if T6613_SUPPORT
  1795. {
  1796. T6613Sensor * sensor = new T6613Sensor();
  1797. sensor->setRX(T6613_RX_PIN);
  1798. sensor->setTX(T6613_TX_PIN);
  1799. _sensors.push_back(sensor);
  1800. }
  1801. #endif
  1802. #if TMP3X_SUPPORT
  1803. {
  1804. TMP3XSensor * sensor = new TMP3XSensor();
  1805. sensor->setType(TMP3X_TYPE);
  1806. _sensors.push_back(sensor);
  1807. }
  1808. #endif
  1809. #if V9261F_SUPPORT
  1810. {
  1811. V9261FSensor * sensor = new V9261FSensor();
  1812. sensor->setRX(V9261F_PIN);
  1813. sensor->setInverted(V9261F_PIN_INVERSE);
  1814. _sensors.push_back(sensor);
  1815. }
  1816. #endif
  1817. #if MAX6675_SUPPORT
  1818. {
  1819. MAX6675Sensor * sensor = new MAX6675Sensor();
  1820. sensor->setCS(MAX6675_CS_PIN);
  1821. sensor->setSO(MAX6675_SO_PIN);
  1822. sensor->setSCK(MAX6675_SCK_PIN);
  1823. _sensors.push_back(sensor);
  1824. }
  1825. #endif
  1826. #if VEML6075_SUPPORT
  1827. {
  1828. VEML6075Sensor * sensor = new VEML6075Sensor();
  1829. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1830. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1831. _sensors.push_back(sensor);
  1832. }
  1833. #endif
  1834. #if VL53L1X_SUPPORT
  1835. {
  1836. VL53L1XSensor * sensor = new VL53L1XSensor();
  1837. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1838. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1839. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1840. _sensors.push_back(sensor);
  1841. }
  1842. #endif
  1843. #if EZOPH_SUPPORT
  1844. {
  1845. EZOPHSensor * sensor = new EZOPHSensor();
  1846. sensor->setRX(EZOPH_RX_PIN);
  1847. sensor->setTX(EZOPH_TX_PIN);
  1848. _sensors.push_back(sensor);
  1849. }
  1850. #endif
  1851. #if ADE7953_SUPPORT
  1852. {
  1853. ADE7953Sensor * sensor = new ADE7953Sensor();
  1854. sensor->setAddress(ADE7953_ADDRESS);
  1855. _sensors.push_back(sensor);
  1856. }
  1857. #endif
  1858. #if SI1145_SUPPORT
  1859. {
  1860. SI1145Sensor * sensor = new SI1145Sensor();
  1861. sensor->setAddress(SI1145_ADDRESS);
  1862. _sensors.push_back(sensor);
  1863. }
  1864. #endif
  1865. #if HDC1080_SUPPORT
  1866. {
  1867. HDC1080Sensor * sensor = new HDC1080Sensor();
  1868. sensor->setAddress(HDC1080_ADDRESS);
  1869. _sensors.push_back(sensor);
  1870. }
  1871. #endif
  1872. #if PZEM004TV30_SUPPORT
  1873. {
  1874. PZEM004TV30Sensor * sensor = PZEM004TV30Sensor::create();
  1875. // TODO: we need an equivalent to the `pzem.address` command
  1876. sensor->setAddress(getSetting("pzemv30Addr", PZEM004TV30Sensor::DefaultAddress));
  1877. sensor->setReadTimeout(getSetting("pzemv30ReadTimeout", PZEM004TV30Sensor::DefaultReadTimeout));
  1878. sensor->setDebug(getSetting("pzemv30Debug", 1 == PZEM004TV30_DEBUG));
  1879. bool soft = getSetting("pzemv30Soft", 1 == PZEM004TV30_USE_SOFT);
  1880. int tx = getSetting("pzemv30TX", PZEM004TV30_TX_PIN);
  1881. int rx = getSetting("pzemv30RX", PZEM004TV30_RX_PIN);
  1882. // we operate only with Serial, as Serial1 cannot not receive any data
  1883. if (!soft) {
  1884. sensor->setStream(&Serial);
  1885. sensor->setDescription("HwSerial");
  1886. Serial.begin(PZEM004TV30Sensor::Baudrate);
  1887. // Core does not allow us to begin(baud, cfg, rx, tx) / pins(rx, tx) before begin(baud)
  1888. // b/c internal UART handler does not exist yet
  1889. // Also see https://github.com/esp8266/Arduino/issues/2380 as to why there is flush()
  1890. if ((tx == 15) && (rx == 13)) {
  1891. Serial.flush();
  1892. Serial.swap();
  1893. }
  1894. } else {
  1895. auto* ptr = new SoftwareSerial(rx, tx);
  1896. sensor->setDescription("SwSerial");
  1897. sensor->setStream(ptr); // we don't care about lifetime
  1898. ptr->begin(PZEM004TV30Sensor::Baudrate);
  1899. }
  1900. //TODO: getSetting("pzemv30*Cfg", (SW)SERIAL_8N1); ?
  1901. // may not be relevant, but some sources claim we need 8N2
  1902. _sensors.push_back(sensor);
  1903. }
  1904. #endif
  1905. }
  1906. String _magnitudeTopicIndex(const sensor_magnitude_t& magnitude) {
  1907. char buffer[32] = {0};
  1908. String topic { magnitudeTopic(magnitude.type) };
  1909. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1910. snprintf(buffer, sizeof(buffer), "%s/%u", topic.c_str(), magnitude.index_global);
  1911. } else {
  1912. snprintf(buffer, sizeof(buffer), "%s", topic.c_str());
  1913. }
  1914. return String(buffer);
  1915. }
  1916. void _sensorReport(unsigned char index, const sensor_magnitude_t& magnitude) {
  1917. // XXX: dtostrf only handles basic floating point values and will never produce scientific notation
  1918. // ensure decimals is within some sane limit and the actual value never goes above this buffer size
  1919. char buffer[64];
  1920. dtostrf(magnitude.reported, 1, magnitude.decimals, buffer);
  1921. for (auto& handler : _magnitude_report_handlers) {
  1922. handler(magnitudeTopic(magnitude.type), magnitude.index_global, magnitude.reported, buffer);
  1923. }
  1924. #if MQTT_SUPPORT
  1925. {
  1926. const String topic(_magnitudeTopicIndex(magnitude));
  1927. mqttSend(topic.c_str(), buffer);
  1928. #if SENSOR_PUBLISH_ADDRESSES
  1929. String address_topic;
  1930. address_topic.reserve(topic.length() + 1 + strlen(SENSOR_ADDRESS_TOPIC));
  1931. address_topic += F(SENSOR_ADDRESS_TOPIC);
  1932. address_topic += '/';
  1933. address_topic += topic;
  1934. mqttSend(address_topic.c_str(), magnitude.sensor->address(magnitude.slot).c_str());
  1935. #endif // SENSOR_PUBLISH_ADDRESSES
  1936. }
  1937. #endif // MQTT_SUPPORT
  1938. // TODO: both integrations depend on the absolute index instead of specific type
  1939. // so, we still need to pass / know the 'global' index inside of _magnitudes[]
  1940. #if THINGSPEAK_SUPPORT
  1941. tspkEnqueueMeasurement(index, buffer);
  1942. #endif // THINGSPEAK_SUPPORT
  1943. #if DOMOTICZ_SUPPORT
  1944. domoticzSendMagnitude(magnitude.type, index, magnitude.reported, buffer);
  1945. #endif // DOMOTICZ_SUPPORT
  1946. }
  1947. void _sensorInit() {
  1948. _sensors_ready = true;
  1949. for (auto& sensor : _sensors) {
  1950. // Do not process an already initialized sensor
  1951. if (sensor->ready()) continue;
  1952. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), sensor->description().c_str());
  1953. // Force sensor to reload config
  1954. sensor->begin();
  1955. if (!sensor->ready()) {
  1956. if (0 != sensor->error()) {
  1957. DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  1958. }
  1959. _sensors_ready = false;
  1960. break;
  1961. }
  1962. // Initialize sensor magnitudes
  1963. for (unsigned char magnitude_index = 0; magnitude_index < sensor->count(); ++magnitude_index) {
  1964. const auto magnitude_type = sensor->type(magnitude_index);
  1965. const auto magnitude_local = sensor->local(magnitude_type);
  1966. _magnitudes.emplace_back(
  1967. magnitude_index, // id of the magnitude, unique to the sensor
  1968. magnitude_local, // index_local, # of the magnitude
  1969. magnitude_type, // specific type of the magnitude
  1970. sensor::Unit::None, // set up later, in configuration
  1971. sensor // bind the sensor to allow us to reference it later
  1972. );
  1973. if (_sensorIsEmon(sensor) && (MAGNITUDE_ENERGY == magnitude_type)) {
  1974. const auto index_global = _magnitudes.back().index_global;
  1975. auto* ptr = static_cast<BaseEmonSensor*>(sensor);
  1976. ptr->resetEnergy(magnitude_local, _sensorEnergyTotal(index_global));
  1977. _sensor_save_count.push_back(0);
  1978. }
  1979. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1980. magnitudeTopic(magnitude_type).c_str(),
  1981. sensor_magnitude_t::counts(magnitude_type)
  1982. );
  1983. }
  1984. // Custom initializations are based on IDs
  1985. switch (sensor->getID()) {
  1986. case SENSOR_MICS2710_ID:
  1987. case SENSOR_MICS5525_ID: {
  1988. auto* ptr = static_cast<BaseAnalogSensor*>(sensor);
  1989. ptr->setR0(getSetting("snsR0", ptr->getR0()));
  1990. ptr->setRS(getSetting("snsRS", ptr->getRS()));
  1991. ptr->setRL(getSetting("snsRL", ptr->getRL()));
  1992. break;
  1993. }
  1994. default:
  1995. break;
  1996. }
  1997. }
  1998. }
  1999. namespace settings {
  2000. namespace internal {
  2001. template <>
  2002. sensor::Unit convert(const String& value) {
  2003. auto len = value.length();
  2004. if (len && isNumber(value)) {
  2005. constexpr int Min { static_cast<int>(sensor::Unit::Min_) };
  2006. constexpr int Max { static_cast<int>(sensor::Unit::Max_) };
  2007. auto num = convert<int>(value);
  2008. if ((Min < num) && (num < Max)) {
  2009. return static_cast<sensor::Unit>(num);
  2010. }
  2011. }
  2012. return sensor::Unit::None;
  2013. }
  2014. String serialize(sensor::Unit unit) {
  2015. return serialize(static_cast<int>(unit));
  2016. }
  2017. } // namespace internal
  2018. } // namespace settings
  2019. void _sensorConfigure() {
  2020. // General sensor settings for reporting and saving
  2021. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  2022. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  2023. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  2024. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  2025. // pre-load some settings that are controlled via old build flags
  2026. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  2027. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  2028. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  2029. // Apply settings based on sensor type
  2030. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  2031. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  2032. {
  2033. if (getSetting("snsResetCalibration", false)) {
  2034. switch (_sensors[index]->getID()) {
  2035. case SENSOR_MICS2710_ID:
  2036. case SENSOR_MICS5525_ID: {
  2037. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  2038. sensor->calibrate();
  2039. setSetting("snsR0", sensor->getR0());
  2040. break;
  2041. }
  2042. default:
  2043. break;
  2044. }
  2045. }
  2046. }
  2047. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  2048. if (_sensorIsEmon(_sensors[index])) {
  2049. // TODO: ::isEmon() ?
  2050. double value;
  2051. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  2052. if ((value = getSetting("pwrExpectedC", 0.0))) {
  2053. sensor->expectedCurrent(value);
  2054. delSetting("pwrExpectedC");
  2055. setSetting("pwrRatioC", sensor->getCurrentRatio());
  2056. }
  2057. if ((value = getSetting("pwrExpectedV", 0.0))) {
  2058. delSetting("pwrExpectedV");
  2059. sensor->expectedVoltage(value);
  2060. setSetting("pwrRatioV", sensor->getVoltageRatio());
  2061. }
  2062. if ((value = getSetting("pwrExpectedP", 0.0))) {
  2063. delSetting("pwrExpectedP");
  2064. sensor->expectedPower(value);
  2065. setSetting("pwrRatioP", sensor->getPowerRatio());
  2066. }
  2067. if (getSetting("pwrResetE", false)) {
  2068. delSetting("pwrResetE");
  2069. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  2070. sensor->resetEnergy(index);
  2071. _sensorResetEnergyTotal(index);
  2072. }
  2073. }
  2074. if (getSetting("pwrResetCalibration", false)) {
  2075. delSetting("pwrResetCalibration");
  2076. delSetting("pwrRatioC");
  2077. delSetting("pwrRatioV");
  2078. delSetting("pwrRatioP");
  2079. sensor->resetRatios();
  2080. }
  2081. } // is emon?
  2082. }
  2083. // Update magnitude config, filter sizes and reset energy if needed
  2084. {
  2085. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  2086. auto& magnitude = _magnitudes.at(index);
  2087. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  2088. if (_sensorIsEmon(magnitude.sensor)) {
  2089. // TODO: compatibility proxy, fetch global key before indexed
  2090. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  2091. return getSetting({key, index}, getSetting(key, default_value));
  2092. };
  2093. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  2094. switch (magnitude.type) {
  2095. case MAGNITUDE_CURRENT:
  2096. sensor->setCurrentRatio(
  2097. magnitude.index_local, get_ratio("pwrRatioC", magnitude.index_global, sensor->defaultCurrentRatio())
  2098. );
  2099. break;
  2100. case MAGNITUDE_POWER_ACTIVE:
  2101. sensor->setPowerRatio(
  2102. magnitude.index_local, get_ratio("pwrRatioP", magnitude.index_global, sensor->defaultPowerRatio())
  2103. );
  2104. break;
  2105. case MAGNITUDE_VOLTAGE:
  2106. sensor->setVoltageRatio(
  2107. magnitude.index_local, get_ratio("pwrRatioV", magnitude.index_global, sensor->defaultVoltageRatio())
  2108. );
  2109. sensor->setVoltage(
  2110. magnitude.index_local, get_ratio("pwrVoltage", magnitude.index_global, sensor->defaultVoltage())
  2111. );
  2112. break;
  2113. case MAGNITUDE_ENERGY:
  2114. sensor->setEnergyRatio(
  2115. magnitude.index_local, get_ratio("pwrRatioE", magnitude.index_global, sensor->defaultEnergyRatio())
  2116. );
  2117. break;
  2118. default:
  2119. break;
  2120. }
  2121. }
  2122. // adjust type-specific units
  2123. {
  2124. const sensor::Unit default_unit { magnitude.sensor->units(magnitude.slot) };
  2125. const String key {
  2126. String(_magnitudeSettingsPrefix(magnitude.type)) + F("Units") + String(magnitude.index_global, 10) };
  2127. magnitude.units = _magnitudeUnitFilter(magnitude, getSetting(key, default_unit));
  2128. }
  2129. // some magnitudes allow to be corrected with an offset
  2130. {
  2131. if (_magnitudeCanUseCorrection(magnitude.type)) {
  2132. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  2133. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  2134. }
  2135. }
  2136. // some sensors can override decimal values if sensor has more precision than default
  2137. {
  2138. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  2139. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  2140. magnitude.decimals = (unsigned char) decimals;
  2141. }
  2142. // Per-magnitude min & max delta settings
  2143. // - min controls whether we report at all when report_count overflows
  2144. // - max will trigger report as soon as read value is greater than the specified delta
  2145. // (atm this works best for accumulated magnitudes, like energy)
  2146. {
  2147. auto min_default = 0.0;
  2148. auto max_default = 0.0;
  2149. switch (magnitude.type) {
  2150. case MAGNITUDE_TEMPERATURE:
  2151. min_default = tmp_min_delta;
  2152. break;
  2153. case MAGNITUDE_HUMIDITY:
  2154. min_default = hum_min_delta;
  2155. break;
  2156. case MAGNITUDE_ENERGY:
  2157. max_default = ene_max_delta;
  2158. break;
  2159. default:
  2160. break;
  2161. }
  2162. magnitude.min_change = getSetting(
  2163. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2164. min_default
  2165. );
  2166. magnitude.max_change = getSetting(
  2167. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2168. max_default
  2169. );
  2170. }
  2171. // Sometimes we want to ensure the value is above certain threshold before reporting
  2172. {
  2173. magnitude.zero_threshold = getSetting(
  2174. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2175. std::numeric_limits<double>::quiet_NaN()
  2176. );
  2177. }
  2178. // in case we don't save energy periodically, purge existing value in ram & settings
  2179. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2180. _sensorResetEnergyTotal(magnitude.index_global);
  2181. }
  2182. }
  2183. }
  2184. saveSettings();
  2185. }
  2186. // -----------------------------------------------------------------------------
  2187. // Public
  2188. // -----------------------------------------------------------------------------
  2189. unsigned char sensorCount() {
  2190. return _sensors.size();
  2191. }
  2192. unsigned char magnitudeCount() {
  2193. return _magnitudes.size();
  2194. }
  2195. unsigned char magnitudeType(unsigned char index) {
  2196. if (index < _magnitudes.size()) {
  2197. return _magnitudes[index].type;
  2198. }
  2199. return MAGNITUDE_NONE;
  2200. }
  2201. double sensor::Value::get() {
  2202. return _sensor_realtime ? last : reported;
  2203. }
  2204. sensor::Value magnitudeValue(unsigned char index) {
  2205. sensor::Value result;
  2206. if (index >= _magnitudes.size()) {
  2207. result.last = std::numeric_limits<double>::quiet_NaN(),
  2208. result.reported = std::numeric_limits<double>::quiet_NaN(),
  2209. result.decimals = 0u;
  2210. return result;
  2211. }
  2212. auto& magnitude = _magnitudes[index];
  2213. result.last = magnitude.last;
  2214. result.reported = magnitude.reported;
  2215. result.decimals = magnitude.decimals;
  2216. return result;
  2217. }
  2218. void magnitudeFormat(const sensor::Value& value, char* out, size_t) {
  2219. // TODO: 'size' does not do anything, since dtostrf used here is expected to be 'sane', but
  2220. // it does not allow any size arguments besides for digits after the decimal point
  2221. dtostrf(
  2222. _sensor_realtime ? value.last : value.reported,
  2223. 1, value.decimals,
  2224. out
  2225. );
  2226. }
  2227. unsigned char magnitudeIndex(unsigned char index) {
  2228. if (index < _magnitudes.size()) {
  2229. return _magnitudes[index].index_global;
  2230. }
  2231. return 0;
  2232. }
  2233. String magnitudeDescription(unsigned char index) {
  2234. if (index < _magnitudes.size()) {
  2235. return _magnitudeDescription(_magnitudes[index]);
  2236. }
  2237. return String();
  2238. }
  2239. String magnitudeTopicIndex(unsigned char index) {
  2240. if (index < _magnitudes.size()) {
  2241. return _magnitudeTopicIndex(_magnitudes[index]);
  2242. }
  2243. return String();
  2244. }
  2245. // -----------------------------------------------------------------------------
  2246. void _sensorBackwards(int version) {
  2247. // Some keys from older versions were longer
  2248. if (version < 3) {
  2249. moveSetting("powerUnits", "pwrUnits");
  2250. moveSetting("energyUnits", "eneUnits");
  2251. }
  2252. // Energy is now indexed (based on magnitude.index_global)
  2253. // Also update PZEM004T energy total across multiple devices
  2254. if (version < 5) {
  2255. moveSetting("eneTotal", "eneTotal0");
  2256. moveSettings("pzEneTotal", "eneTotal");
  2257. }
  2258. // Unit ID is no longer shared, drop when equal to Min_ or None
  2259. if (version < 5) {
  2260. delSetting("pwrUnits");
  2261. delSetting("eneUnits");
  2262. delSetting("tmpUnits");
  2263. }
  2264. }
  2265. void sensorSetup() {
  2266. // Settings backwards compatibility
  2267. _sensorBackwards(migrateVersion());
  2268. // Load configured sensors and set up all of magnitudes
  2269. _sensorLoad();
  2270. _sensorInit();
  2271. // Configure based on settings
  2272. _sensorConfigure();
  2273. // Allow us to query key default
  2274. settingsRegisterDefaults({
  2275. [](const char* key) -> bool {
  2276. if (strncmp(key, "pwr", 3) == 0) return true;
  2277. return false;
  2278. },
  2279. _sensorQueryDefault
  2280. });
  2281. // Websockets integration, send sensor readings and configuration
  2282. #if WEB_SUPPORT
  2283. wsRegister()
  2284. .onVisible(_sensorWebSocketOnVisible)
  2285. .onConnected(_sensorWebSocketOnConnected)
  2286. .onData(_sensorWebSocketSendData)
  2287. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2288. #endif
  2289. // MQTT receive callback, atm only for energy reset
  2290. #if MQTT_SUPPORT
  2291. mqttRegister(_sensorMqttCallback);
  2292. #endif
  2293. // API
  2294. #if API_SUPPORT
  2295. _sensorApiSetup();
  2296. #endif
  2297. // Terminal
  2298. #if TERMINAL_SUPPORT
  2299. _sensorInitCommands();
  2300. #endif
  2301. // Main callbacks
  2302. espurnaRegisterLoop(sensorLoop);
  2303. espurnaRegisterReload(_sensorConfigure);
  2304. }
  2305. void sensorLoop() {
  2306. // Check if we still have uninitialized sensors
  2307. static unsigned long last_init = 0;
  2308. if (!_sensors_ready) {
  2309. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2310. last_init = millis();
  2311. _sensorInit();
  2312. }
  2313. }
  2314. if (_magnitudes.size() == 0) return;
  2315. // Tick hook, called every loop()
  2316. _sensorTick();
  2317. // Check if we should read new data
  2318. static unsigned long last_update = 0;
  2319. static unsigned long report_count = 0;
  2320. if (millis() - last_update > _sensor_read_interval) {
  2321. last_update = millis();
  2322. report_count = (report_count + 1) % _sensor_report_every;
  2323. double value_raw; // holds the raw value as the sensor returns it
  2324. double value_show; // holds the processed value applying units and decimals
  2325. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2326. // Pre-read hook, called every reading
  2327. _sensorPre();
  2328. // Get the first relay state
  2329. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2330. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2331. #endif
  2332. // Get readings
  2333. for (unsigned char magnitude_index = 0; magnitude_index < _magnitudes.size(); ++magnitude_index) {
  2334. auto& magnitude = _magnitudes[magnitude_index];
  2335. if (!magnitude.sensor->status()) continue;
  2336. // -------------------------------------------------------------
  2337. // Instant value
  2338. // -------------------------------------------------------------
  2339. value_raw = magnitude.sensor->value(magnitude.slot);
  2340. // Completely remove spurious values if relay is OFF
  2341. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2342. switch (magnitude.type) {
  2343. case MAGNITUDE_POWER_ACTIVE:
  2344. case MAGNITUDE_POWER_REACTIVE:
  2345. case MAGNITUDE_POWER_APPARENT:
  2346. case MAGNITUDE_POWER_FACTOR:
  2347. case MAGNITUDE_CURRENT:
  2348. case MAGNITUDE_ENERGY_DELTA:
  2349. if (relay_off) {
  2350. value_raw = 0.0;
  2351. }
  2352. break;
  2353. default:
  2354. break;
  2355. }
  2356. #endif
  2357. // In addition to that, we also check that value is above a certain threshold
  2358. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2359. value_raw = 0.0;
  2360. }
  2361. magnitude.last = value_raw;
  2362. magnitude.filter->add(value_raw);
  2363. // -------------------------------------------------------------
  2364. // Procesing (units and decimals)
  2365. // -------------------------------------------------------------
  2366. value_show = _magnitudeProcess(magnitude, value_raw);
  2367. {
  2368. char buffer[64];
  2369. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2370. for (auto& handler : _magnitude_read_handlers) {
  2371. handler(magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2372. }
  2373. }
  2374. // -------------------------------------------------------------
  2375. // Debug
  2376. // -------------------------------------------------------------
  2377. #if SENSOR_DEBUG
  2378. {
  2379. char buffer[64];
  2380. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2381. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2382. _magnitudeDescription(magnitude).c_str(),
  2383. magnitudeTopic(magnitude.type).c_str(),
  2384. buffer,
  2385. _magnitudeUnits(magnitude).c_str()
  2386. );
  2387. }
  2388. #endif
  2389. // -------------------------------------------------------------------
  2390. // Report when
  2391. // - report_count overflows after reaching _sensor_report_every
  2392. // - when magnitude specifies max_change and we greater or equal to it
  2393. // -------------------------------------------------------------------
  2394. bool report = (0 == report_count);
  2395. if (!std::isnan(magnitude.reported) && (magnitude.max_change > 0)) {
  2396. report = (std::abs(value_show - magnitude.reported) >= magnitude.max_change);
  2397. }
  2398. // Special case for energy, save readings to RAM and EEPROM
  2399. if (MAGNITUDE_ENERGY == magnitude.type) {
  2400. _magnitudeSaveEnergyTotal(magnitude, report);
  2401. }
  2402. if (report) {
  2403. value_filtered = _magnitudeProcess(magnitude, magnitude.filter->result());
  2404. magnitude.filter->reset();
  2405. if (magnitude.filter->size() != _sensor_report_every) {
  2406. magnitude.filter->resize(_sensor_report_every);
  2407. }
  2408. // Check if there is a minimum change threshold to report
  2409. if (std::isnan(magnitude.reported) || (std::abs(value_filtered - magnitude.reported) >= magnitude.min_change)) {
  2410. magnitude.reported = value_filtered;
  2411. _sensorReport(magnitude_index, magnitude);
  2412. }
  2413. } // if (report_count == 0)
  2414. }
  2415. // Post-read hook, called every reading
  2416. _sensorPost();
  2417. // And report data to modules that don't specifically track them
  2418. #if WEB_SUPPORT
  2419. wsPost(_sensorWebSocketSendData);
  2420. #endif
  2421. #if THINGSPEAK_SUPPORT
  2422. if (report_count == 0) tspkFlush();
  2423. #endif
  2424. }
  2425. }
  2426. #endif // SENSOR_SUPPORT