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.

2881 lines
84 KiB

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