Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2721 lines
80 KiB

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