Mirror of espurna firmware for wireless switches and more
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.

4322 lines
112 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...)
3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
6 years ago
6 years ago
5 years ago
5 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. Copyright (C) 2020-2022 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  5. */
  6. #include "espurna.h"
  7. #if SENSOR_SUPPORT
  8. #include "sensor.h"
  9. #include "api.h"
  10. #include "domoticz.h"
  11. #include "i2c.h"
  12. #include "mqtt.h"
  13. #include "ntp.h"
  14. #include "relay.h"
  15. #include "terminal.h"
  16. #include "thingspeak.h"
  17. #include "rtcmem.h"
  18. #include "ws.h"
  19. #include <cfloat>
  20. #include <cmath>
  21. #include <cstring>
  22. #include <limits>
  23. #include <vector>
  24. //--------------------------------------------------------------------------------
  25. #include "sensors/BaseSensor.h"
  26. #include "sensors/BaseEmonSensor.h"
  27. #include "sensors/BaseAnalogEmonSensor.h"
  28. #include "sensors/BaseAnalogSensor.h"
  29. #if DUMMY_SENSOR_SUPPORT
  30. #include "sensors/DummySensor.h"
  31. #endif
  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 INA219_SUPPORT
  90. #include "sensors/INA219Sensor.h"
  91. #endif
  92. #if LDR_SUPPORT
  93. #include "sensors/LDRSensor.h"
  94. #endif
  95. #if MAX6675_SUPPORT
  96. #include "sensors/MAX6675Sensor.h"
  97. #endif
  98. #if MICS2710_SUPPORT
  99. #include "sensors/MICS2710Sensor.h"
  100. #endif
  101. #if MICS5525_SUPPORT
  102. #include "sensors/MICS5525Sensor.h"
  103. #endif
  104. #if MHZ19_SUPPORT
  105. #include "sensors/MHZ19Sensor.h"
  106. #endif
  107. #if NTC_SUPPORT
  108. #include "sensors/NTCSensor.h"
  109. #endif
  110. #if SDS011_SUPPORT
  111. #include "sensors/SDS011Sensor.h"
  112. #endif
  113. #if SENSEAIR_SUPPORT
  114. #include "sensors/SenseAirSensor.h"
  115. #endif
  116. #if PM1006_SUPPORT
  117. #include "sensors/PM1006Sensor.h"
  118. #endif
  119. #if PMSX003_SUPPORT
  120. #include "sensors/PMSX003Sensor.h"
  121. #endif
  122. #if PULSEMETER_SUPPORT
  123. #include "sensors/PulseMeterSensor.h"
  124. #endif
  125. #if PZEM004T_SUPPORT
  126. #include "sensors/PZEM004TSensor.h"
  127. #endif
  128. #if SHT3X_I2C_SUPPORT
  129. #include "sensors/SHT3XI2CSensor.h"
  130. #endif
  131. #if SI7021_SUPPORT
  132. #include "sensors/SI7021Sensor.h"
  133. #endif
  134. #if SM300D2_SUPPORT
  135. #include "sensors/SM300D2Sensor.h"
  136. #endif
  137. #if SONAR_SUPPORT
  138. #include "sensors/SonarSensor.h"
  139. #endif
  140. #if T6613_SUPPORT
  141. #include "sensors/T6613Sensor.h"
  142. #endif
  143. #if TMP3X_SUPPORT
  144. #include "sensors/TMP3XSensor.h"
  145. #endif
  146. #if V9261F_SUPPORT
  147. #include "sensors/V9261FSensor.h"
  148. #endif
  149. #if VEML6075_SUPPORT
  150. #include "sensors/VEML6075Sensor.h"
  151. #endif
  152. #if VL53L1X_SUPPORT
  153. #include "sensors/VL53L1XSensor.h"
  154. #endif
  155. #if ADE7953_SUPPORT
  156. #include "sensors/ADE7953Sensor.h"
  157. #endif
  158. #if SI1145_SUPPORT
  159. #include "sensors/SI1145Sensor.h"
  160. #endif
  161. #if HDC1080_SUPPORT
  162. #include "sensors/HDC1080Sensor.h"
  163. #endif
  164. #if PZEM004TV30_SUPPORT
  165. #include "sensors/PZEM004TV30Sensor.h"
  166. #endif
  167. #include "filters/LastFilter.h"
  168. #include "filters/MaxFilter.h"
  169. #include "filters/MedianFilter.h"
  170. #include "filters/MovingAverageFilter.h"
  171. #include "filters/SumFilter.h"
  172. //--------------------------------------------------------------------------------
  173. namespace espurna {
  174. namespace sensor {
  175. Value::operator bool() const {
  176. return !std::isinf(value) && !std::isnan(value);
  177. }
  178. String error(unsigned char error) {
  179. const char* result { nullptr };
  180. switch (error) {
  181. case SENSOR_ERROR_OK:
  182. result = PSTR("OK");
  183. break;
  184. case SENSOR_ERROR_OUT_OF_RANGE:
  185. result = PSTR("Out of Range");
  186. break;
  187. case SENSOR_ERROR_WARM_UP:
  188. result = PSTR("Warming Up");
  189. break;
  190. case SENSOR_ERROR_TIMEOUT:
  191. result = PSTR("Timeout");
  192. break;
  193. case SENSOR_ERROR_UNKNOWN_ID:
  194. result = PSTR("Unknown ID");
  195. break;
  196. case SENSOR_ERROR_CRC:
  197. result = PSTR("CRC / Data Error");
  198. break;
  199. case SENSOR_ERROR_I2C:
  200. result = PSTR("I2C Error");
  201. break;
  202. case SENSOR_ERROR_GPIO_USED:
  203. result = PSTR("GPIO Already Used");
  204. break;
  205. case SENSOR_ERROR_CALIBRATION:
  206. result = PSTR("Calibration Error");
  207. break;
  208. case SENSOR_ERROR_OVERFLOW:
  209. result = PSTR("Value Overflow");
  210. break;
  211. case SENSOR_ERROR_NOT_READY:
  212. result = PSTR("Not Ready");
  213. break;
  214. case SENSOR_ERROR_CONFIG:
  215. result = PSTR("Invalid Configuration");
  216. break;
  217. case SENSOR_ERROR_SUPPORT:
  218. result = PSTR("Not Supported");
  219. break;
  220. case SENSOR_ERROR_OTHER:
  221. default:
  222. result = PSTR("Other / Unknown Error");
  223. break;
  224. }
  225. return result;
  226. }
  227. template <typename T>
  228. void forEachError(T&& callback) {
  229. for (unsigned char error = SENSOR_ERROR_OK; error < SENSOR_ERROR_MAX; ++error) {
  230. callback(error);
  231. }
  232. }
  233. struct ReadValue {
  234. double raw; // as the sensor returns it
  235. double processed; // after applying units and decimals
  236. double filtered; // after applying filters, units and decimals
  237. };
  238. enum class Filter : int {
  239. Last,
  240. Max,
  241. Median,
  242. MovingAverage,
  243. Sum,
  244. };
  245. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  246. Energy::Energy(Energy::Pair pair) :
  247. _kwh(pair.kwh),
  248. _ws(pair.ws)
  249. {}
  250. Energy::Energy(WattSeconds ws) {
  251. _ws.value = ws.value;
  252. while (_ws.value >= WattSecondsMax) {
  253. _ws.value -= WattSecondsMax;
  254. ++_kwh.value;
  255. }
  256. }
  257. Energy::Energy(WattHours other) :
  258. Energy(static_cast<double>(other.value) / 1000.0)
  259. {}
  260. Energy::Energy(double kwh) {
  261. double lhs;
  262. double rhs = fs_modf(kwh, &lhs);
  263. _kwh.value = lhs;
  264. _ws.value = rhs * static_cast<double>(KilowattHours::Ratio::num);
  265. }
  266. Energy& Energy::operator+=(WattSeconds other) {
  267. return *this += Energy(other);
  268. }
  269. Energy Energy::operator+(WattSeconds other) {
  270. Energy result(*this);
  271. result += other;
  272. return result;
  273. }
  274. Energy& Energy::operator+=(const Energy& other) {
  275. _kwh.value += other._kwh.value;
  276. const auto left = WattSecondsMax - _ws.value;
  277. if (other._ws.value >= left) {
  278. _kwh.value += 1;
  279. _ws.value += (other._ws.value - left);
  280. } else {
  281. _ws.value += other._ws.value;
  282. }
  283. return *this;
  284. }
  285. Energy::operator bool() const {
  286. return (_kwh.value > 0) && (_ws.value > 0);
  287. }
  288. WattSeconds Energy::asWattSeconds() const {
  289. using Type = WattSeconds::Type;
  290. static constexpr auto TypeMax = std::numeric_limits<Type>::max();
  291. static constexpr Type KwhMax { TypeMax / WattSecondsMax };
  292. auto kwh = _kwh.value;
  293. while (kwh >= KwhMax) {
  294. kwh -= KwhMax;
  295. }
  296. WattSeconds out;
  297. out.value += _ws.value;
  298. out.value += kwh * WattSecondsMax;
  299. return out;
  300. }
  301. double Energy::asDouble() const {
  302. return static_cast<double>(_kwh.value)
  303. + static_cast<double>(_ws.value)
  304. / static_cast<double>(WattSecondsMax);
  305. }
  306. String Energy::asString() const {
  307. String out;
  308. // Value without `+` is treated as just `<kWh>`
  309. out += String(_kwh.value, 10);
  310. if (_ws.value) {
  311. out += '+';
  312. out += String(_ws.value, 10);
  313. }
  314. return out;
  315. }
  316. void Energy::reset() {
  317. *this = Energy{};
  318. }
  319. namespace {
  320. class BaseSensorPtr {
  321. public:
  322. BaseSensorPtr() = delete;
  323. constexpr BaseSensorPtr(const BaseSensorPtr&) = default;
  324. constexpr BaseSensorPtr(BaseSensorPtr&&) noexcept = default;
  325. #if __cplusplus > 201103L
  326. constexpr BaseSensorPtr& operator=(const BaseSensorPtr&) = default;
  327. constexpr BaseSensorPtr& operator=(BaseSensorPtr&&) noexcept = default;
  328. #else
  329. BaseSensorPtr& operator=(const BaseSensorPtr&) = default;
  330. BaseSensorPtr& operator=(BaseSensorPtr&&) noexcept = default;
  331. #endif
  332. constexpr BaseSensorPtr(std::nullptr_t) = delete;
  333. constexpr BaseSensorPtr& operator=(std::nullptr_t) = delete;
  334. constexpr BaseSensorPtr(BaseSensor* ptr) :
  335. _ptr(ptr)
  336. {}
  337. constexpr BaseSensor* get() const {
  338. return _ptr;
  339. }
  340. constexpr BaseSensor* operator->() const {
  341. return _ptr;
  342. }
  343. private:
  344. BaseSensor* _ptr;
  345. };
  346. using BaseFilterPtr = std::unique_ptr<BaseFilter>;
  347. class Magnitude {
  348. private:
  349. static unsigned char _counts[MAGNITUDE_MAX];
  350. public:
  351. static size_t counts(unsigned char type) {
  352. return _counts[type];
  353. }
  354. Magnitude() = delete;
  355. Magnitude(const Magnitude&) = delete;
  356. Magnitude& operator=(const Magnitude&) = delete;
  357. Magnitude(Magnitude&& other) noexcept = default;
  358. Magnitude& operator=(Magnitude&&) noexcept = default;
  359. Magnitude(BaseSensorPtr, unsigned char slot, unsigned char type);
  360. BaseSensorPtr sensor; // Sensor object, *cannot be empty*
  361. unsigned char slot; // Sensor slot # taken by the magnitude, used to access the measurement
  362. unsigned char type; // Type of measurement, returned by the BaseSensor::type(slot)
  363. unsigned char index_global; // N'th magnitude of it's type, across all of the active sensors
  364. Unit units { Unit::None }; // Units of measurement
  365. unsigned char decimals { 0u }; // Number of decimals in textual representation
  366. Filter filter_type { Filter::Median }; // Instead of using raw value, filter it through a filter object
  367. BaseFilterPtr filter; // *cannot be empty*
  368. double last { Value::Unknown }; // Last raw value from sensor (unfiltered)
  369. double reported { Value::Unknown }; // Last reported value
  370. double min_delta { 0.0 }; // Minimum value change to report
  371. double max_delta { 0.0 }; // Maximum value change to report
  372. double correction { 0.0 }; // Value correction (applied when processing)
  373. double zero_threshold { Value::Unknown }; // Reset value to zero when below threshold (applied when reading)
  374. };
  375. static_assert(
  376. std::is_nothrow_move_constructible<Magnitude>::value,
  377. "std::vector<Magnitude> should be able to work with resize()"
  378. );
  379. static_assert(
  380. !std::is_copy_constructible<Magnitude>::value,
  381. "std::vector<Magnitude> should only use move ctor"
  382. );
  383. Magnitude::Magnitude(BaseSensorPtr sensor, unsigned char slot, unsigned char type) :
  384. sensor(std::move(sensor)),
  385. slot(slot),
  386. type(type),
  387. index_global(_counts[type])
  388. {
  389. ++_counts[type];
  390. }
  391. unsigned char Magnitude::_counts[MAGNITUDE_MAX] = {0};
  392. bool isEmon(BaseSensorPtr sensor) {
  393. return (sensor->kind() == BaseEmonSensor::Kind)
  394. || (sensor->kind() == BaseAnalogEmonSensor::Kind);
  395. }
  396. bool isAnalogEmon(BaseSensorPtr sensor) {
  397. return sensor->kind() == BaseAnalogEmonSensor::Kind;
  398. }
  399. bool isAnalog(BaseSensorPtr sensor) {
  400. return sensor->kind() == BaseAnalogSensor::Kind;
  401. }
  402. } // namespace
  403. namespace convert {
  404. namespace temperature {
  405. namespace {
  406. struct Base {
  407. constexpr Base() = default;
  408. constexpr explicit Base(double value) :
  409. _value(value)
  410. {}
  411. constexpr double value() const {
  412. return _value;
  413. }
  414. constexpr operator double() const {
  415. return _value;
  416. }
  417. private:
  418. double _value { 0.0 };
  419. };
  420. struct Kelvin : public Base {
  421. using Base::Base;
  422. };
  423. struct Farenheit : public Base {
  424. using Base::Base;
  425. };
  426. struct Celcius : public Base {
  427. using Base::Base;
  428. };
  429. static constexpr Celcius AbsoluteZero { -273.15 };
  430. namespace internal {
  431. template <typename To, typename From, typename Same = void>
  432. struct Converter {
  433. };
  434. template <typename To, typename From>
  435. struct Converter<To, From, typename std::enable_if<std::is_same<To, From>::value>::type> {
  436. static constexpr To convert(To value) {
  437. return value;
  438. }
  439. };
  440. static constexpr double celcius_to_kelvin(double celcius) {
  441. return celcius - AbsoluteZero;
  442. }
  443. static constexpr double celcius_to_farenheit(double celcius) {
  444. return (celcius * (9.0 / 5.0)) + 32.0;
  445. }
  446. static constexpr double farenheit_to_celcius(double farenheit) {
  447. return (farenheit - 32.0) * (5.0 / 9.0);
  448. }
  449. static constexpr double farenheit_to_kelvin(double farenheit) {
  450. return celcius_to_kelvin(farenheit_to_celcius(farenheit));
  451. }
  452. static constexpr double kelvin_to_celcius(double kelvin) {
  453. return kelvin + AbsoluteZero;
  454. }
  455. static constexpr double kelvin_to_farenheit(double kelvin) {
  456. return celcius_to_farenheit(kelvin_to_celcius(kelvin));
  457. }
  458. static_assert(celcius_to_kelvin(kelvin_to_celcius(0.0)) == 0.0, "");
  459. static_assert(celcius_to_farenheit(farenheit_to_celcius(0.0)) == 0.0, "");
  460. static_assert(farenheit_to_kelvin(kelvin_to_farenheit(0.0)) == 0.0, "");
  461. static_assert(farenheit_to_celcius(celcius_to_farenheit(0.0)) == 0.0, "");
  462. static_assert(kelvin_to_celcius(celcius_to_kelvin(0.0)) == 0.0, "");
  463. // ref. https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
  464. static constexpr bool almost_equal(double lhs, double rhs, int ulp) {
  465. // the machine epsilon has to be scaled to the magnitude of the values used
  466. // and multiplied by the desired precision in ULPs (units in the last place)
  467. return __builtin_fabs(lhs - rhs) <= std::numeric_limits<double>::epsilon() * __builtin_fabs(lhs + rhs) * ulp
  468. // unless the result is subnormal
  469. || __builtin_fabs(lhs - rhs) < std::numeric_limits<double>::min();
  470. }
  471. static_assert(almost_equal(10.0, kelvin_to_farenheit(farenheit_to_kelvin(10.0)), 3), "");
  472. template <>
  473. struct Converter<Celcius, Kelvin> {
  474. static constexpr Celcius convert(Kelvin kelvin) {
  475. return Celcius{ kelvin_to_celcius(kelvin.value()) };
  476. }
  477. };
  478. template <>
  479. struct Converter<Farenheit, Kelvin> {
  480. static constexpr Farenheit convert(Kelvin kelvin) {
  481. return Farenheit{ kelvin_to_farenheit(kelvin.value()) };
  482. }
  483. };
  484. template <>
  485. struct Converter<Kelvin, Celcius> {
  486. static constexpr Kelvin convert(Celcius celcius) {
  487. return Kelvin{ celcius_to_kelvin(celcius.value()) };
  488. }
  489. };
  490. template <>
  491. struct Converter<Farenheit, Celcius> {
  492. static constexpr Farenheit convert(Celcius celcius) {
  493. return Farenheit{ celcius_to_farenheit(celcius.value()) };
  494. }
  495. };
  496. template <>
  497. struct Converter<Kelvin, Farenheit> {
  498. static constexpr Kelvin convert(Farenheit farenheit) {
  499. return Kelvin{ farenheit_to_kelvin(farenheit.value()) };
  500. }
  501. };
  502. template <>
  503. struct Converter<Celcius, Farenheit> {
  504. static constexpr Celcius convert(Farenheit farenheit) {
  505. return Celcius{ farenheit_to_celcius(farenheit.value()) };
  506. }
  507. };
  508. // just some sanity checks. note that floating point will not always produce exact results
  509. // (and it might not be a good idea to actually have anything compare with the Farenheit one)
  510. static_assert(Converter<Kelvin, Kelvin>::convert(Kelvin{0.0}) == Kelvin{0.0}, "");
  511. static_assert(Converter<Kelvin, Celcius>::convert(AbsoluteZero) == Kelvin{0.0}, "");
  512. static_assert(Converter<Celcius, Celcius>::convert(AbsoluteZero) == AbsoluteZero, "");
  513. static_assert(Converter<Celcius, Kelvin>::convert(Kelvin{0.0}) == AbsoluteZero, "");
  514. } // namespace internal
  515. template <typename To, typename From>
  516. constexpr To unit_cast(From value) {
  517. return internal::Converter<To, From>::convert(value);
  518. }
  519. static_assert(unit_cast<Kelvin>(AbsoluteZero).value() == 0.0, "");
  520. static_assert(unit_cast<Celcius>(AbsoluteZero).value() == AbsoluteZero.value(), "");
  521. constexpr bool supported(Unit unit) {
  522. return (unit == Unit::Celcius)
  523. || (unit == Unit::Kelvin)
  524. || (unit == Unit::Farenheit);
  525. }
  526. // since the outside api only works with the enumeration, make sure to cast it to our types for conversion
  527. // a table like this could've also worked
  528. // > {Unit(from), Unit(to), Converter(double(*)(double))}
  529. // but, it is ~0.6KiB vs. ~0.1KiB for this one. plus, some obstacles with c++11 implementation
  530. // although, there may be a way to make this cheaper in both compile-time and runtime
  531. // attempt to convert the input value from one unit to the other
  532. // will return the input value when units match or there's no known conversion
  533. constexpr double convert(double value, Unit from, Unit to) {
  534. #define UNIT_CAST(LHS, RHS) \
  535. ((from == Unit::LHS) && (to == Unit::RHS)) \
  536. ? (unit_cast<RHS, LHS>(LHS{value})) : \
  537. ((from == Unit::RHS) && (to == Unit::LHS)) \
  538. ? (unit_cast<LHS, RHS>(RHS{value}))
  539. return UNIT_CAST(Kelvin, Celcius) :
  540. UNIT_CAST(Kelvin, Farenheit) :
  541. UNIT_CAST(Celcius, Farenheit) : value;
  542. #undef UNIT_CAST
  543. }
  544. } // namespace
  545. } // namespace temperature
  546. // right now, limited to plain and kilo values
  547. // (since we mostly care about a fairly small values)
  548. // type conversion should only work for related types
  549. namespace metric {
  550. namespace {
  551. template <typename __Ratio>
  552. struct Base {
  553. using Type = double;
  554. using Ratio = __Ratio;
  555. constexpr Base() = default;
  556. constexpr explicit Base(Type value) :
  557. _value(value)
  558. {}
  559. constexpr Type value() const {
  560. return _value;
  561. }
  562. constexpr operator Type() const {
  563. return _value;
  564. }
  565. private:
  566. Type _value { 0.0 };
  567. };
  568. template <typename To, typename From>
  569. struct convertible_base : std::false_type {
  570. };
  571. template <typename To, typename From>
  572. constexpr bool is_convertible_base() {
  573. return std::is_same<To, From>::value
  574. || std::is_base_of<std::true_type, convertible_base<To, From>>::value
  575. || std::is_base_of<std::true_type, convertible_base<From, To>>::value;
  576. }
  577. template <typename To, typename From>
  578. using is_convertible = std::enable_if<is_convertible_base<To, From>()>;
  579. template <typename To, typename From,
  580. typename Divide = std::ratio_divide<typename From::Ratio, typename To::Ratio>,
  581. typename = typename is_convertible<To, From>::type>
  582. constexpr To unit_cast(From value) {
  583. return To(value.value()
  584. * static_cast<typename To::Type>(Divide::num)
  585. / static_cast<typename To::Type>(Divide::den));
  586. }
  587. struct Watt : public Base<std::ratio<1, 1>> {
  588. using Base::Base;
  589. };
  590. struct Kilowatt : public Base<std::ratio<1000, 1>> {
  591. using Base::Base;
  592. };
  593. template <>
  594. struct convertible_base<Watt, Kilowatt> : std::true_type {
  595. };
  596. struct Voltampere : public Base<std::ratio<1, 1>> {
  597. using Base::Base;
  598. };
  599. struct Kilovoltampere : public Base<std::ratio<1000, 1>> {
  600. using Base::Base;
  601. };
  602. template <>
  603. struct convertible_base<Voltampere, Kilovoltampere> : std::true_type {
  604. };
  605. struct VoltampereReactive : public Base<std::ratio<1, 1>> {
  606. using Base::Base;
  607. };
  608. struct KilovoltampereReactive : public Base<std::ratio<1000, 1>> {
  609. using Base::Base;
  610. };
  611. template <>
  612. struct convertible_base<VoltampereReactive, KilovoltampereReactive> : std::true_type {
  613. };
  614. struct WattSecond : public Base<std::ratio<1, 1>> {
  615. using Base::Base;
  616. };
  617. using Joule = WattSecond;
  618. struct KilowattHour : public Base<std::ratio<3600000, 1>> {
  619. using Base::Base;
  620. };
  621. template <>
  622. struct convertible_base<WattSecond, KilowattHour> : std::true_type {
  623. };
  624. static_assert(is_convertible_base<Voltampere, Kilovoltampere>(), "");
  625. static_assert(is_convertible_base<Kilovoltampere, Voltampere>(), "");
  626. static_assert(!is_convertible_base<KilovoltampereReactive, Voltampere>(), "");
  627. static_assert(is_convertible_base<Joule, WattSecond>(), "");
  628. static_assert(unit_cast<Joule>(KilowattHour{0.02}) == 72000.0, "");
  629. static_assert(unit_cast<VoltampereReactive>(KilovoltampereReactive{1234.0}) == 1234000.0, "");
  630. constexpr bool supported(Unit unit) {
  631. return (unit == Unit::Voltampere)
  632. || (unit == Unit::Kilovoltampere)
  633. || (unit == Unit::VoltampereReactive)
  634. || (unit == Unit::KilovoltampereReactive)
  635. || (unit == Unit::Watt)
  636. || (unit == Unit::Kilowatt)
  637. || (unit == Unit::Joule)
  638. || (unit == Unit::WattSecond)
  639. || (unit == Unit::KilowattHour);
  640. }
  641. // Here we only care about the direct counterparts
  642. // Plus, we still don't enforce supported() at compile time,
  643. // only safeguard is unit_cast<> failing for 'incompatible' base types
  644. constexpr double convert(double value, Unit from, Unit to) {
  645. #define UNIT_CAST(LHS, RHS) \
  646. ((from == Unit::LHS) && (to == Unit::RHS)) \
  647. ? (unit_cast<RHS, LHS>(LHS{value})) : \
  648. ((from == Unit::RHS) && (to == Unit::LHS)) \
  649. ? (unit_cast<LHS, RHS>(RHS{value}))
  650. return UNIT_CAST(Watt, Kilowatt) :
  651. UNIT_CAST(Voltampere, Kilovoltampere) :
  652. UNIT_CAST(VoltampereReactive, KilovoltampereReactive) :
  653. UNIT_CAST(Joule, KilowattHour) :
  654. UNIT_CAST(WattSecond, KilowattHour) : value;
  655. #undef UNIT_CAST
  656. }
  657. } // namespace
  658. } // namespace metric
  659. } // namespace convert
  660. namespace build {
  661. namespace {
  662. constexpr double DefaultMinDelta { 0.0 };
  663. constexpr double DefaultMaxDelta { 0.0 };
  664. constexpr espurna::duration::Seconds initInterval() {
  665. return espurna::duration::Seconds(SENSOR_INIT_INTERVAL);
  666. }
  667. constexpr espurna::duration::Seconds ReadIntervalMin { SENSOR_READ_MIN_INTERVAL };
  668. constexpr espurna::duration::Seconds ReadIntervalMax { SENSOR_READ_MAX_INTERVAL };
  669. constexpr espurna::duration::Seconds readInterval() {
  670. return espurna::duration::Seconds(SENSOR_READ_INTERVAL);
  671. }
  672. constexpr size_t ReportEveryMin PROGMEM { SENSOR_REPORT_MIN_EVERY };
  673. constexpr size_t ReportEveryMax PROGMEM { SENSOR_REPORT_MAX_EVERY };
  674. constexpr size_t reportEvery() {
  675. return SENSOR_REPORT_EVERY;
  676. }
  677. constexpr size_t saveEvery() {
  678. return SENSOR_SAVE_EVERY;
  679. }
  680. constexpr bool realTimeValues() {
  681. return SENSOR_REAL_TIME_VALUES == 1;
  682. }
  683. constexpr bool useIndex() {
  684. return SENSOR_USE_INDEX == 1;
  685. }
  686. } // namespace
  687. } // namespace build
  688. namespace settings {
  689. namespace filters {
  690. namespace {
  691. PROGMEM_STRING(Last, "last");
  692. PROGMEM_STRING(Max, "max");
  693. PROGMEM_STRING(Median, "median");
  694. PROGMEM_STRING(MovingAverage, "moving-average");
  695. PROGMEM_STRING(Sum, "sum");
  696. static constexpr espurna::settings::options::Enumeration<Filter> Options[] PROGMEM {
  697. {Filter::Last, Last},
  698. {Filter::Max, Max},
  699. {Filter::Median, Median},
  700. {Filter::MovingAverage, MovingAverage},
  701. {Filter::Sum, Sum},
  702. };
  703. } // namespace
  704. } // namespace filters
  705. namespace units {
  706. namespace {
  707. PROGMEM_STRING(Farenheit, "°F");
  708. PROGMEM_STRING(Celcius, "°C");
  709. PROGMEM_STRING(Kelvin, "K");
  710. PROGMEM_STRING(Percentage, "%");
  711. PROGMEM_STRING(Hectopascal, "hPa");
  712. PROGMEM_STRING(Ampere, "A");
  713. PROGMEM_STRING(Volt, "V");
  714. PROGMEM_STRING(Watt, "W");
  715. PROGMEM_STRING(Kilowatt, "kW");
  716. PROGMEM_STRING(Voltampere, "VA");
  717. PROGMEM_STRING(Kilovoltampere, "kVA");
  718. PROGMEM_STRING(VoltampereReactive, "VAR");
  719. PROGMEM_STRING(KilovoltampereReactive, "kVAR");
  720. PROGMEM_STRING(Joule, "J");
  721. PROGMEM_STRING(KilowattHour, "kWh");
  722. PROGMEM_STRING(MicrogrammPerCubicMeter, "µg/m³");
  723. PROGMEM_STRING(PartsPerMillion, "ppm");
  724. PROGMEM_STRING(Lux, "lux");
  725. PROGMEM_STRING(UltravioletIndex, "UVindex");
  726. PROGMEM_STRING(Ohm, "ohm");
  727. PROGMEM_STRING(MilligrammPerCubicMeter, "mg/m³");
  728. PROGMEM_STRING(CountsPerMinute, "cpm");
  729. PROGMEM_STRING(MicrosievertPerHour, "µSv/h");
  730. PROGMEM_STRING(Meter, "m");
  731. PROGMEM_STRING(Hertz, "Hz");
  732. PROGMEM_STRING(Ph, "pH");
  733. PROGMEM_STRING(None, "none");
  734. static constexpr espurna::settings::options::Enumeration<Unit> Options[] PROGMEM {
  735. {Unit::Farenheit, Farenheit},
  736. {Unit::Celcius, Celcius},
  737. {Unit::Kelvin, Kelvin},
  738. {Unit::Percentage, Percentage},
  739. {Unit::Hectopascal, Hectopascal},
  740. {Unit::Ampere, Ampere},
  741. {Unit::Volt, Volt},
  742. {Unit::Watt, Watt},
  743. {Unit::Kilowatt, Kilowatt},
  744. {Unit::Voltampere, Voltampere},
  745. {Unit::Kilovoltampere, Kilovoltampere},
  746. {Unit::VoltampereReactive, VoltampereReactive},
  747. {Unit::KilovoltampereReactive, KilovoltampereReactive},
  748. {Unit::Joule, Joule},
  749. {Unit::WattSecond, Joule},
  750. {Unit::KilowattHour, KilowattHour},
  751. {Unit::MicrogrammPerCubicMeter, MicrogrammPerCubicMeter},
  752. {Unit::PartsPerMillion, PartsPerMillion},
  753. {Unit::Lux, Lux},
  754. {Unit::UltravioletIndex, UltravioletIndex},
  755. {Unit::Ohm, Ohm},
  756. {Unit::MilligrammPerCubicMeter, MilligrammPerCubicMeter},
  757. {Unit::CountsPerMinute, CountsPerMinute},
  758. {Unit::MicrosievertPerHour, MicrosievertPerHour},
  759. {Unit::Meter, Meter},
  760. {Unit::Hertz, Hertz},
  761. {Unit::Ph, Ph},
  762. {Unit::None, None},
  763. };
  764. } // namespace
  765. } // namespace units
  766. namespace prefix {
  767. namespace {
  768. PROGMEM_STRING(Sensor, "sns");
  769. PROGMEM_STRING(Power, "pwr");
  770. PROGMEM_STRING(Temperature, "tmp");
  771. PROGMEM_STRING(Humidity, "hum");
  772. PROGMEM_STRING(Pressure, "press");
  773. PROGMEM_STRING(Current, "curr");
  774. PROGMEM_STRING(Voltage, "volt");
  775. PROGMEM_STRING(PowerActive, "pwrP");
  776. PROGMEM_STRING(PowerApparent, "pwrQ");
  777. PROGMEM_STRING(PowerReactive, "pwrModS");
  778. PROGMEM_STRING(PowerFactor, "pwrPF");
  779. PROGMEM_STRING(Energy, "ene");
  780. PROGMEM_STRING(EnergyDelta, "eneDelta");
  781. PROGMEM_STRING(Analog, "analog");
  782. PROGMEM_STRING(Digital, "digital");
  783. PROGMEM_STRING(Event, "event");
  784. PROGMEM_STRING(Pm1Dot0, "pm1dot0");
  785. PROGMEM_STRING(Pm2Dot5, "pm2dot5");
  786. PROGMEM_STRING(Pm10, "pm10");
  787. PROGMEM_STRING(Co2, "co2");
  788. PROGMEM_STRING(Voc, "voc");
  789. PROGMEM_STRING(Iaq, "iaq");
  790. PROGMEM_STRING(IaqAccuracy, "iaqAccuracy");
  791. PROGMEM_STRING(IaqStatic, "iaqStatic");
  792. PROGMEM_STRING(Lux, "lux");
  793. PROGMEM_STRING(Uva, "uva");
  794. PROGMEM_STRING(Uvb, "uvb");
  795. PROGMEM_STRING(Uvi, "uvi");
  796. PROGMEM_STRING(Distance, "distance");
  797. PROGMEM_STRING(Hcho, "hcho");
  798. PROGMEM_STRING(GeigerCpm, "gcpm");
  799. PROGMEM_STRING(GeigerSievert, "gsiev");
  800. PROGMEM_STRING(Count, "count");
  801. PROGMEM_STRING(No2, "no2");
  802. PROGMEM_STRING(Co, "co");
  803. PROGMEM_STRING(Resistance, "res");
  804. PROGMEM_STRING(Ph, "ph");
  805. PROGMEM_STRING(Frequency, "freq");
  806. PROGMEM_STRING(Tvoc, "tvoc");
  807. PROGMEM_STRING(Ch2o, "ch2o");
  808. PROGMEM_STRING(Unknown, "unknown");
  809. constexpr StringView get(unsigned char type) {
  810. return (type == MAGNITUDE_TEMPERATURE) ? Temperature :
  811. (type == MAGNITUDE_HUMIDITY) ? Humidity :
  812. (type == MAGNITUDE_PRESSURE) ? Pressure :
  813. (type == MAGNITUDE_CURRENT) ? Current :
  814. (type == MAGNITUDE_VOLTAGE) ? Voltage :
  815. (type == MAGNITUDE_POWER_ACTIVE) ? PowerActive :
  816. (type == MAGNITUDE_POWER_APPARENT) ? PowerApparent :
  817. (type == MAGNITUDE_POWER_REACTIVE) ? PowerReactive :
  818. (type == MAGNITUDE_POWER_FACTOR) ? PowerFactor :
  819. (type == MAGNITUDE_ENERGY) ? Energy :
  820. (type == MAGNITUDE_ENERGY_DELTA) ? EnergyDelta :
  821. (type == MAGNITUDE_ANALOG) ? Analog :
  822. (type == MAGNITUDE_DIGITAL) ? Digital :
  823. (type == MAGNITUDE_EVENT) ? Event :
  824. (type == MAGNITUDE_PM1DOT0) ? Pm1Dot0 :
  825. (type == MAGNITUDE_PM2DOT5) ? Pm2Dot5 :
  826. (type == MAGNITUDE_PM10) ? Pm10 :
  827. (type == MAGNITUDE_CO2) ? Co2 :
  828. (type == MAGNITUDE_VOC) ? Voc :
  829. (type == MAGNITUDE_IAQ) ? Iaq :
  830. (type == MAGNITUDE_IAQ_ACCURACY) ? IaqAccuracy :
  831. (type == MAGNITUDE_IAQ_STATIC) ? IaqStatic :
  832. (type == MAGNITUDE_LUX) ? Lux :
  833. (type == MAGNITUDE_UVA) ? Uva :
  834. (type == MAGNITUDE_UVB) ? Uvb :
  835. (type == MAGNITUDE_UVI) ? Uvi :
  836. (type == MAGNITUDE_DISTANCE) ? Distance :
  837. (type == MAGNITUDE_HCHO) ? Hcho :
  838. (type == MAGNITUDE_GEIGER_CPM) ? GeigerCpm :
  839. (type == MAGNITUDE_GEIGER_SIEVERT) ? GeigerSievert :
  840. (type == MAGNITUDE_COUNT) ? Count :
  841. (type == MAGNITUDE_NO2) ? No2 :
  842. (type == MAGNITUDE_CO) ? Co :
  843. (type == MAGNITUDE_RESISTANCE) ? Resistance :
  844. (type == MAGNITUDE_PH) ? Ph :
  845. (type == MAGNITUDE_FREQUENCY) ? Frequency :
  846. (type == MAGNITUDE_TVOC) ? Tvoc :
  847. (type == MAGNITUDE_CH2O) ? Ch2o :
  848. Unknown;
  849. }
  850. } // namespace
  851. } // namespace prefix
  852. namespace suffix {
  853. namespace {
  854. PROGMEM_STRING(Correction, "Correction");
  855. PROGMEM_STRING(MaxDelta, "MaxDelta");
  856. PROGMEM_STRING(MinDelta, "MinDelta");
  857. PROGMEM_STRING(Precision, "Precision");
  858. PROGMEM_STRING(Ratio, "Ratio");
  859. PROGMEM_STRING(Units, "Units");
  860. PROGMEM_STRING(ZeroThreshold, "ZeroThreshold");
  861. PROGMEM_STRING(Mains, "Mains");
  862. PROGMEM_STRING(Reference, "Reference");
  863. PROGMEM_STRING(Total, "Total");
  864. PROGMEM_STRING(Filter, "Filter");
  865. } // namespace
  866. } // namespace suffix
  867. namespace keys {
  868. namespace {
  869. PROGMEM_STRING(ReadInterval, "snsRead");
  870. PROGMEM_STRING(InitInterval, "snsInit");
  871. PROGMEM_STRING(ReportEvery, "snsReport");
  872. PROGMEM_STRING(SaveEvery, "snsSave");
  873. PROGMEM_STRING(RealTimeValues, "snsRealTime");
  874. espurna::settings::Key get(espurna::StringView prefix, espurna::StringView suffix, size_t index) {
  875. String key;
  876. key.reserve(prefix.length() + suffix.length() + 4);
  877. key.concat(prefix.c_str(), prefix.length());
  878. key.concat(suffix.c_str(), suffix.length());
  879. return espurna::settings::Key(std::move(key), index);
  880. }
  881. espurna::settings::Key get(const Magnitude& magnitude, espurna::StringView suffix) {
  882. return get(prefix::get(magnitude.type), suffix, magnitude.index_global);
  883. }
  884. } // namespace
  885. } // namespace keys
  886. namespace {
  887. espurna::duration::Seconds readInterval() {
  888. return std::clamp(getSetting(FPSTR(keys::ReadInterval), build::readInterval()),
  889. build::ReadIntervalMin, build::ReadIntervalMax);
  890. }
  891. espurna::duration::Seconds initInterval() {
  892. return std::clamp(getSetting(FPSTR(keys::InitInterval), build::initInterval()),
  893. build::ReadIntervalMin, build::ReadIntervalMax);
  894. }
  895. size_t reportEvery() {
  896. return std::clamp(getSetting(FPSTR(keys::ReportEvery), build::reportEvery()),
  897. build::ReportEveryMin, build::ReportEveryMax);
  898. }
  899. int saveEvery() {
  900. return getSetting(FPSTR(keys::SaveEvery), build::saveEvery());
  901. }
  902. bool realTimeValues() {
  903. return getSetting(FPSTR(keys::RealTimeValues), build::realTimeValues());
  904. }
  905. } // namespace
  906. } // namespace settings
  907. alignas(4) static constexpr char List[] PROGMEM_STRING_ATTR =
  908. #if ADE7953_SUPPORT
  909. "ADE7953 "
  910. #endif
  911. #if AM2320_SUPPORT
  912. "AM2320_I2C "
  913. #endif
  914. #if ANALOG_SUPPORT
  915. "ANALOG "
  916. #endif
  917. #if BH1750_SUPPORT
  918. "BH1750 "
  919. #endif
  920. #if BMP180_SUPPORT
  921. "BMP180 "
  922. #endif
  923. #if BMX280_SUPPORT
  924. "BMX280 "
  925. #endif
  926. #if BME680_SUPPORT
  927. "BME680 "
  928. #endif
  929. #if CSE7766_SUPPORT
  930. "CSE7766 "
  931. #endif
  932. #if DALLAS_SUPPORT
  933. "DALLAS "
  934. #endif
  935. #if DHT_SUPPORT
  936. "DHTXX "
  937. #endif
  938. #if DIGITAL_SUPPORT
  939. "DIGITAL "
  940. #endif
  941. #if ECH1560_SUPPORT
  942. "ECH1560 "
  943. #endif
  944. #if EMON_ADC121_SUPPORT
  945. "EMON_ADC121 "
  946. #endif
  947. #if EMON_ADS1X15_SUPPORT
  948. "EMON_ADX1X15 "
  949. #endif
  950. #if EMON_ANALOG_SUPPORT
  951. "EMON_ANALOG "
  952. #endif
  953. #if EVENTS_SUPPORT
  954. "EVENTS "
  955. #endif
  956. #if GEIGER_SUPPORT
  957. "GEIGER "
  958. #endif
  959. #if GUVAS12SD_SUPPORT
  960. "GUVAS12SD "
  961. #endif
  962. #if HDC1080_SUPPORT
  963. "HDC1080 "
  964. #endif
  965. #if HLW8012_SUPPORT
  966. "HLW8012 "
  967. #endif
  968. #if INA219_SUPPORT
  969. "INA219 "
  970. #endif
  971. #if LDR_SUPPORT
  972. "LDR "
  973. #endif
  974. #if MAX6675_SUPPORT
  975. "MAX6675 "
  976. #endif
  977. #if MHZ19_SUPPORT
  978. "MHZ19 "
  979. #endif
  980. #if MICS2710_SUPPORT
  981. "MICS2710 "
  982. #endif
  983. #if MICS5525_SUPPORT
  984. "MICS5525 "
  985. #endif
  986. #if NTC_SUPPORT
  987. "NTC "
  988. #endif
  989. #if PM1006_SUPPORT
  990. "PM1006 "
  991. #endif
  992. #if PMSX003_SUPPORT
  993. "PMSX003 "
  994. #endif
  995. #if PULSEMETER_SUPPORT
  996. "PULSEMETER "
  997. #endif
  998. #if PZEM004T_SUPPORT
  999. "PZEM004T "
  1000. #endif
  1001. #if PZEM004TV30_SUPPORT
  1002. "PZEM004TV30 "
  1003. #endif
  1004. #if SDS011_SUPPORT
  1005. "SDS011 "
  1006. #endif
  1007. #if SENSEAIR_SUPPORT
  1008. "SENSEAIR "
  1009. #endif
  1010. #if SHT3X_I2C_SUPPORT
  1011. "SHT3X_I2C "
  1012. #endif
  1013. #if SI7021_SUPPORT
  1014. "SI7021 "
  1015. #endif
  1016. #if SM300D2_SUPPORT
  1017. "SM300D2 "
  1018. #endif
  1019. #if SONAR_SUPPORT
  1020. "SONAR "
  1021. #endif
  1022. #if T6613_SUPPORT
  1023. "T6613 "
  1024. #endif
  1025. #if TMP3X_SUPPORT
  1026. "TMP3X "
  1027. #endif
  1028. #if V9261F_SUPPORT
  1029. "V9261F "
  1030. #endif
  1031. #if VEML6075_SUPPORT
  1032. "VEML6075 "
  1033. #endif
  1034. #if VL53L1X_SUPPORT
  1035. "VL53L1X "
  1036. #endif
  1037. #if EZOPH_SUPPORT
  1038. "EZOPH "
  1039. #endif
  1040. #if DUMMY_SENSOR_SUPPORT
  1041. "DUMMY "
  1042. #endif
  1043. #if SI1145_SUPPORT
  1044. "SI1145 "
  1045. #endif
  1046. "";
  1047. } // namespace sensor
  1048. namespace settings {
  1049. namespace internal {
  1050. template <>
  1051. espurna::sensor::Unit convert(const String& value) {
  1052. return convert(espurna::sensor::settings::units::Options, value,
  1053. espurna::sensor::Unit::None);
  1054. }
  1055. String serialize(espurna::sensor::Unit unit) {
  1056. return serialize(espurna::sensor::settings::units::Options, unit);
  1057. }
  1058. template <>
  1059. espurna::sensor::Filter convert(const String& value) {
  1060. return convert(espurna::sensor::settings::filters::Options, value,
  1061. espurna::sensor::Filter::Median);
  1062. }
  1063. String serialize(espurna::sensor::Filter filter) {
  1064. return serialize(espurna::sensor::settings::filters::Options, filter);
  1065. }
  1066. } // namespace internal
  1067. } // namespace settings
  1068. namespace sensor {
  1069. namespace magnitude {
  1070. namespace traits {
  1071. constexpr bool correction_supported(unsigned char type) {
  1072. return (type == MAGNITUDE_TEMPERATURE)
  1073. || (type == MAGNITUDE_HUMIDITY)
  1074. || (type == MAGNITUDE_PRESSURE)
  1075. || (type == MAGNITUDE_LUX);
  1076. }
  1077. static constexpr unsigned char ratio_types[] {
  1078. MAGNITUDE_CURRENT,
  1079. MAGNITUDE_VOLTAGE,
  1080. MAGNITUDE_POWER_ACTIVE,
  1081. MAGNITUDE_ENERGY,
  1082. };
  1083. constexpr bool ratio_supported(unsigned char type) {
  1084. return (type == MAGNITUDE_CURRENT)
  1085. || (type == MAGNITUDE_VOLTAGE)
  1086. || (type == MAGNITUDE_POWER_ACTIVE)
  1087. || (type == MAGNITUDE_ENERGY);
  1088. }
  1089. } // namespace traits
  1090. namespace build {
  1091. static constexpr double correction(unsigned char type) {
  1092. return (
  1093. (type == MAGNITUDE_TEMPERATURE) ? (SENSOR_TEMPERATURE_CORRECTION) :
  1094. (type == MAGNITUDE_HUMIDITY) ? (SENSOR_HUMIDITY_CORRECTION) :
  1095. (type == MAGNITUDE_LUX) ? (SENSOR_LUX_CORRECTION) :
  1096. (type == MAGNITUDE_PRESSURE) ? (SENSOR_PRESSURE_CORRECTION) :
  1097. 0.0
  1098. );
  1099. }
  1100. } // namespace build
  1101. namespace {
  1102. String format(const Magnitude& magnitude, double value) {
  1103. // XXX: dtostrf only handles basic floating point values and will never produce scientific notation
  1104. // ensure decimals is within some sane limit and the actual value never goes above this buffer size
  1105. char buffer[64];
  1106. dtostrf(value, 1, magnitude.decimals, buffer);
  1107. return buffer;
  1108. }
  1109. String name(unsigned char type) {
  1110. const char* result = nullptr;
  1111. switch (type) {
  1112. case MAGNITUDE_TEMPERATURE:
  1113. result = PSTR("Temperature");
  1114. break;
  1115. case MAGNITUDE_HUMIDITY:
  1116. result = PSTR("Humidity");
  1117. break;
  1118. case MAGNITUDE_PRESSURE:
  1119. result = PSTR("Pressure");
  1120. break;
  1121. case MAGNITUDE_CURRENT:
  1122. result = PSTR("Current");
  1123. break;
  1124. case MAGNITUDE_VOLTAGE:
  1125. result = PSTR("Voltage");
  1126. break;
  1127. case MAGNITUDE_POWER_ACTIVE:
  1128. result = PSTR("Active Power");
  1129. break;
  1130. case MAGNITUDE_POWER_APPARENT:
  1131. result = PSTR("Apparent Power");
  1132. break;
  1133. case MAGNITUDE_POWER_REACTIVE:
  1134. result = PSTR("Reactive Power");
  1135. break;
  1136. case MAGNITUDE_POWER_FACTOR:
  1137. result = PSTR("Power Factor");
  1138. break;
  1139. case MAGNITUDE_ENERGY:
  1140. result = PSTR("Energy");
  1141. break;
  1142. case MAGNITUDE_ENERGY_DELTA:
  1143. result = PSTR("Energy (delta)");
  1144. break;
  1145. case MAGNITUDE_ANALOG:
  1146. result = PSTR("Analog");
  1147. break;
  1148. case MAGNITUDE_DIGITAL:
  1149. result = PSTR("Digital");
  1150. break;
  1151. case MAGNITUDE_EVENT:
  1152. result = PSTR("Event");
  1153. break;
  1154. case MAGNITUDE_PM1DOT0:
  1155. result = PSTR("PM1.0");
  1156. break;
  1157. case MAGNITUDE_PM2DOT5:
  1158. result = PSTR("PM2.5");
  1159. break;
  1160. case MAGNITUDE_PM10:
  1161. result = PSTR("PM10");
  1162. break;
  1163. case MAGNITUDE_CO2:
  1164. result = PSTR("CO2");
  1165. break;
  1166. case MAGNITUDE_VOC:
  1167. result = PSTR("VOC");
  1168. break;
  1169. case MAGNITUDE_IAQ_STATIC:
  1170. result = PSTR("IAQ (Static)");
  1171. break;
  1172. case MAGNITUDE_IAQ:
  1173. result = PSTR("IAQ");
  1174. break;
  1175. case MAGNITUDE_IAQ_ACCURACY:
  1176. result = PSTR("IAQ Accuracy");
  1177. break;
  1178. case MAGNITUDE_LUX:
  1179. result = PSTR("Lux");
  1180. break;
  1181. case MAGNITUDE_UVA:
  1182. result = PSTR("UVA");
  1183. break;
  1184. case MAGNITUDE_UVB:
  1185. result = PSTR("UVB");
  1186. break;
  1187. case MAGNITUDE_UVI:
  1188. result = PSTR("UVI");
  1189. break;
  1190. case MAGNITUDE_DISTANCE:
  1191. result = PSTR("Distance");
  1192. break;
  1193. case MAGNITUDE_HCHO:
  1194. result = PSTR("HCHO");
  1195. break;
  1196. case MAGNITUDE_GEIGER_CPM:
  1197. case MAGNITUDE_GEIGER_SIEVERT:
  1198. result = PSTR("Local Dose Rate");
  1199. break;
  1200. case MAGNITUDE_COUNT:
  1201. result = PSTR("Count");
  1202. break;
  1203. case MAGNITUDE_NO2:
  1204. result = PSTR("NO2");
  1205. break;
  1206. case MAGNITUDE_CO:
  1207. result = PSTR("CO");
  1208. break;
  1209. case MAGNITUDE_RESISTANCE:
  1210. result = PSTR("Resistance");
  1211. break;
  1212. case MAGNITUDE_PH:
  1213. result = PSTR("pH");
  1214. break;
  1215. case MAGNITUDE_FREQUENCY:
  1216. result = PSTR("Frequency");
  1217. break;
  1218. case MAGNITUDE_TVOC:
  1219. result = PSTR("TVOC");
  1220. break;
  1221. case MAGNITUDE_CH2O:
  1222. result = PSTR("CH2O");
  1223. break;
  1224. case MAGNITUDE_NONE:
  1225. default:
  1226. break;
  1227. }
  1228. return String(result);
  1229. }
  1230. String topic(unsigned char type) {
  1231. const char* result = PSTR("unknown");
  1232. switch (type) {
  1233. case MAGNITUDE_TEMPERATURE:
  1234. result = PSTR("temperature");
  1235. break;
  1236. case MAGNITUDE_HUMIDITY:
  1237. result = PSTR("humidity");
  1238. break;
  1239. case MAGNITUDE_PRESSURE:
  1240. result = PSTR("pressure");
  1241. break;
  1242. case MAGNITUDE_CURRENT:
  1243. result = PSTR("current");
  1244. break;
  1245. case MAGNITUDE_VOLTAGE:
  1246. result = PSTR("voltage");
  1247. break;
  1248. case MAGNITUDE_POWER_ACTIVE:
  1249. result = PSTR("power");
  1250. break;
  1251. case MAGNITUDE_POWER_APPARENT:
  1252. result = PSTR("apparent");
  1253. break;
  1254. case MAGNITUDE_POWER_REACTIVE:
  1255. result = PSTR("reactive");
  1256. break;
  1257. case MAGNITUDE_POWER_FACTOR:
  1258. result = PSTR("factor");
  1259. break;
  1260. case MAGNITUDE_ENERGY:
  1261. result = PSTR("energy");
  1262. break;
  1263. case MAGNITUDE_ENERGY_DELTA:
  1264. result = PSTR("energy_delta");
  1265. break;
  1266. case MAGNITUDE_ANALOG:
  1267. result = PSTR("analog");
  1268. break;
  1269. case MAGNITUDE_DIGITAL:
  1270. result = PSTR("digital");
  1271. break;
  1272. case MAGNITUDE_EVENT:
  1273. result = PSTR("event");
  1274. break;
  1275. case MAGNITUDE_PM1DOT0:
  1276. result = PSTR("pm1dot0");
  1277. break;
  1278. case MAGNITUDE_PM2DOT5:
  1279. result = PSTR("pm2dot5");
  1280. break;
  1281. case MAGNITUDE_PM10:
  1282. result = PSTR("pm10");
  1283. break;
  1284. case MAGNITUDE_CO2:
  1285. result = PSTR("co2");
  1286. break;
  1287. case MAGNITUDE_VOC:
  1288. result = PSTR("voc");
  1289. break;
  1290. case MAGNITUDE_IAQ:
  1291. result = PSTR("iaq");
  1292. break;
  1293. case MAGNITUDE_IAQ_ACCURACY:
  1294. result = PSTR("iaq_accuracy");
  1295. break;
  1296. case MAGNITUDE_IAQ_STATIC:
  1297. result = PSTR("iaq_static");
  1298. break;
  1299. case MAGNITUDE_LUX:
  1300. result = PSTR("lux");
  1301. break;
  1302. case MAGNITUDE_UVA:
  1303. result = PSTR("uva");
  1304. break;
  1305. case MAGNITUDE_UVB:
  1306. result = PSTR("uvb");
  1307. break;
  1308. case MAGNITUDE_UVI:
  1309. result = PSTR("uvi");
  1310. break;
  1311. case MAGNITUDE_DISTANCE:
  1312. result = PSTR("distance");
  1313. break;
  1314. case MAGNITUDE_HCHO:
  1315. result = PSTR("hcho");
  1316. break;
  1317. case MAGNITUDE_GEIGER_CPM:
  1318. result = PSTR("ldr_cpm"); // local dose rate [Counts per minute]
  1319. break;
  1320. case MAGNITUDE_GEIGER_SIEVERT:
  1321. result = PSTR("ldr_uSvh"); // local dose rate [µSievert per hour]
  1322. break;
  1323. case MAGNITUDE_COUNT:
  1324. result = PSTR("count");
  1325. break;
  1326. case MAGNITUDE_NO2:
  1327. result = PSTR("no2");
  1328. break;
  1329. case MAGNITUDE_CO:
  1330. result = PSTR("co");
  1331. break;
  1332. case MAGNITUDE_RESISTANCE:
  1333. result = PSTR("resistance");
  1334. break;
  1335. case MAGNITUDE_PH:
  1336. result = PSTR("ph");
  1337. break;
  1338. case MAGNITUDE_FREQUENCY:
  1339. result = PSTR("frequency");
  1340. break;
  1341. case MAGNITUDE_TVOC:
  1342. result = PSTR("tvoc");
  1343. break;
  1344. case MAGNITUDE_CH2O:
  1345. result = PSTR("ch2o");
  1346. break;
  1347. case MAGNITUDE_NONE:
  1348. default:
  1349. break;
  1350. }
  1351. return String(result);
  1352. }
  1353. String topic(const Magnitude& magnitude) {
  1354. return topic(magnitude.type);
  1355. }
  1356. String topicWithIndex(const Magnitude& magnitude) {
  1357. auto out = topic(magnitude);
  1358. if (sensor::build::useIndex() || (Magnitude::counts(magnitude.type) > 1)) {
  1359. out += '/' + String(magnitude.index_global, 10);
  1360. }
  1361. return out;
  1362. }
  1363. String description(const Magnitude& magnitude) {
  1364. return magnitude.sensor->description(magnitude.slot);
  1365. }
  1366. sensor::Filter defaultFilter(unsigned char type) {
  1367. switch (type) {
  1368. case MAGNITUDE_IAQ:
  1369. case MAGNITUDE_IAQ_STATIC:
  1370. case MAGNITUDE_ENERGY:
  1371. return Filter::Last;
  1372. case MAGNITUDE_EVENT:
  1373. case MAGNITUDE_DIGITAL:
  1374. return Filter::Max;
  1375. case MAGNITUDE_COUNT:
  1376. case MAGNITUDE_ENERGY_DELTA:
  1377. return Filter::Sum;
  1378. case MAGNITUDE_GEIGER_CPM:
  1379. case MAGNITUDE_GEIGER_SIEVERT:
  1380. return Filter::MovingAverage;
  1381. }
  1382. return Filter::Median;
  1383. }
  1384. Filter defaultFilter(const Magnitude& magnitude) {
  1385. return defaultFilter(magnitude.type);
  1386. }
  1387. BaseFilterPtr makeFilter(Filter filter) {
  1388. BaseFilterPtr out;
  1389. switch (filter) {
  1390. case Filter::Last:
  1391. out = std::make_unique<LastFilter>();
  1392. break;
  1393. case Filter::Max:
  1394. out = std::make_unique<MaxFilter>();
  1395. break;
  1396. case Filter::Sum:
  1397. out = std::make_unique<SumFilter>();
  1398. break;
  1399. case Filter::MovingAverage:
  1400. out = std::make_unique<MovingAverageFilter>();
  1401. break;
  1402. case Filter::Median:
  1403. out = std::make_unique<MedianFilter>();
  1404. break;
  1405. }
  1406. return out;
  1407. }
  1408. // Hardcoded decimals for each magnitude
  1409. unsigned char decimals(Unit unit) {
  1410. switch (unit) {
  1411. case Unit::Celcius:
  1412. case Unit::Farenheit:
  1413. return 1;
  1414. case Unit::Percentage:
  1415. return 0;
  1416. case Unit::Hectopascal:
  1417. return 2;
  1418. case Unit::Ampere:
  1419. return 3;
  1420. case Unit::Volt:
  1421. return 0;
  1422. case Unit::Watt:
  1423. case Unit::Voltampere:
  1424. case Unit::VoltampereReactive:
  1425. return 0;
  1426. case Unit::Kilowatt:
  1427. case Unit::Kilovoltampere:
  1428. case Unit::KilovoltampereReactive:
  1429. return 3;
  1430. case Unit::KilowattHour:
  1431. return 3;
  1432. case Unit::WattSecond:
  1433. return 0;
  1434. case Unit::CountsPerMinute:
  1435. case Unit::MicrosievertPerHour:
  1436. return 4;
  1437. case Unit::Meter:
  1438. return 3;
  1439. case Unit::Hertz:
  1440. return 1;
  1441. case Unit::UltravioletIndex:
  1442. return 3;
  1443. case Unit::Ph:
  1444. return 3;
  1445. case Unit::None:
  1446. default:
  1447. break;
  1448. }
  1449. return 0;
  1450. }
  1451. double process(const Magnitude& magnitude, double value) {
  1452. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  1453. const auto sensor_units = magnitude.sensor->units(magnitude.slot);
  1454. if (sensor_units != magnitude.units) {
  1455. using namespace sensor::convert;
  1456. if (temperature::supported(sensor_units) && temperature::supported(magnitude.units)) {
  1457. value = temperature::convert(value, sensor_units, magnitude.units);
  1458. } else if (metric::supported(sensor_units) && metric::supported(magnitude.units)) {
  1459. value = metric::convert(value, sensor_units, magnitude.units);
  1460. }
  1461. }
  1462. // Right now, correction is a simple offset.
  1463. // TODO: math expression?
  1464. value = value + magnitude.correction;
  1465. // RAW value might have more decimal points than necessary.
  1466. return roundTo(value, magnitude.decimals);
  1467. }
  1468. } // namespace
  1469. namespace internal {
  1470. namespace {
  1471. std::vector<Magnitude> magnitudes;
  1472. using ReadHandlers = std::forward_list<MagnitudeReadHandler>;
  1473. ReadHandlers read_handlers;
  1474. ReadHandlers report_handlers;
  1475. } // namespace
  1476. } // namespace internal
  1477. size_t count(unsigned char type) {
  1478. return Magnitude::counts(type);
  1479. }
  1480. size_t count() {
  1481. return internal::magnitudes.size();
  1482. }
  1483. void add(BaseSensorPtr sensor, unsigned char slot, unsigned char type) {
  1484. internal::magnitudes.emplace_back(sensor, slot, type);
  1485. }
  1486. const Magnitude* find(unsigned char type, unsigned char index) {
  1487. const Magnitude* out { nullptr };
  1488. const auto result = std::find_if(
  1489. std::cbegin(internal::magnitudes),
  1490. std::cend(internal::magnitudes),
  1491. [&](const Magnitude& magnitude) {
  1492. return (magnitude.type == type) && (magnitude.index_global == index);
  1493. });
  1494. if (result != internal::magnitudes.end()) {
  1495. out = std::addressof(*result);
  1496. }
  1497. return out;
  1498. }
  1499. Magnitude& get(size_t index) {
  1500. return internal::magnitudes[index];
  1501. }
  1502. template <typename T>
  1503. void forEachInstance(T&& callback) {
  1504. for (auto& magnitude : internal::magnitudes) {
  1505. callback(magnitude);
  1506. }
  1507. }
  1508. template <typename T>
  1509. void forEachCounted(T&& callback) {
  1510. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  1511. if (count(type)) {
  1512. callback(type);
  1513. }
  1514. }
  1515. }
  1516. // check if `callback(type)` returns `true` at least once
  1517. template <typename T>
  1518. bool forEachCountedCheck(T&& callback) {
  1519. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  1520. if (count(type) && callback(type)) {
  1521. return true;
  1522. }
  1523. }
  1524. return false;
  1525. }
  1526. void onRead(MagnitudeReadHandler handler) {
  1527. internal::read_handlers.push_front(handler);
  1528. }
  1529. void read(const Value& value) {
  1530. for (auto& handler : internal::read_handlers) {
  1531. handler(value);
  1532. }
  1533. }
  1534. void onReport(MagnitudeReadHandler handler) {
  1535. internal::report_handlers.push_front(handler);
  1536. }
  1537. void report(const Value& report) {
  1538. for (auto& handler : internal::report_handlers) {
  1539. handler(report);
  1540. }
  1541. #if MQTT_SUPPORT
  1542. {
  1543. mqttSend(report.topic.c_str(), report.repr.c_str());
  1544. #if SENSOR_PUBLISH_ADDRESSES
  1545. {
  1546. static constexpr auto AddressTopic = STRING_VIEW(SENSOR_ADDRESS_TOPIC);
  1547. String address_topic;
  1548. address_topic.reserve(report.topic.length() + AddressTopic.length());
  1549. address_topic.concat(AddressTopic.c_str(), AddressTopic.length());
  1550. address_topic += '/';
  1551. address_topic += report.topic;
  1552. mqttSend(address_topic.c_str(), magnitude.sensor->address(magnitude.slot).c_str());
  1553. }
  1554. #endif // SENSOR_PUBLISH_ADDRESSES
  1555. }
  1556. #endif // MQTT_SUPPORT
  1557. }
  1558. Info info(const Magnitude& magnitude) {
  1559. return Info{
  1560. .type = magnitude.type,
  1561. .index = magnitude.index_global,
  1562. .units = magnitude.units,
  1563. .decimals = magnitude.decimals,
  1564. .topic = topicWithIndex(magnitude),
  1565. };
  1566. }
  1567. Value value(const Magnitude& magnitude, double value) {
  1568. return Value{
  1569. .type = magnitude.type,
  1570. .index = magnitude.index_global,
  1571. .units = magnitude.units,
  1572. .decimals = magnitude.decimals,
  1573. .topic = topicWithIndex(magnitude),
  1574. .value = value,
  1575. .repr = format(magnitude, value),
  1576. };
  1577. }
  1578. template <typename T>
  1579. Value safe_value(size_t index, T&& retrieve) {
  1580. Value out;
  1581. out.value = Value::Unknown;
  1582. if (index < count()) {
  1583. const auto& magnitude = get(index);
  1584. out = value(magnitude, retrieve(magnitude));
  1585. }
  1586. return out;
  1587. }
  1588. Value safe_value_last(size_t index) {
  1589. return safe_value(
  1590. index,
  1591. [](const Magnitude& magnitude) {
  1592. return magnitude.last;
  1593. });
  1594. }
  1595. Value safe_value_reported(size_t index) {
  1596. return safe_value(
  1597. index,
  1598. [](const Magnitude& magnitude) {
  1599. return magnitude.reported;
  1600. });
  1601. }
  1602. } // namespace magnitude
  1603. using TimeSource = espurna::time::CoreClock;
  1604. enum class State {
  1605. None,
  1606. Initial,
  1607. Idle,
  1608. Resume,
  1609. Ready,
  1610. Reading,
  1611. };
  1612. namespace internal {
  1613. std::vector<BaseSensorPtr> sensors;
  1614. size_t read_count;
  1615. bool real_time { build::realTimeValues() };
  1616. size_t report_every { build::reportEvery() };
  1617. duration::Seconds read_interval { build::readInterval() };
  1618. duration::Seconds init_interval { build::initInterval() };
  1619. } // namespace internal
  1620. bool realTimeValues() {
  1621. return internal::real_time;
  1622. }
  1623. void realTimeValues(bool value) {
  1624. internal::real_time = value;
  1625. }
  1626. size_t reportEvery() {
  1627. return internal::report_every;
  1628. }
  1629. void reportEvery(size_t value) {
  1630. internal::report_every = value;
  1631. }
  1632. duration::Seconds readInterval() {
  1633. return internal::read_interval;
  1634. }
  1635. void readInterval(duration::Seconds value) {
  1636. internal::read_interval = value;
  1637. }
  1638. duration::Seconds initInterval() {
  1639. return internal::init_interval;
  1640. }
  1641. void initInterval(duration::Seconds value) {
  1642. internal::init_interval = value;
  1643. }
  1644. template <typename T>
  1645. void forEachInstance(T&& callback) {
  1646. for (auto sensor : internal::sensors) {
  1647. callback(sensor);
  1648. }
  1649. }
  1650. void add(BaseSensor* sensor) {
  1651. internal::sensors.push_back(sensor);
  1652. }
  1653. size_t count() {
  1654. return internal::sensors.size();
  1655. }
  1656. void tick() {
  1657. for (auto sensor : internal::sensors) {
  1658. sensor->tick();
  1659. }
  1660. }
  1661. void pre() {
  1662. for (auto sensor : internal::sensors) {
  1663. sensor->pre();
  1664. if (!sensor->status()) {
  1665. DEBUG_MSG_P(PSTR("[SENSOR] Could not read from %s (%s)\n"),
  1666. sensor->description().c_str(), error(sensor->error()).c_str());
  1667. }
  1668. }
  1669. }
  1670. void post() {
  1671. for (auto sensor : internal::sensors) {
  1672. sensor->post();
  1673. }
  1674. }
  1675. // Registers available sensor classes.
  1676. //
  1677. // Notice that *every* available sensor (*_SUPPORT set to 1) is queued for initialization.
  1678. // For the time being, failure to `begin()` any sensor will stall all subsequent sensors.
  1679. //
  1680. // Future updates *should* work out whether we need to:
  1681. // - allow to 'enable' specific sensor in settings
  1682. // (...would we have too much key prefixes?)
  1683. // - 'probe' sensor (bus scan, attempt to read) separate from actual loading
  1684. // - allow to soft-fail begin()
  1685. // (although, removing stable magnitude IDs)
  1686. //
  1687. // If you want to add another sensor instance of the same type, just duplicate
  1688. // the initialization block and change the respective method arguments.
  1689. // For example, to add a second DHT sensor:
  1690. //
  1691. // #if DHT_SUPPORT
  1692. // {
  1693. // auto* sensor = new DHTSensor();
  1694. // sensor->setGPIO(DHT2_PIN);
  1695. // sensor->setType(DHT2_TYPE);
  1696. // add(sensor);
  1697. // }
  1698. // #endif
  1699. //
  1700. // Obviously, both DHT2_PIN and DHT2_TYPE should be accessible
  1701. // - use `build_src_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1702. // - update config/custom.h or config/sensor.h, adding `#define DHT2_PIN ...` and `#define DHT2_TYPE ...`
  1703. void load() {
  1704. #if AM2320_SUPPORT
  1705. {
  1706. auto* sensor = new AM2320Sensor();
  1707. sensor->setAddress(AM2320_ADDRESS);
  1708. add(sensor);
  1709. }
  1710. #endif
  1711. #if ANALOG_SUPPORT
  1712. {
  1713. auto* sensor = new AnalogSensor();
  1714. sensor->setSamples(ANALOG_SAMPLES);
  1715. sensor->setDelay(ANALOG_DELAY);
  1716. sensor->setFactor(ANALOG_FACTOR);
  1717. sensor->setOffset(ANALOG_OFFSET);
  1718. add(sensor);
  1719. }
  1720. #endif
  1721. #if BH1750_SUPPORT
  1722. {
  1723. auto* sensor = new BH1750Sensor();
  1724. sensor->setAddress(BH1750_ADDRESS);
  1725. sensor->setAccuracy(BH1750_ACCURACY);
  1726. sensor->setSensitivity(BH1750_SENSITIVITY);
  1727. sensor->setMode(BH1750_MODE);
  1728. add(sensor);
  1729. }
  1730. #endif
  1731. #if BMP180_SUPPORT
  1732. {
  1733. auto* sensor = new BMP180Sensor();
  1734. sensor->setAddress(BMP180_ADDRESS);
  1735. add(sensor);
  1736. }
  1737. #endif
  1738. #if BMX280_SUPPORT
  1739. {
  1740. // TODO: bmx280AddressN, do some migrate code based on number?
  1741. // Support up to two sensors with full auto-discovery.
  1742. const auto number = std::clamp(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1743. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1744. // otherwise choose the other unnamed sensor address
  1745. static constexpr uint8_t Address { BMX280_ADDRESS };
  1746. const decltype(Address) first = getSetting("bmx280Address", Address);
  1747. const decltype(Address) second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1748. const decltype(Address) address_map[2] { first, second };
  1749. for (unsigned char n=0; n < number; ++n) {
  1750. auto* sensor = new BMX280Sensor();
  1751. sensor->setAddress(address_map[n]);
  1752. add(sensor);
  1753. }
  1754. }
  1755. #endif
  1756. #if BME680_SUPPORT
  1757. {
  1758. auto* sensor = new BME680Sensor();
  1759. sensor->setAddress(BME680_I2C_ADDRESS);
  1760. add(sensor);
  1761. }
  1762. #endif
  1763. #if CSE7766_SUPPORT
  1764. {
  1765. const auto port = uartPort(CSE7766_PORT - 1);
  1766. if (!port) {
  1767. return;
  1768. }
  1769. auto* sensor = new CSE7766Sensor();
  1770. sensor->setPort(port->stream);
  1771. add(sensor);
  1772. }
  1773. #endif
  1774. #if DALLAS_SUPPORT
  1775. {
  1776. auto* sensor = new DallasSensor();
  1777. sensor->setGPIO(DALLAS_PIN);
  1778. add(sensor);
  1779. }
  1780. #endif
  1781. #if DHT_SUPPORT
  1782. {
  1783. auto* sensor = new DHTSensor();
  1784. sensor->setGPIO(DHT_PIN);
  1785. sensor->setType(DHT_TYPE);
  1786. add(sensor);
  1787. }
  1788. #endif
  1789. #if DIGITAL_SUPPORT
  1790. {
  1791. const auto pins = gpioPins();
  1792. for (size_t index = 0; index < pins; ++index) {
  1793. const auto pin = DigitalSensor::defaultPin(index);
  1794. if (pin == GPIO_NONE) {
  1795. break;
  1796. }
  1797. auto* sensor = new DigitalSensor();
  1798. sensor->setPin(pin);
  1799. sensor->setPinMode(DigitalSensor::defaultPinMode(index));
  1800. sensor->setDefault(DigitalSensor::defaultState(index));
  1801. add(sensor);
  1802. }
  1803. }
  1804. #endif
  1805. #if DUMMY_SENSOR_SUPPORT
  1806. {
  1807. add(new DummySensor());
  1808. }
  1809. #endif
  1810. #if ECH1560_SUPPORT
  1811. {
  1812. auto* sensor = new ECH1560Sensor();
  1813. sensor->setCLK(ECH1560_CLK_PIN);
  1814. sensor->setMISO(ECH1560_MISO_PIN);
  1815. sensor->setInverted(ECH1560_INVERTED);
  1816. add(sensor);
  1817. }
  1818. #endif
  1819. #if EMON_ADC121_SUPPORT
  1820. {
  1821. auto* sensor = new EmonADC121Sensor();
  1822. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1823. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1824. sensor->setReferenceVoltage(EMON_REFERENCE_VOLTAGE);
  1825. add(sensor);
  1826. }
  1827. #endif
  1828. #if EMON_ADS1X15_SUPPORT
  1829. {
  1830. auto port = std::make_shared<EmonADS1X15Sensor::I2CPort>(
  1831. EMON_ADS1X15_I2C_ADDRESS, EMON_ADS1X15_TYPE, EMON_ADS1X15_GAIN, EMON_ADS1X15_DATARATE);
  1832. constexpr unsigned char FirstBit { 1 };
  1833. unsigned char mask { EMON_ADS1X15_MASK };
  1834. unsigned char channel { 0 };
  1835. while (mask) {
  1836. if (mask & FirstBit) {
  1837. auto* sensor = new EmonADS1X15Sensor(port);
  1838. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1839. sensor->setChannel(channel);
  1840. add(sensor);
  1841. }
  1842. ++channel;
  1843. mask >>= 1;
  1844. }
  1845. }
  1846. #endif
  1847. #if EMON_ANALOG_SUPPORT
  1848. {
  1849. auto* sensor = new EmonAnalogSensor();
  1850. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1851. sensor->setReferenceVoltage(EMON_REFERENCE_VOLTAGE);
  1852. sensor->setResolution(EMON_ANALOG_RESOLUTION);
  1853. add(sensor);
  1854. }
  1855. #endif
  1856. #if EVENTS_SUPPORT
  1857. {
  1858. for (size_t index = 0; index < EventSensor::SensorsMax; ++index) {
  1859. const auto pin = EventSensor::defaultPin(index);
  1860. if (pin == GPIO_NONE) {
  1861. break;
  1862. }
  1863. auto* sensor = new EventSensor();
  1864. sensor->setPin(pin);
  1865. sensor->setPinMode(
  1866. EventSensor::defaultPinMode(index));
  1867. sensor->setDebounceTime(
  1868. EventSensor::defaultDebounceTime(index));
  1869. sensor->setInterruptMode(
  1870. EventSensor::defaultInterruptMode(index));
  1871. add(sensor);
  1872. }
  1873. }
  1874. #endif
  1875. #if GEIGER_SUPPORT
  1876. {
  1877. auto* sensor = new GeigerSensor();
  1878. sensor->setGPIO(GEIGER_PIN);
  1879. sensor->setMode(GEIGER_PIN_MODE);
  1880. sensor->setDebounceTime(
  1881. GeigerSensor::TimeSource::duration { GEIGER_DEBOUNCE });
  1882. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE);
  1883. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT);
  1884. add(sensor);
  1885. }
  1886. #endif
  1887. #if GUVAS12SD_SUPPORT
  1888. {
  1889. auto* sensor = new GUVAS12SDSensor();
  1890. sensor->setGPIO(GUVAS12SD_PIN);
  1891. add(sensor);
  1892. }
  1893. #endif
  1894. #if SONAR_SUPPORT
  1895. {
  1896. auto* sensor = new SonarSensor();
  1897. sensor->setEcho(SONAR_ECHO);
  1898. sensor->setIterations(SONAR_ITERATIONS);
  1899. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1900. sensor->setTrigger(SONAR_TRIGGER);
  1901. add(sensor);
  1902. }
  1903. #endif
  1904. #if HLW8012_SUPPORT
  1905. {
  1906. auto* sensor = new HLW8012Sensor();
  1907. sensor->setSEL(getSetting(F("hlw8012SEL"), HLW8012_SEL_PIN));
  1908. sensor->setCF(getSetting(F("hlw8012CF"), HLW8012_CF_PIN));
  1909. sensor->setCF1(getSetting(F("hlw8012CF1"), HLW8012_CF1_PIN));
  1910. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1911. add(sensor);
  1912. }
  1913. #endif
  1914. #if INA219_SUPPORT
  1915. {
  1916. auto* sensor = new INA219Sensor();
  1917. sensor->setAddress(INA219_ADDRESS);
  1918. sensor->setOperatingMode(INA219Sensor::INA219_OPERATING_MODE);
  1919. sensor->setShuntMode(INA219Sensor::INA219_SHUNT_MODE);
  1920. sensor->setBusMode(INA219Sensor::INA219_BUS_MODE);
  1921. sensor->setBusRange(INA219Sensor::INA219_BUS_RANGE);
  1922. sensor->setGain(INA219Sensor::INA219_GAIN);
  1923. sensor->setShuntResistance(INA219_SHUNT_RESISTANCE);
  1924. sensor->setMaxExpectedCurrent(INA219_MAX_EXPECTED_CURRENT);
  1925. add(sensor);
  1926. }
  1927. #endif
  1928. #if LDR_SUPPORT
  1929. {
  1930. auto* sensor = new LDRSensor();
  1931. sensor->setSamples(LDR_SAMPLES);
  1932. sensor->setDelay(LDR_DELAY);
  1933. sensor->setType(LDR_TYPE);
  1934. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1935. sensor->setResistor(LDR_RESISTOR);
  1936. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1937. add(sensor);
  1938. }
  1939. #endif
  1940. #if MHZ19_SUPPORT
  1941. {
  1942. const auto port = uartPort(MHZ19_PORT - 1);
  1943. if (!port) {
  1944. return;
  1945. }
  1946. auto* sensor = new MHZ19Sensor();
  1947. sensor->setPort(port->stream);
  1948. sensor->setCalibrateAuto(
  1949. getSetting("mhz19CalibrateAuto", MHZ19_CALIBRATE_AUTO == 1));
  1950. sensor->setDetectionRange(
  1951. getSetting("mhz19DetectionRange", uint32_t{ MHZ19_DETECTION_RANGE }));
  1952. add(sensor);
  1953. }
  1954. #endif
  1955. #if MICS2710_SUPPORT
  1956. {
  1957. auto* sensor = new MICS2710Sensor();
  1958. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1959. sensor->setR0(MICS2710_R0);
  1960. sensor->setRL(MICS2710_RL);
  1961. sensor->setRS(0);
  1962. add(sensor);
  1963. }
  1964. #endif
  1965. #if MICS5525_SUPPORT
  1966. {
  1967. auto* sensor = new MICS5525Sensor();
  1968. sensor->setR0(MICS5525_R0);
  1969. sensor->setRL(MICS5525_RL);
  1970. sensor->setRS(0);
  1971. add(sensor);
  1972. }
  1973. #endif
  1974. #if NTC_SUPPORT
  1975. {
  1976. auto* sensor = new NTCSensor();
  1977. sensor->setSamples(NTC_SAMPLES);
  1978. sensor->setDelay(NTC_DELAY);
  1979. sensor->setUpstreamResistor(NTC_R_UP);
  1980. sensor->setDownstreamResistor(NTC_R_DOWN);
  1981. sensor->setInputVoltage(NTC_INPUT_VOLTAGE);
  1982. sensor->setBeta(NTC_BETA);
  1983. sensor->setR0(NTC_R0);
  1984. sensor->setT0(NTC_T0);
  1985. add(sensor);
  1986. }
  1987. #endif
  1988. #if PM1006_SUPPORT
  1989. {
  1990. const auto port = uartPort(PM1006_PORT - 1);
  1991. if (!port) {
  1992. return;
  1993. }
  1994. auto* sensor = new PM1006Sensor();
  1995. sensor->setPort(port->stream);
  1996. add(sensor);
  1997. }
  1998. #endif
  1999. #if PMSX003_SUPPORT
  2000. {
  2001. const auto port = uartPort(PMS_PORT - 1);
  2002. if (!port) {
  2003. return;
  2004. }
  2005. auto* sensor = new PMSX003Sensor();
  2006. sensor->setPort(port->stream);
  2007. sensor->setType(PMS_TYPE);
  2008. add(sensor);
  2009. }
  2010. #endif
  2011. #if PULSEMETER_SUPPORT
  2012. {
  2013. auto* sensor = new PulseMeterSensor();
  2014. sensor->setPin(PULSEMETER_PIN);
  2015. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  2016. sensor->setDebounceTime(
  2017. PulseMeterSensor::TimeSource::duration{PULSEMETER_DEBOUNCE});
  2018. add(sensor);
  2019. }
  2020. #endif
  2021. #if PZEM004T_SUPPORT
  2022. {
  2023. const auto port = uartPort(PZEM004T_PORT - 1);
  2024. if (!port) {
  2025. return;
  2026. }
  2027. auto serial = std::make_shared<PZEM004TSensor::SerialPort>(port->stream);
  2028. bool initialized { false };
  2029. #if !defined(PZEM004T_ADDRESSES)
  2030. for (size_t index = 0; index < PZEM004TSensor::DevicesMax; ++index) {
  2031. auto address = getSetting({"pzemAddr", index}, PZEM004TSensor::defaultAddress(index));
  2032. if (!address.isSet()) {
  2033. break;
  2034. }
  2035. auto* ptr = PZEM004TSensor::make(serial, address);
  2036. if (ptr) {
  2037. add(ptr);
  2038. initialized = true;
  2039. }
  2040. }
  2041. #else
  2042. String addrs = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  2043. constexpr size_t BufferSize{64};
  2044. char buffer[BufferSize]{0};
  2045. if (addrs.length() < BufferSize) {
  2046. std::copy(addrs.c_str(), addrs.c_str() + addrs.length(), buffer);
  2047. buffer[addrs.length()] = '\0';
  2048. size_t device{0};
  2049. char* address{strtok(buffer, " ")};
  2050. while ((device < PZEM004TSensor::DevicesMax) && (address != nullptr)) {
  2051. auto* ptr = PZEM004TSensor::make(serial, IPAddress(address));
  2052. if (ptr) {
  2053. add(ptr);
  2054. initialized = true;
  2055. }
  2056. }
  2057. }
  2058. #endif
  2059. if (initialized) {
  2060. PZEM004TSensor::registerTerminalCommands();
  2061. }
  2062. }
  2063. #endif
  2064. #if SENSEAIR_SUPPORT
  2065. {
  2066. const auto port = uartPort(SENSEAIR_PORT - 1);
  2067. if (!port) {
  2068. return;
  2069. }
  2070. auto* sensor = new SenseAirSensor();
  2071. sensor->setPort(port->stream);
  2072. add(sensor);
  2073. }
  2074. #endif
  2075. #if SDS011_SUPPORT
  2076. {
  2077. const auto port = uartPort(SDS011_PORT - 1);
  2078. if (!port) {
  2079. return;
  2080. }
  2081. auto* sensor = new SDS011Sensor();
  2082. sensor->setPort(port->stream);
  2083. add(sensor);
  2084. }
  2085. #endif
  2086. #if SHT3X_I2C_SUPPORT
  2087. {
  2088. auto* sensor = new SHT3XI2CSensor();
  2089. sensor->setAddress(SHT3X_I2C_ADDRESS);
  2090. add(sensor);
  2091. }
  2092. #endif
  2093. #if SI7021_SUPPORT
  2094. {
  2095. auto* sensor = new SI7021Sensor();
  2096. sensor->setAddress(SI7021_ADDRESS);
  2097. add(sensor);
  2098. }
  2099. #endif
  2100. #if SM300D2_SUPPORT
  2101. {
  2102. const auto port = uartPort(SM300D2_PORT - 1);
  2103. if (!port) {
  2104. return;
  2105. }
  2106. auto* sensor = new SM300D2Sensor();
  2107. sensor->setPort(port->stream);
  2108. add(sensor);
  2109. }
  2110. #endif
  2111. #if T6613_SUPPORT
  2112. {
  2113. const auto port = uartPort(T6613_PORT - 1);
  2114. if (!port) {
  2115. return;
  2116. }
  2117. auto* sensor = new T6613Sensor();
  2118. sensor->setPort(port->stream);
  2119. add(sensor);
  2120. }
  2121. #endif
  2122. #if TMP3X_SUPPORT
  2123. {
  2124. auto* sensor = new TMP3XSensor();
  2125. sensor->setType(TMP3X_TYPE);
  2126. add(sensor);
  2127. }
  2128. #endif
  2129. #if V9261F_SUPPORT
  2130. {
  2131. const auto port = uartPort(V9261F_PORT - 1);
  2132. if (!port) {
  2133. return;
  2134. }
  2135. auto* sensor = new V9261FSensor();
  2136. sensor->setPort(port->stream);
  2137. add(sensor);
  2138. }
  2139. #endif
  2140. #if MAX6675_SUPPORT
  2141. {
  2142. auto* sensor = new MAX6675Sensor();
  2143. sensor->setCS(MAX6675_CS_PIN);
  2144. sensor->setSO(MAX6675_SO_PIN);
  2145. sensor->setSCK(MAX6675_SCK_PIN);
  2146. add(sensor);
  2147. }
  2148. #endif
  2149. #if VEML6075_SUPPORT
  2150. {
  2151. auto* sensor = new VEML6075Sensor();
  2152. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  2153. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  2154. add(sensor);
  2155. }
  2156. #endif
  2157. #if VL53L1X_SUPPORT
  2158. {
  2159. auto* sensor = new VL53L1XSensor();
  2160. sensor->setInterMeasurementPeriod(
  2161. VL53L1XSensor::InterMeasurementPeriod{VL53L1X_INTER_MEASUREMENT_PERIOD});
  2162. sensor->setMeasurementTimingBudget(
  2163. VL53L1XSensor::MeasurementTimingBudget{VL53L1X_MEASUREMENT_TIMING_BUDGET});
  2164. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  2165. add(sensor);
  2166. }
  2167. #endif
  2168. #if EZOPH_SUPPORT
  2169. {
  2170. const auto port = uartPort(EZOPH_PORT - 1);
  2171. if (!port) {
  2172. return;
  2173. }
  2174. auto* sensor = new EZOPHSensor();
  2175. sensor->setPort(port->stream);
  2176. add(sensor);
  2177. }
  2178. #endif
  2179. #if ADE7953_SUPPORT
  2180. {
  2181. auto* sensor = new ADE7953Sensor();
  2182. sensor->setAddress(ADE7953_ADDRESS);
  2183. add(sensor);
  2184. }
  2185. #endif
  2186. #if SI1145_SUPPORT
  2187. {
  2188. auto* sensor = new SI1145Sensor();
  2189. sensor->setAddress(SI1145_ADDRESS);
  2190. add(sensor);
  2191. }
  2192. #endif
  2193. #if HDC1080_SUPPORT
  2194. {
  2195. auto* sensor = new HDC1080Sensor();
  2196. sensor->setAddress(HDC1080_ADDRESS);
  2197. add(sensor);
  2198. }
  2199. #endif
  2200. #if PZEM004TV30_SUPPORT
  2201. {
  2202. const auto port = uartPort(PZEM004TV30_PORT - 1);
  2203. if (!port) {
  2204. return;
  2205. }
  2206. auto* sensor = PZEM004TV30Sensor::make(port->stream,
  2207. getSetting("pzemv30Addr", PZEM004TV30Sensor::DefaultAddress),
  2208. getSetting("pzemv30ReadTimeout", PZEM004TV30Sensor::DefaultReadTimeout));
  2209. sensor->setDebug(
  2210. getSetting("pzemv30Debug", PZEM004TV30Sensor::DefaultDebug));
  2211. add(sensor);
  2212. }
  2213. #endif
  2214. }
  2215. namespace units {
  2216. namespace {
  2217. struct Range {
  2218. Range() = default;
  2219. template <size_t Size>
  2220. explicit Range(const Unit (&units)[Size]) :
  2221. _begin(std::begin(units)),
  2222. _end(std::end(units))
  2223. {}
  2224. template <size_t Size>
  2225. Range& operator=(const Unit (&units)[Size]) {
  2226. _begin = std::begin(units);
  2227. _end = std::end(units);
  2228. return *this;
  2229. }
  2230. const Unit* begin() const {
  2231. return _begin;
  2232. }
  2233. const Unit* end() const {
  2234. return _end;
  2235. }
  2236. private:
  2237. const Unit* _begin { nullptr };
  2238. const Unit* _end { nullptr };
  2239. };
  2240. Range range(unsigned char type) {
  2241. #define MAGNITUDE_UNITS_RANGE(...)\
  2242. static const Unit units[] PROGMEM {\
  2243. __VA_ARGS__\
  2244. };\
  2245. \
  2246. out = units
  2247. Range out;
  2248. switch (type) {
  2249. case MAGNITUDE_TEMPERATURE: {
  2250. MAGNITUDE_UNITS_RANGE(
  2251. Unit::Celcius,
  2252. Unit::Farenheit,
  2253. Unit::Kelvin
  2254. );
  2255. break;
  2256. }
  2257. case MAGNITUDE_HUMIDITY:
  2258. case MAGNITUDE_POWER_FACTOR: {
  2259. MAGNITUDE_UNITS_RANGE(
  2260. Unit::Percentage
  2261. );
  2262. break;
  2263. }
  2264. case MAGNITUDE_PRESSURE: {
  2265. MAGNITUDE_UNITS_RANGE(
  2266. Unit::Hectopascal
  2267. );
  2268. break;
  2269. }
  2270. case MAGNITUDE_CURRENT: {
  2271. MAGNITUDE_UNITS_RANGE(
  2272. Unit::Ampere
  2273. );
  2274. break;
  2275. }
  2276. case MAGNITUDE_VOLTAGE: {
  2277. MAGNITUDE_UNITS_RANGE(
  2278. Unit::Volt
  2279. );
  2280. break;
  2281. }
  2282. case MAGNITUDE_POWER_ACTIVE: {
  2283. MAGNITUDE_UNITS_RANGE(
  2284. Unit::Watt,
  2285. Unit::Kilowatt
  2286. );
  2287. break;
  2288. }
  2289. case MAGNITUDE_POWER_APPARENT: {
  2290. MAGNITUDE_UNITS_RANGE(
  2291. Unit::Voltampere,
  2292. Unit::Kilovoltampere
  2293. );
  2294. break;
  2295. }
  2296. case MAGNITUDE_POWER_REACTIVE: {
  2297. MAGNITUDE_UNITS_RANGE(
  2298. Unit::VoltampereReactive,
  2299. Unit::KilovoltampereReactive
  2300. );
  2301. break;
  2302. }
  2303. case MAGNITUDE_ENERGY_DELTA: {
  2304. MAGNITUDE_UNITS_RANGE(
  2305. Unit::Joule
  2306. );
  2307. break;
  2308. }
  2309. case MAGNITUDE_ENERGY: {
  2310. MAGNITUDE_UNITS_RANGE(
  2311. Unit::Joule,
  2312. Unit::KilowattHour
  2313. );
  2314. break;
  2315. }
  2316. case MAGNITUDE_PM1DOT0:
  2317. case MAGNITUDE_PM2DOT5:
  2318. case MAGNITUDE_PM10:
  2319. case MAGNITUDE_TVOC:
  2320. case MAGNITUDE_CH2O: {
  2321. MAGNITUDE_UNITS_RANGE(
  2322. Unit::MicrogrammPerCubicMeter,
  2323. Unit::MilligrammPerCubicMeter
  2324. );
  2325. break;
  2326. }
  2327. case MAGNITUDE_CO:
  2328. case MAGNITUDE_CO2:
  2329. case MAGNITUDE_NO2:
  2330. case MAGNITUDE_VOC: {
  2331. MAGNITUDE_UNITS_RANGE(
  2332. Unit::PartsPerMillion
  2333. );
  2334. break;
  2335. }
  2336. case MAGNITUDE_LUX: {
  2337. MAGNITUDE_UNITS_RANGE(
  2338. Unit::Lux
  2339. );
  2340. break;
  2341. }
  2342. case MAGNITUDE_RESISTANCE: {
  2343. MAGNITUDE_UNITS_RANGE(
  2344. Unit::Ohm
  2345. );
  2346. break;
  2347. }
  2348. case MAGNITUDE_HCHO: {
  2349. MAGNITUDE_UNITS_RANGE(
  2350. Unit::MilligrammPerCubicMeter
  2351. );
  2352. break;
  2353. }
  2354. case MAGNITUDE_GEIGER_CPM: {
  2355. MAGNITUDE_UNITS_RANGE(
  2356. Unit::CountsPerMinute
  2357. );
  2358. break;
  2359. }
  2360. case MAGNITUDE_GEIGER_SIEVERT: {
  2361. MAGNITUDE_UNITS_RANGE(
  2362. Unit::MicrosievertPerHour
  2363. );
  2364. break;
  2365. }
  2366. case MAGNITUDE_DISTANCE: {
  2367. MAGNITUDE_UNITS_RANGE(
  2368. Unit::Meter
  2369. );
  2370. break;
  2371. }
  2372. case MAGNITUDE_FREQUENCY: {
  2373. MAGNITUDE_UNITS_RANGE(
  2374. Unit::Hertz
  2375. );
  2376. break;
  2377. }
  2378. case MAGNITUDE_PH: {
  2379. MAGNITUDE_UNITS_RANGE(
  2380. Unit::Ph
  2381. );
  2382. break;
  2383. }
  2384. }
  2385. #undef MAGNITUDE_UNITS_RANGE
  2386. return out;
  2387. }
  2388. bool supported(const Magnitude& magnitude, Unit unit) {
  2389. const auto range = units::range(magnitude.type);
  2390. return std::any_of(range.begin(), range.end(), [&](sensor::Unit supported) {
  2391. return (unit == supported);
  2392. });
  2393. }
  2394. sensor::Unit filter(const Magnitude& magnitude, Unit unit) {
  2395. return supported(magnitude, unit) ? unit : magnitude.units;
  2396. }
  2397. String name(Unit unit) {
  2398. return espurna::settings::internal::serialize(unit);
  2399. }
  2400. String name(const Magnitude& magnitude) {
  2401. return name(magnitude.units);
  2402. }
  2403. } // namespace
  2404. } // namespace units
  2405. // -----------------------------------------------------------------------------
  2406. // Energy persistence
  2407. // -----------------------------------------------------------------------------
  2408. namespace energy {
  2409. namespace {
  2410. struct Persist {
  2411. Persist(size_t index, Energy energy) :
  2412. _index(index),
  2413. _energy(energy)
  2414. {}
  2415. void operator()() const {
  2416. setSetting({F("eneTotal"), _index}, _energy.asString());
  2417. #if NTP_SUPPORT
  2418. if (ntpSynced()) {
  2419. setSetting({F("eneTime"), _index}, ntpDateTime());
  2420. }
  2421. #endif
  2422. }
  2423. private:
  2424. size_t _index;
  2425. Energy _energy;
  2426. };
  2427. struct Tracker {
  2428. using Reference = std::reference_wrapper<const Magnitude>;
  2429. struct Counter {
  2430. Reference magnitude;
  2431. int value;
  2432. };
  2433. using Counters = std::vector<Counter>;
  2434. explicit operator bool() const {
  2435. return _every > 0;
  2436. }
  2437. int every() const {
  2438. return _every;
  2439. }
  2440. void add(Reference magnitude) {
  2441. _count.push_back(Counter{
  2442. .magnitude = magnitude,
  2443. .value = 0
  2444. });
  2445. }
  2446. size_t size() const {
  2447. return _count.size();
  2448. }
  2449. int count(size_t index) const {
  2450. return _count[index].value;
  2451. }
  2452. template <typename Callback>
  2453. void tick(unsigned char index, Callback&& callback) {
  2454. _count[index].value = (_count[index].value + 1) % _every;
  2455. if (_count[index].value == 0) {
  2456. callback();
  2457. }
  2458. }
  2459. void every(int every) {
  2460. _every = every;
  2461. for (auto& count : _count) {
  2462. count.value = 0;
  2463. }
  2464. }
  2465. private:
  2466. Counters _count;
  2467. int _every;
  2468. };
  2469. struct ParseResult {
  2470. ParseResult() = default;
  2471. ParseResult& operator=(sensor::Energy value) {
  2472. _value = value;
  2473. _result = true;
  2474. return *this;
  2475. }
  2476. explicit operator bool() const {
  2477. return _result;
  2478. }
  2479. Energy value() const {
  2480. return _value;
  2481. }
  2482. private:
  2483. bool _result { false };
  2484. Energy _value;
  2485. };
  2486. namespace internal {
  2487. Tracker tracker;
  2488. } // namespace internal
  2489. Energy get_rtcmem(unsigned char index) {
  2490. return Energy {
  2491. Energy::Pair {
  2492. .kwh = KilowattHours(Rtcmem->energy[index].kwh),
  2493. .ws = WattSeconds(Rtcmem->energy[index].ws),
  2494. }};
  2495. }
  2496. void set_rtcmem(unsigned char index, const Energy& source) {
  2497. const auto pair = source.pair();
  2498. Rtcmem->energy[index].kwh = pair.kwh.value;
  2499. Rtcmem->energy[index].ws = pair.ws.value;
  2500. }
  2501. ParseResult convert(StringView value) {
  2502. ParseResult out;
  2503. if (!value.length()) {
  2504. return out;
  2505. }
  2506. const auto begin = value.begin();
  2507. const auto end = value.end();
  2508. String kwh_number;
  2509. auto it = begin;
  2510. while (it != end) {
  2511. if (*it == '+') {
  2512. break;
  2513. }
  2514. kwh_number += *it;
  2515. ++it;
  2516. }
  2517. KilowattHours::Type kwh { 0 };
  2518. WattSeconds::Type ws { 0 };
  2519. const auto result = parseUnsigned(kwh_number, 10);
  2520. if (!result.ok) {
  2521. return out;
  2522. }
  2523. kwh = result.value;
  2524. if ((it != end) && (*it == '+')) {
  2525. ++it;
  2526. if (it == end) {
  2527. return out;
  2528. }
  2529. const auto result = parseUnsigned(
  2530. StringView(it, end), 10);
  2531. if (!result.ok) {
  2532. return out;
  2533. }
  2534. ws = result.value;
  2535. }
  2536. out = Energy {
  2537. Energy::Pair {
  2538. .kwh = KilowattHours(kwh),
  2539. .ws = WattSeconds(ws),
  2540. }};
  2541. return out;
  2542. }
  2543. Energy get_settings(unsigned char index) {
  2544. using namespace settings;
  2545. const auto current = getSetting(
  2546. keys::get(prefix::get(MAGNITUDE_ENERGY), suffix::Total, index));
  2547. return convert(current).value();
  2548. }
  2549. void set(const Magnitude& magnitude, const Energy& energy) {
  2550. if (isEmon(magnitude.sensor)) {
  2551. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor.get());
  2552. sensor->resetEnergy(magnitude.slot, energy);
  2553. }
  2554. }
  2555. void set(const Magnitude& magnitude, StringView payload) {
  2556. if (!payload.length()) {
  2557. return;
  2558. }
  2559. auto energy = convert(payload);
  2560. if (!energy) {
  2561. return;
  2562. }
  2563. set(magnitude, energy.value());
  2564. }
  2565. Energy get(unsigned char index) {
  2566. Energy result;
  2567. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  2568. result = get_rtcmem(index);
  2569. } else {
  2570. result = get_settings(index);
  2571. }
  2572. return result;
  2573. }
  2574. void reset(unsigned char index) {
  2575. delSetting({F("eneTotal"), index});
  2576. delSetting({F("eneTime"), index});
  2577. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  2578. Rtcmem->energy[index].kwh = 0;
  2579. Rtcmem->energy[index].ws = 0;
  2580. }
  2581. }
  2582. int every() {
  2583. return internal::tracker.every();
  2584. }
  2585. void every(int value) {
  2586. internal::tracker.every(value);
  2587. }
  2588. void update(const Magnitude& magnitude, bool persistent) {
  2589. if (!isEmon(magnitude.sensor)) {
  2590. return;
  2591. }
  2592. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor.get());
  2593. const auto energy = sensor->totalEnergy(magnitude.slot);
  2594. // Always save to RTCMEM
  2595. if (magnitude.index_global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  2596. set_rtcmem(magnitude.index_global, energy);
  2597. }
  2598. // Save to EEPROM every '_sensor_save_every' readings
  2599. if (persistent && internal::tracker) {
  2600. internal::tracker.tick(magnitude.index_global,
  2601. Persist{magnitude.index_global, energy});
  2602. }
  2603. }
  2604. void reset() {
  2605. for (auto type : magnitude::traits::ratio_types) {
  2606. for (size_t index = 0; index < Magnitude::counts(type); ++index) {
  2607. delSetting(settings::keys::get(settings::prefix::get(type), settings::suffix::Ratio, index));
  2608. }
  2609. }
  2610. for (auto ptr : sensor::internal::sensors) {
  2611. if (isEmon(ptr)) {
  2612. DEBUG_MSG_P(PSTR("[EMON] Resetting %s\n"), ptr->description().c_str());
  2613. static_cast<BaseEmonSensor*>(ptr.get())->resetRatios();
  2614. }
  2615. }
  2616. }
  2617. double ratioFromValue(const Magnitude& magnitude, double expected) {
  2618. if (!isEmon(magnitude.sensor)) {
  2619. return BaseEmonSensor::DefaultRatio;
  2620. }
  2621. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor.get());
  2622. return sensor->ratioFromValue(magnitude.slot, sensor->value(magnitude.slot), expected);
  2623. }
  2624. void setup(const Magnitude& magnitude) {
  2625. if (!isEmon(magnitude.sensor)) {
  2626. return;
  2627. }
  2628. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor.get());
  2629. sensor->initialEnergy(magnitude.slot, get(magnitude.index_global));
  2630. internal::tracker.add(magnitude);
  2631. DEBUG_MSG_P(PSTR("[ENERGY] Tracking %s/%u for %s\n"),
  2632. magnitude::topic(magnitude).c_str(),
  2633. magnitude.index_global,
  2634. magnitude.sensor->description().c_str());
  2635. }
  2636. } // namespace
  2637. } // namespace energy
  2638. namespace settings {
  2639. namespace query {
  2640. namespace {
  2641. namespace getter {
  2642. struct Type {
  2643. using Check = bool(*)(unsigned char);
  2644. using Get = String(*)(const Magnitude&);
  2645. StringView suffix;
  2646. Check check;
  2647. Get get;
  2648. };
  2649. #define EXACT_VALUE(NAME)\
  2650. String NAME (const Magnitude& magnitude) {\
  2651. return espurna::settings::internal::serialize(magnitude.NAME);\
  2652. }
  2653. EXACT_VALUE(correction)
  2654. EXACT_VALUE(decimals)
  2655. EXACT_VALUE(filter_type)
  2656. String ratio(const Magnitude& magnitude) {
  2657. const auto ptr = reinterpret_cast<BaseEmonSensor*>(magnitude.sensor.get());
  2658. return String(ptr->defaultRatio(magnitude.slot));
  2659. }
  2660. EXACT_VALUE(units)
  2661. #undef EXACT_VALUE
  2662. static constexpr std::array<Type, 5> List PROGMEM {{
  2663. {suffix::Correction, magnitude::traits::correction_supported, correction},
  2664. {suffix::Filter, nullptr, filter_type},
  2665. {suffix::Precision, nullptr, decimals},
  2666. {suffix::Ratio, magnitude::traits::ratio_supported, ratio},
  2667. {suffix::Units, nullptr, units},
  2668. }};
  2669. } // namespace getter
  2670. bool check(StringView key) {
  2671. if (key.length() < 3) {
  2672. return false;
  2673. }
  2674. using espurna::settings::query::samePrefix;
  2675. if (samePrefix(key, settings::prefix::Sensor)) {
  2676. return true;
  2677. }
  2678. if (samePrefix(key, settings::prefix::Power)) {
  2679. return true;
  2680. }
  2681. return magnitude::forEachCountedCheck([&](unsigned char type) {
  2682. return samePrefix(key, prefix::get(type));
  2683. });
  2684. }
  2685. String get(StringView key) {
  2686. String out;
  2687. for (auto& magnitude : magnitude::internal::magnitudes) {
  2688. for (const auto& type : getter::List) {
  2689. if (type.check && !type.check(magnitude.type)) {
  2690. continue;
  2691. }
  2692. const auto expected = keys::get(magnitude, type.suffix);
  2693. if (key == expected.value()) {
  2694. out = type.get(magnitude);
  2695. goto out;
  2696. }
  2697. }
  2698. }
  2699. out:
  2700. return out;
  2701. }
  2702. void setup() {
  2703. settingsRegisterQueryHandler({
  2704. .check = check,
  2705. .get = get,
  2706. });
  2707. }
  2708. } // namespace
  2709. } // namespace query
  2710. void migrate(int version) {
  2711. auto firstKey = [](unsigned char type, StringView suffix) {
  2712. return keys::get(prefix::get(type), suffix, 0).value();
  2713. };
  2714. // Some keys from older versions were longer
  2715. if (version < 3) {
  2716. moveSetting(F("powerUnits"), F("pwrUnits"));
  2717. moveSetting(F("energyUnits"), F("eneUnits"));
  2718. }
  2719. // Energy is now indexed (based on magnitude.index_global)
  2720. // Also update PZEM004T energy total across multiple devices
  2721. if (version < 5) {
  2722. moveSetting(F("eneTotal"), firstKey(MAGNITUDE_ENERGY, suffix::Total));
  2723. moveSettings(F("pzEneTotal"), prefix::get(MAGNITUDE_ENERGY).toString() + StringView(suffix::Total));
  2724. }
  2725. // Unit ID is no longer shared, drop when equal to Min_ or None
  2726. if (version < 5) {
  2727. delSetting(F("pwrUnits"));
  2728. delSetting(F("eneUnits"));
  2729. delSetting(F("tmpUnits"));
  2730. }
  2731. // Generic pwr settings now have type-specific prefixes
  2732. // (index 0, assuming there's only one emon sensor)
  2733. if (version < 7) {
  2734. moveSetting(F("pwrVoltage"), firstKey(MAGNITUDE_VOLTAGE, suffix::Mains));
  2735. moveSetting(F("pwrRatioC"), firstKey(MAGNITUDE_CURRENT, suffix::Ratio));
  2736. moveSetting(F("pwrRatioV"), firstKey(MAGNITUDE_VOLTAGE, suffix::Ratio));
  2737. moveSetting(F("pwrRatioP"), firstKey(MAGNITUDE_POWER_ACTIVE, suffix::Ratio));
  2738. moveSetting(F("pwrRatioE"), firstKey(MAGNITUDE_ENERGY, suffix::Ratio));
  2739. }
  2740. #if HLW8012_SUPPORT
  2741. if (version < 9) {
  2742. moveSetting(F("snsHlw8012SelGPIO"), F("hlw8012SEL"));
  2743. moveSetting(F("snsHlw8012CfGPIO"), F("hlw8012CF"));
  2744. moveSetting(F("snsHlw8012Cf1GPIO"), F("hlw8012CF1"));
  2745. }
  2746. #endif
  2747. if (version < 11) {
  2748. moveSetting(F("apiRealTime"), FPSTR(keys::RealTimeValues));
  2749. moveSetting(F("tmpMinDelta"), firstKey(MAGNITUDE_TEMPERATURE, suffix::MinDelta));
  2750. moveSetting(F("humMinDelta"), firstKey(MAGNITUDE_HUMIDITY, suffix::MinDelta));
  2751. moveSetting(F("eneMaxDelta"), firstKey(MAGNITUDE_ENERGY, suffix::MaxDelta));
  2752. }
  2753. }
  2754. } // namespace settings
  2755. // -----------------------------------------------------------------------------
  2756. // WebUI value display and actions
  2757. // -----------------------------------------------------------------------------
  2758. #if WEB_SUPPORT
  2759. namespace web {
  2760. namespace {
  2761. bool onKeyCheck(StringView key, const JsonVariant&) {
  2762. return settings::query::check(key);
  2763. }
  2764. // Entries related to things reported by the module.
  2765. // - types of magnitudes that are available and the string values associated with them
  2766. // - error types and stringified versions of them
  2767. // - units are the value types of the magnitude
  2768. // TODO: magnitude types have some common keys and some specific ones, only implemented for the type
  2769. // e.g. voltMains is specific to the MAGNITUDE_VOLTAGE but *only* in analog mode, or eneRatio specific to MAGNITUDE_ENERGY
  2770. // but, notice that the sensor will probably be used to 'get' certain properties, to generate certain keys list
  2771. void types(JsonObject& root) {
  2772. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("types")};
  2773. payload(STRING_VIEW("values"), {MAGNITUDE_NONE + 1, MAGNITUDE_MAX},
  2774. [](size_t type) {
  2775. return Magnitude::counts(type) > 0;
  2776. },
  2777. {{STRING_VIEW("type"), [](JsonArray& out, size_t index) {
  2778. out.add(index);
  2779. }},
  2780. {STRING_VIEW("prefix"), [](JsonArray& out, size_t index) {
  2781. out.add(FPSTR(settings::prefix::get(index).c_str()));
  2782. }},
  2783. {STRING_VIEW("name"), [](JsonArray& out, size_t index) {
  2784. out.add(sensor::magnitude::name(index));
  2785. }}
  2786. });
  2787. }
  2788. void errors(JsonObject& root) {
  2789. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("errors")};
  2790. payload(STRING_VIEW("values"), SENSOR_ERROR_MAX,
  2791. {{STRING_VIEW("type"), [](JsonArray& out, size_t index) {
  2792. out.add(index);
  2793. }},
  2794. {STRING_VIEW("name"), [](JsonArray& out, size_t index) {
  2795. out.add(error(index));
  2796. }}
  2797. });
  2798. }
  2799. void units(JsonObject& root) {
  2800. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("units")};
  2801. payload(STRING_VIEW("values"), magnitude::internal::magnitudes.size(),
  2802. {{STRING_VIEW("supported"), [](JsonArray& out, size_t index) {
  2803. JsonArray& units = out.createNestedArray();
  2804. const auto range = units::range(magnitude::get(index).type);
  2805. for (auto it = range.begin(); it != range.end(); ++it) {
  2806. JsonArray& unit = units.createNestedArray();
  2807. unit.add(static_cast<int>(*it)); // raw id
  2808. unit.add(units::name(*it)); // as string
  2809. }
  2810. }}
  2811. });
  2812. }
  2813. void initial(JsonObject& root) {
  2814. if (!magnitude::count()) {
  2815. return;
  2816. }
  2817. JsonObject& container = root.createNestedObject(F("magnitudes-init"));
  2818. types(container);
  2819. errors(container);
  2820. units(container);
  2821. }
  2822. void list(JsonObject& root) {
  2823. if (!magnitude::count()) {
  2824. return;
  2825. }
  2826. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("magnitudes-list")};
  2827. payload(STRING_VIEW("values"), magnitude::count(),
  2828. {{STRING_VIEW("index_global"), [](JsonArray& out, size_t index) {
  2829. out.add(magnitude::get(index).index_global);
  2830. }},
  2831. {STRING_VIEW("type"), [](JsonArray& out, size_t index) {
  2832. out.add(magnitude::get(index).type);
  2833. }},
  2834. {STRING_VIEW("description"), [](JsonArray& out, size_t index) {
  2835. out.add(magnitude::description(magnitude::get(index)));
  2836. }},
  2837. {STRING_VIEW("units"), [](JsonArray& out, size_t index) {
  2838. out.add(static_cast<int>(magnitude::get(index).units));
  2839. }}
  2840. });
  2841. }
  2842. void settings(JsonObject& root) {
  2843. if (!magnitude::count()) {
  2844. return;
  2845. }
  2846. // XXX: inject 'null' in the output. need this for optional fields, since the current
  2847. // version of serializer only does this for char ptr and even makes NaN serialized as
  2848. // NaN, instead of more commonly used null (but, expect this to be fixed after switching to v6+)
  2849. static const char* const NullSymbol { nullptr };
  2850. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("magnitudes-settings")};
  2851. payload(STRING_VIEW("values"), magnitude::count(),
  2852. {{settings::suffix::Correction, [](JsonArray& out, size_t index) {
  2853. const auto& magnitude = magnitude::get(index);
  2854. if (magnitude::traits::correction_supported(magnitude.type)) {
  2855. out.add(magnitude.correction);
  2856. } else {
  2857. out.add(NullSymbol);
  2858. }
  2859. }},
  2860. {settings::suffix::Ratio, [](JsonArray& out, size_t index) {
  2861. const auto& magnitude = magnitude::get(index);
  2862. if (magnitude::traits::ratio_supported(magnitude.type)) {
  2863. out.add(static_cast<BaseEmonSensor*>(magnitude.sensor.get())->getRatio(magnitude.slot));
  2864. } else {
  2865. out.add(NullSymbol);
  2866. }
  2867. }},
  2868. {settings::suffix::ZeroThreshold, [](JsonArray& out, size_t index) {
  2869. const auto threshold = magnitude::get(index).zero_threshold;
  2870. if (!std::isnan(threshold)) {
  2871. out.add(threshold);
  2872. } else {
  2873. out.add(NullSymbol);
  2874. }
  2875. }},
  2876. {settings::suffix::MinDelta, [](JsonArray& out, size_t index) {
  2877. out.add(magnitude::get(index).min_delta);
  2878. }},
  2879. {settings::suffix::MaxDelta, [](JsonArray& out, size_t index) {
  2880. out.add(magnitude::get(index).max_delta);
  2881. }}
  2882. });
  2883. root[FPSTR(settings::keys::RealTimeValues)] = realTimeValues();
  2884. root[FPSTR(settings::keys::ReadInterval)] = readInterval().count();
  2885. root[FPSTR(settings::keys::InitInterval)] = initInterval().count();
  2886. root[FPSTR(settings::keys::ReportEvery)] = reportEvery();
  2887. root[FPSTR(settings::keys::SaveEvery)] = energy::internal::tracker.every();
  2888. }
  2889. void energy(JsonObject& root) {
  2890. #if NTP_SUPPORT
  2891. if (!energy::internal::tracker || !energy::internal::tracker.size()) {
  2892. return;
  2893. }
  2894. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("energy")};
  2895. payload(STRING_VIEW("values"), espurna::settings::Iota(magnitude::count()),
  2896. [](size_t index) {
  2897. return magnitude::get(index).type == MAGNITUDE_ENERGY;
  2898. },
  2899. {{STRING_VIEW("id"), [](JsonArray& out, size_t index) {
  2900. out.add(index);
  2901. }},
  2902. {STRING_VIEW("saved"), [](JsonArray& out, size_t index) {
  2903. if (energy::internal::tracker) {
  2904. out.add(getSetting({F("eneTime"), magnitude::get(index).index_global}, F("(unknown)")));
  2905. } else {
  2906. out.add("");
  2907. }
  2908. }}
  2909. });
  2910. #endif
  2911. }
  2912. void magnitudes(JsonObject& root) {
  2913. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("magnitudes")};
  2914. payload(STRING_VIEW("values"), magnitude::count(), {
  2915. {STRING_VIEW("value"), [](JsonArray& out, size_t index) {
  2916. const auto& magnitude = magnitude::get(index);
  2917. out.add(magnitude::format(magnitude,
  2918. magnitude::process(magnitude, magnitude.last)));
  2919. }},
  2920. {STRING_VIEW("units"), [](JsonArray& out, size_t index) {
  2921. out.add(static_cast<int>(magnitude::get(index).units));
  2922. }},
  2923. {STRING_VIEW("error"), [](JsonArray& out, size_t index) {
  2924. out.add(magnitude::get(index).sensor->error());
  2925. }},
  2926. });
  2927. }
  2928. void onData(JsonObject& root) {
  2929. if (magnitude::count()) {
  2930. magnitudes(root);
  2931. energy(root);
  2932. }
  2933. }
  2934. void onAction(uint32_t client_id, const char* action, JsonObject& data) {
  2935. if (STRING_VIEW("emon-expected") == action) {
  2936. auto id = data["id"].as<size_t>();
  2937. if (id < magnitude::count()) {
  2938. auto expected = data["expected"].as<float>();
  2939. wsPost(client_id, [id, expected](JsonObject& root) {
  2940. const auto& magnitude = magnitude::get(id);
  2941. String key { F("result:") };
  2942. key += settings::keys::get(
  2943. magnitude, settings::suffix::Ratio).value();
  2944. root[key] = energy::ratioFromValue(magnitude, expected);
  2945. });
  2946. }
  2947. return;
  2948. }
  2949. if (STRING_VIEW("emon-reset-ratios") == action) {
  2950. energy::reset();
  2951. return;
  2952. }
  2953. }
  2954. void onVisible(JsonObject& root) {
  2955. wsPayloadModule(root, PSTR("sns"));
  2956. for (auto sensor : internal::sensors) {
  2957. if (isEmon(sensor)) {
  2958. wsPayloadModule(root, PSTR("emon"));
  2959. }
  2960. if (isAnalog(sensor)) {
  2961. wsPayloadModule(root, PSTR("analog"));
  2962. }
  2963. switch (sensor->id()) {
  2964. #if HLW8012_SUPPORT
  2965. case SENSOR_HLW8012_ID:
  2966. wsPayloadModule(root, PSTR("hlw"));
  2967. break;
  2968. #endif
  2969. #if CSE7766_SUPPORT
  2970. case SENSOR_CSE7766_ID:
  2971. wsPayloadModule(root, PSTR("cse"));
  2972. break;
  2973. #endif
  2974. #if PZEM004T_SUPPORT || PZEM004TV30_SUPPORT
  2975. case SENSOR_PZEM004T_ID:
  2976. case SENSOR_PZEM004TV30_ID:
  2977. wsPayloadModule(root, PSTR("pzem"));
  2978. break;
  2979. #endif
  2980. #if PULSEMETER_SUPPORT
  2981. case SENSOR_PULSEMETER_ID:
  2982. wsPayloadModule(root, PSTR("pm"));
  2983. break;
  2984. #endif
  2985. }
  2986. }
  2987. }
  2988. void module(JsonObject& root, const char* prefix, SensorWebSocketMagnitudesCallback callback) {
  2989. espurna::web::ws::EnumerablePayload payload{root, STRING_VIEW("magnitudes-module")};
  2990. auto& container = payload.root();
  2991. container[F("prefix")] = FPSTR(prefix);
  2992. payload(STRING_VIEW("values"), magnitude::count(),
  2993. {{STRING_VIEW("type"), [](JsonArray& out, size_t index) {
  2994. out.add(magnitude::get(index).type);
  2995. }},
  2996. {STRING_VIEW("index_global"), [](JsonArray& out, size_t index) {
  2997. out.add(magnitude::get(index).index_global);
  2998. }},
  2999. {STRING_VIEW("index_module"), callback}
  3000. });
  3001. }
  3002. void setup() {
  3003. wsRegister()
  3004. .onConnected(initial)
  3005. .onConnected(list)
  3006. .onConnected(settings)
  3007. .onVisible(onVisible)
  3008. .onData(onData)
  3009. .onAction(onAction)
  3010. .onKeyCheck(onKeyCheck);
  3011. }
  3012. } // namespace
  3013. } // namespace web
  3014. #endif
  3015. #if API_SUPPORT
  3016. namespace api {
  3017. namespace {
  3018. template <typename T>
  3019. bool tryHandle(ApiRequest& request, unsigned char type, T&& callback) {
  3020. size_t index = 0;
  3021. if (request.wildcards()) {
  3022. const auto param = request.wildcard(0);
  3023. if (!::tryParseId(param, magnitude::count(type), index)) {
  3024. return false;
  3025. }
  3026. }
  3027. const auto* magnitude = magnitude::find(type, index);
  3028. if (magnitude) {
  3029. callback(*magnitude);
  3030. return true;
  3031. }
  3032. return false;
  3033. }
  3034. void setup() {
  3035. apiRegister(F("magnitudes"),
  3036. [](ApiRequest&, JsonObject& root) {
  3037. JsonArray& magnitudes = root.createNestedArray("magnitudes");
  3038. for (auto& magnitude : magnitude::internal::magnitudes) {
  3039. JsonArray& data = magnitudes.createNestedArray();
  3040. data.add(sensor::magnitude::topicWithIndex(magnitude));
  3041. data.add(magnitude.last);
  3042. data.add(magnitude.reported);
  3043. }
  3044. return true;
  3045. },
  3046. nullptr
  3047. );
  3048. magnitude::forEachCounted([](unsigned char type) {
  3049. auto pattern = magnitude::topic(type);
  3050. if (sensor::build::useIndex() || (magnitude::count(type) > 1)) {
  3051. pattern += STRING_VIEW("/+");
  3052. }
  3053. ApiBasicHandler get = [type](ApiRequest& request) {
  3054. return tryHandle(request, type,
  3055. [&](const Magnitude& magnitude) {
  3056. request.send(magnitude::format(magnitude,
  3057. realTimeValues() ? magnitude.last : magnitude.reported));
  3058. return true;
  3059. });
  3060. };
  3061. ApiBasicHandler put;
  3062. if (type == MAGNITUDE_ENERGY) {
  3063. put = [](ApiRequest& request) {
  3064. return tryHandle(request, MAGNITUDE_ENERGY,
  3065. [&](const Magnitude& magnitude) {
  3066. energy::set(magnitude, request.param(F("value")));
  3067. });
  3068. };
  3069. }
  3070. apiRegister(std::move(pattern), std::move(get), std::move(put));
  3071. });
  3072. }
  3073. } // namespace
  3074. } // namespace api
  3075. #endif
  3076. #if MQTT_SUPPORT
  3077. namespace mqtt {
  3078. namespace {
  3079. void callback(unsigned int type, StringView topic, StringView payload) {
  3080. if (!magnitude::count(MAGNITUDE_ENERGY)) {
  3081. return;
  3082. }
  3083. static const auto base = magnitude::topic(MAGNITUDE_ENERGY);
  3084. switch (type) {
  3085. case MQTT_MESSAGE_EVENT:
  3086. {
  3087. auto t = mqttMagnitude(topic);
  3088. if (!t.startsWith(base)) {
  3089. break;
  3090. }
  3091. size_t index;
  3092. if (!tryParseIdPath(t, magnitude::count(MAGNITUDE_ENERGY), index)) {
  3093. break;
  3094. }
  3095. const auto* magnitude = magnitude::find(MAGNITUDE_ENERGY, index);
  3096. if (magnitude) {
  3097. energy::set(*magnitude, payload.toString());
  3098. }
  3099. break;
  3100. }
  3101. case MQTT_CONNECT_EVENT:
  3102. mqttSubscribe((base + F("/+")).c_str());
  3103. break;
  3104. }
  3105. }
  3106. void setup() {
  3107. ::mqttRegister(callback);
  3108. }
  3109. } // namespace
  3110. } // namespace mqtt
  3111. #endif
  3112. #if TERMINAL_SUPPORT
  3113. namespace terminal {
  3114. namespace {
  3115. namespace commands {
  3116. PROGMEM_STRING(Magnitudes, "MAGNITUDES");
  3117. void magnitudes(::terminal::CommandContext&& ctx) {
  3118. if (!magnitude::count()) {
  3119. terminalError(ctx, F("No magnitudes"));
  3120. return;
  3121. }
  3122. size_t index = 0;
  3123. for (const auto& magnitude : magnitude::internal::magnitudes) {
  3124. ctx.output.printf_P(PSTR("%2zu * %s @ %s (read:%s reported:%s units:%s)\n"),
  3125. index++, magnitude::topicWithIndex(magnitude).c_str(),
  3126. magnitude::description(magnitude).c_str(),
  3127. magnitude::format(magnitude, magnitude.last).c_str(),
  3128. magnitude::format(magnitude, magnitude.reported).c_str(),
  3129. units::name(magnitude).c_str());
  3130. }
  3131. terminalOK(ctx);
  3132. }
  3133. PROGMEM_STRING(Expected, "EXPECTED");
  3134. void expected(::terminal::CommandContext&& ctx) {
  3135. if (ctx.argv.size() == 3) {
  3136. const auto id = espurna::settings::internal::convert<size_t>(ctx.argv[1]);
  3137. if (id < magnitude::count()) {
  3138. const auto& magnitude = magnitude::get(id);
  3139. const auto result = energy::ratioFromValue(
  3140. magnitude, espurna::settings::internal::convert<double>(ctx.argv[2]));
  3141. const auto key = settings::keys::get(
  3142. magnitude, settings::suffix::Ratio);
  3143. ctx.output.printf("%s => %s\n", key.c_str(), String(result).c_str());
  3144. terminalOK(ctx);
  3145. return;
  3146. }
  3147. terminalError(ctx, F("Invalid magnitude ID"));
  3148. return;
  3149. }
  3150. terminalError(ctx, F("EXPECTED <ID> <VALUE>"));
  3151. }
  3152. PROGMEM_STRING(ResetRatios, "RESET.RATIOS");
  3153. void reset_ratios(::terminal::CommandContext&& ctx) {
  3154. energy::reset();
  3155. terminalOK(ctx);
  3156. }
  3157. PROGMEM_STRING(Energy, "ENERGY");
  3158. void energy(::terminal::CommandContext&& ctx) {
  3159. using IndexType = decltype(Magnitude::index_global);
  3160. if (ctx.argv.size() < 2) {
  3161. terminalError(ctx, F("ENERGY <ID> [<VALUE>]"));
  3162. return;
  3163. }
  3164. const auto index = espurna::settings::internal::convert<IndexType>(ctx.argv[1]);
  3165. const auto* magnitude = magnitude::find(MAGNITUDE_ENERGY, index);
  3166. if (!magnitude) {
  3167. terminalError(ctx, F("Invalid magnitude ID"));
  3168. return;
  3169. }
  3170. if (ctx.argv.size() == 2) {
  3171. ctx.output.printf_P(PSTR("%s => %s (%s)\n"),
  3172. magnitude::topicWithIndex(*magnitude).c_str(),
  3173. magnitude::format(*magnitude, magnitude->reported).c_str(),
  3174. units::name(*magnitude).c_str());
  3175. terminalOK(ctx);
  3176. return;
  3177. }
  3178. if (ctx.argv.size() == 3) {
  3179. const auto energy = energy::convert(ctx.argv[2]);
  3180. if (!energy) {
  3181. terminalError(ctx, F("Invalid energy string"));
  3182. return;
  3183. }
  3184. energy::set(*magnitude, energy.value());
  3185. }
  3186. }
  3187. static constexpr ::terminal::Command List[] PROGMEM {
  3188. {Magnitudes, commands::magnitudes},
  3189. {Expected, commands::expected},
  3190. {ResetRatios, commands::reset_ratios},
  3191. {Energy, commands::energy},
  3192. };
  3193. } // namespace commands
  3194. void setup() {
  3195. espurna::terminal::add(commands::List);
  3196. }
  3197. } // namespace
  3198. } // namespace terminal
  3199. #endif
  3200. // -----------------------------------------------------------------------------
  3201. // Sensor initialization
  3202. // -----------------------------------------------------------------------------
  3203. namespace internal {
  3204. State state;
  3205. TimeSource::time_point last_init;
  3206. TimeSource::time_point last_reading;
  3207. } // namespace internal
  3208. void suspend() {
  3209. for (auto& sensor : internal::sensors) {
  3210. sensor->suspend();
  3211. }
  3212. }
  3213. void resume() {
  3214. internal::last_init = TimeSource::now();
  3215. internal::last_reading = TimeSource::now();
  3216. internal::read_count = 1;
  3217. magnitude::forEachInstance(
  3218. [](sensor::Magnitude& instance) {
  3219. instance.filter->reset();
  3220. });
  3221. for (auto& sensor : internal::sensors) {
  3222. sensor->resume();
  3223. }
  3224. }
  3225. bool init() {
  3226. bool out { true };
  3227. for (auto sensor : internal::sensors) {
  3228. // Do not process an already initialized sensor
  3229. if (sensor->ready()) {
  3230. continue;
  3231. }
  3232. // Force sensor to reload config
  3233. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"),
  3234. sensor->description().c_str());
  3235. sensor->begin();
  3236. if (!sensor->ready()) {
  3237. const auto error = sensor->error();
  3238. if (error != SENSOR_ERROR_OK) {
  3239. DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %s (%hhu)\n"),
  3240. sensor::error(error).c_str(), error);
  3241. }
  3242. out = false;
  3243. break;
  3244. }
  3245. const auto slots = sensor->count();
  3246. for (auto slot = 0; slot < slots; ++slot) {
  3247. magnitude::add(sensor, slot, sensor->type(slot));
  3248. }
  3249. }
  3250. // Energy tracking is implemented by looking at the specific magnitude & it's index at read time
  3251. // TODO: shuffle some functions around so that debug can be in the init func instead and still be inline?
  3252. for (auto& magnitude : magnitude::internal::magnitudes) {
  3253. if (MAGNITUDE_ENERGY == magnitude.type) {
  3254. energy::setup(magnitude);
  3255. }
  3256. }
  3257. if (out) {
  3258. internal::state = State::Ready;
  3259. DEBUG_MSG_P(PSTR("[SENSOR] Finished initialization for %zu sensor(s) and %zu magnitude(s)\n"),
  3260. sensor::count(), magnitude::count());
  3261. }
  3262. return out;
  3263. }
  3264. bool try_init() {
  3265. const auto timestamp = TimeSource::now();
  3266. if (timestamp - internal::last_init > initInterval()) {
  3267. internal::last_init = timestamp;
  3268. return init();
  3269. }
  3270. return false;
  3271. }
  3272. bool ready_to_read() {
  3273. const auto timestamp = TimeSource::now();
  3274. if (timestamp - internal::last_reading > readInterval()) {
  3275. internal::last_reading = timestamp;
  3276. internal::read_count = (internal::read_count + 1) % reportEvery();
  3277. return true;
  3278. }
  3279. return false;
  3280. }
  3281. bool ready_to_report() {
  3282. return internal::read_count == 0;
  3283. }
  3284. void loop() {
  3285. // TODO: allow to do nothing
  3286. if (internal::state == State::Idle) {
  3287. return;
  3288. }
  3289. // Continiously repeat initialization if there are still some un-initialized sensors after setup()
  3290. if (internal::state == State::None) {
  3291. internal::state = State::Initial;
  3292. }
  3293. // General initialization, generate magnitudes from available sensors
  3294. if (internal::state == State::Initial) {
  3295. if (try_init()) {
  3296. internal::state = State::Ready;
  3297. }
  3298. }
  3299. // If magnitudes were initialized and we are ready, prepare to read sensor data
  3300. if (internal::state == State::Ready) {
  3301. if (magnitude::internal::magnitudes.size() != 0) {
  3302. internal::state = State::Reading;
  3303. }
  3304. }
  3305. if (internal::state != State::Reading) {
  3306. return;
  3307. }
  3308. // Tick hook, called every loop()
  3309. sensor::tick();
  3310. if (ready_to_read()) {
  3311. // Pre-read hook, called every reading
  3312. sensor::pre();
  3313. // XXX: Filter out certain magnitude types when relay is turned OFF
  3314. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  3315. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  3316. #endif
  3317. auto value = sensor::ReadValue{};
  3318. for (size_t index = 0; index < magnitude::count(); ++index) {
  3319. auto& magnitude = magnitude::get(index);
  3320. if (!magnitude.sensor->status()) {
  3321. continue;
  3322. }
  3323. // -------------------------------------------------------------
  3324. // RAW value, returned from the sensor
  3325. // -------------------------------------------------------------
  3326. value.raw = magnitude.sensor->value(magnitude.slot);
  3327. // But, completely remove spurious values if relay is OFF
  3328. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  3329. switch (magnitude.type) {
  3330. case MAGNITUDE_POWER_ACTIVE:
  3331. case MAGNITUDE_POWER_REACTIVE:
  3332. case MAGNITUDE_POWER_APPARENT:
  3333. case MAGNITUDE_POWER_FACTOR:
  3334. case MAGNITUDE_CURRENT:
  3335. case MAGNITUDE_ENERGY_DELTA:
  3336. if (relay_off) {
  3337. value.raw = 0.0;
  3338. }
  3339. break;
  3340. default:
  3341. break;
  3342. }
  3343. #endif
  3344. // We also check that value is above a certain threshold
  3345. if ((!std::isnan(magnitude.zero_threshold)) && ((value.raw < magnitude.zero_threshold))) {
  3346. value.raw = 0.0;
  3347. }
  3348. magnitude.last = value.raw;
  3349. magnitude.filter->update(value.raw);
  3350. // -------------------------------------------------------------
  3351. // Procesing (units and decimals)
  3352. // -------------------------------------------------------------
  3353. value.processed = magnitude::process(magnitude, value.raw);
  3354. magnitude::read(magnitude::value(magnitude, value.processed));
  3355. // -------------------------------------------------------------------
  3356. // Reporting
  3357. // -------------------------------------------------------------------
  3358. // Initial status or after report counter overflows
  3359. bool report { ready_to_report() };
  3360. // In case magnitude was configured with ${name}MaxDelta, override report check
  3361. // when the value change is greater than the delta
  3362. if (!std::isnan(magnitude.reported) && (magnitude.max_delta > build::DefaultMaxDelta)) {
  3363. report = std::abs(value.processed - magnitude.reported) >= magnitude.max_delta;
  3364. }
  3365. // Special case for energy, save readings to RAM and EEPROM
  3366. if (MAGNITUDE_ENERGY == magnitude.type) {
  3367. energy::update(magnitude, report);
  3368. }
  3369. if (report) {
  3370. value.filtered = magnitude::process(magnitude, magnitude.filter->value());
  3371. // Make sure that report value is calculated using every read value before it
  3372. magnitude.filter->reset();
  3373. // Check ${name}MinDelta if there is a minimum change threshold to report
  3374. if (std::isnan(magnitude.reported) || (std::abs(value.filtered - magnitude.reported) >= magnitude.min_delta)) {
  3375. const auto report = magnitude::value(magnitude, value.filtered);
  3376. magnitude::report(report);
  3377. #if THINGSPEAK_SUPPORT
  3378. tspkEnqueueMagnitude(index, report.repr);
  3379. #endif
  3380. #if DOMOTICZ_SUPPORT
  3381. domoticzSendMagnitude(index, report);
  3382. #endif
  3383. magnitude.reported = value.filtered;
  3384. }
  3385. }
  3386. #if SENSOR_DEBUG
  3387. {
  3388. auto withUnits = [&](double value, Unit units) {
  3389. String out;
  3390. out += magnitude::format(magnitude, value);
  3391. if (units != Unit::None) {
  3392. out += units::name(units);
  3393. }
  3394. return out;
  3395. };
  3396. DEBUG_MSG_P(PSTR("[SENSOR] %s -> raw %s processed %s filtered %s\n"),
  3397. magnitude::topic(magnitude).c_str(),
  3398. withUnits(value.raw, magnitude.sensor->units(magnitude.slot)).c_str(),
  3399. withUnits(value.processed, magnitude.units).c_str(),
  3400. withUnits(value.filtered, magnitude.units).c_str());
  3401. }
  3402. #endif
  3403. }
  3404. sensor::post();
  3405. #if WEB_SUPPORT
  3406. wsPost(web::onData);
  3407. #endif
  3408. }
  3409. }
  3410. void configure() {
  3411. // Read interval is shared between every sensor
  3412. // TODO: implement scheduling in the sensor itself.
  3413. // allow reads faster than 1sec, not just internal ones via tick()
  3414. // allow 'manual' sensors that may be triggered programatically
  3415. readInterval(sensor::settings::readInterval());
  3416. initInterval(sensor::settings::initInterval());
  3417. reportEvery(sensor::settings::reportEvery());
  3418. realTimeValues(sensor::settings::realTimeValues());
  3419. // TODO: something more generic? energy is an accumulating value, only allow for similar ones?
  3420. // TODO: move to an external module?
  3421. energy::every(sensor::settings::saveEvery());
  3422. // Update magnitude config, filter sizes and reset energy if needed
  3423. // TODO: namespace and various helpers need some naming tweaks...
  3424. for (auto& magnitude : magnitude::internal::magnitudes) {
  3425. // Only initialized once, notify about reset requirement?
  3426. if (!magnitude.filter) {
  3427. magnitude.filter_type = getSetting(
  3428. settings::keys::get(magnitude, settings::suffix::Filter),
  3429. magnitude::defaultFilter(magnitude));
  3430. magnitude.filter = magnitude::makeFilter(magnitude.filter_type);
  3431. }
  3432. // Some filters must be able store up to a certain amount of readings.
  3433. if (magnitude.filter->capacity() != reportEvery()) {
  3434. magnitude.filter->resize(reportEvery());
  3435. }
  3436. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  3437. if (isEmon(magnitude.sensor) && magnitude::traits::ratio_supported(magnitude.type)) {
  3438. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor.get());
  3439. sensor->setRatio(magnitude.slot, getSetting(
  3440. settings::keys::get(magnitude, settings::suffix::Ratio),
  3441. sensor->defaultRatio(magnitude.slot)));
  3442. }
  3443. // analog variant of emon sensor has some additional settings
  3444. if (isAnalogEmon(magnitude.sensor) && (magnitude.type == MAGNITUDE_VOLTAGE)) {
  3445. auto* sensor = static_cast<BaseAnalogEmonSensor*>(magnitude.sensor.get());
  3446. sensor->setVoltage(getSetting(
  3447. settings::keys::get(magnitude, settings::suffix::Mains),
  3448. sensor->defaultVoltage()));
  3449. sensor->setReferenceVoltage(getSetting(
  3450. settings::keys::get(magnitude, settings::suffix::Reference),
  3451. sensor->defaultReferenceVoltage()));
  3452. }
  3453. // adjust units based on magnitude's type
  3454. magnitude.units = units::filter(magnitude,
  3455. getSetting(
  3456. settings::keys::get(magnitude, settings::suffix::Units),
  3457. magnitude.sensor->units(magnitude.slot)));
  3458. // adjust resulting value (simple plus or minus)
  3459. // TODO: inject math or rpnlib expression?
  3460. if (magnitude::traits::correction_supported(magnitude.type)) {
  3461. magnitude.correction = getSetting(
  3462. settings::keys::get(magnitude, settings::suffix::Correction),
  3463. magnitude::build::correction(magnitude.type));
  3464. }
  3465. // pick decimal precision either from our (sane) defaults of from the sensor itself
  3466. // (specifically, when sensor has more or less precision than we expect)
  3467. {
  3468. const auto decimals = magnitude.sensor->decimals(magnitude.units);
  3469. magnitude.decimals = getSetting(
  3470. settings::keys::get(magnitude, settings::suffix::Precision),
  3471. (decimals >= 0)
  3472. ? static_cast<unsigned char>(decimals)
  3473. : magnitude::decimals(magnitude.units));
  3474. }
  3475. // Per-magnitude min & max delta settings for reporting the value
  3476. // - ${prefix}DeltaMin${index} controls whether we report when report counter overflows
  3477. // (default is set to 0.0 aka value has changed from the last recorded one)
  3478. // - ${prefix}DeltaMax${index} will trigger report as soon as read value is greater than the specified delta
  3479. // (default is 0.0 as well, but this needs to be >0 to actually do something)
  3480. magnitude.min_delta = getSetting(
  3481. settings::keys::get(magnitude, settings::suffix::MinDelta),
  3482. build::DefaultMinDelta);
  3483. magnitude.max_delta = getSetting(
  3484. settings::keys::get(magnitude, settings::suffix::MaxDelta),
  3485. build::DefaultMaxDelta);
  3486. // Sometimes we want to ensure the value is above certain threshold before reporting
  3487. magnitude.zero_threshold = getSetting(
  3488. settings::keys::get(magnitude, settings::suffix::ZeroThreshold),
  3489. Value::Unknown);
  3490. // When we don't save energy, purge existing value in both RAM & settings
  3491. if (isEmon(magnitude.sensor) && (MAGNITUDE_ENERGY == magnitude.type) && (0 == energy::every())) {
  3492. energy::reset(magnitude.index_global);
  3493. }
  3494. }
  3495. }
  3496. void setup() {
  3497. migrateVersion(settings::migrate);
  3498. sensor::load();
  3499. sensor::init();
  3500. // Configure based on settings
  3501. sensor::configure();
  3502. // Allow us to query key default
  3503. sensor::settings::query::setup();
  3504. // Websockets integration, send sensor readings and configuration
  3505. #if WEB_SUPPORT
  3506. web::setup();
  3507. #endif
  3508. // Publishes sensor reports, and {re,}set energy
  3509. #if MQTT_SUPPORT
  3510. mqtt::setup();
  3511. #endif
  3512. #if API_SUPPORT
  3513. api::setup();
  3514. #endif
  3515. #if TERMINAL_SUPPORT
  3516. terminal::setup();
  3517. #endif
  3518. systemBeforeSleep(sensor::suspend);
  3519. systemAfterSleep(sensor::resume);
  3520. espurnaRegisterLoop(sensor::loop);
  3521. espurnaRegisterReload(sensor::configure);
  3522. }
  3523. } // namespace sensor
  3524. } // namespace espurna
  3525. // -----------------------------------------------------------------------------
  3526. // Public
  3527. // -----------------------------------------------------------------------------
  3528. #if WEB_SUPPORT
  3529. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  3530. // Prefix controls the UI templates, supplied callback should retrieve module-specific value Id
  3531. void sensorWebSocketMagnitudes(JsonObject& root, const char* prefix, SensorWebSocketMagnitudesCallback callback) {
  3532. espurna::sensor::web::module(root, prefix, callback);
  3533. }
  3534. #endif // WEB_SUPPORT
  3535. void sensorOnMagnitudeRead(MagnitudeReadHandler handler) {
  3536. espurna::sensor::magnitude::onRead(handler);
  3537. }
  3538. void sensorOnMagnitudeReport(MagnitudeReadHandler handler) {
  3539. espurna::sensor::magnitude::onReport(handler);
  3540. }
  3541. size_t magnitudeCount() {
  3542. return espurna::sensor::magnitude::count();
  3543. }
  3544. unsigned char magnitudeIndex(unsigned char index) {
  3545. using namespace espurna::sensor;
  3546. if (index < magnitude::count()) {
  3547. return magnitude::get(index).index_global;
  3548. }
  3549. return 0;
  3550. }
  3551. unsigned char magnitudeType(unsigned char index) {
  3552. using namespace espurna::sensor;
  3553. if (index < magnitude::count()) {
  3554. return magnitude::get(index).type;
  3555. }
  3556. return MAGNITUDE_NONE;
  3557. }
  3558. espurna::sensor::Value magnitudeReadValue(unsigned char index) {
  3559. return espurna::sensor::magnitude::safe_value_last(index);
  3560. }
  3561. espurna::sensor::Value magnitudeReportValue(unsigned char index) {
  3562. return espurna::sensor::magnitude::safe_value_reported(index);
  3563. }
  3564. espurna::sensor::Value magnitudeValue(unsigned char index) {
  3565. return espurna::sensor::realTimeValues()
  3566. ? espurna::sensor::magnitude::safe_value_last(index)
  3567. : espurna::sensor::magnitude::safe_value_reported(index);
  3568. }
  3569. String magnitudeDescription(unsigned char index) {
  3570. using namespace espurna::sensor;
  3571. if (index < magnitude::count()) {
  3572. return magnitude::description(magnitude::get(index));
  3573. }
  3574. return String();
  3575. }
  3576. String magnitudeTopic(unsigned char index) {
  3577. using namespace espurna::sensor;
  3578. if (index < magnitude::count()) {
  3579. return magnitude::topicWithIndex(magnitude::get(index));
  3580. }
  3581. return String();
  3582. }
  3583. String magnitudeTypeTopic(unsigned char type) {
  3584. return espurna::sensor::magnitude::topic(type);
  3585. }
  3586. String magnitudeUnitsName(espurna::sensor::Unit units) {
  3587. return espurna::sensor::units::name(units);
  3588. }
  3589. espurna::sensor::Info magnitudeInfo(unsigned char index) {
  3590. using namespace espurna::sensor;
  3591. if (index < magnitude::count()) {
  3592. return magnitude::info(magnitude::get(index));
  3593. }
  3594. return Info {
  3595. .type = MAGNITUDE_NONE,
  3596. .index = 0,
  3597. .units = Unit::None,
  3598. .decimals = 0,
  3599. };
  3600. }
  3601. espurna::StringView sensorList() {
  3602. return espurna::sensor::List;
  3603. }
  3604. void sensorSetup() {
  3605. espurna::sensor::setup();
  3606. }
  3607. #endif // SENSOR_SUPPORT