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.

2898 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
6 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
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
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 "broker.h"
  9. #include "domoticz.h"
  10. #include "i2c.h"
  11. #include "mqtt.h"
  12. #include "ntp.h"
  13. #include "relay.h"
  14. #include "terminal.h"
  15. #include "thingspeak.h"
  16. #include "rtcmem.h"
  17. #include "ws.h"
  18. #include <cfloat>
  19. #include <cmath>
  20. #include <limits>
  21. #include <vector>
  22. //--------------------------------------------------------------------------------
  23. // TODO: namespace { ... } ? sensor ctors need to work though
  24. #include "filters/LastFilter.h"
  25. #include "filters/MaxFilter.h"
  26. #include "filters/MedianFilter.h"
  27. #include "filters/MovingAverageFilter.h"
  28. #include "filters/SumFilter.h"
  29. #include "sensors/BaseSensor.h"
  30. #include "sensors/BaseEmonSensor.h"
  31. #include "sensors/BaseAnalogSensor.h"
  32. #if AM2320_SUPPORT
  33. #include "sensors/AM2320Sensor.h"
  34. #endif
  35. #if ANALOG_SUPPORT
  36. #include "sensors/AnalogSensor.h"
  37. #endif
  38. #if BH1750_SUPPORT
  39. #include "sensors/BH1750Sensor.h"
  40. #endif
  41. #if BMP180_SUPPORT
  42. #include "sensors/BMP180Sensor.h"
  43. #endif
  44. #if BMX280_SUPPORT
  45. #include "sensors/BMX280Sensor.h"
  46. #endif
  47. #if BME680_SUPPORT
  48. #include "sensors/BME680Sensor.h"
  49. #endif
  50. #if CSE7766_SUPPORT
  51. #include "sensors/CSE7766Sensor.h"
  52. #endif
  53. #if DALLAS_SUPPORT
  54. #include "sensors/DallasSensor.h"
  55. #endif
  56. #if DHT_SUPPORT
  57. #include "sensors/DHTSensor.h"
  58. #endif
  59. #if DIGITAL_SUPPORT
  60. #include "sensors/DigitalSensor.h"
  61. #endif
  62. #if ECH1560_SUPPORT
  63. #include "sensors/ECH1560Sensor.h"
  64. #endif
  65. #if EMON_ADC121_SUPPORT
  66. #include "sensors/EmonADC121Sensor.h"
  67. #endif
  68. #if EMON_ADS1X15_SUPPORT
  69. #include "sensors/EmonADS1X15Sensor.h"
  70. #endif
  71. #if EMON_ANALOG_SUPPORT
  72. #include "sensors/EmonAnalogSensor.h"
  73. #endif
  74. #if EVENTS_SUPPORT
  75. #include "sensors/EventSensor.h"
  76. #endif
  77. #if EZOPH_SUPPORT
  78. #include "sensors/EZOPHSensor.h"
  79. #endif
  80. #if GEIGER_SUPPORT
  81. #include "sensors/GeigerSensor.h"
  82. #endif
  83. #if GUVAS12SD_SUPPORT
  84. #include "sensors/GUVAS12SDSensor.h"
  85. #endif
  86. #if HLW8012_SUPPORT
  87. #include "sensors/HLW8012Sensor.h"
  88. #endif
  89. #if LDR_SUPPORT
  90. #include "sensors/LDRSensor.h"
  91. #endif
  92. #if MAX6675_SUPPORT
  93. #include "sensors/MAX6675Sensor.h"
  94. #endif
  95. #if MICS2710_SUPPORT
  96. #include "sensors/MICS2710Sensor.h"
  97. #endif
  98. #if MICS5525_SUPPORT
  99. #include "sensors/MICS5525Sensor.h"
  100. #endif
  101. #if MHZ19_SUPPORT
  102. #include "sensors/MHZ19Sensor.h"
  103. #endif
  104. #if NTC_SUPPORT
  105. #include "sensors/NTCSensor.h"
  106. #endif
  107. #if SDS011_SUPPORT
  108. #include "sensors/SDS011Sensor.h"
  109. #endif
  110. #if SENSEAIR_SUPPORT
  111. #include "sensors/SenseAirSensor.h"
  112. #endif
  113. #if PMSX003_SUPPORT
  114. #include "sensors/PMSX003Sensor.h"
  115. #endif
  116. #if PULSEMETER_SUPPORT
  117. #include "sensors/PulseMeterSensor.h"
  118. #endif
  119. #if PZEM004T_SUPPORT
  120. #include "sensors/PZEM004TSensor.h"
  121. #endif
  122. #if SHT3X_I2C_SUPPORT
  123. #include "sensors/SHT3XI2CSensor.h"
  124. #endif
  125. #if SI7021_SUPPORT
  126. #include "sensors/SI7021Sensor.h"
  127. #endif
  128. #if SONAR_SUPPORT
  129. #include "sensors/SonarSensor.h"
  130. #endif
  131. #if T6613_SUPPORT
  132. #include "sensors/T6613Sensor.h"
  133. #endif
  134. #if TMP3X_SUPPORT
  135. #include "sensors/TMP3XSensor.h"
  136. #endif
  137. #if V9261F_SUPPORT
  138. #include "sensors/V9261FSensor.h"
  139. #endif
  140. #if VEML6075_SUPPORT
  141. #include "sensors/VEML6075Sensor.h"
  142. #endif
  143. #if VL53L1X_SUPPORT
  144. #include "sensors/VL53L1XSensor.h"
  145. #endif
  146. #if ADE7953_SUPPORT
  147. #include "sensors/ADE7953Sensor.h"
  148. #endif
  149. #if SI1145_SUPPORT
  150. #include "sensors/SI1145Sensor.h"
  151. #endif
  152. #if HDC1080_SUPPORT
  153. #include "sensors/HDC1080Sensor.h"
  154. #endif
  155. #if PZEM004TV30_SUPPORT
  156. // TODO: this is temporary, until we have external API giving us swserial stream objects
  157. #include <SoftwareSerial.h>
  158. #include "sensors/PZEM004TV30Sensor.h"
  159. #endif
  160. //--------------------------------------------------------------------------------
  161. struct sensor_magnitude_t {
  162. private:
  163. constexpr static double _unset = std::numeric_limits<double>::quiet_NaN();
  164. static unsigned char _counts[MAGNITUDE_MAX];
  165. sensor_magnitude_t& operator=(const sensor_magnitude_t&) = default;
  166. void move(sensor_magnitude_t&& other) noexcept {
  167. *this = other;
  168. other.filter = nullptr;
  169. }
  170. public:
  171. static unsigned char counts(unsigned char type) {
  172. return _counts[type];
  173. }
  174. sensor_magnitude_t() = delete;
  175. sensor_magnitude_t(const sensor_magnitude_t&) = delete;
  176. sensor_magnitude_t(sensor_magnitude_t&& other) noexcept {
  177. *this = other;
  178. other.filter = nullptr;
  179. }
  180. sensor_magnitude_t& operator=(sensor_magnitude_t&& other) noexcept {
  181. move(std::move(other));
  182. return *this;
  183. }
  184. ~sensor_magnitude_t() noexcept {
  185. delete filter;
  186. }
  187. sensor_magnitude_t(unsigned char slot, unsigned char index_local, unsigned char type, sensor::Unit units, BaseSensor* sensor);
  188. BaseSensor * sensor { nullptr }; // Sensor object
  189. BaseFilter * filter { nullptr }; // Filter object
  190. unsigned char slot { 0u }; // Sensor slot # taken by the magnitude, used to access the measurement
  191. unsigned char type { MAGNITUDE_NONE }; // Type of measurement, returned by the BaseSensor::type(slot)
  192. unsigned char index_local { 0u }; // N'th magnitude of it's type, local to the sensor
  193. unsigned char index_global { 0u }; // ... and across all of the active sensors
  194. sensor::Unit units { sensor::Unit::None }; // Units of measurement
  195. unsigned char decimals { 0u }; // Number of decimals in textual representation
  196. double last { _unset }; // Last raw value from sensor (unfiltered)
  197. double reported { _unset }; // Last reported value
  198. double min_change { 0.0 }; // Minimum value change to report
  199. double max_change { 0.0 }; // Maximum value change to report
  200. double correction { 0.0 }; // Value correction (applied when processing)
  201. double zero_threshold { _unset }; // Reset value to zero when below threshold (applied when reading)
  202. };
  203. static_assert(
  204. std::is_nothrow_move_constructible<sensor_magnitude_t>::value,
  205. "std::vector<sensor_magnitude_t> should be able to work with resize()"
  206. );
  207. static_assert(
  208. !std::is_copy_constructible<sensor_magnitude_t>::value,
  209. "std::vector<sensor_magnitude_t> should only use move ctor"
  210. );
  211. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX] = {0};
  212. namespace sensor {
  213. // Base units
  214. // TODO: implement through a single class and allow direct access to the ::value
  215. KWh::KWh() :
  216. value(0)
  217. {}
  218. KWh::KWh(uint32_t value) :
  219. value(value)
  220. {}
  221. Ws::Ws() :
  222. value(0)
  223. {}
  224. Ws::Ws(uint32_t value) :
  225. value(value)
  226. {}
  227. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  228. Energy::Energy(KWh kwh, Ws ws) :
  229. kwh(kwh)
  230. {
  231. *this += ws;
  232. }
  233. Energy::Energy(KWh kwh) :
  234. kwh(kwh),
  235. ws()
  236. {}
  237. Energy::Energy(Ws ws) :
  238. kwh()
  239. {
  240. *this += ws;
  241. }
  242. Energy::Energy(double raw) {
  243. *this = raw;
  244. }
  245. Energy& Energy::operator =(double raw) {
  246. double _wh;
  247. kwh = modf(raw, &_wh);
  248. ws = _wh * 3600.0;
  249. return *this;
  250. }
  251. Energy& Energy::operator +=(Ws _ws) {
  252. while (_ws.value >= KwhMultiplier) {
  253. _ws.value -= KwhMultiplier;
  254. ++kwh.value;
  255. }
  256. ws.value += _ws.value;
  257. while (ws.value >= KwhMultiplier) {
  258. ws.value -= KwhMultiplier;
  259. ++kwh.value;
  260. }
  261. return *this;
  262. }
  263. Energy Energy::operator +(Ws watt_s) {
  264. Energy result(*this);
  265. result += watt_s;
  266. return result;
  267. }
  268. Energy::operator bool() {
  269. return (kwh.value > 0) && (ws.value > 0);
  270. }
  271. Ws Energy::asWs() {
  272. auto _kwh = kwh.value;
  273. while (_kwh >= KwhLimit) {
  274. _kwh -= KwhLimit;
  275. }
  276. return (_kwh * KwhMultiplier) + ws.value;
  277. }
  278. double Energy::asDouble() {
  279. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  280. }
  281. void Energy::reset() {
  282. kwh.value = 0;
  283. ws.value = 0;
  284. }
  285. } // namespace sensor
  286. // -----------------------------------------------------------------------------
  287. // Configuration
  288. // -----------------------------------------------------------------------------
  289. constexpr double _magnitudeCorrection(unsigned char type) {
  290. return (
  291. (MAGNITUDE_TEMPERATURE == type) ? (SENSOR_TEMPERATURE_CORRECTION) :
  292. (MAGNITUDE_HUMIDITY == type) ? (SENSOR_HUMIDITY_CORRECTION) :
  293. (MAGNITUDE_LUX == type) ? (SENSOR_LUX_CORRECTION) :
  294. (MAGNITUDE_PRESSURE == type) ? (SENSOR_PRESSURE_CORRECTION) :
  295. 0.0
  296. );
  297. }
  298. constexpr bool _magnitudeCanUseCorrection(unsigned char type) {
  299. return (
  300. (MAGNITUDE_TEMPERATURE == type) ? (true) :
  301. (MAGNITUDE_HUMIDITY == type) ? (true) :
  302. (MAGNITUDE_LUX == type) ? (true) :
  303. (MAGNITUDE_PRESSURE == type) ? (true) :
  304. false
  305. );
  306. }
  307. // -----------------------------------------------------------------------------
  308. // Energy persistence
  309. // -----------------------------------------------------------------------------
  310. std::vector<unsigned char> _sensor_save_count;
  311. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  312. bool _sensorIsEmon(BaseSensor* sensor) {
  313. return sensor->type() & sensor::type::Emon;
  314. }
  315. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  316. return sensor::Energy {
  317. sensor::KWh { Rtcmem->energy[index].kwh },
  318. sensor::Ws { Rtcmem->energy[index].ws }
  319. };
  320. }
  321. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  322. Rtcmem->energy[index].kwh = source.kwh.value;
  323. Rtcmem->energy[index].ws = source.ws.value;
  324. }
  325. sensor::Energy _sensorParseEnergy(const String& value) {
  326. sensor::Energy result;
  327. if (!value.length()) {
  328. return result;
  329. }
  330. const char* p { value.c_str() };
  331. char* endp { nullptr };
  332. auto kwh = strtoul(p, &endp, 10);
  333. if (!endp || (endp == p)) {
  334. return result;
  335. }
  336. result.kwh = kwh;
  337. const char* plus { strchr(p, '+') };
  338. if (!plus) {
  339. return result;
  340. }
  341. p = plus + 1;
  342. if (*p == '\0') {
  343. return result;
  344. }
  345. auto ws = strtoul(p, &endp, 10);
  346. if (!endp || (endp == p)) {
  347. return result;
  348. }
  349. result.ws = ws;
  350. return result;
  351. }
  352. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  353. if (!payload || !strlen(payload)) return;
  354. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  355. auto energy = _sensorParseEnergy(payload);
  356. sensor->resetEnergy(magnitude.index_local, energy);
  357. }
  358. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const String& payload) {
  359. _sensorApiResetEnergy(magnitude, payload.c_str());
  360. }
  361. sensor::Energy _sensorEnergyTotal(unsigned char index) {
  362. sensor::Energy result;
  363. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  364. result = _sensorRtcmemLoadEnergy(index);
  365. } else {
  366. result = _sensorParseEnergy(getSetting({"eneTotal", index}));
  367. }
  368. return result;
  369. }
  370. sensor::Energy sensorEnergyTotal() {
  371. return _sensorEnergyTotal(0);
  372. }
  373. void _sensorResetEnergyTotal(unsigned char index) {
  374. delSetting({"eneTotal", index});
  375. delSetting({"eneTime", index});
  376. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  377. Rtcmem->energy[index].kwh = 0;
  378. Rtcmem->energy[index].ws = 0;
  379. }
  380. }
  381. void _magnitudeSaveEnergyTotal(sensor_magnitude_t& magnitude, bool persistent) {
  382. if (magnitude.type != MAGNITUDE_ENERGY) return;
  383. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  384. const auto energy = sensor->totalEnergy();
  385. // Always save to RTCMEM
  386. if (magnitude.index_global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  387. _sensorRtcmemSaveEnergy(magnitude.index_global, energy);
  388. }
  389. // Save to EEPROM every '_sensor_save_every' readings
  390. // Format is `<kwh>+<ws>`, value without `+` is treated as `<ws>`
  391. if (persistent && _sensor_save_every) {
  392. _sensor_save_count[magnitude.index_global] =
  393. (_sensor_save_count[magnitude.index_global] + 1) % _sensor_save_every;
  394. if (0 == _sensor_save_count[magnitude.index_global]) {
  395. const String total = String(energy.kwh.value) + "+" + String(energy.ws.value);
  396. setSetting({"eneTotal", magnitude.index_global}, total);
  397. #if NTP_SUPPORT
  398. if (ntpSynced()) setSetting({"eneTime", magnitude.index_global}, ntpDateTime());
  399. #endif
  400. }
  401. }
  402. }
  403. // ---------------------------------------------------------------------------
  404. BrokerBind(SensorReadBroker);
  405. BrokerBind(SensorReportBroker);
  406. std::vector<BaseSensor *> _sensors;
  407. std::vector<sensor_magnitude_t> _magnitudes;
  408. bool _sensors_ready = false;
  409. bool _sensor_realtime = API_REAL_TIME_VALUES;
  410. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  411. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  412. // -----------------------------------------------------------------------------
  413. // Private
  414. // -----------------------------------------------------------------------------
  415. BaseFilter* _magnitudeCreateFilter(unsigned char type, size_t size) {
  416. BaseFilter* filter { nullptr };
  417. switch (type) {
  418. case MAGNITUDE_IAQ:
  419. case MAGNITUDE_IAQ_STATIC:
  420. case MAGNITUDE_ENERGY:
  421. filter = new LastFilter();
  422. break;
  423. case MAGNITUDE_COUNT:
  424. case MAGNITUDE_GEIGER_CPM:
  425. case MAGNITUDE_GEIGER_SIEVERT:
  426. case MAGNITUDE_ENERGY_DELTA:
  427. filter = new SumFilter();
  428. break;
  429. case MAGNITUDE_EVENT:
  430. case MAGNITUDE_DIGITAL:
  431. filter = new MaxFilter();
  432. break;
  433. default:
  434. filter = new MedianFilter();
  435. break;
  436. }
  437. filter->resize(size);
  438. return filter;
  439. }
  440. sensor_magnitude_t::sensor_magnitude_t(unsigned char slot_, unsigned char index_local_, unsigned char type_, sensor::Unit units_, BaseSensor* sensor_) :
  441. sensor(sensor_),
  442. filter(_magnitudeCreateFilter(type_, _sensor_report_every)),
  443. slot(slot_),
  444. type(type_),
  445. index_local(index_local_),
  446. index_global(_counts[type]),
  447. units(units_)
  448. {
  449. ++_counts[type];
  450. }
  451. // Hardcoded decimals for each magnitude
  452. unsigned char _sensorUnitDecimals(sensor::Unit unit) {
  453. switch (unit) {
  454. case sensor::Unit::Celcius:
  455. case sensor::Unit::Farenheit:
  456. return 1;
  457. case sensor::Unit::Percentage:
  458. return 0;
  459. case sensor::Unit::Hectopascal:
  460. return 2;
  461. case sensor::Unit::Ampere:
  462. return 3;
  463. case sensor::Unit::Volt:
  464. return 0;
  465. case sensor::Unit::Watt:
  466. case sensor::Unit::Voltampere:
  467. case sensor::Unit::VoltampereReactive:
  468. return 0;
  469. case sensor::Unit::Kilowatt:
  470. case sensor::Unit::Kilovoltampere:
  471. case sensor::Unit::KilovoltampereReactive:
  472. return 3;
  473. case sensor::Unit::KilowattHour:
  474. return 3;
  475. case sensor::Unit::WattSecond:
  476. return 0;
  477. case sensor::Unit::CountsPerMinute:
  478. case sensor::Unit::MicrosievertPerHour:
  479. return 4;
  480. case sensor::Unit::Meter:
  481. return 3;
  482. case sensor::Unit::Hertz:
  483. return 1;
  484. case sensor::Unit::UltravioletIndex:
  485. return 3;
  486. case sensor::Unit::Ph:
  487. return 3;
  488. case sensor::Unit::None:
  489. default:
  490. return 0;
  491. }
  492. }
  493. String magnitudeTopic(unsigned char type) {
  494. const __FlashStringHelper* result = nullptr;
  495. switch (type) {
  496. case MAGNITUDE_TEMPERATURE:
  497. result = F("temperature");
  498. break;
  499. case MAGNITUDE_HUMIDITY:
  500. result = F("humidity");
  501. break;
  502. case MAGNITUDE_PRESSURE:
  503. result = F("pressure");
  504. break;
  505. case MAGNITUDE_CURRENT:
  506. result = F("current");
  507. break;
  508. case MAGNITUDE_VOLTAGE:
  509. result = F("voltage");
  510. break;
  511. case MAGNITUDE_POWER_ACTIVE:
  512. result = F("power");
  513. break;
  514. case MAGNITUDE_POWER_APPARENT:
  515. result = F("apparent");
  516. break;
  517. case MAGNITUDE_POWER_REACTIVE:
  518. result = F("reactive");
  519. break;
  520. case MAGNITUDE_POWER_FACTOR:
  521. result = F("factor");
  522. break;
  523. case MAGNITUDE_ENERGY:
  524. result = F("energy");
  525. break;
  526. case MAGNITUDE_ENERGY_DELTA:
  527. result = F("energy_delta");
  528. break;
  529. case MAGNITUDE_ANALOG:
  530. result = F("analog");
  531. break;
  532. case MAGNITUDE_DIGITAL:
  533. result = F("digital");
  534. break;
  535. case MAGNITUDE_EVENT:
  536. result = F("event");
  537. break;
  538. case MAGNITUDE_PM1dot0:
  539. result = F("pm1dot0");
  540. break;
  541. case MAGNITUDE_PM2dot5:
  542. result = F("pm2dot5");
  543. break;
  544. case MAGNITUDE_PM10:
  545. result = F("pm10");
  546. break;
  547. case MAGNITUDE_CO2:
  548. result = F("co2");
  549. break;
  550. case MAGNITUDE_VOC:
  551. result = F("voc");
  552. break;
  553. case MAGNITUDE_IAQ:
  554. result = F("iaq");
  555. break;
  556. case MAGNITUDE_IAQ_ACCURACY:
  557. result = F("iaq_accuracy");
  558. break;
  559. case MAGNITUDE_IAQ_STATIC:
  560. result = F("iaq_static");
  561. break;
  562. case MAGNITUDE_LUX:
  563. result = F("lux");
  564. break;
  565. case MAGNITUDE_UVA:
  566. result = F("uva");
  567. break;
  568. case MAGNITUDE_UVB:
  569. result = F("uvb");
  570. break;
  571. case MAGNITUDE_UVI:
  572. result = F("uvi");
  573. break;
  574. case MAGNITUDE_DISTANCE:
  575. result = F("distance");
  576. break;
  577. case MAGNITUDE_HCHO:
  578. result = F("hcho");
  579. break;
  580. case MAGNITUDE_GEIGER_CPM:
  581. result = F("ldr_cpm"); // local dose rate [Counts per minute]
  582. break;
  583. case MAGNITUDE_GEIGER_SIEVERT:
  584. result = F("ldr_uSvh"); // local dose rate [µSievert per hour]
  585. break;
  586. case MAGNITUDE_COUNT:
  587. result = F("count");
  588. break;
  589. case MAGNITUDE_NO2:
  590. result = F("no2");
  591. break;
  592. case MAGNITUDE_CO:
  593. result = F("co");
  594. break;
  595. case MAGNITUDE_RESISTANCE:
  596. result = F("resistance");
  597. break;
  598. case MAGNITUDE_PH:
  599. result = F("ph");
  600. break;
  601. case MAGNITUDE_FREQUENCY:
  602. result = F("frequency");
  603. break;
  604. case MAGNITUDE_NONE:
  605. default:
  606. result = F("unknown");
  607. break;
  608. }
  609. return String(result);
  610. }
  611. String _magnitudeTopic(const sensor_magnitude_t& magnitude) {
  612. return magnitudeTopic(magnitude.type);
  613. }
  614. String _magnitudeUnits(const sensor_magnitude_t& magnitude) {
  615. const __FlashStringHelper* result = nullptr;
  616. switch (magnitude.units) {
  617. case sensor::Unit::Farenheit:
  618. result = F("°F");
  619. break;
  620. case sensor::Unit::Celcius:
  621. result = F("°C");
  622. break;
  623. case sensor::Unit::Percentage:
  624. result = F("%");
  625. break;
  626. case sensor::Unit::Hectopascal:
  627. result = F("hPa");
  628. break;
  629. case sensor::Unit::Ampere:
  630. result = F("A");
  631. break;
  632. case sensor::Unit::Volt:
  633. result = F("V");
  634. break;
  635. case sensor::Unit::Watt:
  636. result = F("W");
  637. break;
  638. case sensor::Unit::Kilowatt:
  639. result = F("kW");
  640. break;
  641. case sensor::Unit::Voltampere:
  642. result = F("VA");
  643. break;
  644. case sensor::Unit::Kilovoltampere:
  645. result = F("kVA");
  646. break;
  647. case sensor::Unit::VoltampereReactive:
  648. result = F("VAR");
  649. break;
  650. case sensor::Unit::KilovoltampereReactive:
  651. result = F("kVAR");
  652. break;
  653. case sensor::Unit::Joule:
  654. //aka case sensor::Unit::WattSecond:
  655. result = F("J");
  656. break;
  657. case sensor::Unit::KilowattHour:
  658. result = F("kWh");
  659. break;
  660. case sensor::Unit::MicrogrammPerCubicMeter:
  661. result = F("µg/m³");
  662. break;
  663. case sensor::Unit::PartsPerMillion:
  664. result = F("ppm");
  665. break;
  666. case sensor::Unit::Lux:
  667. result = F("lux");
  668. break;
  669. case sensor::Unit::Ohm:
  670. result = F("ohm");
  671. break;
  672. case sensor::Unit::MilligrammPerCubicMeter:
  673. result = F("mg/m³");
  674. break;
  675. case sensor::Unit::CountsPerMinute:
  676. result = F("cpm");
  677. break;
  678. case sensor::Unit::MicrosievertPerHour:
  679. result = F("µSv/h");
  680. break;
  681. case sensor::Unit::Meter:
  682. result = F("m");
  683. break;
  684. case sensor::Unit::Hertz:
  685. result = F("Hz");
  686. break;
  687. case sensor::Unit::None:
  688. default:
  689. result = F("");
  690. break;
  691. }
  692. return String(result);
  693. }
  694. String magnitudeUnits(unsigned char index) {
  695. if (index >= magnitudeCount()) return String();
  696. return _magnitudeUnits(_magnitudes[index]);
  697. }
  698. // Choose unit based on type of magnitude we use
  699. sensor::Unit _magnitudeUnitFilter(const sensor_magnitude_t& magnitude, sensor::Unit updated) {
  700. auto result = magnitude.units;
  701. switch (magnitude.type) {
  702. case MAGNITUDE_TEMPERATURE: {
  703. switch (updated) {
  704. case sensor::Unit::Celcius:
  705. case sensor::Unit::Farenheit:
  706. case sensor::Unit::Kelvin:
  707. result = updated;
  708. break;
  709. default:
  710. break;
  711. }
  712. break;
  713. }
  714. case MAGNITUDE_POWER_ACTIVE: {
  715. switch (updated) {
  716. case sensor::Unit::Kilowatt:
  717. case sensor::Unit::Watt:
  718. result = updated;
  719. break;
  720. default:
  721. break;
  722. }
  723. break;
  724. }
  725. case MAGNITUDE_ENERGY: {
  726. switch (updated) {
  727. case sensor::Unit::KilowattHour:
  728. case sensor::Unit::Joule:
  729. result = updated;
  730. break;
  731. default:
  732. break;
  733. }
  734. break;
  735. }
  736. default:
  737. result = updated;
  738. break;
  739. }
  740. return result;
  741. };
  742. double _magnitudeProcess(const sensor_magnitude_t& magnitude, double value) {
  743. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  744. switch (magnitude.sensor->units(magnitude.slot)) {
  745. case sensor::Unit::Celcius:
  746. if (magnitude.units == sensor::Unit::Farenheit) {
  747. value = (value * 1.8) + 32.0;
  748. } else if (magnitude.units == sensor::Unit::Kelvin) {
  749. value = value + 273.15;
  750. }
  751. break;
  752. case sensor::Unit::Percentage:
  753. value = constrain(value, 0.0, 100.0);
  754. break;
  755. case sensor::Unit::Watt:
  756. case sensor::Unit::Voltampere:
  757. case sensor::Unit::VoltampereReactive:
  758. if ((magnitude.units == sensor::Unit::Kilowatt)
  759. || (magnitude.units == sensor::Unit::Kilovoltampere)
  760. || (magnitude.units == sensor::Unit::KilovoltampereReactive)) {
  761. value = value / 1.0e+3;
  762. }
  763. break;
  764. case sensor::Unit::KilowattHour:
  765. // TODO: we may end up with inf at some point?
  766. if (magnitude.units == sensor::Unit::Joule) {
  767. value = value * 3.6e+6;
  768. }
  769. break;
  770. default:
  771. break;
  772. }
  773. value = value + magnitude.correction;
  774. return roundTo(value, magnitude.decimals);
  775. }
  776. String _magnitudeDescription(const sensor_magnitude_t& magnitude) {
  777. return magnitude.sensor->description(magnitude.slot);
  778. }
  779. // -----------------------------------------------------------------------------
  780. // do `callback(type)` for each present magnitude
  781. template<typename T>
  782. void _magnitudeForEachCounted(T callback) {
  783. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  784. if (sensor_magnitude_t::counts(type)) {
  785. callback(type);
  786. }
  787. }
  788. }
  789. // check if `callback(type)` returns `true` at least once
  790. template<typename T>
  791. bool _magnitudeForEachCountedCheck(T callback) {
  792. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  793. if (sensor_magnitude_t::counts(type) && callback(type)) {
  794. return true;
  795. }
  796. }
  797. return false;
  798. }
  799. // do `callback(type)` for each error type
  800. template<typename T>
  801. void _sensorForEachError(T callback) {
  802. for (unsigned char error = SENSOR_ERROR_OK; error < SENSOR_ERROR_MAX; ++error) {
  803. callback(error);
  804. }
  805. }
  806. const char * const _magnitudeSettingsPrefix(unsigned char type) {
  807. switch (type) {
  808. case MAGNITUDE_TEMPERATURE: return "tmp";
  809. case MAGNITUDE_HUMIDITY: return "hum";
  810. case MAGNITUDE_PRESSURE: return "press";
  811. case MAGNITUDE_CURRENT: return "curr";
  812. case MAGNITUDE_VOLTAGE: return "volt";
  813. case MAGNITUDE_POWER_ACTIVE: return "pwrP";
  814. case MAGNITUDE_POWER_APPARENT: return "pwrQ";
  815. case MAGNITUDE_POWER_REACTIVE: return "pwrModS";
  816. case MAGNITUDE_POWER_FACTOR: return "pwrPF";
  817. case MAGNITUDE_ENERGY: return "ene";
  818. case MAGNITUDE_ENERGY_DELTA: return "eneDelta";
  819. case MAGNITUDE_ANALOG: return "analog";
  820. case MAGNITUDE_DIGITAL: return "digital";
  821. case MAGNITUDE_EVENT: return "event";
  822. case MAGNITUDE_PM1dot0: return "pm1dot0";
  823. case MAGNITUDE_PM2dot5: return "pm1dot5";
  824. case MAGNITUDE_PM10: return "pm10";
  825. case MAGNITUDE_CO2: return "co2";
  826. case MAGNITUDE_VOC: return "voc";
  827. case MAGNITUDE_IAQ: return "iaq";
  828. case MAGNITUDE_IAQ_ACCURACY: return "iaqAccuracy";
  829. case MAGNITUDE_IAQ_STATIC: return "iaqStatic";
  830. case MAGNITUDE_LUX: return "lux";
  831. case MAGNITUDE_UVA: return "uva";
  832. case MAGNITUDE_UVB: return "uvb";
  833. case MAGNITUDE_UVI: return "uvi";
  834. case MAGNITUDE_DISTANCE: return "distance";
  835. case MAGNITUDE_HCHO: return "hcho";
  836. case MAGNITUDE_GEIGER_CPM: return "gcpm";
  837. case MAGNITUDE_GEIGER_SIEVERT: return "gsiev";
  838. case MAGNITUDE_COUNT: return "count";
  839. case MAGNITUDE_NO2: return "no2";
  840. case MAGNITUDE_CO: return "co";
  841. case MAGNITUDE_RESISTANCE: return "res";
  842. case MAGNITUDE_PH: return "ph";
  843. case MAGNITUDE_FREQUENCY: return "freq";
  844. default: return nullptr;
  845. }
  846. }
  847. template <typename T>
  848. String _magnitudeSettingsKey(sensor_magnitude_t& magnitude, T&& suffix) {
  849. return String(_magnitudeSettingsPrefix(magnitude.type)) + suffix;
  850. }
  851. bool _sensorMatchKeyPrefix(const char * key) {
  852. if (strncmp(key, "sns", 3) == 0) return true;
  853. if (strncmp(key, "pwr", 3) == 0) return true;
  854. return _magnitudeForEachCountedCheck([key](unsigned char type) {
  855. const char* const prefix { _magnitudeSettingsPrefix(type) };
  856. return (strncmp(prefix, key, strlen(prefix)) == 0);
  857. });
  858. }
  859. const String _sensorQueryDefault(const String& key) {
  860. auto get_defaults = [](unsigned char type, BaseSensor* ptr) -> String {
  861. if (!ptr) return String();
  862. auto* sensor = static_cast<BaseEmonSensor*>(ptr);
  863. switch (type) {
  864. case MAGNITUDE_CURRENT:
  865. return String(sensor->defaultCurrentRatio());
  866. case MAGNITUDE_VOLTAGE:
  867. return String(sensor->defaultVoltageRatio());
  868. case MAGNITUDE_POWER_ACTIVE:
  869. return String(sensor->defaultPowerRatio());
  870. case MAGNITUDE_ENERGY:
  871. return String(sensor->defaultEnergyRatio());
  872. default:
  873. return String();
  874. }
  875. };
  876. auto magnitude_key = [](const sensor_magnitude_t& magnitude) -> SettingsKey {
  877. switch (magnitude.type) {
  878. case MAGNITUDE_CURRENT:
  879. return {"pwrRatioC", magnitude.index_global};
  880. case MAGNITUDE_VOLTAGE:
  881. return {"pwrRatioV", magnitude.index_global};
  882. case MAGNITUDE_POWER_ACTIVE:
  883. return {"pwrRatioP", magnitude.index_global};
  884. case MAGNITUDE_ENERGY:
  885. return {"pwrRatioE", magnitude.index_global};
  886. default:
  887. return "";
  888. }
  889. };
  890. unsigned char type = MAGNITUDE_NONE;
  891. BaseSensor* target = nullptr;
  892. for (auto& magnitude : _magnitudes) {
  893. switch (magnitude.type) {
  894. case MAGNITUDE_CURRENT:
  895. case MAGNITUDE_VOLTAGE:
  896. case MAGNITUDE_POWER_ACTIVE:
  897. case MAGNITUDE_ENERGY: {
  898. auto ratioKey(magnitude_key(magnitude));
  899. if (ratioKey == key) {
  900. target = magnitude.sensor;
  901. type = magnitude.type;
  902. goto return_defaults;
  903. }
  904. break;
  905. }
  906. default:
  907. break;
  908. }
  909. }
  910. return_defaults:
  911. return get_defaults(type, target);
  912. }
  913. #if WEB_SUPPORT
  914. bool _sensorWebSocketOnKeyCheck(const char* key, JsonVariant&) {
  915. return _sensorMatchKeyPrefix(key);
  916. }
  917. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  918. void sensorWebSocketMagnitudes(JsonObject& root, const String& prefix) {
  919. // ws produces flat list <prefix>Magnitudes
  920. const String ws_name = prefix + "Magnitudes";
  921. // config uses <prefix>Magnitude<index> (cut 's')
  922. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  923. JsonObject& list = root.createNestedObject(ws_name);
  924. list["size"] = magnitudeCount();
  925. JsonArray& type = list.createNestedArray("type");
  926. JsonArray& index = list.createNestedArray("index");
  927. JsonArray& idx = list.createNestedArray("idx");
  928. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  929. type.add(magnitudeType(i));
  930. index.add(magnitudeIndex(i));
  931. idx.add(getSetting({conf_name, i}, 0));
  932. }
  933. }
  934. String sensorError(unsigned char error) {
  935. const __FlashStringHelper* result = nullptr;
  936. switch (error) {
  937. case SENSOR_ERROR_OK:
  938. result = F("OK");
  939. break;
  940. case SENSOR_ERROR_OUT_OF_RANGE:
  941. result = F("Out of Range");
  942. break;
  943. case SENSOR_ERROR_WARM_UP:
  944. result = F("Warming Up");
  945. break;
  946. case SENSOR_ERROR_TIMEOUT:
  947. result = F("Timeout");
  948. break;
  949. case SENSOR_ERROR_UNKNOWN_ID:
  950. result = F("Unknown ID");
  951. break;
  952. case SENSOR_ERROR_CRC:
  953. result = F("CRC / Data Error");
  954. break;
  955. case SENSOR_ERROR_I2C:
  956. result = F("I2C Error");
  957. break;
  958. case SENSOR_ERROR_GPIO_USED:
  959. result = F("GPIO Already Used");
  960. break;
  961. case SENSOR_ERROR_CALIBRATION:
  962. result = F("Calibration Error");
  963. break;
  964. default:
  965. case SENSOR_ERROR_OTHER:
  966. result = F("Other / Unknown Error");
  967. break;
  968. }
  969. return result;
  970. }
  971. String magnitudeName(unsigned char type) {
  972. const __FlashStringHelper* result = nullptr;
  973. switch (type) {
  974. case MAGNITUDE_TEMPERATURE:
  975. result = F("Temperature");
  976. break;
  977. case MAGNITUDE_HUMIDITY:
  978. result = F("Humidity");
  979. break;
  980. case MAGNITUDE_PRESSURE:
  981. result = F("Pressure");
  982. break;
  983. case MAGNITUDE_CURRENT:
  984. result = F("Current");
  985. break;
  986. case MAGNITUDE_VOLTAGE:
  987. result = F("Voltage");
  988. break;
  989. case MAGNITUDE_POWER_ACTIVE:
  990. result = F("Active Power");
  991. break;
  992. case MAGNITUDE_POWER_APPARENT:
  993. result = F("Apparent Power");
  994. break;
  995. case MAGNITUDE_POWER_REACTIVE:
  996. result = F("Reactive Power");
  997. break;
  998. case MAGNITUDE_POWER_FACTOR:
  999. result = F("Power Factor");
  1000. break;
  1001. case MAGNITUDE_ENERGY:
  1002. result = F("Energy");
  1003. break;
  1004. case MAGNITUDE_ENERGY_DELTA:
  1005. result = F("Energy (delta)");
  1006. break;
  1007. case MAGNITUDE_ANALOG:
  1008. result = F("Analog");
  1009. break;
  1010. case MAGNITUDE_DIGITAL:
  1011. result = F("Digital");
  1012. break;
  1013. case MAGNITUDE_EVENT:
  1014. result = F("Event");
  1015. break;
  1016. case MAGNITUDE_PM1dot0:
  1017. result = F("PM1.0");
  1018. break;
  1019. case MAGNITUDE_PM2dot5:
  1020. result = F("PM2.5");
  1021. break;
  1022. case MAGNITUDE_PM10:
  1023. result = F("PM10");
  1024. break;
  1025. case MAGNITUDE_CO2:
  1026. result = F("CO2");
  1027. break;
  1028. case MAGNITUDE_VOC:
  1029. result = F("VOC");
  1030. break;
  1031. case MAGNITUDE_IAQ_STATIC:
  1032. result = F("IAQ (Static)");
  1033. break;
  1034. case MAGNITUDE_IAQ:
  1035. result = F("IAQ");
  1036. break;
  1037. case MAGNITUDE_IAQ_ACCURACY:
  1038. result = F("IAQ Accuracy");
  1039. break;
  1040. case MAGNITUDE_LUX:
  1041. result = F("Lux");
  1042. break;
  1043. case MAGNITUDE_UVA:
  1044. result = F("UVA");
  1045. break;
  1046. case MAGNITUDE_UVB:
  1047. result = F("UVB");
  1048. break;
  1049. case MAGNITUDE_UVI:
  1050. result = F("UVI");
  1051. break;
  1052. case MAGNITUDE_DISTANCE:
  1053. result = F("Distance");
  1054. break;
  1055. case MAGNITUDE_HCHO:
  1056. result = F("HCHO");
  1057. break;
  1058. case MAGNITUDE_GEIGER_CPM:
  1059. case MAGNITUDE_GEIGER_SIEVERT:
  1060. result = F("Local Dose Rate");
  1061. break;
  1062. case MAGNITUDE_COUNT:
  1063. result = F("Count");
  1064. break;
  1065. case MAGNITUDE_NO2:
  1066. result = F("NO2");
  1067. break;
  1068. case MAGNITUDE_CO:
  1069. result = F("CO");
  1070. break;
  1071. case MAGNITUDE_RESISTANCE:
  1072. result = F("Resistance");
  1073. break;
  1074. case MAGNITUDE_PH:
  1075. result = F("pH");
  1076. break;
  1077. case MAGNITUDE_FREQUENCY:
  1078. result = F("Frequency");
  1079. break;
  1080. case MAGNITUDE_NONE:
  1081. default:
  1082. break;
  1083. }
  1084. return String(result);
  1085. }
  1086. void _sensorWebSocketOnVisible(JsonObject& root) {
  1087. root["snsVisible"] = 1;
  1088. // prepare available magnitude types
  1089. JsonArray& magnitudes = root.createNestedArray("snsMagnitudes");
  1090. _magnitudeForEachCounted([&magnitudes](unsigned char type) {
  1091. JsonArray& tuple = magnitudes.createNestedArray();
  1092. tuple.add(type);
  1093. tuple.add(_magnitudeSettingsPrefix(type));
  1094. tuple.add(magnitudeName(type));
  1095. });
  1096. // and available error types
  1097. JsonArray& errors = root.createNestedArray("snsErrors");
  1098. _sensorForEachError([&errors](unsigned char error) {
  1099. JsonArray& tuple = errors.createNestedArray();
  1100. tuple.add(error);
  1101. tuple.add(sensorError(error));
  1102. });
  1103. }
  1104. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  1105. // retrieve per-type ...Correction settings, when available
  1106. _magnitudeForEachCounted([&root](unsigned char type) {
  1107. if (_magnitudeCanUseCorrection(type)) {
  1108. auto key = String(_magnitudeSettingsPrefix(type)) + F("Correction");
  1109. root[key] = getSetting(key, _magnitudeCorrection(type));
  1110. }
  1111. });
  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. #if BROKER_SUPPORT
  1922. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, magnitude.reported, buffer);
  1923. #endif
  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& string) {
  2003. const int value = string.toInt();
  2004. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  2005. return static_cast<sensor::Unit>(value);
  2006. }
  2007. return sensor::Unit::None;
  2008. }
  2009. template <>
  2010. String serialize(const sensor::Unit& unit) {
  2011. return String(static_cast<int>(unit));
  2012. }
  2013. } // ns settings::internal
  2014. } // ns settings
  2015. void _sensorConfigure() {
  2016. // General sensor settings for reporting and saving
  2017. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  2018. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  2019. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  2020. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  2021. // pre-load some settings that are controlled via old build flags
  2022. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  2023. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  2024. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  2025. // Apply settings based on sensor type
  2026. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  2027. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  2028. {
  2029. if (getSetting("snsResetCalibration", false)) {
  2030. switch (_sensors[index]->getID()) {
  2031. case SENSOR_MICS2710_ID:
  2032. case SENSOR_MICS5525_ID: {
  2033. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  2034. sensor->calibrate();
  2035. setSetting("snsR0", sensor->getR0());
  2036. break;
  2037. }
  2038. default:
  2039. break;
  2040. }
  2041. }
  2042. }
  2043. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  2044. if (_sensorIsEmon(_sensors[index])) {
  2045. // TODO: ::isEmon() ?
  2046. double value;
  2047. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  2048. if ((value = getSetting("pwrExpectedC", 0.0))) {
  2049. sensor->expectedCurrent(value);
  2050. delSetting("pwrExpectedC");
  2051. setSetting("pwrRatioC", sensor->getCurrentRatio());
  2052. }
  2053. if ((value = getSetting("pwrExpectedV", 0.0))) {
  2054. delSetting("pwrExpectedV");
  2055. sensor->expectedVoltage(value);
  2056. setSetting("pwrRatioV", sensor->getVoltageRatio());
  2057. }
  2058. if ((value = getSetting("pwrExpectedP", 0.0))) {
  2059. delSetting("pwrExpectedP");
  2060. sensor->expectedPower(value);
  2061. setSetting("pwrRatioP", sensor->getPowerRatio());
  2062. }
  2063. if (getSetting("pwrResetE", false)) {
  2064. delSetting("pwrResetE");
  2065. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  2066. sensor->resetEnergy(index);
  2067. _sensorResetEnergyTotal(index);
  2068. }
  2069. }
  2070. if (getSetting("pwrResetCalibration", false)) {
  2071. delSetting("pwrResetCalibration");
  2072. delSetting("pwrRatioC");
  2073. delSetting("pwrRatioV");
  2074. delSetting("pwrRatioP");
  2075. sensor->resetRatios();
  2076. }
  2077. } // is emon?
  2078. }
  2079. // Update magnitude config, filter sizes and reset energy if needed
  2080. {
  2081. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  2082. auto& magnitude = _magnitudes.at(index);
  2083. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  2084. if (_sensorIsEmon(magnitude.sensor)) {
  2085. // TODO: compatibility proxy, fetch global key before indexed
  2086. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  2087. return getSetting({key, index}, getSetting(key, default_value));
  2088. };
  2089. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  2090. switch (magnitude.type) {
  2091. case MAGNITUDE_CURRENT:
  2092. sensor->setCurrentRatio(
  2093. magnitude.index_local, get_ratio("pwrRatioC", magnitude.index_global, sensor->defaultCurrentRatio())
  2094. );
  2095. break;
  2096. case MAGNITUDE_POWER_ACTIVE:
  2097. sensor->setPowerRatio(
  2098. magnitude.index_local, get_ratio("pwrRatioP", magnitude.index_global, sensor->defaultPowerRatio())
  2099. );
  2100. break;
  2101. case MAGNITUDE_VOLTAGE:
  2102. sensor->setVoltageRatio(
  2103. magnitude.index_local, get_ratio("pwrRatioV", magnitude.index_global, sensor->defaultVoltageRatio())
  2104. );
  2105. sensor->setVoltage(
  2106. magnitude.index_local, get_ratio("pwrVoltage", magnitude.index_global, sensor->defaultVoltage())
  2107. );
  2108. break;
  2109. case MAGNITUDE_ENERGY:
  2110. sensor->setEnergyRatio(
  2111. magnitude.index_local, get_ratio("pwrRatioE", magnitude.index_global, sensor->defaultEnergyRatio())
  2112. );
  2113. break;
  2114. default:
  2115. break;
  2116. }
  2117. }
  2118. // adjust type-specific units
  2119. {
  2120. const sensor::Unit default_unit { magnitude.sensor->units(magnitude.slot) };
  2121. const String key {
  2122. String(_magnitudeSettingsPrefix(magnitude.type)) + F("Units") + String(magnitude.index_global, 10) };
  2123. magnitude.units = _magnitudeUnitFilter(magnitude, getSetting(key, default_unit));
  2124. }
  2125. // some magnitudes allow to be corrected with an offset
  2126. {
  2127. if (_magnitudeCanUseCorrection(magnitude.type)) {
  2128. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  2129. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  2130. }
  2131. }
  2132. // some sensors can override decimal values if sensor has more precision than default
  2133. {
  2134. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  2135. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  2136. magnitude.decimals = (unsigned char) decimals;
  2137. }
  2138. // Per-magnitude min & max delta settings
  2139. // - min controls whether we report at all when report_count overflows
  2140. // - max will trigger report as soon as read value is greater than the specified delta
  2141. // (atm this works best for accumulated magnitudes, like energy)
  2142. {
  2143. auto min_default = 0.0;
  2144. auto max_default = 0.0;
  2145. switch (magnitude.type) {
  2146. case MAGNITUDE_TEMPERATURE:
  2147. min_default = tmp_min_delta;
  2148. break;
  2149. case MAGNITUDE_HUMIDITY:
  2150. min_default = hum_min_delta;
  2151. break;
  2152. case MAGNITUDE_ENERGY:
  2153. max_default = ene_max_delta;
  2154. break;
  2155. default:
  2156. break;
  2157. }
  2158. magnitude.min_change = getSetting(
  2159. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2160. min_default
  2161. );
  2162. magnitude.max_change = getSetting(
  2163. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2164. max_default
  2165. );
  2166. }
  2167. // Sometimes we want to ensure the value is above certain threshold before reporting
  2168. {
  2169. magnitude.zero_threshold = getSetting(
  2170. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2171. std::numeric_limits<double>::quiet_NaN()
  2172. );
  2173. }
  2174. // in case we don't save energy periodically, purge existing value in ram & settings
  2175. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2176. _sensorResetEnergyTotal(magnitude.index_global);
  2177. }
  2178. }
  2179. }
  2180. saveSettings();
  2181. }
  2182. // -----------------------------------------------------------------------------
  2183. // Public
  2184. // -----------------------------------------------------------------------------
  2185. unsigned char sensorCount() {
  2186. return _sensors.size();
  2187. }
  2188. unsigned char magnitudeCount() {
  2189. return _magnitudes.size();
  2190. }
  2191. unsigned char magnitudeType(unsigned char index) {
  2192. if (index < _magnitudes.size()) {
  2193. return _magnitudes[index].type;
  2194. }
  2195. return MAGNITUDE_NONE;
  2196. }
  2197. double sensor::Value::get() {
  2198. return _sensor_realtime ? last : reported;
  2199. }
  2200. sensor::Value magnitudeValue(unsigned char index) {
  2201. sensor::Value result;
  2202. if (index >= _magnitudes.size()) {
  2203. result.last = std::numeric_limits<double>::quiet_NaN(),
  2204. result.reported = std::numeric_limits<double>::quiet_NaN(),
  2205. result.decimals = 0u;
  2206. return result;
  2207. }
  2208. auto& magnitude = _magnitudes[index];
  2209. result.last = magnitude.last;
  2210. result.reported = magnitude.reported;
  2211. result.decimals = magnitude.decimals;
  2212. return result;
  2213. }
  2214. void magnitudeFormat(const sensor::Value& value, char* out, size_t) {
  2215. // TODO: 'size' does not do anything, since dtostrf used here is expected to be 'sane', but
  2216. // it does not allow any size arguments besides for digits after the decimal point
  2217. dtostrf(
  2218. _sensor_realtime ? value.last : value.reported,
  2219. 1, value.decimals,
  2220. out
  2221. );
  2222. }
  2223. unsigned char magnitudeIndex(unsigned char index) {
  2224. if (index < _magnitudes.size()) {
  2225. return _magnitudes[index].index_global;
  2226. }
  2227. return 0;
  2228. }
  2229. String magnitudeDescription(unsigned char index) {
  2230. if (index < _magnitudes.size()) {
  2231. return _magnitudeDescription(_magnitudes[index]);
  2232. }
  2233. return String();
  2234. }
  2235. String magnitudeTopicIndex(unsigned char index) {
  2236. if (index < _magnitudes.size()) {
  2237. return _magnitudeTopicIndex(_magnitudes[index]);
  2238. }
  2239. return String();
  2240. }
  2241. // -----------------------------------------------------------------------------
  2242. void _sensorBackwards() {
  2243. // Some keys from older versions were longer
  2244. moveSetting("powerUnits", "pwrUnits");
  2245. moveSetting("energyUnits", "eneUnits");
  2246. // Energy is now indexed (based on magnitude.index_global)
  2247. moveSetting("eneTotal", "eneTotal0");
  2248. // Update PZEM004T energy total across multiple devices
  2249. moveSettings("pzEneTotal", "eneTotal");
  2250. // Unit ID is no longer shared, drop when equal to Min_ or None
  2251. const char *keys[3] = {
  2252. "pwrUnits", "eneUnits", "tmpUnits"
  2253. };
  2254. for (auto* key : keys) {
  2255. const auto units = getSetting(key);
  2256. if (units.length() && (units.equals("0") || units.equals("1"))) {
  2257. delSetting(key);
  2258. }
  2259. }
  2260. }
  2261. void sensorSetup() {
  2262. // Settings backwards compatibility
  2263. _sensorBackwards();
  2264. // Load configured sensors and set up all of magnitudes
  2265. _sensorLoad();
  2266. _sensorInit();
  2267. // Configure based on settings
  2268. _sensorConfigure();
  2269. // Allow us to query key default
  2270. settingsRegisterDefaults({
  2271. [](const char* key) -> bool {
  2272. if (strncmp(key, "pwr", 3) == 0) return true;
  2273. return false;
  2274. },
  2275. _sensorQueryDefault
  2276. });
  2277. // Websockets integration, send sensor readings and configuration
  2278. #if WEB_SUPPORT
  2279. wsRegister()
  2280. .onVisible(_sensorWebSocketOnVisible)
  2281. .onConnected(_sensorWebSocketOnConnected)
  2282. .onData(_sensorWebSocketSendData)
  2283. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2284. #endif
  2285. // MQTT receive callback, atm only for energy reset
  2286. #if MQTT_SUPPORT
  2287. mqttRegister(_sensorMqttCallback);
  2288. #endif
  2289. // API
  2290. #if API_SUPPORT
  2291. _sensorApiSetup();
  2292. #endif
  2293. // Terminal
  2294. #if TERMINAL_SUPPORT
  2295. _sensorInitCommands();
  2296. #endif
  2297. // Main callbacks
  2298. espurnaRegisterLoop(sensorLoop);
  2299. espurnaRegisterReload(_sensorConfigure);
  2300. }
  2301. void sensorLoop() {
  2302. // Check if we still have uninitialized sensors
  2303. static unsigned long last_init = 0;
  2304. if (!_sensors_ready) {
  2305. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2306. last_init = millis();
  2307. _sensorInit();
  2308. }
  2309. }
  2310. if (_magnitudes.size() == 0) return;
  2311. // Tick hook, called every loop()
  2312. _sensorTick();
  2313. // Check if we should read new data
  2314. static unsigned long last_update = 0;
  2315. static unsigned long report_count = 0;
  2316. if (millis() - last_update > _sensor_read_interval) {
  2317. last_update = millis();
  2318. report_count = (report_count + 1) % _sensor_report_every;
  2319. double value_raw; // holds the raw value as the sensor returns it
  2320. double value_show; // holds the processed value applying units and decimals
  2321. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2322. // Pre-read hook, called every reading
  2323. _sensorPre();
  2324. // Get the first relay state
  2325. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2326. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2327. #endif
  2328. // Get readings
  2329. for (unsigned char magnitude_index = 0; magnitude_index < _magnitudes.size(); ++magnitude_index) {
  2330. auto& magnitude = _magnitudes[magnitude_index];
  2331. if (!magnitude.sensor->status()) continue;
  2332. // -------------------------------------------------------------
  2333. // Instant value
  2334. // -------------------------------------------------------------
  2335. value_raw = magnitude.sensor->value(magnitude.slot);
  2336. // Completely remove spurious values if relay is OFF
  2337. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2338. switch (magnitude.type) {
  2339. case MAGNITUDE_POWER_ACTIVE:
  2340. case MAGNITUDE_POWER_REACTIVE:
  2341. case MAGNITUDE_POWER_APPARENT:
  2342. case MAGNITUDE_POWER_FACTOR:
  2343. case MAGNITUDE_CURRENT:
  2344. case MAGNITUDE_ENERGY_DELTA:
  2345. if (relay_off) {
  2346. value_raw = 0.0;
  2347. }
  2348. break;
  2349. default:
  2350. break;
  2351. }
  2352. #endif
  2353. // In addition to that, we also check that value is above a certain threshold
  2354. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2355. value_raw = 0.0;
  2356. }
  2357. magnitude.last = value_raw;
  2358. magnitude.filter->add(value_raw);
  2359. // -------------------------------------------------------------
  2360. // Procesing (units and decimals)
  2361. // -------------------------------------------------------------
  2362. value_show = _magnitudeProcess(magnitude, value_raw);
  2363. #if BROKER_SUPPORT
  2364. {
  2365. char buffer[64];
  2366. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2367. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2368. }
  2369. #endif
  2370. // -------------------------------------------------------------
  2371. // Debug
  2372. // -------------------------------------------------------------
  2373. #if SENSOR_DEBUG
  2374. {
  2375. char buffer[64];
  2376. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2377. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2378. _magnitudeDescription(magnitude).c_str(),
  2379. magnitudeTopic(magnitude.type).c_str(),
  2380. buffer,
  2381. _magnitudeUnits(magnitude).c_str()
  2382. );
  2383. }
  2384. #endif
  2385. // -------------------------------------------------------------------
  2386. // Report when
  2387. // - report_count overflows after reaching _sensor_report_every
  2388. // - when magnitude specifies max_change and we greater or equal to it
  2389. // -------------------------------------------------------------------
  2390. bool report = (0 == report_count);
  2391. if (!std::isnan(magnitude.reported) && (magnitude.max_change > 0)) {
  2392. report = (std::abs(value_show - magnitude.reported) >= magnitude.max_change);
  2393. }
  2394. // Special case for energy, save readings to RAM and EEPROM
  2395. if (MAGNITUDE_ENERGY == magnitude.type) {
  2396. _magnitudeSaveEnergyTotal(magnitude, report);
  2397. }
  2398. if (report) {
  2399. value_filtered = _magnitudeProcess(magnitude, magnitude.filter->result());
  2400. magnitude.filter->reset();
  2401. if (magnitude.filter->size() != _sensor_report_every) {
  2402. magnitude.filter->resize(_sensor_report_every);
  2403. }
  2404. // Check if there is a minimum change threshold to report
  2405. if (std::isnan(magnitude.reported) || (std::abs(value_filtered - magnitude.reported) >= magnitude.min_change)) {
  2406. magnitude.reported = value_filtered;
  2407. _sensorReport(magnitude_index, magnitude);
  2408. }
  2409. } // if (report_count == 0)
  2410. }
  2411. // Post-read hook, called every reading
  2412. _sensorPost();
  2413. // And report data to modules that don't specifically track them
  2414. #if WEB_SUPPORT
  2415. wsPost(_sensorWebSocketSendData);
  2416. #endif
  2417. #if THINGSPEAK_SUPPORT
  2418. if (report_count == 0) tspkFlush();
  2419. #endif
  2420. }
  2421. }
  2422. #endif // SENSOR_SUPPORT