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.

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