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.

2890 lines
84 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...)
3 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...)
3 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...)
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...)
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...)
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...)
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...)
3 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
6 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. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  1106. uint8_t size = 0;
  1107. JsonArray& index = magnitudes.createNestedArray("index");
  1108. JsonArray& type = magnitudes.createNestedArray("type");
  1109. JsonArray& units = magnitudes.createNestedArray("units");
  1110. JsonArray& description = magnitudes.createNestedArray("description");
  1111. for (auto& magnitude : _magnitudes) {
  1112. // TODO: we don't display event for some reason?
  1113. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1114. ++size;
  1115. index.add<uint8_t>(magnitude.index_global);
  1116. type.add<uint8_t>(magnitude.type);
  1117. units.add(_magnitudeUnits(magnitude));
  1118. description.add(_magnitudeDescription(magnitude));
  1119. }
  1120. magnitudes["size"] = size;
  1121. }
  1122. void _sensorWebSocketSendData(JsonObject& root) {
  1123. char buffer[64];
  1124. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  1125. uint8_t size = 0;
  1126. JsonArray& value = magnitudes.createNestedArray("value");
  1127. JsonArray& error = magnitudes.createNestedArray("error");
  1128. #if NTP_SUPPORT
  1129. JsonArray& info = magnitudes.createNestedArray("info");
  1130. #endif
  1131. for (auto& magnitude : _magnitudes) {
  1132. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1133. ++size;
  1134. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  1135. value.add(buffer);
  1136. error.add(magnitude.sensor->error());
  1137. #if NTP_SUPPORT
  1138. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  1139. String string = F("Last saved: ");
  1140. string += getSetting({"eneTime", magnitude.index_global}, F("(unknown)"));
  1141. info.add(string);
  1142. } else {
  1143. info.add((uint8_t)0);
  1144. }
  1145. #endif
  1146. }
  1147. magnitudes["size"] = size;
  1148. }
  1149. void _sensorWebSocketOnConnected(JsonObject& root) {
  1150. for (auto* sensor [[gnu::unused]] : _sensors) {
  1151. if (_sensorIsEmon(sensor)) {
  1152. root["emonVisible"] = 1;
  1153. root["pwrVisible"] = 1;
  1154. }
  1155. #if EMON_ANALOG_SUPPORT
  1156. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  1157. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  1158. }
  1159. #endif
  1160. #if HLW8012_SUPPORT
  1161. if (sensor->getID() == SENSOR_HLW8012_ID) {
  1162. root["hlwVisible"] = 1;
  1163. }
  1164. #endif
  1165. #if CSE7766_SUPPORT
  1166. if (sensor->getID() == SENSOR_CSE7766_ID) {
  1167. root["cseVisible"] = 1;
  1168. }
  1169. #endif
  1170. #if PZEM004T_SUPPORT || PZEM004TV30_SUPPORT
  1171. switch (sensor->getID()) {
  1172. case SENSOR_PZEM004T_ID:
  1173. case SENSOR_PZEM004TV30_ID:
  1174. root["pzemVisible"] = 1;
  1175. break;
  1176. default:
  1177. break;
  1178. }
  1179. #endif
  1180. #if PULSEMETER_SUPPORT
  1181. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  1182. root["pmVisible"] = 1;
  1183. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  1184. }
  1185. #endif
  1186. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1187. switch (sensor->getID()) {
  1188. case SENSOR_MICS2710_ID:
  1189. case SENSOR_MICS5525_ID:
  1190. root["micsVisible"] = 1;
  1191. break;
  1192. default:
  1193. break;
  1194. }
  1195. #endif
  1196. }
  1197. if (magnitudeCount()) {
  1198. root["snsRead"] = _sensor_read_interval / 1000;
  1199. root["snsReport"] = _sensor_report_every;
  1200. root["snsSave"] = _sensor_save_every;
  1201. _sensorWebSocketMagnitudesConfig(root);
  1202. }
  1203. }
  1204. #endif // WEB_SUPPORT
  1205. #if API_SUPPORT
  1206. String _sensorApiMagnitudeName(sensor_magnitude_t& magnitude) {
  1207. String name = magnitudeTopic(magnitude.type);
  1208. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) name = name + "/" + String(magnitude.index_global);
  1209. return name;
  1210. }
  1211. bool _sensorApiTryParseMagnitudeIndex(const char* p, unsigned char type, unsigned char& magnitude_index) {
  1212. char* endp { nullptr };
  1213. const unsigned long result { strtoul(p, &endp, 10) };
  1214. if ((endp == p) || (*endp != '\0') || (result >= sensor_magnitude_t::counts(type))) {
  1215. DEBUG_MSG_P(PSTR("[SENSOR] Invalid magnitude ID (%s)\n"), p);
  1216. return false;
  1217. }
  1218. magnitude_index = result;
  1219. return true;
  1220. }
  1221. template <typename T>
  1222. bool _sensorApiTryHandle(ApiRequest& request, unsigned char type, T&& callback) {
  1223. unsigned char index { 0u };
  1224. if (request.wildcards()) {
  1225. auto index_param = request.wildcard(0);
  1226. if (!_sensorApiTryParseMagnitudeIndex(index_param.c_str(), type, index)) {
  1227. return false;
  1228. }
  1229. }
  1230. for (auto& magnitude : _magnitudes) {
  1231. if ((type == magnitude.type) && (index == magnitude.index_global)) {
  1232. callback(magnitude);
  1233. return true;
  1234. }
  1235. }
  1236. return false;
  1237. }
  1238. void _sensorApiSetup() {
  1239. apiRegister(F("magnitudes"),
  1240. [](ApiRequest&, JsonObject& root) {
  1241. JsonArray& magnitudes = root.createNestedArray("magnitudes");
  1242. for (auto& magnitude : _magnitudes) {
  1243. JsonArray& data = magnitudes.createNestedArray();
  1244. data.add(_sensorApiMagnitudeName(magnitude));
  1245. data.add(magnitude.last);
  1246. data.add(magnitude.reported);
  1247. }
  1248. return true;
  1249. },
  1250. nullptr
  1251. );
  1252. _magnitudeForEachCounted([](unsigned char type) {
  1253. String pattern = magnitudeTopic(type);
  1254. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(type) > 1)) {
  1255. pattern += "/+";
  1256. }
  1257. ApiBasicHandler get {
  1258. [type](ApiRequest& request) {
  1259. return _sensorApiTryHandle(request, type, [&](const sensor_magnitude_t& magnitude) {
  1260. char buffer[64] { 0 };
  1261. dtostrf(
  1262. _sensor_realtime ? magnitude.last : magnitude.reported,
  1263. 1, magnitude.decimals,
  1264. buffer
  1265. );
  1266. request.send(String(buffer));
  1267. return true;
  1268. });
  1269. }
  1270. };
  1271. ApiBasicHandler put { nullptr };
  1272. if (type == MAGNITUDE_ENERGY) {
  1273. put = [](ApiRequest& request) {
  1274. return _sensorApiTryHandle(request, MAGNITUDE_ENERGY, [&](const sensor_magnitude_t& magnitude) {
  1275. _sensorApiResetEnergy(magnitude, request.param(F("value")));
  1276. });
  1277. };
  1278. }
  1279. apiRegister(pattern, std::move(get), std::move(put));
  1280. });
  1281. }
  1282. #endif // API_SUPPORT == 1
  1283. #if MQTT_SUPPORT
  1284. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  1285. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  1286. switch (type) {
  1287. case MQTT_MESSAGE_EVENT: {
  1288. String t = mqttMagnitude((char *) topic);
  1289. if (!t.startsWith(energy_topic)) break;
  1290. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  1291. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  1292. for (auto& magnitude : _magnitudes) {
  1293. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  1294. if (index != magnitude.index_global) continue;
  1295. _sensorApiResetEnergy(magnitude, payload);
  1296. break;
  1297. }
  1298. }
  1299. case MQTT_CONNECT_EVENT: {
  1300. for (auto& magnitude : _magnitudes) {
  1301. if (MAGNITUDE_ENERGY == magnitude.type) {
  1302. const String topic = energy_topic + "/+";
  1303. mqttSubscribe(topic.c_str());
  1304. break;
  1305. }
  1306. }
  1307. }
  1308. case MQTT_DISCONNECT_EVENT:
  1309. default:
  1310. break;
  1311. }
  1312. }
  1313. #endif // MQTT_SUPPORT == 1
  1314. #if TERMINAL_SUPPORT
  1315. void _sensorInitCommands() {
  1316. terminalRegisterCommand(F("MAGNITUDES"), [](const terminal::CommandContext&) {
  1317. char last[64];
  1318. char reported[64];
  1319. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1320. auto& magnitude = _magnitudes.at(index);
  1321. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  1322. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  1323. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  1324. index,
  1325. magnitudeTopic(magnitude.type).c_str(),
  1326. magnitude.index_global,
  1327. _magnitudeDescription(magnitude).c_str(),
  1328. last, reported
  1329. );
  1330. }
  1331. terminalOK();
  1332. });
  1333. }
  1334. #endif // TERMINAL_SUPPORT == 1
  1335. void _sensorTick() {
  1336. for (auto* sensor : _sensors) {
  1337. sensor->tick();
  1338. }
  1339. }
  1340. void _sensorPre() {
  1341. for (auto* sensor : _sensors) {
  1342. sensor->pre();
  1343. if (!sensor->status()) {
  1344. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  1345. sensor->description().c_str(),
  1346. sensor->error()
  1347. );
  1348. }
  1349. }
  1350. }
  1351. void _sensorPost() {
  1352. for (auto* sensor : _sensors) {
  1353. sensor->post();
  1354. }
  1355. }
  1356. // -----------------------------------------------------------------------------
  1357. // Sensor initialization
  1358. // -----------------------------------------------------------------------------
  1359. void _sensorLoad() {
  1360. /*
  1361. This is temporal, in the future sensors will be initialized based on
  1362. soft configuration (data stored in EEPROM config) so you will be able
  1363. to define and configure new sensors on the fly
  1364. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  1365. loaded and initialized here. If you want to add new sensors of the same type
  1366. just duplicate the block and change the arguments for the set* methods.
  1367. For example, how to add a second DHT sensor:
  1368. #if DHT_SUPPORT
  1369. {
  1370. DHTSensor * sensor = new DHTSensor();
  1371. sensor->setGPIO(DHT2_PIN);
  1372. sensor->setType(DHT2_TYPE);
  1373. _sensors.push_back(sensor);
  1374. }
  1375. #endif
  1376. DHT2_PIN and DHT2_TYPE should be globally accessible:
  1377. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1378. - in custom.h, as `#define ...`
  1379. */
  1380. #if AM2320_SUPPORT
  1381. {
  1382. AM2320Sensor * sensor = new AM2320Sensor();
  1383. sensor->setAddress(AM2320_ADDRESS);
  1384. _sensors.push_back(sensor);
  1385. }
  1386. #endif
  1387. #if ANALOG_SUPPORT
  1388. {
  1389. AnalogSensor * sensor = new AnalogSensor();
  1390. sensor->setSamples(ANALOG_SAMPLES);
  1391. sensor->setDelay(ANALOG_DELAY);
  1392. //CICM For analog scaling
  1393. sensor->setFactor(ANALOG_FACTOR);
  1394. sensor->setOffset(ANALOG_OFFSET);
  1395. _sensors.push_back(sensor);
  1396. }
  1397. #endif
  1398. #if BH1750_SUPPORT
  1399. {
  1400. BH1750Sensor * sensor = new BH1750Sensor();
  1401. sensor->setAddress(BH1750_ADDRESS);
  1402. sensor->setMode(BH1750_MODE);
  1403. _sensors.push_back(sensor);
  1404. }
  1405. #endif
  1406. #if BMP180_SUPPORT
  1407. {
  1408. BMP180Sensor * sensor = new BMP180Sensor();
  1409. sensor->setAddress(BMP180_ADDRESS);
  1410. _sensors.push_back(sensor);
  1411. }
  1412. #endif
  1413. #if BMX280_SUPPORT
  1414. {
  1415. // Support up to two sensors with full auto-discovery.
  1416. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1417. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1418. // otherwise choose the other unnamed sensor address
  1419. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  1420. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1421. const decltype(first) address_map[2] { first, second };
  1422. for (unsigned char n=0; n < number; ++n) {
  1423. BMX280Sensor * sensor = new BMX280Sensor();
  1424. sensor->setAddress(address_map[n]);
  1425. _sensors.push_back(sensor);
  1426. }
  1427. }
  1428. #endif
  1429. #if BME680_SUPPORT
  1430. {
  1431. BME680Sensor * sensor = new BME680Sensor();
  1432. sensor->setAddress(BME680_I2C_ADDRESS);
  1433. _sensors.push_back(sensor);
  1434. }
  1435. #endif
  1436. #if CSE7766_SUPPORT
  1437. {
  1438. CSE7766Sensor * sensor = new CSE7766Sensor();
  1439. sensor->setRX(CSE7766_RX_PIN);
  1440. _sensors.push_back(sensor);
  1441. }
  1442. #endif
  1443. #if DALLAS_SUPPORT
  1444. {
  1445. DallasSensor * sensor = new DallasSensor();
  1446. sensor->setGPIO(DALLAS_PIN);
  1447. _sensors.push_back(sensor);
  1448. }
  1449. #endif
  1450. #if DHT_SUPPORT
  1451. {
  1452. DHTSensor * sensor = new DHTSensor();
  1453. sensor->setGPIO(DHT_PIN);
  1454. sensor->setType(DHT_TYPE);
  1455. _sensors.push_back(sensor);
  1456. }
  1457. #endif
  1458. #if DIGITAL_SUPPORT
  1459. {
  1460. auto getPin = [](unsigned char index) -> int {
  1461. switch (index) {
  1462. case 0: return DIGITAL1_PIN;
  1463. case 1: return DIGITAL2_PIN;
  1464. case 2: return DIGITAL3_PIN;
  1465. case 3: return DIGITAL4_PIN;
  1466. case 4: return DIGITAL5_PIN;
  1467. case 5: return DIGITAL6_PIN;
  1468. case 6: return DIGITAL7_PIN;
  1469. case 7: return DIGITAL8_PIN;
  1470. default: return GPIO_NONE;
  1471. }
  1472. };
  1473. auto getDefaultState = [](unsigned char index) -> int {
  1474. switch (index) {
  1475. case 0: return DIGITAL1_DEFAULT_STATE;
  1476. case 1: return DIGITAL2_DEFAULT_STATE;
  1477. case 2: return DIGITAL3_DEFAULT_STATE;
  1478. case 3: return DIGITAL4_DEFAULT_STATE;
  1479. case 4: return DIGITAL5_DEFAULT_STATE;
  1480. case 5: return DIGITAL6_DEFAULT_STATE;
  1481. case 6: return DIGITAL7_DEFAULT_STATE;
  1482. case 7: return DIGITAL8_DEFAULT_STATE;
  1483. default: return 1;
  1484. }
  1485. };
  1486. auto getMode = [](unsigned char index) -> int {
  1487. switch (index) {
  1488. case 0: return DIGITAL1_PIN_MODE;
  1489. case 1: return DIGITAL2_PIN_MODE;
  1490. case 2: return DIGITAL3_PIN_MODE;
  1491. case 3: return DIGITAL4_PIN_MODE;
  1492. case 4: return DIGITAL5_PIN_MODE;
  1493. case 5: return DIGITAL6_PIN_MODE;
  1494. case 6: return DIGITAL7_PIN_MODE;
  1495. case 7: return DIGITAL8_PIN_MODE;
  1496. default: return INPUT_PULLUP;
  1497. }
  1498. };
  1499. auto pins = gpioPins();
  1500. for (unsigned char index = 0; index < pins; ++index) {
  1501. const auto pin = getPin(index);
  1502. if (pin == GPIO_NONE) break;
  1503. DigitalSensor * sensor = new DigitalSensor();
  1504. sensor->setGPIO(pin);
  1505. sensor->setMode(getMode(index));
  1506. sensor->setDefault(getDefaultState(index));
  1507. _sensors.push_back(sensor);
  1508. }
  1509. }
  1510. #endif
  1511. #if ECH1560_SUPPORT
  1512. {
  1513. ECH1560Sensor * sensor = new ECH1560Sensor();
  1514. sensor->setCLK(ECH1560_CLK_PIN);
  1515. sensor->setMISO(ECH1560_MISO_PIN);
  1516. sensor->setInverted(ECH1560_INVERTED);
  1517. _sensors.push_back(sensor);
  1518. }
  1519. #endif
  1520. #if EMON_ADC121_SUPPORT
  1521. {
  1522. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1523. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1524. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1525. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1526. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1527. _sensors.push_back(sensor);
  1528. }
  1529. #endif
  1530. #if EMON_ADS1X15_SUPPORT
  1531. {
  1532. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  1533. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  1534. sensor->setType(EMON_ADS1X15_TYPE);
  1535. sensor->setMask(EMON_ADS1X15_MASK);
  1536. sensor->setGain(EMON_ADS1X15_GAIN);
  1537. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1538. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1539. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  1540. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  1541. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  1542. _sensors.push_back(sensor);
  1543. }
  1544. #endif
  1545. #if EMON_ANALOG_SUPPORT
  1546. {
  1547. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  1548. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1549. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1550. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1551. _sensors.push_back(sensor);
  1552. }
  1553. #endif
  1554. #if EVENTS_SUPPORT
  1555. {
  1556. auto getPin = [](unsigned char index) -> int {
  1557. switch (index) {
  1558. case 0: return EVENTS1_PIN;
  1559. case 1: return EVENTS2_PIN;
  1560. case 2: return EVENTS3_PIN;
  1561. case 3: return EVENTS4_PIN;
  1562. case 4: return EVENTS5_PIN;
  1563. case 5: return EVENTS6_PIN;
  1564. case 6: return EVENTS7_PIN;
  1565. case 7: return EVENTS8_PIN;
  1566. default: return GPIO_NONE;
  1567. }
  1568. };
  1569. auto getMode = [](unsigned char index) -> int {
  1570. switch (index) {
  1571. case 0: return EVENTS1_PIN_MODE;
  1572. case 1: return EVENTS2_PIN_MODE;
  1573. case 2: return EVENTS3_PIN_MODE;
  1574. case 3: return EVENTS4_PIN_MODE;
  1575. case 4: return EVENTS5_PIN_MODE;
  1576. case 5: return EVENTS6_PIN_MODE;
  1577. case 6: return EVENTS7_PIN_MODE;
  1578. case 7: return EVENTS8_PIN_MODE;
  1579. default: return INPUT;
  1580. }
  1581. };
  1582. auto getDebounce = [](unsigned char index) -> unsigned long {
  1583. switch (index) {
  1584. case 0: return EVENTS1_DEBOUNCE;
  1585. case 1: return EVENTS2_DEBOUNCE;
  1586. case 2: return EVENTS3_DEBOUNCE;
  1587. case 3: return EVENTS4_DEBOUNCE;
  1588. case 4: return EVENTS5_DEBOUNCE;
  1589. case 5: return EVENTS6_DEBOUNCE;
  1590. case 6: return EVENTS7_DEBOUNCE;
  1591. case 7: return EVENTS8_DEBOUNCE;
  1592. default: return 50;
  1593. }
  1594. };
  1595. auto getIsrMode = [](unsigned char index) -> int {
  1596. switch (index) {
  1597. case 0: return EVENTS1_INTERRUPT_MODE;
  1598. case 1: return EVENTS2_INTERRUPT_MODE;
  1599. case 2: return EVENTS3_INTERRUPT_MODE;
  1600. case 3: return EVENTS4_INTERRUPT_MODE;
  1601. case 4: return EVENTS5_INTERRUPT_MODE;
  1602. case 5: return EVENTS6_INTERRUPT_MODE;
  1603. case 6: return EVENTS7_INTERRUPT_MODE;
  1604. case 7: return EVENTS8_INTERRUPT_MODE;
  1605. default: return RISING;
  1606. }
  1607. };
  1608. auto pins = gpioPins();
  1609. for (unsigned char index = 0; index < pins; ++index) {
  1610. const auto pin = getPin(index);
  1611. if (pin == GPIO_NONE) break;
  1612. EventSensor * sensor = new EventSensor();
  1613. sensor->setGPIO(pin);
  1614. sensor->setPinMode(getMode(index));
  1615. sensor->setDebounceTime(getDebounce(index));
  1616. sensor->setInterruptMode(getIsrMode(index));
  1617. _sensors.push_back(sensor);
  1618. }
  1619. }
  1620. #endif
  1621. #if GEIGER_SUPPORT
  1622. {
  1623. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1624. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1625. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1626. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1627. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1628. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1629. _sensors.push_back(sensor);
  1630. }
  1631. #endif
  1632. #if GUVAS12SD_SUPPORT
  1633. {
  1634. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1635. sensor->setGPIO(GUVAS12SD_PIN);
  1636. _sensors.push_back(sensor);
  1637. }
  1638. #endif
  1639. #if SONAR_SUPPORT
  1640. {
  1641. SonarSensor * sensor = new SonarSensor();
  1642. sensor->setEcho(SONAR_ECHO);
  1643. sensor->setIterations(SONAR_ITERATIONS);
  1644. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1645. sensor->setTrigger(SONAR_TRIGGER);
  1646. _sensors.push_back(sensor);
  1647. }
  1648. #endif
  1649. #if HLW8012_SUPPORT
  1650. {
  1651. HLW8012Sensor * sensor = new HLW8012Sensor();
  1652. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1653. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1654. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1655. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1656. _sensors.push_back(sensor);
  1657. }
  1658. #endif
  1659. #if LDR_SUPPORT
  1660. {
  1661. LDRSensor * sensor = new LDRSensor();
  1662. sensor->setSamples(LDR_SAMPLES);
  1663. sensor->setDelay(LDR_DELAY);
  1664. sensor->setType(LDR_TYPE);
  1665. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1666. sensor->setResistor(LDR_RESISTOR);
  1667. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1668. _sensors.push_back(sensor);
  1669. }
  1670. #endif
  1671. #if MHZ19_SUPPORT
  1672. {
  1673. MHZ19Sensor * sensor = new MHZ19Sensor();
  1674. sensor->setRX(MHZ19_RX_PIN);
  1675. sensor->setTX(MHZ19_TX_PIN);
  1676. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1677. _sensors.push_back(sensor);
  1678. }
  1679. #endif
  1680. #if MICS2710_SUPPORT
  1681. {
  1682. MICS2710Sensor * sensor = new MICS2710Sensor();
  1683. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1684. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1685. sensor->setR0(MICS2710_R0);
  1686. sensor->setRL(MICS2710_RL);
  1687. sensor->setRS(0);
  1688. _sensors.push_back(sensor);
  1689. }
  1690. #endif
  1691. #if MICS5525_SUPPORT
  1692. {
  1693. MICS5525Sensor * sensor = new MICS5525Sensor();
  1694. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1695. sensor->setR0(MICS5525_R0);
  1696. sensor->setRL(MICS5525_RL);
  1697. sensor->setRS(0);
  1698. _sensors.push_back(sensor);
  1699. }
  1700. #endif
  1701. #if NTC_SUPPORT
  1702. {
  1703. NTCSensor * sensor = new NTCSensor();
  1704. sensor->setSamples(NTC_SAMPLES);
  1705. sensor->setDelay(NTC_DELAY);
  1706. sensor->setUpstreamResistor(NTC_R_UP);
  1707. sensor->setDownstreamResistor(NTC_R_DOWN);
  1708. sensor->setBeta(NTC_BETA);
  1709. sensor->setR0(NTC_R0);
  1710. sensor->setT0(NTC_T0);
  1711. _sensors.push_back(sensor);
  1712. }
  1713. #endif
  1714. #if PMSX003_SUPPORT
  1715. {
  1716. PMSX003Sensor * sensor = new PMSX003Sensor();
  1717. #if PMS_USE_SOFT
  1718. sensor->setRX(PMS_RX_PIN);
  1719. sensor->setTX(PMS_TX_PIN);
  1720. #else
  1721. sensor->setSerial(& PMS_HW_PORT);
  1722. #endif
  1723. sensor->setType(PMS_TYPE);
  1724. _sensors.push_back(sensor);
  1725. }
  1726. #endif
  1727. #if PULSEMETER_SUPPORT
  1728. {
  1729. PulseMeterSensor * sensor = new PulseMeterSensor();
  1730. sensor->setGPIO(PULSEMETER_PIN);
  1731. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1732. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1733. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1734. _sensors.push_back(sensor);
  1735. }
  1736. #endif
  1737. #if PZEM004T_SUPPORT
  1738. {
  1739. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1740. if (!addresses.length()) {
  1741. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1742. return;
  1743. }
  1744. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1745. sensor->setAddresses(addresses.c_str());
  1746. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1747. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1748. if (!getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1749. sensor->setSerial(& PZEM004T_HW_PORT);
  1750. }
  1751. _sensors.push_back(sensor);
  1752. #if TERMINAL_SUPPORT
  1753. pzem004tInitCommands();
  1754. #endif
  1755. }
  1756. #endif
  1757. #if SENSEAIR_SUPPORT
  1758. {
  1759. SenseAirSensor * sensor = new SenseAirSensor();
  1760. sensor->setRX(SENSEAIR_RX_PIN);
  1761. sensor->setTX(SENSEAIR_TX_PIN);
  1762. _sensors.push_back(sensor);
  1763. }
  1764. #endif
  1765. #if SDS011_SUPPORT
  1766. {
  1767. SDS011Sensor * sensor = new SDS011Sensor();
  1768. sensor->setRX(SDS011_RX_PIN);
  1769. sensor->setTX(SDS011_TX_PIN);
  1770. _sensors.push_back(sensor);
  1771. }
  1772. #endif
  1773. #if SHT3X_I2C_SUPPORT
  1774. {
  1775. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1776. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1777. _sensors.push_back(sensor);
  1778. }
  1779. #endif
  1780. #if SI7021_SUPPORT
  1781. {
  1782. SI7021Sensor * sensor = new SI7021Sensor();
  1783. sensor->setAddress(SI7021_ADDRESS);
  1784. _sensors.push_back(sensor);
  1785. }
  1786. #endif
  1787. #if T6613_SUPPORT
  1788. {
  1789. T6613Sensor * sensor = new T6613Sensor();
  1790. sensor->setRX(T6613_RX_PIN);
  1791. sensor->setTX(T6613_TX_PIN);
  1792. _sensors.push_back(sensor);
  1793. }
  1794. #endif
  1795. #if TMP3X_SUPPORT
  1796. {
  1797. TMP3XSensor * sensor = new TMP3XSensor();
  1798. sensor->setType(TMP3X_TYPE);
  1799. _sensors.push_back(sensor);
  1800. }
  1801. #endif
  1802. #if V9261F_SUPPORT
  1803. {
  1804. V9261FSensor * sensor = new V9261FSensor();
  1805. sensor->setRX(V9261F_PIN);
  1806. sensor->setInverted(V9261F_PIN_INVERSE);
  1807. _sensors.push_back(sensor);
  1808. }
  1809. #endif
  1810. #if MAX6675_SUPPORT
  1811. {
  1812. MAX6675Sensor * sensor = new MAX6675Sensor();
  1813. sensor->setCS(MAX6675_CS_PIN);
  1814. sensor->setSO(MAX6675_SO_PIN);
  1815. sensor->setSCK(MAX6675_SCK_PIN);
  1816. _sensors.push_back(sensor);
  1817. }
  1818. #endif
  1819. #if VEML6075_SUPPORT
  1820. {
  1821. VEML6075Sensor * sensor = new VEML6075Sensor();
  1822. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1823. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1824. _sensors.push_back(sensor);
  1825. }
  1826. #endif
  1827. #if VL53L1X_SUPPORT
  1828. {
  1829. VL53L1XSensor * sensor = new VL53L1XSensor();
  1830. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1831. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1832. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1833. _sensors.push_back(sensor);
  1834. }
  1835. #endif
  1836. #if EZOPH_SUPPORT
  1837. {
  1838. EZOPHSensor * sensor = new EZOPHSensor();
  1839. sensor->setRX(EZOPH_RX_PIN);
  1840. sensor->setTX(EZOPH_TX_PIN);
  1841. _sensors.push_back(sensor);
  1842. }
  1843. #endif
  1844. #if ADE7953_SUPPORT
  1845. {
  1846. ADE7953Sensor * sensor = new ADE7953Sensor();
  1847. sensor->setAddress(ADE7953_ADDRESS);
  1848. _sensors.push_back(sensor);
  1849. }
  1850. #endif
  1851. #if SI1145_SUPPORT
  1852. {
  1853. SI1145Sensor * sensor = new SI1145Sensor();
  1854. sensor->setAddress(SI1145_ADDRESS);
  1855. _sensors.push_back(sensor);
  1856. }
  1857. #endif
  1858. #if HDC1080_SUPPORT
  1859. {
  1860. HDC1080Sensor * sensor = new HDC1080Sensor();
  1861. sensor->setAddress(HDC1080_ADDRESS);
  1862. _sensors.push_back(sensor);
  1863. }
  1864. #endif
  1865. #if PZEM004TV30_SUPPORT
  1866. {
  1867. PZEM004TV30Sensor * sensor = PZEM004TV30Sensor::create();
  1868. // TODO: we need an equivalent to the `pzem.address` command
  1869. sensor->setAddress(getSetting("pzemv30Addr", PZEM004TV30Sensor::DefaultAddress));
  1870. sensor->setReadTimeout(getSetting("pzemv30ReadTimeout", PZEM004TV30Sensor::DefaultReadTimeout));
  1871. sensor->setDebug(getSetting("pzemv30Debug", 1 == PZEM004TV30_DEBUG));
  1872. bool soft = getSetting("pzemv30Soft", 1 == PZEM004TV30_USE_SOFT);
  1873. int tx = getSetting("pzemv30TX", PZEM004TV30_TX_PIN);
  1874. int rx = getSetting("pzemv30RX", PZEM004TV30_RX_PIN);
  1875. // we operate only with Serial, as Serial1 cannot not receive any data
  1876. if (!soft) {
  1877. sensor->setStream(&Serial);
  1878. sensor->setDescription("HwSerial");
  1879. Serial.begin(PZEM004TV30Sensor::Baudrate);
  1880. // Core does not allow us to begin(baud, cfg, rx, tx) / pins(rx, tx) before begin(baud)
  1881. // b/c internal UART handler does not exist yet
  1882. // Also see https://github.com/esp8266/Arduino/issues/2380 as to why there is flush()
  1883. if ((tx == 15) && (rx == 13)) {
  1884. Serial.flush();
  1885. Serial.swap();
  1886. }
  1887. } else {
  1888. auto* ptr = new SoftwareSerial(rx, tx);
  1889. sensor->setDescription("SwSerial");
  1890. sensor->setStream(ptr); // we don't care about lifetime
  1891. ptr->begin(PZEM004TV30Sensor::Baudrate);
  1892. }
  1893. //TODO: getSetting("pzemv30*Cfg", (SW)SERIAL_8N1); ?
  1894. // may not be relevant, but some sources claim we need 8N2
  1895. _sensors.push_back(sensor);
  1896. }
  1897. #endif
  1898. }
  1899. String _magnitudeTopicIndex(const sensor_magnitude_t& magnitude) {
  1900. char buffer[32] = {0};
  1901. String topic { magnitudeTopic(magnitude.type) };
  1902. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1903. snprintf(buffer, sizeof(buffer), "%s/%u", topic.c_str(), magnitude.index_global);
  1904. } else {
  1905. snprintf(buffer, sizeof(buffer), "%s", topic.c_str());
  1906. }
  1907. return String(buffer);
  1908. }
  1909. void _sensorReport(unsigned char index, const sensor_magnitude_t& magnitude) {
  1910. // XXX: dtostrf only handles basic floating point values and will never produce scientific notation
  1911. // ensure decimals is within some sane limit and the actual value never goes above this buffer size
  1912. char buffer[64];
  1913. dtostrf(magnitude.reported, 1, magnitude.decimals, buffer);
  1914. #if BROKER_SUPPORT
  1915. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, magnitude.reported, buffer);
  1916. #endif
  1917. #if MQTT_SUPPORT
  1918. {
  1919. const String topic(_magnitudeTopicIndex(magnitude));
  1920. mqttSend(topic.c_str(), buffer);
  1921. #if SENSOR_PUBLISH_ADDRESSES
  1922. String address_topic;
  1923. address_topic.reserve(topic.length() + 1 + strlen(SENSOR_ADDRESS_TOPIC));
  1924. address_topic += F(SENSOR_ADDRESS_TOPIC);
  1925. address_topic += '/';
  1926. address_topic += topic;
  1927. mqttSend(address_topic.c_str(), magnitude.sensor->address(magnitude.slot).c_str());
  1928. #endif // SENSOR_PUBLISH_ADDRESSES
  1929. }
  1930. #endif // MQTT_SUPPORT
  1931. // TODO: both integrations depend on the absolute index instead of specific type
  1932. // so, we still need to pass / know the 'global' index inside of _magnitudes[]
  1933. #if THINGSPEAK_SUPPORT
  1934. tspkEnqueueMeasurement(index, buffer);
  1935. #endif // THINGSPEAK_SUPPORT
  1936. #if DOMOTICZ_SUPPORT
  1937. domoticzSendMagnitude(magnitude.type, index, magnitude.reported, buffer);
  1938. #endif // DOMOTICZ_SUPPORT
  1939. }
  1940. void _sensorInit() {
  1941. _sensors_ready = true;
  1942. for (auto& sensor : _sensors) {
  1943. // Do not process an already initialized sensor
  1944. if (sensor->ready()) continue;
  1945. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), sensor->description().c_str());
  1946. // Force sensor to reload config
  1947. sensor->begin();
  1948. if (!sensor->ready()) {
  1949. if (0 != sensor->error()) {
  1950. DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  1951. }
  1952. _sensors_ready = false;
  1953. break;
  1954. }
  1955. // Initialize sensor magnitudes
  1956. for (unsigned char magnitude_index = 0; magnitude_index < sensor->count(); ++magnitude_index) {
  1957. const auto magnitude_type = sensor->type(magnitude_index);
  1958. const auto magnitude_local = sensor->local(magnitude_type);
  1959. _magnitudes.emplace_back(
  1960. magnitude_index, // id of the magnitude, unique to the sensor
  1961. magnitude_local, // index_local, # of the magnitude
  1962. magnitude_type, // specific type of the magnitude
  1963. sensor::Unit::None, // set up later, in configuration
  1964. sensor // bind the sensor to allow us to reference it later
  1965. );
  1966. if (_sensorIsEmon(sensor) && (MAGNITUDE_ENERGY == magnitude_type)) {
  1967. const auto index_global = _magnitudes.back().index_global;
  1968. auto* ptr = static_cast<BaseEmonSensor*>(sensor);
  1969. ptr->resetEnergy(magnitude_local, _sensorEnergyTotal(index_global));
  1970. _sensor_save_count.push_back(0);
  1971. }
  1972. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1973. magnitudeTopic(magnitude_type).c_str(),
  1974. sensor_magnitude_t::counts(magnitude_type)
  1975. );
  1976. }
  1977. // Custom initializations are based on IDs
  1978. switch (sensor->getID()) {
  1979. case SENSOR_MICS2710_ID:
  1980. case SENSOR_MICS5525_ID: {
  1981. auto* ptr = static_cast<BaseAnalogSensor*>(sensor);
  1982. ptr->setR0(getSetting("snsR0", ptr->getR0()));
  1983. ptr->setRS(getSetting("snsRS", ptr->getRS()));
  1984. ptr->setRL(getSetting("snsRL", ptr->getRL()));
  1985. break;
  1986. }
  1987. default:
  1988. break;
  1989. }
  1990. }
  1991. }
  1992. namespace settings {
  1993. namespace internal {
  1994. template <>
  1995. sensor::Unit convert(const String& string) {
  1996. const int value = string.toInt();
  1997. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1998. return static_cast<sensor::Unit>(value);
  1999. }
  2000. return sensor::Unit::None;
  2001. }
  2002. template <>
  2003. String serialize(const sensor::Unit& unit) {
  2004. return String(static_cast<int>(unit));
  2005. }
  2006. } // ns settings::internal
  2007. } // ns settings
  2008. void _sensorConfigure() {
  2009. // General sensor settings for reporting and saving
  2010. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  2011. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  2012. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  2013. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  2014. // pre-load some settings that are controlled via old build flags
  2015. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  2016. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  2017. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  2018. // Apply settings based on sensor type
  2019. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  2020. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  2021. {
  2022. if (getSetting("snsResetCalibration", false)) {
  2023. switch (_sensors[index]->getID()) {
  2024. case SENSOR_MICS2710_ID:
  2025. case SENSOR_MICS5525_ID: {
  2026. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  2027. sensor->calibrate();
  2028. setSetting("snsR0", sensor->getR0());
  2029. break;
  2030. }
  2031. default:
  2032. break;
  2033. }
  2034. }
  2035. }
  2036. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  2037. if (_sensorIsEmon(_sensors[index])) {
  2038. // TODO: ::isEmon() ?
  2039. double value;
  2040. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  2041. if ((value = getSetting("pwrExpectedC", 0.0))) {
  2042. sensor->expectedCurrent(value);
  2043. delSetting("pwrExpectedC");
  2044. setSetting("pwrRatioC", sensor->getCurrentRatio());
  2045. }
  2046. if ((value = getSetting("pwrExpectedV", 0.0))) {
  2047. delSetting("pwrExpectedV");
  2048. sensor->expectedVoltage(value);
  2049. setSetting("pwrRatioV", sensor->getVoltageRatio());
  2050. }
  2051. if ((value = getSetting("pwrExpectedP", 0.0))) {
  2052. delSetting("pwrExpectedP");
  2053. sensor->expectedPower(value);
  2054. setSetting("pwrRatioP", sensor->getPowerRatio());
  2055. }
  2056. if (getSetting("pwrResetE", false)) {
  2057. delSetting("pwrResetE");
  2058. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  2059. sensor->resetEnergy(index);
  2060. _sensorResetEnergyTotal(index);
  2061. }
  2062. }
  2063. if (getSetting("pwrResetCalibration", false)) {
  2064. delSetting("pwrResetCalibration");
  2065. delSetting("pwrRatioC");
  2066. delSetting("pwrRatioV");
  2067. delSetting("pwrRatioP");
  2068. sensor->resetRatios();
  2069. }
  2070. } // is emon?
  2071. }
  2072. // Update magnitude config, filter sizes and reset energy if needed
  2073. {
  2074. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  2075. auto& magnitude = _magnitudes.at(index);
  2076. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  2077. if (_sensorIsEmon(magnitude.sensor)) {
  2078. // TODO: compatibility proxy, fetch global key before indexed
  2079. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  2080. return getSetting({key, index}, getSetting(key, default_value));
  2081. };
  2082. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  2083. switch (magnitude.type) {
  2084. case MAGNITUDE_CURRENT:
  2085. sensor->setCurrentRatio(
  2086. magnitude.index_local, get_ratio("pwrRatioC", magnitude.index_global, sensor->defaultCurrentRatio())
  2087. );
  2088. break;
  2089. case MAGNITUDE_POWER_ACTIVE:
  2090. sensor->setPowerRatio(
  2091. magnitude.index_local, get_ratio("pwrRatioP", magnitude.index_global, sensor->defaultPowerRatio())
  2092. );
  2093. break;
  2094. case MAGNITUDE_VOLTAGE:
  2095. sensor->setVoltageRatio(
  2096. magnitude.index_local, get_ratio("pwrRatioV", magnitude.index_global, sensor->defaultVoltageRatio())
  2097. );
  2098. sensor->setVoltage(
  2099. magnitude.index_local, get_ratio("pwrVoltage", magnitude.index_global, sensor->defaultVoltage())
  2100. );
  2101. break;
  2102. case MAGNITUDE_ENERGY:
  2103. sensor->setEnergyRatio(
  2104. magnitude.index_local, get_ratio("pwrRatioE", magnitude.index_global, sensor->defaultEnergyRatio())
  2105. );
  2106. break;
  2107. default:
  2108. break;
  2109. }
  2110. }
  2111. // adjust type-specific units
  2112. {
  2113. const sensor::Unit default_unit { magnitude.sensor->units(magnitude.slot) };
  2114. const String key {
  2115. String(_magnitudeSettingsPrefix(magnitude.type)) + F("Units") + String(magnitude.index_global, 10) };
  2116. magnitude.units = _magnitudeUnitFilter(magnitude, getSetting(key, default_unit));
  2117. }
  2118. // some magnitudes allow to be corrected with an offset
  2119. {
  2120. if (_magnitudeCanUseCorrection(magnitude.type)) {
  2121. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  2122. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  2123. }
  2124. }
  2125. // some sensors can override decimal values if sensor has more precision than default
  2126. {
  2127. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  2128. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  2129. magnitude.decimals = (unsigned char) decimals;
  2130. }
  2131. // Per-magnitude min & max delta settings
  2132. // - min controls whether we report at all when report_count overflows
  2133. // - max will trigger report as soon as read value is greater than the specified delta
  2134. // (atm this works best for accumulated magnitudes, like energy)
  2135. {
  2136. auto min_default = 0.0;
  2137. auto max_default = 0.0;
  2138. switch (magnitude.type) {
  2139. case MAGNITUDE_TEMPERATURE:
  2140. min_default = tmp_min_delta;
  2141. break;
  2142. case MAGNITUDE_HUMIDITY:
  2143. min_default = hum_min_delta;
  2144. break;
  2145. case MAGNITUDE_ENERGY:
  2146. max_default = ene_max_delta;
  2147. break;
  2148. default:
  2149. break;
  2150. }
  2151. magnitude.min_change = getSetting(
  2152. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2153. min_default
  2154. );
  2155. magnitude.max_change = getSetting(
  2156. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2157. max_default
  2158. );
  2159. }
  2160. // Sometimes we want to ensure the value is above certain threshold before reporting
  2161. {
  2162. magnitude.zero_threshold = getSetting(
  2163. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2164. std::numeric_limits<double>::quiet_NaN()
  2165. );
  2166. }
  2167. // in case we don't save energy periodically, purge existing value in ram & settings
  2168. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2169. _sensorResetEnergyTotal(magnitude.index_global);
  2170. }
  2171. }
  2172. }
  2173. saveSettings();
  2174. }
  2175. // -----------------------------------------------------------------------------
  2176. // Public
  2177. // -----------------------------------------------------------------------------
  2178. unsigned char sensorCount() {
  2179. return _sensors.size();
  2180. }
  2181. unsigned char magnitudeCount() {
  2182. return _magnitudes.size();
  2183. }
  2184. unsigned char magnitudeType(unsigned char index) {
  2185. if (index < _magnitudes.size()) {
  2186. return _magnitudes[index].type;
  2187. }
  2188. return MAGNITUDE_NONE;
  2189. }
  2190. double sensor::Value::get() {
  2191. return _sensor_realtime ? last : reported;
  2192. }
  2193. sensor::Value magnitudeValue(unsigned char index) {
  2194. sensor::Value result;
  2195. if (index >= _magnitudes.size()) {
  2196. result.last = std::numeric_limits<double>::quiet_NaN(),
  2197. result.reported = std::numeric_limits<double>::quiet_NaN(),
  2198. result.decimals = 0u;
  2199. return result;
  2200. }
  2201. auto& magnitude = _magnitudes[index];
  2202. result.last = magnitude.last;
  2203. result.reported = magnitude.reported;
  2204. result.decimals = magnitude.decimals;
  2205. return result;
  2206. }
  2207. void magnitudeFormat(const sensor::Value& value, char* out, size_t) {
  2208. // TODO: 'size' does not do anything, since dtostrf used here is expected to be 'sane', but
  2209. // it does not allow any size arguments besides for digits after the decimal point
  2210. dtostrf(
  2211. _sensor_realtime ? value.last : value.reported,
  2212. 1, value.decimals,
  2213. out
  2214. );
  2215. }
  2216. unsigned char magnitudeIndex(unsigned char index) {
  2217. if (index < _magnitudes.size()) {
  2218. return _magnitudes[index].index_global;
  2219. }
  2220. return 0;
  2221. }
  2222. String magnitudeDescription(unsigned char index) {
  2223. if (index < _magnitudes.size()) {
  2224. return _magnitudeDescription(_magnitudes[index]);
  2225. }
  2226. return String();
  2227. }
  2228. String magnitudeTopicIndex(unsigned char index) {
  2229. if (index < _magnitudes.size()) {
  2230. return _magnitudeTopicIndex(_magnitudes[index]);
  2231. }
  2232. return String();
  2233. }
  2234. // -----------------------------------------------------------------------------
  2235. void _sensorBackwards() {
  2236. // Some keys from older versions were longer
  2237. moveSetting("powerUnits", "pwrUnits");
  2238. moveSetting("energyUnits", "eneUnits");
  2239. // Energy is now indexed (based on magnitude.index_global)
  2240. moveSetting("eneTotal", "eneTotal0");
  2241. // Update PZEM004T energy total across multiple devices
  2242. moveSettings("pzEneTotal", "eneTotal");
  2243. // Unit ID is no longer shared, drop when equal to Min_ or None
  2244. const char *keys[3] = {
  2245. "pwrUnits", "eneUnits", "tmpUnits"
  2246. };
  2247. for (auto* key : keys) {
  2248. const auto units = getSetting(key);
  2249. if (units.length() && (units.equals("0") || units.equals("1"))) {
  2250. delSetting(key);
  2251. }
  2252. }
  2253. }
  2254. void sensorSetup() {
  2255. // Settings backwards compatibility
  2256. _sensorBackwards();
  2257. // Load configured sensors and set up all of magnitudes
  2258. _sensorLoad();
  2259. _sensorInit();
  2260. // Configure based on settings
  2261. _sensorConfigure();
  2262. // Allow us to query key default
  2263. settingsRegisterDefaults({
  2264. [](const char* key) -> bool {
  2265. if (strncmp(key, "pwr", 3) == 0) return true;
  2266. return false;
  2267. },
  2268. _sensorQueryDefault
  2269. });
  2270. // Websockets integration, send sensor readings and configuration
  2271. #if WEB_SUPPORT
  2272. wsRegister()
  2273. .onVisible(_sensorWebSocketOnVisible)
  2274. .onConnected(_sensorWebSocketOnConnected)
  2275. .onData(_sensorWebSocketSendData)
  2276. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2277. #endif
  2278. // MQTT receive callback, atm only for energy reset
  2279. #if MQTT_SUPPORT
  2280. mqttRegister(_sensorMqttCallback);
  2281. #endif
  2282. // API
  2283. #if API_SUPPORT
  2284. _sensorApiSetup();
  2285. #endif
  2286. // Terminal
  2287. #if TERMINAL_SUPPORT
  2288. _sensorInitCommands();
  2289. #endif
  2290. // Main callbacks
  2291. espurnaRegisterLoop(sensorLoop);
  2292. espurnaRegisterReload(_sensorConfigure);
  2293. }
  2294. void sensorLoop() {
  2295. // Check if we still have uninitialized sensors
  2296. static unsigned long last_init = 0;
  2297. if (!_sensors_ready) {
  2298. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2299. last_init = millis();
  2300. _sensorInit();
  2301. }
  2302. }
  2303. if (_magnitudes.size() == 0) return;
  2304. // Tick hook, called every loop()
  2305. _sensorTick();
  2306. // Check if we should read new data
  2307. static unsigned long last_update = 0;
  2308. static unsigned long report_count = 0;
  2309. if (millis() - last_update > _sensor_read_interval) {
  2310. last_update = millis();
  2311. report_count = (report_count + 1) % _sensor_report_every;
  2312. double value_raw; // holds the raw value as the sensor returns it
  2313. double value_show; // holds the processed value applying units and decimals
  2314. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2315. // Pre-read hook, called every reading
  2316. _sensorPre();
  2317. // Get the first relay state
  2318. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2319. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2320. #endif
  2321. // Get readings
  2322. for (unsigned char magnitude_index = 0; magnitude_index < _magnitudes.size(); ++magnitude_index) {
  2323. auto& magnitude = _magnitudes[magnitude_index];
  2324. if (!magnitude.sensor->status()) continue;
  2325. // -------------------------------------------------------------
  2326. // Instant value
  2327. // -------------------------------------------------------------
  2328. value_raw = magnitude.sensor->value(magnitude.slot);
  2329. // Completely remove spurious values if relay is OFF
  2330. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2331. switch (magnitude.type) {
  2332. case MAGNITUDE_POWER_ACTIVE:
  2333. case MAGNITUDE_POWER_REACTIVE:
  2334. case MAGNITUDE_POWER_APPARENT:
  2335. case MAGNITUDE_POWER_FACTOR:
  2336. case MAGNITUDE_CURRENT:
  2337. case MAGNITUDE_ENERGY_DELTA:
  2338. if (relay_off) {
  2339. value_raw = 0.0;
  2340. }
  2341. break;
  2342. default:
  2343. break;
  2344. }
  2345. #endif
  2346. // In addition to that, we also check that value is above a certain threshold
  2347. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2348. value_raw = 0.0;
  2349. }
  2350. magnitude.last = value_raw;
  2351. magnitude.filter->add(value_raw);
  2352. // -------------------------------------------------------------
  2353. // Procesing (units and decimals)
  2354. // -------------------------------------------------------------
  2355. value_show = _magnitudeProcess(magnitude, value_raw);
  2356. #if BROKER_SUPPORT
  2357. {
  2358. char buffer[64];
  2359. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2360. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2361. }
  2362. #endif
  2363. // -------------------------------------------------------------
  2364. // Debug
  2365. // -------------------------------------------------------------
  2366. #if SENSOR_DEBUG
  2367. {
  2368. char buffer[64];
  2369. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2370. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2371. _magnitudeDescription(magnitude).c_str(),
  2372. magnitudeTopic(magnitude.type).c_str(),
  2373. buffer,
  2374. _magnitudeUnits(magnitude).c_str()
  2375. );
  2376. }
  2377. #endif
  2378. // -------------------------------------------------------------------
  2379. // Report when
  2380. // - report_count overflows after reaching _sensor_report_every
  2381. // - when magnitude specifies max_change and we greater or equal to it
  2382. // -------------------------------------------------------------------
  2383. bool report = (0 == report_count);
  2384. if (!std::isnan(magnitude.reported) && (magnitude.max_change > 0)) {
  2385. report = (std::abs(value_show - magnitude.reported) >= magnitude.max_change);
  2386. }
  2387. // Special case for energy, save readings to RAM and EEPROM
  2388. if (MAGNITUDE_ENERGY == magnitude.type) {
  2389. _magnitudeSaveEnergyTotal(magnitude, report);
  2390. }
  2391. if (report) {
  2392. value_filtered = _magnitudeProcess(magnitude, magnitude.filter->result());
  2393. magnitude.filter->reset();
  2394. if (magnitude.filter->size() != _sensor_report_every) {
  2395. magnitude.filter->resize(_sensor_report_every);
  2396. }
  2397. // Check if there is a minimum change threshold to report
  2398. if (std::isnan(magnitude.reported) || (std::abs(value_filtered - magnitude.reported) >= magnitude.min_change)) {
  2399. magnitude.reported = value_filtered;
  2400. _sensorReport(magnitude_index, magnitude);
  2401. }
  2402. } // if (report_count == 0)
  2403. }
  2404. // Post-read hook, called every reading
  2405. _sensorPost();
  2406. // And report data to modules that don't specifically track them
  2407. #if WEB_SUPPORT
  2408. wsPost(_sensorWebSocketSendData);
  2409. #endif
  2410. #if THINGSPEAK_SUPPORT
  2411. if (report_count == 0) tspkFlush();
  2412. #endif
  2413. }
  2414. }
  2415. #endif // SENSOR_SUPPORT