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.

2857 lines
85 KiB

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