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.

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