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.

2729 lines
81 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. double zero_threshold; // Reset value to zero when below threshold (applied when reading)
  174. };
  175. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX] = {0};
  176. namespace sensor {
  177. // Base units
  178. // TODO: implement through a single class and allow direct access to the ::value
  179. KWh::KWh() :
  180. value(0)
  181. {}
  182. KWh::KWh(uint32_t value) :
  183. value(value)
  184. {}
  185. Ws::Ws() :
  186. value(0)
  187. {}
  188. Ws::Ws(uint32_t value) :
  189. value(value)
  190. {}
  191. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  192. Energy::Energy(KWh kwh, Ws ws) :
  193. kwh(kwh)
  194. {
  195. *this += ws;
  196. }
  197. Energy::Energy(KWh kwh) :
  198. kwh(kwh),
  199. ws()
  200. {}
  201. Energy::Energy(Ws ws) :
  202. kwh()
  203. {
  204. *this += ws;
  205. }
  206. Energy::Energy(double raw) {
  207. *this = raw;
  208. }
  209. Energy& Energy::operator =(double raw) {
  210. double _wh;
  211. kwh = modf(raw, &_wh);
  212. ws = _wh * 3600.0;
  213. return *this;
  214. }
  215. Energy& Energy::operator +=(Ws _ws) {
  216. while (_ws.value >= KwhMultiplier) {
  217. _ws.value -= KwhMultiplier;
  218. ++kwh.value;
  219. }
  220. ws.value += _ws.value;
  221. while (ws.value >= KwhMultiplier) {
  222. ws.value -= KwhMultiplier;
  223. ++kwh.value;
  224. }
  225. return *this;
  226. }
  227. Energy Energy::operator +(Ws watt_s) {
  228. Energy result(*this);
  229. result += watt_s;
  230. return result;
  231. }
  232. Energy::operator bool() {
  233. return (kwh.value > 0) && (ws.value > 0);
  234. }
  235. Ws Energy::asWs() {
  236. auto _kwh = kwh.value;
  237. while (_kwh >= KwhLimit) {
  238. _kwh -= KwhLimit;
  239. }
  240. return (_kwh * KwhMultiplier) + ws.value;
  241. }
  242. double Energy::asDouble() {
  243. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  244. }
  245. void Energy::reset() {
  246. kwh.value = 0;
  247. ws.value = 0;
  248. }
  249. } // namespace sensor
  250. // -----------------------------------------------------------------------------
  251. // Configuration
  252. // -----------------------------------------------------------------------------
  253. constexpr double _magnitudeCorrection(unsigned char type) {
  254. return (
  255. (MAGNITUDE_TEMPERATURE == type) ? (SENSOR_TEMPERATURE_CORRECTION) :
  256. (MAGNITUDE_HUMIDITY == type) ? (SENSOR_HUMIDITY_CORRECTION) :
  257. (MAGNITUDE_LUX == type) ? (SENSOR_LUX_CORRECTION) :
  258. (MAGNITUDE_PRESSURE == type) ? (SENSOR_PRESSURE_CORRECTION) :
  259. 0.0
  260. );
  261. }
  262. constexpr bool _magnitudeCanUseCorrection(unsigned char type) {
  263. return (
  264. (MAGNITUDE_TEMPERATURE == type) ? (true) :
  265. (MAGNITUDE_HUMIDITY == type) ? (true) :
  266. (MAGNITUDE_LUX == type) ? (true) :
  267. (MAGNITUDE_PRESSURE == type) ? (true) :
  268. false
  269. );
  270. }
  271. // -----------------------------------------------------------------------------
  272. // Energy persistence
  273. // -----------------------------------------------------------------------------
  274. std::vector<unsigned char> _sensor_save_count;
  275. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  276. bool _sensorIsEmon(BaseSensor* sensor) {
  277. return sensor->type() & sensor::type::Emon;
  278. }
  279. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  280. return sensor::Energy {
  281. sensor::KWh { Rtcmem->energy[index].kwh },
  282. sensor::Ws { Rtcmem->energy[index].ws }
  283. };
  284. }
  285. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  286. Rtcmem->energy[index].kwh = source.kwh.value;
  287. Rtcmem->energy[index].ws = source.ws.value;
  288. }
  289. sensor::Energy _sensorParseEnergy(const String& value) {
  290. sensor::Energy result;
  291. const bool separator = value.indexOf('+') > 0;
  292. if (value.length() && (separator > 0)) {
  293. const String before = value.substring(0, separator);
  294. const String after = value.substring(separator + 1);
  295. result.kwh = strtoul(before.c_str(), nullptr, 10);
  296. result.ws = strtoul(after.c_str(), nullptr, 10);
  297. }
  298. return result;
  299. }
  300. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  301. if (!payload || !strlen(payload)) return;
  302. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  303. auto energy = _sensorParseEnergy(payload);
  304. sensor->resetEnergy(magnitude.index_local, 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. template <typename T>
  780. String _magnitudeSettingsKey(sensor_magnitude_t& magnitude, T&& suffix) {
  781. return String(_magnitudeSettingsPrefix(magnitude.type)) + suffix;
  782. }
  783. bool _sensorMatchKeyPrefix(const char * key) {
  784. if (strncmp(key, "sns", 3) == 0) return true;
  785. if (strncmp(key, "pwr", 3) == 0) return true;
  786. return _magnitudeForEachCountedCheck([key](unsigned char type) {
  787. const char* const prefix { _magnitudeSettingsPrefix(type) };
  788. return (strncmp(prefix, key, strlen(prefix)) == 0);
  789. });
  790. }
  791. const String _sensorQueryDefault(const String& key) {
  792. auto get_defaults = [](unsigned char type, BaseSensor* ptr) -> String {
  793. if (!ptr) return String();
  794. auto* sensor = static_cast<BaseEmonSensor*>(ptr);
  795. switch (type) {
  796. case MAGNITUDE_CURRENT:
  797. return String(sensor->defaultCurrentRatio());
  798. case MAGNITUDE_VOLTAGE:
  799. return String(sensor->defaultVoltageRatio());
  800. case MAGNITUDE_POWER_ACTIVE:
  801. return String(sensor->defaultPowerRatio());
  802. case MAGNITUDE_ENERGY:
  803. return String(sensor->defaultEnergyRatio());
  804. default:
  805. return String();
  806. }
  807. };
  808. auto magnitude_key = [](const sensor_magnitude_t& magnitude) -> settings_key_t {
  809. switch (magnitude.type) {
  810. case MAGNITUDE_CURRENT:
  811. return {"pwrRatioC", magnitude.index_global};
  812. case MAGNITUDE_VOLTAGE:
  813. return {"pwrRatioV", magnitude.index_global};
  814. case MAGNITUDE_POWER_ACTIVE:
  815. return {"pwrRatioP", magnitude.index_global};
  816. case MAGNITUDE_ENERGY:
  817. return {"pwrRatioE", magnitude.index_global};
  818. default:
  819. return {};
  820. }
  821. };
  822. unsigned char type = MAGNITUDE_NONE;
  823. BaseSensor* target = nullptr;
  824. for (auto& magnitude : _magnitudes) {
  825. switch (magnitude.type) {
  826. case MAGNITUDE_CURRENT:
  827. case MAGNITUDE_VOLTAGE:
  828. case MAGNITUDE_POWER_ACTIVE:
  829. case MAGNITUDE_ENERGY: {
  830. auto ratioKey(magnitude_key(magnitude));
  831. if (ratioKey.match(key)) {
  832. target = magnitude.sensor;
  833. type = magnitude.type;
  834. goto return_defaults;
  835. }
  836. break;
  837. }
  838. default:
  839. break;
  840. }
  841. }
  842. return_defaults:
  843. return get_defaults(type, target);
  844. }
  845. #if WEB_SUPPORT
  846. bool _sensorWebSocketOnKeyCheck(const char* key, JsonVariant&) {
  847. return _sensorMatchKeyPrefix(key);
  848. }
  849. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  850. void sensorWebSocketMagnitudes(JsonObject& root, const String& prefix) {
  851. // ws produces flat list <prefix>Magnitudes
  852. const String ws_name = prefix + "Magnitudes";
  853. // config uses <prefix>Magnitude<index> (cut 's')
  854. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  855. JsonObject& list = root.createNestedObject(ws_name);
  856. list["size"] = magnitudeCount();
  857. JsonArray& type = list.createNestedArray("type");
  858. JsonArray& index = list.createNestedArray("index");
  859. JsonArray& idx = list.createNestedArray("idx");
  860. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  861. type.add(magnitudeType(i));
  862. index.add(magnitudeIndex(i));
  863. idx.add(getSetting({conf_name, i}, 0));
  864. }
  865. }
  866. String sensorError(unsigned char error) {
  867. const __FlashStringHelper* result = nullptr;
  868. switch (error) {
  869. case SENSOR_ERROR_OK:
  870. result = F("OK");
  871. break;
  872. case SENSOR_ERROR_OUT_OF_RANGE:
  873. result = F("Out of Range");
  874. break;
  875. case SENSOR_ERROR_WARM_UP:
  876. result = F("Warming Up");
  877. break;
  878. case SENSOR_ERROR_TIMEOUT:
  879. result = F("Timeout");
  880. break;
  881. case SENSOR_ERROR_UNKNOWN_ID:
  882. result = F("Unknown ID");
  883. break;
  884. case SENSOR_ERROR_CRC:
  885. result = F("CRC / Data Error");
  886. break;
  887. case SENSOR_ERROR_I2C:
  888. result = F("I2C Error");
  889. break;
  890. case SENSOR_ERROR_GPIO_USED:
  891. result = F("GPIO Already Used");
  892. break;
  893. case SENSOR_ERROR_CALIBRATION:
  894. result = F("Calibration Error");
  895. break;
  896. default:
  897. case SENSOR_ERROR_OTHER:
  898. result = F("Other / Unknown Error");
  899. break;
  900. }
  901. return result;
  902. }
  903. String magnitudeName(unsigned char type) {
  904. const __FlashStringHelper* result = nullptr;
  905. switch (type) {
  906. case MAGNITUDE_TEMPERATURE:
  907. result = F("Temperature");
  908. break;
  909. case MAGNITUDE_HUMIDITY:
  910. result = F("Humidity");
  911. break;
  912. case MAGNITUDE_PRESSURE:
  913. result = F("Pressure");
  914. break;
  915. case MAGNITUDE_CURRENT:
  916. result = F("Current");
  917. break;
  918. case MAGNITUDE_VOLTAGE:
  919. result = F("Voltage");
  920. break;
  921. case MAGNITUDE_POWER_ACTIVE:
  922. result = F("Active Power");
  923. break;
  924. case MAGNITUDE_POWER_APPARENT:
  925. result = F("Apparent Power");
  926. break;
  927. case MAGNITUDE_POWER_REACTIVE:
  928. result = F("Reactive Power");
  929. break;
  930. case MAGNITUDE_POWER_FACTOR:
  931. result = F("Power Factor");
  932. break;
  933. case MAGNITUDE_ENERGY:
  934. result = F("Energy");
  935. break;
  936. case MAGNITUDE_ENERGY_DELTA:
  937. result = F("Energy (delta)");
  938. break;
  939. case MAGNITUDE_ANALOG:
  940. result = F("Analog");
  941. break;
  942. case MAGNITUDE_DIGITAL:
  943. result = F("Digital");
  944. break;
  945. case MAGNITUDE_EVENT:
  946. result = F("Event");
  947. break;
  948. case MAGNITUDE_PM1dot0:
  949. result = F("PM1.0");
  950. break;
  951. case MAGNITUDE_PM2dot5:
  952. result = F("PM2.5");
  953. break;
  954. case MAGNITUDE_PM10:
  955. result = F("PM10");
  956. break;
  957. case MAGNITUDE_CO2:
  958. result = F("CO2");
  959. break;
  960. case MAGNITUDE_LUX:
  961. result = F("Lux");
  962. break;
  963. case MAGNITUDE_UVA:
  964. result = F("UVA");
  965. break;
  966. case MAGNITUDE_UVB:
  967. result = F("UVB");
  968. break;
  969. case MAGNITUDE_UVI:
  970. result = F("UVI");
  971. break;
  972. case MAGNITUDE_DISTANCE:
  973. result = F("Distance");
  974. break;
  975. case MAGNITUDE_HCHO:
  976. result = F("HCHO");
  977. break;
  978. case MAGNITUDE_GEIGER_CPM:
  979. case MAGNITUDE_GEIGER_SIEVERT:
  980. result = F("Local Dose Rate");
  981. break;
  982. case MAGNITUDE_COUNT:
  983. result = F("Count");
  984. break;
  985. case MAGNITUDE_NO2:
  986. result = F("NO2");
  987. break;
  988. case MAGNITUDE_CO:
  989. result = F("CO");
  990. break;
  991. case MAGNITUDE_RESISTANCE:
  992. result = F("Resistance");
  993. break;
  994. case MAGNITUDE_PH:
  995. result = F("pH");
  996. break;
  997. case MAGNITUDE_NONE:
  998. default:
  999. break;
  1000. }
  1001. return String(result);
  1002. }
  1003. void _sensorWebSocketOnVisible(JsonObject& root) {
  1004. root["snsVisible"] = 1;
  1005. // prepare available magnitude types
  1006. JsonArray& magnitudes = root.createNestedArray("snsMagnitudes");
  1007. _magnitudeForEachCounted([&magnitudes](unsigned char type) {
  1008. JsonArray& tuple = magnitudes.createNestedArray();
  1009. tuple.add(type);
  1010. tuple.add(_magnitudeSettingsPrefix(type));
  1011. tuple.add(magnitudeName(type));
  1012. });
  1013. // and available error types
  1014. JsonArray& errors = root.createNestedArray("snsErrors");
  1015. _sensorForEachError([&errors](unsigned char error) {
  1016. JsonArray& tuple = errors.createNestedArray();
  1017. tuple.add(error);
  1018. tuple.add(sensorError(error));
  1019. });
  1020. }
  1021. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  1022. // retrieve per-type ...Correction settings, when available
  1023. _magnitudeForEachCounted([&root](unsigned char type) {
  1024. if (_magnitudeCanUseCorrection(type)) {
  1025. auto key = String(_magnitudeSettingsPrefix(type)) + F("Correction");
  1026. root[key] = getSetting(key, _magnitudeCorrection(type));
  1027. }
  1028. });
  1029. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  1030. uint8_t size = 0;
  1031. JsonArray& index = magnitudes.createNestedArray("index");
  1032. JsonArray& type = magnitudes.createNestedArray("type");
  1033. JsonArray& units = magnitudes.createNestedArray("units");
  1034. JsonArray& description = magnitudes.createNestedArray("description");
  1035. for (auto& magnitude : _magnitudes) {
  1036. // TODO: we don't display event for some reason?
  1037. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1038. ++size;
  1039. index.add<uint8_t>(magnitude.index_global);
  1040. type.add<uint8_t>(magnitude.type);
  1041. units.add(_magnitudeUnits(magnitude));
  1042. description.add(_magnitudeDescription(magnitude));
  1043. }
  1044. magnitudes["size"] = size;
  1045. }
  1046. void _sensorWebSocketSendData(JsonObject& root) {
  1047. char buffer[64];
  1048. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  1049. uint8_t size = 0;
  1050. JsonArray& value = magnitudes.createNestedArray("value");
  1051. JsonArray& error = magnitudes.createNestedArray("error");
  1052. #if NTP_SUPPORT
  1053. JsonArray& info = magnitudes.createNestedArray("info");
  1054. #endif
  1055. for (auto& magnitude : _magnitudes) {
  1056. if (magnitude.type == MAGNITUDE_EVENT) continue;
  1057. ++size;
  1058. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  1059. value.add(buffer);
  1060. error.add(magnitude.sensor->error());
  1061. #if NTP_SUPPORT
  1062. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  1063. String string = F("Last saved: ");
  1064. string += getSetting({"eneTime", magnitude.index_global}, F("(unknown)"));
  1065. info.add(string);
  1066. } else {
  1067. info.add((uint8_t)0);
  1068. }
  1069. #endif
  1070. }
  1071. magnitudes["size"] = size;
  1072. }
  1073. void _sensorWebSocketOnConnected(JsonObject& root) {
  1074. for (auto* sensor [[gnu::unused]] : _sensors) {
  1075. if (_sensorIsEmon(sensor)) {
  1076. root["emonVisible"] = 1;
  1077. root["pwrVisible"] = 1;
  1078. }
  1079. #if EMON_ANALOG_SUPPORT
  1080. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  1081. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  1082. }
  1083. #endif
  1084. #if HLW8012_SUPPORT
  1085. if (sensor->getID() == SENSOR_HLW8012_ID) {
  1086. root["hlwVisible"] = 1;
  1087. }
  1088. #endif
  1089. #if CSE7766_SUPPORT
  1090. if (sensor->getID() == SENSOR_CSE7766_ID) {
  1091. root["cseVisible"] = 1;
  1092. }
  1093. #endif
  1094. #if PZEM004T_SUPPORT
  1095. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  1096. root["pzemVisible"] = 1;
  1097. }
  1098. #endif
  1099. #if PULSEMETER_SUPPORT
  1100. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  1101. root["pmVisible"] = 1;
  1102. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  1103. }
  1104. #endif
  1105. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1106. switch (sensor->getID()) {
  1107. case SENSOR_MICS2710_ID:
  1108. case SENSOR_MICS5525_ID:
  1109. root["micsVisible"] = 1;
  1110. break;
  1111. default:
  1112. break;
  1113. }
  1114. #endif
  1115. }
  1116. if (magnitudeCount()) {
  1117. root["snsRead"] = _sensor_read_interval / 1000;
  1118. root["snsReport"] = _sensor_report_every;
  1119. root["snsSave"] = _sensor_save_every;
  1120. _sensorWebSocketMagnitudesConfig(root);
  1121. }
  1122. }
  1123. #endif // WEB_SUPPORT
  1124. #if API_SUPPORT
  1125. void _sensorAPISetup() {
  1126. for (auto& magnitude : _magnitudes) {
  1127. String topic = magnitudeTopic(magnitude.type);
  1128. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) topic = topic + "/" + String(magnitude.index_global);
  1129. api_get_callback_f get_cb = [&magnitude](char * buffer, size_t len) {
  1130. double value = _sensor_realtime ? magnitude.last : magnitude.reported;
  1131. dtostrf(value, 1, magnitude.decimals, buffer);
  1132. };
  1133. api_put_callback_f put_cb = nullptr;
  1134. if (magnitude.type == MAGNITUDE_ENERGY) {
  1135. put_cb = [&magnitude](const char* payload) {
  1136. _sensorApiResetEnergy(magnitude, payload);
  1137. };
  1138. }
  1139. apiRegister(topic.c_str(), get_cb, put_cb);
  1140. }
  1141. }
  1142. #endif // API_SUPPORT == 1
  1143. #if MQTT_SUPPORT
  1144. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  1145. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  1146. switch (type) {
  1147. case MQTT_MESSAGE_EVENT: {
  1148. String t = mqttMagnitude((char *) topic);
  1149. if (!t.startsWith(energy_topic)) break;
  1150. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  1151. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  1152. for (auto& magnitude : _magnitudes) {
  1153. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  1154. if (index != magnitude.index_global) continue;
  1155. _sensorApiResetEnergy(magnitude, payload);
  1156. break;
  1157. }
  1158. }
  1159. case MQTT_CONNECT_EVENT: {
  1160. for (auto& magnitude : _magnitudes) {
  1161. if (MAGNITUDE_ENERGY == magnitude.type) {
  1162. const String topic = energy_topic + "/+";
  1163. mqttSubscribe(topic.c_str());
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. case MQTT_DISCONNECT_EVENT:
  1169. default:
  1170. break;
  1171. }
  1172. }
  1173. #endif // MQTT_SUPPORT == 1
  1174. #if TERMINAL_SUPPORT
  1175. void _sensorInitCommands() {
  1176. terminalRegisterCommand(F("MAGNITUDES"), [](const terminal::CommandContext&) {
  1177. char last[64];
  1178. char reported[64];
  1179. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1180. auto& magnitude = _magnitudes.at(index);
  1181. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  1182. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  1183. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  1184. index,
  1185. magnitudeTopic(magnitude.type).c_str(),
  1186. magnitude.index_global,
  1187. _magnitudeDescription(magnitude).c_str(),
  1188. last, reported
  1189. );
  1190. }
  1191. terminalOK();
  1192. });
  1193. }
  1194. #endif // TERMINAL_SUPPORT == 1
  1195. void _sensorTick() {
  1196. for (auto* sensor : _sensors) {
  1197. sensor->tick();
  1198. }
  1199. }
  1200. void _sensorPre() {
  1201. for (auto* sensor : _sensors) {
  1202. sensor->pre();
  1203. if (!sensor->status()) {
  1204. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  1205. sensor->description().c_str(),
  1206. sensor->error()
  1207. );
  1208. }
  1209. }
  1210. }
  1211. void _sensorPost() {
  1212. for (auto* sensor : _sensors) {
  1213. sensor->post();
  1214. }
  1215. }
  1216. // -----------------------------------------------------------------------------
  1217. // Sensor initialization
  1218. // -----------------------------------------------------------------------------
  1219. void _sensorLoad() {
  1220. /*
  1221. This is temporal, in the future sensors will be initialized based on
  1222. soft configuration (data stored in EEPROM config) so you will be able
  1223. to define and configure new sensors on the fly
  1224. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  1225. loaded and initialized here. If you want to add new sensors of the same type
  1226. just duplicate the block and change the arguments for the set* methods.
  1227. For example, how to add a second DHT sensor:
  1228. #if DHT_SUPPORT
  1229. {
  1230. DHTSensor * sensor = new DHTSensor();
  1231. sensor->setGPIO(DHT2_PIN);
  1232. sensor->setType(DHT2_TYPE);
  1233. _sensors.push_back(sensor);
  1234. }
  1235. #endif
  1236. DHT2_PIN and DHT2_TYPE should be globally accessible:
  1237. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1238. - in custom.h, as `#define ...`
  1239. */
  1240. #if AM2320_SUPPORT
  1241. {
  1242. AM2320Sensor * sensor = new AM2320Sensor();
  1243. sensor->setAddress(AM2320_ADDRESS);
  1244. _sensors.push_back(sensor);
  1245. }
  1246. #endif
  1247. #if ANALOG_SUPPORT
  1248. {
  1249. AnalogSensor * sensor = new AnalogSensor();
  1250. sensor->setSamples(ANALOG_SAMPLES);
  1251. sensor->setDelay(ANALOG_DELAY);
  1252. //CICM For analog scaling
  1253. sensor->setFactor(ANALOG_FACTOR);
  1254. sensor->setOffset(ANALOG_OFFSET);
  1255. _sensors.push_back(sensor);
  1256. }
  1257. #endif
  1258. #if BH1750_SUPPORT
  1259. {
  1260. BH1750Sensor * sensor = new BH1750Sensor();
  1261. sensor->setAddress(BH1750_ADDRESS);
  1262. sensor->setMode(BH1750_MODE);
  1263. _sensors.push_back(sensor);
  1264. }
  1265. #endif
  1266. #if BMP180_SUPPORT
  1267. {
  1268. BMP180Sensor * sensor = new BMP180Sensor();
  1269. sensor->setAddress(BMP180_ADDRESS);
  1270. _sensors.push_back(sensor);
  1271. }
  1272. #endif
  1273. #if BMX280_SUPPORT
  1274. {
  1275. // Support up to two sensors with full auto-discovery.
  1276. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1277. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1278. // otherwise choose the other unnamed sensor address
  1279. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  1280. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1281. const decltype(first) address_map[2] { first, second };
  1282. for (unsigned char n=0; n < number; ++n) {
  1283. BMX280Sensor * sensor = new BMX280Sensor();
  1284. sensor->setAddress(address_map[n]);
  1285. _sensors.push_back(sensor);
  1286. }
  1287. }
  1288. #endif
  1289. #if CSE7766_SUPPORT
  1290. {
  1291. CSE7766Sensor * sensor = new CSE7766Sensor();
  1292. sensor->setRX(CSE7766_PIN);
  1293. _sensors.push_back(sensor);
  1294. }
  1295. #endif
  1296. #if DALLAS_SUPPORT
  1297. {
  1298. DallasSensor * sensor = new DallasSensor();
  1299. sensor->setGPIO(DALLAS_PIN);
  1300. _sensors.push_back(sensor);
  1301. }
  1302. #endif
  1303. #if DHT_SUPPORT
  1304. {
  1305. DHTSensor * sensor = new DHTSensor();
  1306. sensor->setGPIO(DHT_PIN);
  1307. sensor->setType(DHT_TYPE);
  1308. _sensors.push_back(sensor);
  1309. }
  1310. #endif
  1311. #if DIGITAL_SUPPORT
  1312. {
  1313. auto getPin = [](unsigned char index) -> int {
  1314. switch (index) {
  1315. case 0: return DIGITAL1_PIN;
  1316. case 1: return DIGITAL2_PIN;
  1317. case 2: return DIGITAL3_PIN;
  1318. case 3: return DIGITAL4_PIN;
  1319. case 4: return DIGITAL5_PIN;
  1320. case 5: return DIGITAL6_PIN;
  1321. case 6: return DIGITAL7_PIN;
  1322. case 7: return DIGITAL8_PIN;
  1323. default: return GPIO_NONE;
  1324. }
  1325. };
  1326. auto getDefaultState = [](unsigned char index) -> int {
  1327. switch (index) {
  1328. case 0: return DIGITAL1_DEFAULT_STATE;
  1329. case 1: return DIGITAL2_DEFAULT_STATE;
  1330. case 2: return DIGITAL3_DEFAULT_STATE;
  1331. case 3: return DIGITAL4_DEFAULT_STATE;
  1332. case 4: return DIGITAL5_DEFAULT_STATE;
  1333. case 5: return DIGITAL6_DEFAULT_STATE;
  1334. case 6: return DIGITAL7_DEFAULT_STATE;
  1335. case 7: return DIGITAL8_DEFAULT_STATE;
  1336. default: return 1;
  1337. }
  1338. };
  1339. auto getMode = [](unsigned char index) -> int {
  1340. switch (index) {
  1341. case 0: return DIGITAL1_PIN_MODE;
  1342. case 1: return DIGITAL2_PIN_MODE;
  1343. case 2: return DIGITAL3_PIN_MODE;
  1344. case 3: return DIGITAL4_PIN_MODE;
  1345. case 4: return DIGITAL5_PIN_MODE;
  1346. case 5: return DIGITAL6_PIN_MODE;
  1347. case 6: return DIGITAL7_PIN_MODE;
  1348. case 7: return DIGITAL8_PIN_MODE;
  1349. default: return INPUT_PULLUP;
  1350. }
  1351. };
  1352. for (unsigned char index = 0; index < GpioPins; ++index) {
  1353. const auto pin = getPin(index);
  1354. if (pin == GPIO_NONE) break;
  1355. DigitalSensor * sensor = new DigitalSensor();
  1356. sensor->setGPIO(pin);
  1357. sensor->setMode(getMode(index));
  1358. sensor->setDefault(getDefaultState(index));
  1359. _sensors.push_back(sensor);
  1360. }
  1361. }
  1362. #endif
  1363. #if ECH1560_SUPPORT
  1364. {
  1365. ECH1560Sensor * sensor = new ECH1560Sensor();
  1366. sensor->setCLK(ECH1560_CLK_PIN);
  1367. sensor->setMISO(ECH1560_MISO_PIN);
  1368. sensor->setInverted(ECH1560_INVERTED);
  1369. _sensors.push_back(sensor);
  1370. }
  1371. #endif
  1372. #if EMON_ADC121_SUPPORT
  1373. {
  1374. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1375. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1376. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1377. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1378. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1379. _sensors.push_back(sensor);
  1380. }
  1381. #endif
  1382. #if EMON_ADS1X15_SUPPORT
  1383. {
  1384. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  1385. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  1386. sensor->setType(EMON_ADS1X15_TYPE);
  1387. sensor->setMask(EMON_ADS1X15_MASK);
  1388. sensor->setGain(EMON_ADS1X15_GAIN);
  1389. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1390. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1391. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  1392. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  1393. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  1394. _sensors.push_back(sensor);
  1395. }
  1396. #endif
  1397. #if EMON_ANALOG_SUPPORT
  1398. {
  1399. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  1400. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1401. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1402. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1403. _sensors.push_back(sensor);
  1404. }
  1405. #endif
  1406. #if EVENTS_SUPPORT
  1407. {
  1408. #if (EVENTS1_PIN != GPIO_NONE)
  1409. {
  1410. EventSensor * sensor = new EventSensor();
  1411. sensor->setGPIO(EVENTS1_PIN);
  1412. sensor->setTrigger(EVENTS1_TRIGGER);
  1413. sensor->setPinMode(EVENTS1_PIN_MODE);
  1414. sensor->setDebounceTime(EVENTS1_DEBOUNCE);
  1415. sensor->setInterruptMode(EVENTS1_INTERRUPT_MODE);
  1416. _sensors.push_back(sensor);
  1417. }
  1418. #endif
  1419. #if (EVENTS2_PIN != GPIO_NONE)
  1420. {
  1421. EventSensor * sensor = new EventSensor();
  1422. sensor->setGPIO(EVENTS2_PIN);
  1423. sensor->setTrigger(EVENTS2_TRIGGER);
  1424. sensor->setPinMode(EVENTS2_PIN_MODE);
  1425. sensor->setDebounceTime(EVENTS2_DEBOUNCE);
  1426. sensor->setInterruptMode(EVENTS2_INTERRUPT_MODE);
  1427. _sensors.push_back(sensor);
  1428. }
  1429. #endif
  1430. #if (EVENTS3_PIN != GPIO_NONE)
  1431. {
  1432. EventSensor * sensor = new EventSensor();
  1433. sensor->setGPIO(EVENTS3_PIN);
  1434. sensor->setTrigger(EVENTS3_TRIGGER);
  1435. sensor->setPinMode(EVENTS3_PIN_MODE);
  1436. sensor->setDebounceTime(EVENTS3_DEBOUNCE);
  1437. sensor->setInterruptMode(EVENTS3_INTERRUPT_MODE);
  1438. _sensors.push_back(sensor);
  1439. }
  1440. #endif
  1441. #if (EVENTS4_PIN != GPIO_NONE)
  1442. {
  1443. EventSensor * sensor = new EventSensor();
  1444. sensor->setGPIO(EVENTS4_PIN);
  1445. sensor->setTrigger(EVENTS4_TRIGGER);
  1446. sensor->setPinMode(EVENTS4_PIN_MODE);
  1447. sensor->setDebounceTime(EVENTS4_DEBOUNCE);
  1448. sensor->setInterruptMode(EVENTS4_INTERRUPT_MODE);
  1449. _sensors.push_back(sensor);
  1450. }
  1451. #endif
  1452. #if (EVENTS5_PIN != GPIO_NONE)
  1453. {
  1454. EventSensor * sensor = new EventSensor();
  1455. sensor->setGPIO(EVENTS5_PIN);
  1456. sensor->setTrigger(EVENTS5_TRIGGER);
  1457. sensor->setPinMode(EVENTS5_PIN_MODE);
  1458. sensor->setDebounceTime(EVENTS5_DEBOUNCE);
  1459. sensor->setInterruptMode(EVENTS5_INTERRUPT_MODE);
  1460. _sensors.push_back(sensor);
  1461. }
  1462. #endif
  1463. #if (EVENTS6_PIN != GPIO_NONE)
  1464. {
  1465. EventSensor * sensor = new EventSensor();
  1466. sensor->setGPIO(EVENTS6_PIN);
  1467. sensor->setTrigger(EVENTS6_TRIGGER);
  1468. sensor->setPinMode(EVENTS6_PIN_MODE);
  1469. sensor->setDebounceTime(EVENTS6_DEBOUNCE);
  1470. sensor->setInterruptMode(EVENTS6_INTERRUPT_MODE);
  1471. _sensors.push_back(sensor);
  1472. }
  1473. #endif
  1474. #if (EVENTS7_PIN != GPIO_NONE)
  1475. {
  1476. EventSensor * sensor = new EventSensor();
  1477. sensor->setGPIO(EVENTS7_PIN);
  1478. sensor->setTrigger(EVENTS7_TRIGGER);
  1479. sensor->setPinMode(EVENTS7_PIN_MODE);
  1480. sensor->setDebounceTime(EVENTS7_DEBOUNCE);
  1481. sensor->setInterruptMode(EVENTS7_INTERRUPT_MODE);
  1482. _sensors.push_back(sensor);
  1483. }
  1484. #endif
  1485. #if (EVENTS8_PIN != GPIO_NONE)
  1486. {
  1487. EventSensor * sensor = new EventSensor();
  1488. sensor->setGPIO(EVENTS8_PIN);
  1489. sensor->setTrigger(EVENTS8_TRIGGER);
  1490. sensor->setPinMode(EVENTS8_PIN_MODE);
  1491. sensor->setDebounceTime(EVENTS8_DEBOUNCE);
  1492. sensor->setInterruptMode(EVENTS8_INTERRUPT_MODE);
  1493. _sensors.push_back(sensor);
  1494. }
  1495. #endif
  1496. }
  1497. #endif
  1498. #if GEIGER_SUPPORT
  1499. {
  1500. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1501. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1502. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1503. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1504. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1505. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1506. _sensors.push_back(sensor);
  1507. }
  1508. #endif
  1509. #if GUVAS12SD_SUPPORT
  1510. {
  1511. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1512. sensor->setGPIO(GUVAS12SD_PIN);
  1513. _sensors.push_back(sensor);
  1514. }
  1515. #endif
  1516. #if SONAR_SUPPORT
  1517. {
  1518. SonarSensor * sensor = new SonarSensor();
  1519. sensor->setEcho(SONAR_ECHO);
  1520. sensor->setIterations(SONAR_ITERATIONS);
  1521. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1522. sensor->setTrigger(SONAR_TRIGGER);
  1523. _sensors.push_back(sensor);
  1524. }
  1525. #endif
  1526. #if HLW8012_SUPPORT
  1527. {
  1528. HLW8012Sensor * sensor = new HLW8012Sensor();
  1529. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1530. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1531. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1532. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1533. _sensors.push_back(sensor);
  1534. }
  1535. #endif
  1536. #if LDR_SUPPORT
  1537. {
  1538. LDRSensor * sensor = new LDRSensor();
  1539. sensor->setSamples(LDR_SAMPLES);
  1540. sensor->setDelay(LDR_DELAY);
  1541. sensor->setType(LDR_TYPE);
  1542. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1543. sensor->setResistor(LDR_RESISTOR);
  1544. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1545. _sensors.push_back(sensor);
  1546. }
  1547. #endif
  1548. #if MHZ19_SUPPORT
  1549. {
  1550. MHZ19Sensor * sensor = new MHZ19Sensor();
  1551. sensor->setRX(MHZ19_RX_PIN);
  1552. sensor->setTX(MHZ19_TX_PIN);
  1553. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1554. _sensors.push_back(sensor);
  1555. }
  1556. #endif
  1557. #if MICS2710_SUPPORT
  1558. {
  1559. MICS2710Sensor * sensor = new MICS2710Sensor();
  1560. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1561. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1562. sensor->setR0(MICS2710_R0);
  1563. sensor->setRL(MICS2710_RL);
  1564. sensor->setRS(0);
  1565. _sensors.push_back(sensor);
  1566. }
  1567. #endif
  1568. #if MICS5525_SUPPORT
  1569. {
  1570. MICS5525Sensor * sensor = new MICS5525Sensor();
  1571. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1572. sensor->setR0(MICS5525_R0);
  1573. sensor->setRL(MICS5525_RL);
  1574. sensor->setRS(0);
  1575. _sensors.push_back(sensor);
  1576. }
  1577. #endif
  1578. #if NTC_SUPPORT
  1579. {
  1580. NTCSensor * sensor = new NTCSensor();
  1581. sensor->setSamples(NTC_SAMPLES);
  1582. sensor->setDelay(NTC_DELAY);
  1583. sensor->setUpstreamResistor(NTC_R_UP);
  1584. sensor->setDownstreamResistor(NTC_R_DOWN);
  1585. sensor->setBeta(NTC_BETA);
  1586. sensor->setR0(NTC_R0);
  1587. sensor->setT0(NTC_T0);
  1588. _sensors.push_back(sensor);
  1589. }
  1590. #endif
  1591. #if PMSX003_SUPPORT
  1592. {
  1593. PMSX003Sensor * sensor = new PMSX003Sensor();
  1594. #if PMS_USE_SOFT
  1595. sensor->setRX(PMS_RX_PIN);
  1596. sensor->setTX(PMS_TX_PIN);
  1597. #else
  1598. sensor->setSerial(& PMS_HW_PORT);
  1599. #endif
  1600. sensor->setType(PMS_TYPE);
  1601. _sensors.push_back(sensor);
  1602. }
  1603. #endif
  1604. #if PULSEMETER_SUPPORT
  1605. {
  1606. PulseMeterSensor * sensor = new PulseMeterSensor();
  1607. sensor->setGPIO(PULSEMETER_PIN);
  1608. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1609. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1610. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1611. _sensors.push_back(sensor);
  1612. }
  1613. #endif
  1614. #if PZEM004T_SUPPORT
  1615. {
  1616. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1617. if (!addresses.length()) {
  1618. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1619. return;
  1620. }
  1621. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1622. sensor->setAddresses(addresses.c_str());
  1623. if (getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1624. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1625. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1626. } else {
  1627. sensor->setSerial(& PZEM004T_HW_PORT);
  1628. }
  1629. _sensors.push_back(sensor);
  1630. #if TERMINAL_SUPPORT
  1631. pzem004tInitCommands();
  1632. #endif
  1633. }
  1634. #endif
  1635. #if SENSEAIR_SUPPORT
  1636. {
  1637. SenseAirSensor * sensor = new SenseAirSensor();
  1638. sensor->setRX(SENSEAIR_RX_PIN);
  1639. sensor->setTX(SENSEAIR_TX_PIN);
  1640. _sensors.push_back(sensor);
  1641. }
  1642. #endif
  1643. #if SDS011_SUPPORT
  1644. {
  1645. SDS011Sensor * sensor = new SDS011Sensor();
  1646. sensor->setRX(SDS011_RX_PIN);
  1647. sensor->setTX(SDS011_TX_PIN);
  1648. _sensors.push_back(sensor);
  1649. }
  1650. #endif
  1651. #if SHT3X_I2C_SUPPORT
  1652. {
  1653. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1654. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1655. _sensors.push_back(sensor);
  1656. }
  1657. #endif
  1658. #if SI7021_SUPPORT
  1659. {
  1660. SI7021Sensor * sensor = new SI7021Sensor();
  1661. sensor->setAddress(SI7021_ADDRESS);
  1662. _sensors.push_back(sensor);
  1663. }
  1664. #endif
  1665. #if T6613_SUPPORT
  1666. {
  1667. T6613Sensor * sensor = new T6613Sensor();
  1668. sensor->setRX(T6613_RX_PIN);
  1669. sensor->setTX(T6613_TX_PIN);
  1670. _sensors.push_back(sensor);
  1671. }
  1672. #endif
  1673. #if TMP3X_SUPPORT
  1674. {
  1675. TMP3XSensor * sensor = new TMP3XSensor();
  1676. sensor->setType(TMP3X_TYPE);
  1677. _sensors.push_back(sensor);
  1678. }
  1679. #endif
  1680. #if V9261F_SUPPORT
  1681. {
  1682. V9261FSensor * sensor = new V9261FSensor();
  1683. sensor->setRX(V9261F_PIN);
  1684. sensor->setInverted(V9261F_PIN_INVERSE);
  1685. _sensors.push_back(sensor);
  1686. }
  1687. #endif
  1688. #if MAX6675_SUPPORT
  1689. {
  1690. MAX6675Sensor * sensor = new MAX6675Sensor();
  1691. sensor->setCS(MAX6675_CS_PIN);
  1692. sensor->setSO(MAX6675_SO_PIN);
  1693. sensor->setSCK(MAX6675_SCK_PIN);
  1694. _sensors.push_back(sensor);
  1695. }
  1696. #endif
  1697. #if VEML6075_SUPPORT
  1698. {
  1699. VEML6075Sensor * sensor = new VEML6075Sensor();
  1700. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1701. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1702. _sensors.push_back(sensor);
  1703. }
  1704. #endif
  1705. #if VL53L1X_SUPPORT
  1706. {
  1707. VL53L1XSensor * sensor = new VL53L1XSensor();
  1708. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1709. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1710. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1711. _sensors.push_back(sensor);
  1712. }
  1713. #endif
  1714. #if EZOPH_SUPPORT
  1715. {
  1716. EZOPHSensor * sensor = new EZOPHSensor();
  1717. sensor->setRX(EZOPH_RX_PIN);
  1718. sensor->setTX(EZOPH_TX_PIN);
  1719. _sensors.push_back(sensor);
  1720. }
  1721. #endif
  1722. #if ADE7953_SUPPORT
  1723. {
  1724. ADE7953Sensor * sensor = new ADE7953Sensor();
  1725. sensor->setAddress(ADE7953_ADDRESS);
  1726. _sensors.push_back(sensor);
  1727. }
  1728. #endif
  1729. #if SI1145_SUPPORT
  1730. {
  1731. SI1145Sensor * sensor = new SI1145Sensor();
  1732. sensor->setAddress(SI1145_ADDRESS);
  1733. _sensors.push_back(sensor);
  1734. }
  1735. #endif
  1736. #if HDC1080_SUPPORT
  1737. {
  1738. HDC1080Sensor * sensor = new HDC1080Sensor();
  1739. sensor->setAddress(HDC1080_ADDRESS);
  1740. _sensors.push_back(sensor);
  1741. }
  1742. #endif
  1743. }
  1744. void _sensorReport(unsigned char index, double value) {
  1745. const auto& magnitude = _magnitudes.at(index);
  1746. // XXX: ensure that the received 'value' will fit here
  1747. // dtostrf 2nd arg only controls leading zeroes and the
  1748. // 3rd is only for the part after the dot
  1749. char buffer[64];
  1750. dtostrf(value, 1, magnitude.decimals, buffer);
  1751. #if BROKER_SUPPORT
  1752. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value, buffer);
  1753. #endif
  1754. #if MQTT_SUPPORT
  1755. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1756. #if SENSOR_PUBLISH_ADDRESSES
  1757. char topic[32];
  1758. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1759. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1760. mqttSend(topic, magnitude.index_global, magnitude.sensor->address(magnitude.slot).c_str());
  1761. } else {
  1762. mqttSend(topic, magnitude.sensor->address(magnitude.slot).c_str());
  1763. }
  1764. #endif // SENSOR_PUBLISH_ADDRESSES
  1765. #endif // MQTT_SUPPORT
  1766. #if THINGSPEAK_SUPPORT
  1767. tspkEnqueueMeasurement(index, buffer);
  1768. #endif // THINGSPEAK_SUPPORT
  1769. #if DOMOTICZ_SUPPORT
  1770. domoticzSendMagnitude(magnitude.type, index, value, buffer);
  1771. #endif // DOMOTICZ_SUPPORT
  1772. }
  1773. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  1774. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  1775. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  1776. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  1777. _sensorReport(k, value);
  1778. return;
  1779. }
  1780. }
  1781. }
  1782. void _sensorInit() {
  1783. _sensors_ready = true;
  1784. for (unsigned char i=0; i<_sensors.size(); i++) {
  1785. // Do not process an already initialized sensor
  1786. if (_sensors[i]->ready()) continue;
  1787. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  1788. // Force sensor to reload config
  1789. _sensors[i]->begin();
  1790. if (!_sensors[i]->ready()) {
  1791. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  1792. _sensors_ready = false;
  1793. break;
  1794. }
  1795. // Initialize sensor magnitudes
  1796. for (unsigned char magnitude_index = 0; magnitude_index < _sensors[i]->count(); ++magnitude_index) {
  1797. const auto magnitude_type = _sensors[i]->type(magnitude_index);
  1798. const auto magnitude_local = _sensors[i]->local(magnitude_type);
  1799. _magnitudes.emplace_back(
  1800. magnitude_index, // id of the magnitude, unique to the sensor
  1801. magnitude_local, // index_local, # of the magnitude
  1802. magnitude_type, // specific type of the magnitude
  1803. sensor::Unit::None, // set up later, in configuration
  1804. _sensors[i] // bind the sensor to allow us to reference it later
  1805. );
  1806. if (_sensorIsEmon(_sensors[i]) && (MAGNITUDE_ENERGY == magnitude_type)) {
  1807. const auto index_global = _magnitudes.back().index_global;
  1808. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[i]);
  1809. sensor->resetEnergy(magnitude_local, _sensorEnergyTotal(index_global));
  1810. _sensor_save_count.push_back(0);
  1811. }
  1812. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1813. magnitudeTopic(magnitude_type).c_str(),
  1814. sensor_magnitude_t::counts(magnitude_type)
  1815. );
  1816. }
  1817. // Hook callback
  1818. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1819. _sensorCallback(i, type, value);
  1820. });
  1821. // Custom initializations, based on IDs
  1822. switch (_sensors[i]->getID()) {
  1823. case SENSOR_MICS2710_ID:
  1824. case SENSOR_MICS5525_ID: {
  1825. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[i]);
  1826. sensor->setR0(getSetting("snsR0", sensor->getR0()));
  1827. sensor->setRS(getSetting("snsRS", sensor->getRS()));
  1828. sensor->setRL(getSetting("snsRL", sensor->getRL()));
  1829. break;
  1830. }
  1831. default:
  1832. break;
  1833. }
  1834. }
  1835. }
  1836. namespace settings {
  1837. namespace internal {
  1838. template <>
  1839. sensor::Unit convert(const String& string) {
  1840. const int value = string.toInt();
  1841. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1842. return static_cast<sensor::Unit>(value);
  1843. }
  1844. return sensor::Unit::None;
  1845. }
  1846. template <>
  1847. String serialize(const sensor::Unit& unit) {
  1848. return String(static_cast<int>(unit));
  1849. }
  1850. } // ns settings::internal
  1851. } // ns settings
  1852. void _sensorConfigure() {
  1853. // General sensor settings for reporting and saving
  1854. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1855. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1856. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  1857. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  1858. // pre-load some settings that are controlled via old build flags
  1859. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  1860. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  1861. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  1862. // Apply settings based on sensor type
  1863. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  1864. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1865. {
  1866. if (getSetting("snsResetCalibration", false)) {
  1867. switch (_sensors[index]->getID()) {
  1868. case SENSOR_MICS2710_ID:
  1869. case SENSOR_MICS5525_ID: {
  1870. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  1871. sensor->calibrate();
  1872. setSetting("snsR0", sensor->getR0());
  1873. break;
  1874. }
  1875. default:
  1876. break;
  1877. }
  1878. }
  1879. }
  1880. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  1881. if (_sensorIsEmon(_sensors[index])) {
  1882. // TODO: ::isEmon() ?
  1883. double value;
  1884. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  1885. if ((value = getSetting("pwrExpectedC", 0.0))) {
  1886. sensor->expectedCurrent(value);
  1887. delSetting("pwrExpectedC");
  1888. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1889. }
  1890. if ((value = getSetting("pwrExpectedV", 0.0))) {
  1891. delSetting("pwrExpectedV");
  1892. sensor->expectedVoltage(value);
  1893. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1894. }
  1895. if ((value = getSetting("pwrExpectedP", 0.0))) {
  1896. delSetting("pwrExpectedP");
  1897. sensor->expectedPower(value);
  1898. setSetting("pwrRatioP", sensor->getPowerRatio());
  1899. }
  1900. if (getSetting("pwrResetE", false)) {
  1901. delSetting("pwrResetE");
  1902. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1903. sensor->resetEnergy(index);
  1904. _sensorResetEnergyTotal(index);
  1905. }
  1906. }
  1907. if (getSetting("pwrResetCalibration", false)) {
  1908. delSetting("pwrResetCalibration");
  1909. delSetting("pwrRatioC");
  1910. delSetting("pwrRatioV");
  1911. delSetting("pwrRatioP");
  1912. sensor->resetRatios();
  1913. }
  1914. } // is emon?
  1915. }
  1916. // Update magnitude config, filter sizes and reset energy if needed
  1917. {
  1918. // TODO: instead of using global enum, have a local mapping?
  1919. const auto tmpUnits = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS);
  1920. const auto pwrUnits = getSetting("pwrUnits", SENSOR_POWER_UNITS);
  1921. const auto eneUnits = getSetting("eneUnits", SENSOR_ENERGY_UNITS);
  1922. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  1923. auto& magnitude = _magnitudes.at(index);
  1924. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  1925. if (_sensorIsEmon(magnitude.sensor)) {
  1926. // TODO: compatibility proxy, fetch global key before indexed
  1927. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  1928. return getSetting({key, index}, getSetting(key, default_value));
  1929. };
  1930. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  1931. switch (magnitude.type) {
  1932. case MAGNITUDE_CURRENT:
  1933. sensor->setCurrentRatio(
  1934. magnitude.index_local, get_ratio("pwrRatioC", magnitude.index_global, sensor->defaultCurrentRatio())
  1935. );
  1936. break;
  1937. case MAGNITUDE_POWER_ACTIVE:
  1938. sensor->setPowerRatio(
  1939. magnitude.index_local, get_ratio("pwrRatioP", magnitude.index_global, sensor->defaultPowerRatio())
  1940. );
  1941. break;
  1942. case MAGNITUDE_VOLTAGE:
  1943. sensor->setVoltageRatio(
  1944. magnitude.index_local, get_ratio("pwrRatioV", magnitude.index_global, sensor->defaultVoltageRatio())
  1945. );
  1946. sensor->setVoltage(
  1947. magnitude.index_local, get_ratio("pwrVoltage", magnitude.index_global, sensor->defaultVoltage())
  1948. );
  1949. break;
  1950. case MAGNITUDE_ENERGY:
  1951. sensor->setEnergyRatio(
  1952. magnitude.index_local, get_ratio("pwrRatioE", magnitude.index_global, sensor->defaultEnergyRatio())
  1953. );
  1954. break;
  1955. default:
  1956. break;
  1957. }
  1958. }
  1959. // adjust type-specific units (TODO: try to adjust settings to use type prefixes?)
  1960. switch (magnitude.type) {
  1961. case MAGNITUDE_TEMPERATURE:
  1962. magnitude.units = _magnitudeUnitFilter(
  1963. magnitude,
  1964. getSetting({"tmpUnits", magnitude.index_global}, tmpUnits)
  1965. );
  1966. break;
  1967. case MAGNITUDE_POWER_ACTIVE:
  1968. magnitude.units = _magnitudeUnitFilter(
  1969. magnitude,
  1970. getSetting({"pwrUnits", magnitude.index_global}, pwrUnits)
  1971. );
  1972. break;
  1973. case MAGNITUDE_ENERGY:
  1974. magnitude.units = _magnitudeUnitFilter(
  1975. magnitude,
  1976. getSetting({"eneUnits", magnitude.index_global}, eneUnits)
  1977. );
  1978. break;
  1979. default:
  1980. magnitude.units = magnitude.sensor->units(magnitude.slot);
  1981. break;
  1982. }
  1983. // some magnitudes allow to be corrected with an offset
  1984. {
  1985. if (_magnitudeCanUseCorrection(magnitude.type)) {
  1986. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  1987. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  1988. }
  1989. }
  1990. // some sensors can override decimal values if sensor has more precision than default
  1991. {
  1992. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  1993. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  1994. magnitude.decimals = (unsigned char) decimals;
  1995. }
  1996. // Per-magnitude min & max delta settings
  1997. // - min controls whether we report at all when report_count overflows
  1998. // - max will trigger report as soon as read value is greater than the specified delta
  1999. // (atm this works best for accumulated magnitudes, like energy)
  2000. {
  2001. auto min_default = 0.0;
  2002. auto max_default = 0.0;
  2003. switch (magnitude.type) {
  2004. case MAGNITUDE_TEMPERATURE:
  2005. min_default = tmp_min_delta;
  2006. break;
  2007. case MAGNITUDE_HUMIDITY:
  2008. min_default = hum_min_delta;
  2009. break;
  2010. case MAGNITUDE_ENERGY:
  2011. max_default = ene_max_delta;
  2012. break;
  2013. default:
  2014. break;
  2015. }
  2016. magnitude.min_change = getSetting(
  2017. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2018. min_default
  2019. );
  2020. magnitude.max_change = getSetting(
  2021. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2022. max_default
  2023. );
  2024. }
  2025. // Sometimes we want to ensure the value is above certain threshold before reporting
  2026. {
  2027. magnitude.zero_threshold = getSetting(
  2028. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2029. std::numeric_limits<double>::quiet_NaN()
  2030. );
  2031. }
  2032. // in case we don't save energy periodically, purge existing value in ram & settings
  2033. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2034. _sensorResetEnergyTotal(magnitude.index_global);
  2035. }
  2036. }
  2037. }
  2038. saveSettings();
  2039. }
  2040. // -----------------------------------------------------------------------------
  2041. // Public
  2042. // -----------------------------------------------------------------------------
  2043. unsigned char sensorCount() {
  2044. return _sensors.size();
  2045. }
  2046. unsigned char magnitudeCount() {
  2047. return _magnitudes.size();
  2048. }
  2049. unsigned char magnitudeType(unsigned char index) {
  2050. if (index < _magnitudes.size()) {
  2051. return _magnitudes[index].type;
  2052. }
  2053. return MAGNITUDE_NONE;
  2054. }
  2055. double magnitudeValue(unsigned char index) {
  2056. if (index < _magnitudes.size()) {
  2057. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  2058. }
  2059. return DBL_MIN;
  2060. }
  2061. unsigned char magnitudeIndex(unsigned char index) {
  2062. if (index < _magnitudes.size()) {
  2063. return _magnitudes[index].index_global;
  2064. }
  2065. return 0;
  2066. }
  2067. String magnitudeDescription(unsigned char index) {
  2068. if (index < _magnitudes.size()) {
  2069. return _magnitudeDescription(_magnitudes[index]);
  2070. }
  2071. return String();
  2072. }
  2073. String magnitudeTopicIndex(unsigned char index) {
  2074. char topic[32] = {0};
  2075. if (index < _magnitudes.size()) {
  2076. sensor_magnitude_t magnitude = _magnitudes[index];
  2077. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  2078. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.index_global);
  2079. } else {
  2080. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  2081. }
  2082. }
  2083. return String(topic);
  2084. }
  2085. // -----------------------------------------------------------------------------
  2086. void _sensorBackwards() {
  2087. // Some keys from older versions were longer
  2088. moveSetting("powerUnits", "pwrUnits");
  2089. moveSetting("energyUnits", "eneUnits");
  2090. // Energy is now indexed (based on magnitude.index_global)
  2091. moveSetting("eneTotal", "eneTotal0");
  2092. // Update PZEM004T energy total across multiple devices
  2093. moveSettings("pzEneTotal", "eneTotal");
  2094. // Unit ID is no longer shared, drop when equal to Min_ or None
  2095. const char *keys[3] = {
  2096. "pwrUnits", "eneUnits", "tmpUnits"
  2097. };
  2098. for (auto* key : keys) {
  2099. const auto units = getSetting(key);
  2100. if (units.length() && (units.equals("0") || units.equals("1"))) {
  2101. delSetting(key);
  2102. }
  2103. }
  2104. }
  2105. void sensorSetup() {
  2106. // Settings backwards compatibility
  2107. _sensorBackwards();
  2108. // Load configured sensors and set up all of magnitudes
  2109. _sensorLoad();
  2110. _sensorInit();
  2111. // Configure based on settings
  2112. _sensorConfigure();
  2113. // Allow us to query key default
  2114. settingsRegisterDefaults({
  2115. [](const char* key) -> bool {
  2116. if (strncmp(key, "pwr", 3) == 0) return true;
  2117. return false;
  2118. },
  2119. _sensorQueryDefault
  2120. });
  2121. // Websockets integration, send sensor readings and configuration
  2122. #if WEB_SUPPORT
  2123. wsRegister()
  2124. .onVisible(_sensorWebSocketOnVisible)
  2125. .onConnected(_sensorWebSocketOnConnected)
  2126. .onData(_sensorWebSocketSendData)
  2127. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2128. #endif
  2129. // MQTT receive callback, atm only for energy reset
  2130. #if MQTT_SUPPORT
  2131. mqttRegister(_sensorMqttCallback);
  2132. #endif
  2133. // API
  2134. #if API_SUPPORT
  2135. _sensorAPISetup();
  2136. #endif
  2137. // Terminal
  2138. #if TERMINAL_SUPPORT
  2139. _sensorInitCommands();
  2140. #endif
  2141. // Main callbacks
  2142. espurnaRegisterLoop(sensorLoop);
  2143. espurnaRegisterReload(_sensorConfigure);
  2144. }
  2145. void sensorLoop() {
  2146. // Check if we still have uninitialized sensors
  2147. static unsigned long last_init = 0;
  2148. if (!_sensors_ready) {
  2149. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2150. last_init = millis();
  2151. _sensorInit();
  2152. }
  2153. }
  2154. if (_magnitudes.size() == 0) return;
  2155. // Tick hook, called every loop()
  2156. _sensorTick();
  2157. // Check if we should read new data
  2158. static unsigned long last_update = 0;
  2159. static unsigned long report_count = 0;
  2160. if (millis() - last_update > _sensor_read_interval) {
  2161. last_update = millis();
  2162. report_count = (report_count + 1) % _sensor_report_every;
  2163. double value_raw; // holds the raw value as the sensor returns it
  2164. double value_show; // holds the processed value applying units and decimals
  2165. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2166. // Pre-read hook, called every reading
  2167. _sensorPre();
  2168. // Get the first relay state
  2169. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2170. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2171. #endif
  2172. // Get readings
  2173. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  2174. sensor_magnitude_t magnitude = _magnitudes[i];
  2175. if (magnitude.sensor->status()) {
  2176. // -------------------------------------------------------------
  2177. // Instant value
  2178. // -------------------------------------------------------------
  2179. value_raw = magnitude.sensor->value(magnitude.slot);
  2180. // Completely remove spurious values if relay is OFF
  2181. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2182. switch (magnitude.type) {
  2183. case MAGNITUDE_POWER_ACTIVE:
  2184. case MAGNITUDE_POWER_REACTIVE:
  2185. case MAGNITUDE_POWER_APPARENT:
  2186. case MAGNITUDE_POWER_FACTOR:
  2187. case MAGNITUDE_CURRENT:
  2188. case MAGNITUDE_ENERGY_DELTA:
  2189. if (relay_off) {
  2190. value_raw = 0.0;
  2191. }
  2192. break;
  2193. default:
  2194. break;
  2195. }
  2196. #endif
  2197. // In addition to that, we also check that value is above a certain threshold
  2198. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2199. value_raw = 0.0;
  2200. }
  2201. _magnitudes[i].last = value_raw;
  2202. // -------------------------------------------------------------
  2203. // Processing (filters)
  2204. // -------------------------------------------------------------
  2205. magnitude.filter->add(value_raw);
  2206. // Special case for MovingAverageFilter
  2207. switch (magnitude.type) {
  2208. case MAGNITUDE_COUNT:
  2209. case MAGNITUDE_GEIGER_CPM:
  2210. case MAGNITUDE_GEIGER_SIEVERT:
  2211. value_raw = magnitude.filter->result();
  2212. break;
  2213. default:
  2214. break;
  2215. }
  2216. // -------------------------------------------------------------
  2217. // Procesing (units and decimals)
  2218. // -------------------------------------------------------------
  2219. value_show = _magnitudeProcess(magnitude, value_raw);
  2220. #if BROKER_SUPPORT
  2221. {
  2222. char buffer[64];
  2223. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2224. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2225. }
  2226. #endif
  2227. // -------------------------------------------------------------
  2228. // Debug
  2229. // -------------------------------------------------------------
  2230. #if SENSOR_DEBUG
  2231. {
  2232. char buffer[64];
  2233. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2234. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2235. _magnitudeDescription(magnitude).c_str(),
  2236. magnitudeTopic(magnitude.type).c_str(),
  2237. buffer,
  2238. _magnitudeUnits(magnitude).c_str()
  2239. );
  2240. }
  2241. #endif // SENSOR_DEBUG
  2242. // -------------------------------------------------------------------
  2243. // Report when
  2244. // - report_count overflows after reaching _sensor_report_every
  2245. // - when magnitude specifies max_change and we greater or equal to it
  2246. // -------------------------------------------------------------------
  2247. bool report = (0 == report_count);
  2248. if (magnitude.max_change > 0) {
  2249. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  2250. }
  2251. // Special case for energy, save readings to RAM and EEPROM
  2252. if (MAGNITUDE_ENERGY == magnitude.type) {
  2253. _magnitudeSaveEnergyTotal(magnitude, report);
  2254. }
  2255. if (report) {
  2256. value_filtered = magnitude.filter->result();
  2257. value_filtered = _magnitudeProcess(magnitude, value_filtered);
  2258. magnitude.filter->reset();
  2259. if (magnitude.filter->size() != _sensor_report_every) {
  2260. magnitude.filter->resize(_sensor_report_every);
  2261. }
  2262. // Check if there is a minimum change threshold to report
  2263. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  2264. _magnitudes[i].reported = value_filtered;
  2265. _sensorReport(i, value_filtered);
  2266. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  2267. } // if (report_count == 0)
  2268. } // if (magnitude.sensor->status())
  2269. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  2270. // Post-read hook, called every reading
  2271. _sensorPost();
  2272. // And report data to modules that don't specifically track them
  2273. #if WEB_SUPPORT
  2274. wsPost(_sensorWebSocketSendData);
  2275. #endif
  2276. #if THINGSPEAK_SUPPORT
  2277. if (report_count == 0) tspkFlush();
  2278. #endif
  2279. }
  2280. }
  2281. #endif // SENSOR_SUPPORT