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.

2834 lines
84 KiB

7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "sensor.h"
  6. #if SENSOR_SUPPORT
  7. #include <vector>
  8. #include <float.h>
  9. #include "api.h"
  10. #include "broker.h"
  11. #include "domoticz.h"
  12. #include "i2c.h"
  13. #include "mqtt.h"
  14. #include "ntp.h"
  15. #include "relay.h"
  16. #include "terminal.h"
  17. #include "thingspeak.h"
  18. #include "rtcmem.h"
  19. #include "ws.h"
  20. //--------------------------------------------------------------------------------
  21. // TODO: namespace { ... } ? sensor ctors need to work though
  22. #include "filters/LastFilter.h"
  23. #include "filters/MaxFilter.h"
  24. #include "filters/MedianFilter.h"
  25. #include "filters/MovingAverageFilter.h"
  26. #include "filters/SumFilter.h"
  27. #include "sensors/BaseSensor.h"
  28. #include "sensors/BaseEmonSensor.h"
  29. #include "sensors/BaseAnalogSensor.h"
  30. #if AM2320_SUPPORT
  31. #include "sensors/AM2320Sensor.h"
  32. #endif
  33. #if ANALOG_SUPPORT
  34. #include "sensors/AnalogSensor.h"
  35. #endif
  36. #if BH1750_SUPPORT
  37. #include "sensors/BH1750Sensor.h"
  38. #endif
  39. #if BMP180_SUPPORT
  40. #include "sensors/BMP180Sensor.h"
  41. #endif
  42. #if BMX280_SUPPORT
  43. #include "sensors/BMX280Sensor.h"
  44. #endif
  45. #if 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. void _sensorAPISetup() {
  1183. for (auto& magnitude : _magnitudes) {
  1184. String topic = magnitudeTopic(magnitude.type);
  1185. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) topic = topic + "/" + String(magnitude.index_global);
  1186. api_get_callback_f get_cb = [&magnitude](char * buffer, size_t len) {
  1187. double value = _sensor_realtime ? magnitude.last : magnitude.reported;
  1188. dtostrf(value, 1, magnitude.decimals, buffer);
  1189. };
  1190. api_put_callback_f put_cb = nullptr;
  1191. if (magnitude.type == MAGNITUDE_ENERGY) {
  1192. put_cb = [&magnitude](const char* payload) {
  1193. _sensorApiResetEnergy(magnitude, payload);
  1194. };
  1195. }
  1196. apiRegister(topic.c_str(), get_cb, put_cb);
  1197. }
  1198. }
  1199. #endif // API_SUPPORT == 1
  1200. #if MQTT_SUPPORT
  1201. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  1202. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  1203. switch (type) {
  1204. case MQTT_MESSAGE_EVENT: {
  1205. String t = mqttMagnitude((char *) topic);
  1206. if (!t.startsWith(energy_topic)) break;
  1207. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  1208. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  1209. for (auto& magnitude : _magnitudes) {
  1210. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  1211. if (index != magnitude.index_global) continue;
  1212. _sensorApiResetEnergy(magnitude, payload);
  1213. break;
  1214. }
  1215. }
  1216. case MQTT_CONNECT_EVENT: {
  1217. for (auto& magnitude : _magnitudes) {
  1218. if (MAGNITUDE_ENERGY == magnitude.type) {
  1219. const String topic = energy_topic + "/+";
  1220. mqttSubscribe(topic.c_str());
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. case MQTT_DISCONNECT_EVENT:
  1226. default:
  1227. break;
  1228. }
  1229. }
  1230. #endif // MQTT_SUPPORT == 1
  1231. #if TERMINAL_SUPPORT
  1232. void _sensorInitCommands() {
  1233. terminalRegisterCommand(F("MAGNITUDES"), [](const terminal::CommandContext&) {
  1234. char last[64];
  1235. char reported[64];
  1236. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1237. auto& magnitude = _magnitudes.at(index);
  1238. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  1239. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  1240. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  1241. index,
  1242. magnitudeTopic(magnitude.type).c_str(),
  1243. magnitude.index_global,
  1244. _magnitudeDescription(magnitude).c_str(),
  1245. last, reported
  1246. );
  1247. }
  1248. terminalOK();
  1249. });
  1250. }
  1251. #endif // TERMINAL_SUPPORT == 1
  1252. void _sensorTick() {
  1253. for (auto* sensor : _sensors) {
  1254. sensor->tick();
  1255. }
  1256. }
  1257. void _sensorPre() {
  1258. for (auto* sensor : _sensors) {
  1259. sensor->pre();
  1260. if (!sensor->status()) {
  1261. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  1262. sensor->description().c_str(),
  1263. sensor->error()
  1264. );
  1265. }
  1266. }
  1267. }
  1268. void _sensorPost() {
  1269. for (auto* sensor : _sensors) {
  1270. sensor->post();
  1271. }
  1272. }
  1273. // -----------------------------------------------------------------------------
  1274. // Sensor initialization
  1275. // -----------------------------------------------------------------------------
  1276. void _sensorLoad() {
  1277. /*
  1278. This is temporal, in the future sensors will be initialized based on
  1279. soft configuration (data stored in EEPROM config) so you will be able
  1280. to define and configure new sensors on the fly
  1281. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  1282. loaded and initialized here. If you want to add new sensors of the same type
  1283. just duplicate the block and change the arguments for the set* methods.
  1284. For example, how to add a second DHT sensor:
  1285. #if DHT_SUPPORT
  1286. {
  1287. DHTSensor * sensor = new DHTSensor();
  1288. sensor->setGPIO(DHT2_PIN);
  1289. sensor->setType(DHT2_TYPE);
  1290. _sensors.push_back(sensor);
  1291. }
  1292. #endif
  1293. DHT2_PIN and DHT2_TYPE should be globally accessible:
  1294. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1295. - in custom.h, as `#define ...`
  1296. */
  1297. #if AM2320_SUPPORT
  1298. {
  1299. AM2320Sensor * sensor = new AM2320Sensor();
  1300. sensor->setAddress(AM2320_ADDRESS);
  1301. _sensors.push_back(sensor);
  1302. }
  1303. #endif
  1304. #if ANALOG_SUPPORT
  1305. {
  1306. AnalogSensor * sensor = new AnalogSensor();
  1307. sensor->setSamples(ANALOG_SAMPLES);
  1308. sensor->setDelay(ANALOG_DELAY);
  1309. //CICM For analog scaling
  1310. sensor->setFactor(ANALOG_FACTOR);
  1311. sensor->setOffset(ANALOG_OFFSET);
  1312. _sensors.push_back(sensor);
  1313. }
  1314. #endif
  1315. #if BH1750_SUPPORT
  1316. {
  1317. BH1750Sensor * sensor = new BH1750Sensor();
  1318. sensor->setAddress(BH1750_ADDRESS);
  1319. sensor->setMode(BH1750_MODE);
  1320. _sensors.push_back(sensor);
  1321. }
  1322. #endif
  1323. #if BMP180_SUPPORT
  1324. {
  1325. BMP180Sensor * sensor = new BMP180Sensor();
  1326. sensor->setAddress(BMP180_ADDRESS);
  1327. _sensors.push_back(sensor);
  1328. }
  1329. #endif
  1330. #if BMX280_SUPPORT
  1331. {
  1332. // Support up to two sensors with full auto-discovery.
  1333. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1334. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1335. // otherwise choose the other unnamed sensor address
  1336. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  1337. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1338. const decltype(first) address_map[2] { first, second };
  1339. for (unsigned char n=0; n < number; ++n) {
  1340. BMX280Sensor * sensor = new BMX280Sensor();
  1341. sensor->setAddress(address_map[n]);
  1342. _sensors.push_back(sensor);
  1343. }
  1344. }
  1345. #endif
  1346. #if BME680_SUPPORT
  1347. {
  1348. BME680Sensor * sensor = new BME680Sensor();
  1349. sensor->setAddress(BME680_I2C_ADDRESS);
  1350. _sensors.push_back(sensor);
  1351. }
  1352. #endif
  1353. #if CSE7766_SUPPORT
  1354. {
  1355. CSE7766Sensor * sensor = new CSE7766Sensor();
  1356. sensor->setRX(CSE7766_RX_PIN);
  1357. _sensors.push_back(sensor);
  1358. }
  1359. #endif
  1360. #if DALLAS_SUPPORT
  1361. {
  1362. DallasSensor * sensor = new DallasSensor();
  1363. sensor->setGPIO(DALLAS_PIN);
  1364. _sensors.push_back(sensor);
  1365. }
  1366. #endif
  1367. #if DHT_SUPPORT
  1368. {
  1369. DHTSensor * sensor = new DHTSensor();
  1370. sensor->setGPIO(DHT_PIN);
  1371. sensor->setType(DHT_TYPE);
  1372. _sensors.push_back(sensor);
  1373. }
  1374. #endif
  1375. #if DIGITAL_SUPPORT
  1376. {
  1377. auto getPin = [](unsigned char index) -> int {
  1378. switch (index) {
  1379. case 0: return DIGITAL1_PIN;
  1380. case 1: return DIGITAL2_PIN;
  1381. case 2: return DIGITAL3_PIN;
  1382. case 3: return DIGITAL4_PIN;
  1383. case 4: return DIGITAL5_PIN;
  1384. case 5: return DIGITAL6_PIN;
  1385. case 6: return DIGITAL7_PIN;
  1386. case 7: return DIGITAL8_PIN;
  1387. default: return GPIO_NONE;
  1388. }
  1389. };
  1390. auto getDefaultState = [](unsigned char index) -> int {
  1391. switch (index) {
  1392. case 0: return DIGITAL1_DEFAULT_STATE;
  1393. case 1: return DIGITAL2_DEFAULT_STATE;
  1394. case 2: return DIGITAL3_DEFAULT_STATE;
  1395. case 3: return DIGITAL4_DEFAULT_STATE;
  1396. case 4: return DIGITAL5_DEFAULT_STATE;
  1397. case 5: return DIGITAL6_DEFAULT_STATE;
  1398. case 6: return DIGITAL7_DEFAULT_STATE;
  1399. case 7: return DIGITAL8_DEFAULT_STATE;
  1400. default: return 1;
  1401. }
  1402. };
  1403. auto getMode = [](unsigned char index) -> int {
  1404. switch (index) {
  1405. case 0: return DIGITAL1_PIN_MODE;
  1406. case 1: return DIGITAL2_PIN_MODE;
  1407. case 2: return DIGITAL3_PIN_MODE;
  1408. case 3: return DIGITAL4_PIN_MODE;
  1409. case 4: return DIGITAL5_PIN_MODE;
  1410. case 5: return DIGITAL6_PIN_MODE;
  1411. case 6: return DIGITAL7_PIN_MODE;
  1412. case 7: return DIGITAL8_PIN_MODE;
  1413. default: return INPUT_PULLUP;
  1414. }
  1415. };
  1416. for (unsigned char index = 0; index < GpioPins; ++index) {
  1417. const auto pin = getPin(index);
  1418. if (pin == GPIO_NONE) break;
  1419. DigitalSensor * sensor = new DigitalSensor();
  1420. sensor->setGPIO(pin);
  1421. sensor->setMode(getMode(index));
  1422. sensor->setDefault(getDefaultState(index));
  1423. _sensors.push_back(sensor);
  1424. }
  1425. }
  1426. #endif
  1427. #if ECH1560_SUPPORT
  1428. {
  1429. ECH1560Sensor * sensor = new ECH1560Sensor();
  1430. sensor->setCLK(ECH1560_CLK_PIN);
  1431. sensor->setMISO(ECH1560_MISO_PIN);
  1432. sensor->setInverted(ECH1560_INVERTED);
  1433. _sensors.push_back(sensor);
  1434. }
  1435. #endif
  1436. #if EMON_ADC121_SUPPORT
  1437. {
  1438. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1439. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1440. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1441. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1442. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1443. _sensors.push_back(sensor);
  1444. }
  1445. #endif
  1446. #if EMON_ADS1X15_SUPPORT
  1447. {
  1448. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  1449. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  1450. sensor->setType(EMON_ADS1X15_TYPE);
  1451. sensor->setMask(EMON_ADS1X15_MASK);
  1452. sensor->setGain(EMON_ADS1X15_GAIN);
  1453. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1454. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1455. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  1456. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  1457. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  1458. _sensors.push_back(sensor);
  1459. }
  1460. #endif
  1461. #if EMON_ANALOG_SUPPORT
  1462. {
  1463. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  1464. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1465. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1466. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1467. _sensors.push_back(sensor);
  1468. }
  1469. #endif
  1470. #if EVENTS_SUPPORT
  1471. {
  1472. #if (EVENTS1_PIN != GPIO_NONE)
  1473. {
  1474. EventSensor * sensor = new EventSensor();
  1475. sensor->setGPIO(EVENTS1_PIN);
  1476. sensor->setTrigger(EVENTS1_TRIGGER);
  1477. sensor->setPinMode(EVENTS1_PIN_MODE);
  1478. sensor->setDebounceTime(EVENTS1_DEBOUNCE);
  1479. sensor->setInterruptMode(EVENTS1_INTERRUPT_MODE);
  1480. _sensors.push_back(sensor);
  1481. }
  1482. #endif
  1483. #if (EVENTS2_PIN != GPIO_NONE)
  1484. {
  1485. EventSensor * sensor = new EventSensor();
  1486. sensor->setGPIO(EVENTS2_PIN);
  1487. sensor->setTrigger(EVENTS2_TRIGGER);
  1488. sensor->setPinMode(EVENTS2_PIN_MODE);
  1489. sensor->setDebounceTime(EVENTS2_DEBOUNCE);
  1490. sensor->setInterruptMode(EVENTS2_INTERRUPT_MODE);
  1491. _sensors.push_back(sensor);
  1492. }
  1493. #endif
  1494. #if (EVENTS3_PIN != GPIO_NONE)
  1495. {
  1496. EventSensor * sensor = new EventSensor();
  1497. sensor->setGPIO(EVENTS3_PIN);
  1498. sensor->setTrigger(EVENTS3_TRIGGER);
  1499. sensor->setPinMode(EVENTS3_PIN_MODE);
  1500. sensor->setDebounceTime(EVENTS3_DEBOUNCE);
  1501. sensor->setInterruptMode(EVENTS3_INTERRUPT_MODE);
  1502. _sensors.push_back(sensor);
  1503. }
  1504. #endif
  1505. #if (EVENTS4_PIN != GPIO_NONE)
  1506. {
  1507. EventSensor * sensor = new EventSensor();
  1508. sensor->setGPIO(EVENTS4_PIN);
  1509. sensor->setTrigger(EVENTS4_TRIGGER);
  1510. sensor->setPinMode(EVENTS4_PIN_MODE);
  1511. sensor->setDebounceTime(EVENTS4_DEBOUNCE);
  1512. sensor->setInterruptMode(EVENTS4_INTERRUPT_MODE);
  1513. _sensors.push_back(sensor);
  1514. }
  1515. #endif
  1516. #if (EVENTS5_PIN != GPIO_NONE)
  1517. {
  1518. EventSensor * sensor = new EventSensor();
  1519. sensor->setGPIO(EVENTS5_PIN);
  1520. sensor->setTrigger(EVENTS5_TRIGGER);
  1521. sensor->setPinMode(EVENTS5_PIN_MODE);
  1522. sensor->setDebounceTime(EVENTS5_DEBOUNCE);
  1523. sensor->setInterruptMode(EVENTS5_INTERRUPT_MODE);
  1524. _sensors.push_back(sensor);
  1525. }
  1526. #endif
  1527. #if (EVENTS6_PIN != GPIO_NONE)
  1528. {
  1529. EventSensor * sensor = new EventSensor();
  1530. sensor->setGPIO(EVENTS6_PIN);
  1531. sensor->setTrigger(EVENTS6_TRIGGER);
  1532. sensor->setPinMode(EVENTS6_PIN_MODE);
  1533. sensor->setDebounceTime(EVENTS6_DEBOUNCE);
  1534. sensor->setInterruptMode(EVENTS6_INTERRUPT_MODE);
  1535. _sensors.push_back(sensor);
  1536. }
  1537. #endif
  1538. #if (EVENTS7_PIN != GPIO_NONE)
  1539. {
  1540. EventSensor * sensor = new EventSensor();
  1541. sensor->setGPIO(EVENTS7_PIN);
  1542. sensor->setTrigger(EVENTS7_TRIGGER);
  1543. sensor->setPinMode(EVENTS7_PIN_MODE);
  1544. sensor->setDebounceTime(EVENTS7_DEBOUNCE);
  1545. sensor->setInterruptMode(EVENTS7_INTERRUPT_MODE);
  1546. _sensors.push_back(sensor);
  1547. }
  1548. #endif
  1549. #if (EVENTS8_PIN != GPIO_NONE)
  1550. {
  1551. EventSensor * sensor = new EventSensor();
  1552. sensor->setGPIO(EVENTS8_PIN);
  1553. sensor->setTrigger(EVENTS8_TRIGGER);
  1554. sensor->setPinMode(EVENTS8_PIN_MODE);
  1555. sensor->setDebounceTime(EVENTS8_DEBOUNCE);
  1556. sensor->setInterruptMode(EVENTS8_INTERRUPT_MODE);
  1557. _sensors.push_back(sensor);
  1558. }
  1559. #endif
  1560. }
  1561. #endif
  1562. #if GEIGER_SUPPORT
  1563. {
  1564. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1565. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1566. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1567. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1568. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1569. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1570. _sensors.push_back(sensor);
  1571. }
  1572. #endif
  1573. #if GUVAS12SD_SUPPORT
  1574. {
  1575. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1576. sensor->setGPIO(GUVAS12SD_PIN);
  1577. _sensors.push_back(sensor);
  1578. }
  1579. #endif
  1580. #if SONAR_SUPPORT
  1581. {
  1582. SonarSensor * sensor = new SonarSensor();
  1583. sensor->setEcho(SONAR_ECHO);
  1584. sensor->setIterations(SONAR_ITERATIONS);
  1585. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1586. sensor->setTrigger(SONAR_TRIGGER);
  1587. _sensors.push_back(sensor);
  1588. }
  1589. #endif
  1590. #if HLW8012_SUPPORT
  1591. {
  1592. HLW8012Sensor * sensor = new HLW8012Sensor();
  1593. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1594. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1595. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1596. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1597. _sensors.push_back(sensor);
  1598. }
  1599. #endif
  1600. #if LDR_SUPPORT
  1601. {
  1602. LDRSensor * sensor = new LDRSensor();
  1603. sensor->setSamples(LDR_SAMPLES);
  1604. sensor->setDelay(LDR_DELAY);
  1605. sensor->setType(LDR_TYPE);
  1606. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1607. sensor->setResistor(LDR_RESISTOR);
  1608. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1609. _sensors.push_back(sensor);
  1610. }
  1611. #endif
  1612. #if MHZ19_SUPPORT
  1613. {
  1614. MHZ19Sensor * sensor = new MHZ19Sensor();
  1615. sensor->setRX(MHZ19_RX_PIN);
  1616. sensor->setTX(MHZ19_TX_PIN);
  1617. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1618. _sensors.push_back(sensor);
  1619. }
  1620. #endif
  1621. #if MICS2710_SUPPORT
  1622. {
  1623. MICS2710Sensor * sensor = new MICS2710Sensor();
  1624. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1625. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1626. sensor->setR0(MICS2710_R0);
  1627. sensor->setRL(MICS2710_RL);
  1628. sensor->setRS(0);
  1629. _sensors.push_back(sensor);
  1630. }
  1631. #endif
  1632. #if MICS5525_SUPPORT
  1633. {
  1634. MICS5525Sensor * sensor = new MICS5525Sensor();
  1635. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1636. sensor->setR0(MICS5525_R0);
  1637. sensor->setRL(MICS5525_RL);
  1638. sensor->setRS(0);
  1639. _sensors.push_back(sensor);
  1640. }
  1641. #endif
  1642. #if NTC_SUPPORT
  1643. {
  1644. NTCSensor * sensor = new NTCSensor();
  1645. sensor->setSamples(NTC_SAMPLES);
  1646. sensor->setDelay(NTC_DELAY);
  1647. sensor->setUpstreamResistor(NTC_R_UP);
  1648. sensor->setDownstreamResistor(NTC_R_DOWN);
  1649. sensor->setBeta(NTC_BETA);
  1650. sensor->setR0(NTC_R0);
  1651. sensor->setT0(NTC_T0);
  1652. _sensors.push_back(sensor);
  1653. }
  1654. #endif
  1655. #if PMSX003_SUPPORT
  1656. {
  1657. PMSX003Sensor * sensor = new PMSX003Sensor();
  1658. #if PMS_USE_SOFT
  1659. sensor->setRX(PMS_RX_PIN);
  1660. sensor->setTX(PMS_TX_PIN);
  1661. #else
  1662. sensor->setSerial(& PMS_HW_PORT);
  1663. #endif
  1664. sensor->setType(PMS_TYPE);
  1665. _sensors.push_back(sensor);
  1666. }
  1667. #endif
  1668. #if PULSEMETER_SUPPORT
  1669. {
  1670. PulseMeterSensor * sensor = new PulseMeterSensor();
  1671. sensor->setGPIO(PULSEMETER_PIN);
  1672. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1673. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1674. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1675. _sensors.push_back(sensor);
  1676. }
  1677. #endif
  1678. #if PZEM004T_SUPPORT
  1679. {
  1680. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1681. if (!addresses.length()) {
  1682. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1683. return;
  1684. }
  1685. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1686. sensor->setAddresses(addresses.c_str());
  1687. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1688. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1689. if (!getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1690. sensor->setSerial(& PZEM004T_HW_PORT);
  1691. }
  1692. _sensors.push_back(sensor);
  1693. #if TERMINAL_SUPPORT
  1694. pzem004tInitCommands();
  1695. #endif
  1696. }
  1697. #endif
  1698. #if SENSEAIR_SUPPORT
  1699. {
  1700. SenseAirSensor * sensor = new SenseAirSensor();
  1701. sensor->setRX(SENSEAIR_RX_PIN);
  1702. sensor->setTX(SENSEAIR_TX_PIN);
  1703. _sensors.push_back(sensor);
  1704. }
  1705. #endif
  1706. #if SDS011_SUPPORT
  1707. {
  1708. SDS011Sensor * sensor = new SDS011Sensor();
  1709. sensor->setRX(SDS011_RX_PIN);
  1710. sensor->setTX(SDS011_TX_PIN);
  1711. _sensors.push_back(sensor);
  1712. }
  1713. #endif
  1714. #if SHT3X_I2C_SUPPORT
  1715. {
  1716. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1717. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1718. _sensors.push_back(sensor);
  1719. }
  1720. #endif
  1721. #if SI7021_SUPPORT
  1722. {
  1723. SI7021Sensor * sensor = new SI7021Sensor();
  1724. sensor->setAddress(SI7021_ADDRESS);
  1725. _sensors.push_back(sensor);
  1726. }
  1727. #endif
  1728. #if T6613_SUPPORT
  1729. {
  1730. T6613Sensor * sensor = new T6613Sensor();
  1731. sensor->setRX(T6613_RX_PIN);
  1732. sensor->setTX(T6613_TX_PIN);
  1733. _sensors.push_back(sensor);
  1734. }
  1735. #endif
  1736. #if TMP3X_SUPPORT
  1737. {
  1738. TMP3XSensor * sensor = new TMP3XSensor();
  1739. sensor->setType(TMP3X_TYPE);
  1740. _sensors.push_back(sensor);
  1741. }
  1742. #endif
  1743. #if V9261F_SUPPORT
  1744. {
  1745. V9261FSensor * sensor = new V9261FSensor();
  1746. sensor->setRX(V9261F_PIN);
  1747. sensor->setInverted(V9261F_PIN_INVERSE);
  1748. _sensors.push_back(sensor);
  1749. }
  1750. #endif
  1751. #if MAX6675_SUPPORT
  1752. {
  1753. MAX6675Sensor * sensor = new MAX6675Sensor();
  1754. sensor->setCS(MAX6675_CS_PIN);
  1755. sensor->setSO(MAX6675_SO_PIN);
  1756. sensor->setSCK(MAX6675_SCK_PIN);
  1757. _sensors.push_back(sensor);
  1758. }
  1759. #endif
  1760. #if VEML6075_SUPPORT
  1761. {
  1762. VEML6075Sensor * sensor = new VEML6075Sensor();
  1763. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1764. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1765. _sensors.push_back(sensor);
  1766. }
  1767. #endif
  1768. #if VL53L1X_SUPPORT
  1769. {
  1770. VL53L1XSensor * sensor = new VL53L1XSensor();
  1771. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1772. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1773. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1774. _sensors.push_back(sensor);
  1775. }
  1776. #endif
  1777. #if EZOPH_SUPPORT
  1778. {
  1779. EZOPHSensor * sensor = new EZOPHSensor();
  1780. sensor->setRX(EZOPH_RX_PIN);
  1781. sensor->setTX(EZOPH_TX_PIN);
  1782. _sensors.push_back(sensor);
  1783. }
  1784. #endif
  1785. #if ADE7953_SUPPORT
  1786. {
  1787. ADE7953Sensor * sensor = new ADE7953Sensor();
  1788. sensor->setAddress(ADE7953_ADDRESS);
  1789. _sensors.push_back(sensor);
  1790. }
  1791. #endif
  1792. #if SI1145_SUPPORT
  1793. {
  1794. SI1145Sensor * sensor = new SI1145Sensor();
  1795. sensor->setAddress(SI1145_ADDRESS);
  1796. _sensors.push_back(sensor);
  1797. }
  1798. #endif
  1799. #if HDC1080_SUPPORT
  1800. {
  1801. HDC1080Sensor * sensor = new HDC1080Sensor();
  1802. sensor->setAddress(HDC1080_ADDRESS);
  1803. _sensors.push_back(sensor);
  1804. }
  1805. #endif
  1806. #if PZEM004TV30_SUPPORT
  1807. {
  1808. PZEM004TV30Sensor * sensor = PZEM004TV30Sensor::create();
  1809. // TODO: we need an equivalent to the `pzem.address` command
  1810. sensor->setAddress(getSetting("pzemv30Addr", PZEM004TV30Sensor::DefaultAddress));
  1811. sensor->setReadTimeout(getSetting("pzemv30ReadTimeout", PZEM004TV30Sensor::DefaultReadTimeout));
  1812. sensor->setDebug(getSetting("pzemv30Debug", 1 == PZEM004TV30_DEBUG));
  1813. bool soft = getSetting("pzemv30Soft", 1 == PZEM004TV30_USE_SOFT);
  1814. int tx = getSetting("pzemv30TX", PZEM004TV30_TX_PIN);
  1815. int rx = getSetting("pzemv30RX", PZEM004TV30_RX_PIN);
  1816. // we operate only with Serial, as Serial1 cannot not receive any data
  1817. if (!soft) {
  1818. sensor->setStream(&Serial);
  1819. sensor->setDescription("HwSerial");
  1820. Serial.begin(PZEM004TV30Sensor::Baudrate);
  1821. // Core does not allow us to begin(baud, cfg, rx, tx) / pins(rx, tx) before begin(baud)
  1822. // b/c internal UART handler does not exist yet
  1823. // Also see https://github.com/esp8266/Arduino/issues/2380 as to why there is flush()
  1824. if ((tx == 15) && (rx == 13)) {
  1825. Serial.flush();
  1826. Serial.swap();
  1827. }
  1828. } else {
  1829. auto* ptr = new SoftwareSerial(rx, tx);
  1830. sensor->setDescription("SwSerial");
  1831. sensor->setStream(ptr); // we don't care about lifetime
  1832. ptr->begin(PZEM004TV30Sensor::Baudrate);
  1833. }
  1834. //TODO: getSetting("pzemv30*Cfg", (SW)SERIAL_8N1); ?
  1835. // may not be relevant, but some sources claim we need 8N2
  1836. _sensors.push_back(sensor);
  1837. }
  1838. #endif
  1839. }
  1840. void _sensorReport(unsigned char index, double value) {
  1841. const auto& magnitude = _magnitudes.at(index);
  1842. // XXX: ensure that the received 'value' will fit here
  1843. // dtostrf 2nd arg only controls leading zeroes and the
  1844. // 3rd is only for the part after the dot
  1845. char buffer[64];
  1846. dtostrf(value, 1, magnitude.decimals, buffer);
  1847. #if BROKER_SUPPORT
  1848. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value, buffer);
  1849. #endif
  1850. #if MQTT_SUPPORT
  1851. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1852. #if SENSOR_PUBLISH_ADDRESSES
  1853. char topic[32];
  1854. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1855. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1856. mqttSend(topic, magnitude.index_global, magnitude.sensor->address(magnitude.slot).c_str());
  1857. } else {
  1858. mqttSend(topic, magnitude.sensor->address(magnitude.slot).c_str());
  1859. }
  1860. #endif // SENSOR_PUBLISH_ADDRESSES
  1861. #endif // MQTT_SUPPORT
  1862. #if THINGSPEAK_SUPPORT
  1863. tspkEnqueueMeasurement(index, buffer);
  1864. #endif // THINGSPEAK_SUPPORT
  1865. #if DOMOTICZ_SUPPORT
  1866. domoticzSendMagnitude(magnitude.type, index, value, buffer);
  1867. #endif // DOMOTICZ_SUPPORT
  1868. }
  1869. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  1870. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  1871. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  1872. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  1873. _sensorReport(k, value);
  1874. return;
  1875. }
  1876. }
  1877. }
  1878. void _sensorInit() {
  1879. _sensors_ready = true;
  1880. for (unsigned char i=0; i<_sensors.size(); i++) {
  1881. // Do not process an already initialized sensor
  1882. if (_sensors[i]->ready()) continue;
  1883. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  1884. // Force sensor to reload config
  1885. _sensors[i]->begin();
  1886. if (!_sensors[i]->ready()) {
  1887. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  1888. _sensors_ready = false;
  1889. break;
  1890. }
  1891. // Initialize sensor magnitudes
  1892. for (unsigned char magnitude_index = 0; magnitude_index < _sensors[i]->count(); ++magnitude_index) {
  1893. const auto magnitude_type = _sensors[i]->type(magnitude_index);
  1894. const auto magnitude_local = _sensors[i]->local(magnitude_type);
  1895. _magnitudes.emplace_back(
  1896. magnitude_index, // id of the magnitude, unique to the sensor
  1897. magnitude_local, // index_local, # of the magnitude
  1898. magnitude_type, // specific type of the magnitude
  1899. sensor::Unit::None, // set up later, in configuration
  1900. _sensors[i] // bind the sensor to allow us to reference it later
  1901. );
  1902. if (_sensorIsEmon(_sensors[i]) && (MAGNITUDE_ENERGY == magnitude_type)) {
  1903. const auto index_global = _magnitudes.back().index_global;
  1904. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[i]);
  1905. sensor->resetEnergy(magnitude_local, _sensorEnergyTotal(index_global));
  1906. _sensor_save_count.push_back(0);
  1907. }
  1908. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1909. magnitudeTopic(magnitude_type).c_str(),
  1910. sensor_magnitude_t::counts(magnitude_type)
  1911. );
  1912. }
  1913. // Hook callback
  1914. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1915. _sensorCallback(i, type, value);
  1916. });
  1917. // Custom initializations, based on IDs
  1918. switch (_sensors[i]->getID()) {
  1919. case SENSOR_MICS2710_ID:
  1920. case SENSOR_MICS5525_ID: {
  1921. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[i]);
  1922. sensor->setR0(getSetting("snsR0", sensor->getR0()));
  1923. sensor->setRS(getSetting("snsRS", sensor->getRS()));
  1924. sensor->setRL(getSetting("snsRL", sensor->getRL()));
  1925. break;
  1926. }
  1927. default:
  1928. break;
  1929. }
  1930. }
  1931. }
  1932. namespace settings {
  1933. namespace internal {
  1934. template <>
  1935. sensor::Unit convert(const String& string) {
  1936. const int value = string.toInt();
  1937. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1938. return static_cast<sensor::Unit>(value);
  1939. }
  1940. return sensor::Unit::None;
  1941. }
  1942. template <>
  1943. String serialize(const sensor::Unit& unit) {
  1944. return String(static_cast<int>(unit));
  1945. }
  1946. } // ns settings::internal
  1947. } // ns settings
  1948. void _sensorConfigure() {
  1949. // General sensor settings for reporting and saving
  1950. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1951. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1952. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  1953. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  1954. // pre-load some settings that are controlled via old build flags
  1955. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  1956. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  1957. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  1958. // Apply settings based on sensor type
  1959. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  1960. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1961. {
  1962. if (getSetting("snsResetCalibration", false)) {
  1963. switch (_sensors[index]->getID()) {
  1964. case SENSOR_MICS2710_ID:
  1965. case SENSOR_MICS5525_ID: {
  1966. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  1967. sensor->calibrate();
  1968. setSetting("snsR0", sensor->getR0());
  1969. break;
  1970. }
  1971. default:
  1972. break;
  1973. }
  1974. }
  1975. }
  1976. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  1977. if (_sensorIsEmon(_sensors[index])) {
  1978. // TODO: ::isEmon() ?
  1979. double value;
  1980. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  1981. if ((value = getSetting("pwrExpectedC", 0.0))) {
  1982. sensor->expectedCurrent(value);
  1983. delSetting("pwrExpectedC");
  1984. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1985. }
  1986. if ((value = getSetting("pwrExpectedV", 0.0))) {
  1987. delSetting("pwrExpectedV");
  1988. sensor->expectedVoltage(value);
  1989. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1990. }
  1991. if ((value = getSetting("pwrExpectedP", 0.0))) {
  1992. delSetting("pwrExpectedP");
  1993. sensor->expectedPower(value);
  1994. setSetting("pwrRatioP", sensor->getPowerRatio());
  1995. }
  1996. if (getSetting("pwrResetE", false)) {
  1997. delSetting("pwrResetE");
  1998. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1999. sensor->resetEnergy(index);
  2000. _sensorResetEnergyTotal(index);
  2001. }
  2002. }
  2003. if (getSetting("pwrResetCalibration", false)) {
  2004. delSetting("pwrResetCalibration");
  2005. delSetting("pwrRatioC");
  2006. delSetting("pwrRatioV");
  2007. delSetting("pwrRatioP");
  2008. sensor->resetRatios();
  2009. }
  2010. } // is emon?
  2011. }
  2012. // Update magnitude config, filter sizes and reset energy if needed
  2013. {
  2014. // TODO: instead of using global enum, have a local mapping?
  2015. const auto tmpUnits = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS);
  2016. const auto pwrUnits = getSetting("pwrUnits", SENSOR_POWER_UNITS);
  2017. const auto eneUnits = getSetting("eneUnits", SENSOR_ENERGY_UNITS);
  2018. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  2019. auto& magnitude = _magnitudes.at(index);
  2020. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  2021. if (_sensorIsEmon(magnitude.sensor)) {
  2022. // TODO: compatibility proxy, fetch global key before indexed
  2023. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  2024. return getSetting({key, index}, getSetting(key, default_value));
  2025. };
  2026. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  2027. switch (magnitude.type) {
  2028. case MAGNITUDE_CURRENT:
  2029. sensor->setCurrentRatio(
  2030. magnitude.index_local, get_ratio("pwrRatioC", magnitude.index_global, sensor->defaultCurrentRatio())
  2031. );
  2032. break;
  2033. case MAGNITUDE_POWER_ACTIVE:
  2034. sensor->setPowerRatio(
  2035. magnitude.index_local, get_ratio("pwrRatioP", magnitude.index_global, sensor->defaultPowerRatio())
  2036. );
  2037. break;
  2038. case MAGNITUDE_VOLTAGE:
  2039. sensor->setVoltageRatio(
  2040. magnitude.index_local, get_ratio("pwrRatioV", magnitude.index_global, sensor->defaultVoltageRatio())
  2041. );
  2042. sensor->setVoltage(
  2043. magnitude.index_local, get_ratio("pwrVoltage", magnitude.index_global, sensor->defaultVoltage())
  2044. );
  2045. break;
  2046. case MAGNITUDE_ENERGY:
  2047. sensor->setEnergyRatio(
  2048. magnitude.index_local, get_ratio("pwrRatioE", magnitude.index_global, sensor->defaultEnergyRatio())
  2049. );
  2050. break;
  2051. default:
  2052. break;
  2053. }
  2054. }
  2055. // adjust type-specific units (TODO: try to adjust settings to use type prefixes?)
  2056. switch (magnitude.type) {
  2057. case MAGNITUDE_TEMPERATURE:
  2058. magnitude.units = _magnitudeUnitFilter(
  2059. magnitude,
  2060. getSetting({"tmpUnits", magnitude.index_global}, tmpUnits)
  2061. );
  2062. break;
  2063. case MAGNITUDE_POWER_ACTIVE:
  2064. magnitude.units = _magnitudeUnitFilter(
  2065. magnitude,
  2066. getSetting({"pwrUnits", magnitude.index_global}, pwrUnits)
  2067. );
  2068. break;
  2069. case MAGNITUDE_ENERGY:
  2070. magnitude.units = _magnitudeUnitFilter(
  2071. magnitude,
  2072. getSetting({"eneUnits", magnitude.index_global}, eneUnits)
  2073. );
  2074. break;
  2075. default:
  2076. magnitude.units = magnitude.sensor->units(magnitude.slot);
  2077. break;
  2078. }
  2079. // some magnitudes allow to be corrected with an offset
  2080. {
  2081. if (_magnitudeCanUseCorrection(magnitude.type)) {
  2082. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  2083. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  2084. }
  2085. }
  2086. // some sensors can override decimal values if sensor has more precision than default
  2087. {
  2088. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  2089. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  2090. magnitude.decimals = (unsigned char) decimals;
  2091. }
  2092. // Per-magnitude min & max delta settings
  2093. // - min controls whether we report at all when report_count overflows
  2094. // - max will trigger report as soon as read value is greater than the specified delta
  2095. // (atm this works best for accumulated magnitudes, like energy)
  2096. {
  2097. auto min_default = 0.0;
  2098. auto max_default = 0.0;
  2099. switch (magnitude.type) {
  2100. case MAGNITUDE_TEMPERATURE:
  2101. min_default = tmp_min_delta;
  2102. break;
  2103. case MAGNITUDE_HUMIDITY:
  2104. min_default = hum_min_delta;
  2105. break;
  2106. case MAGNITUDE_ENERGY:
  2107. max_default = ene_max_delta;
  2108. break;
  2109. default:
  2110. break;
  2111. }
  2112. magnitude.min_change = getSetting(
  2113. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2114. min_default
  2115. );
  2116. magnitude.max_change = getSetting(
  2117. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2118. max_default
  2119. );
  2120. }
  2121. // Sometimes we want to ensure the value is above certain threshold before reporting
  2122. {
  2123. magnitude.zero_threshold = getSetting(
  2124. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2125. std::numeric_limits<double>::quiet_NaN()
  2126. );
  2127. }
  2128. // in case we don't save energy periodically, purge existing value in ram & settings
  2129. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2130. _sensorResetEnergyTotal(magnitude.index_global);
  2131. }
  2132. }
  2133. }
  2134. saveSettings();
  2135. }
  2136. // -----------------------------------------------------------------------------
  2137. // Public
  2138. // -----------------------------------------------------------------------------
  2139. unsigned char sensorCount() {
  2140. return _sensors.size();
  2141. }
  2142. unsigned char magnitudeCount() {
  2143. return _magnitudes.size();
  2144. }
  2145. unsigned char magnitudeType(unsigned char index) {
  2146. if (index < _magnitudes.size()) {
  2147. return _magnitudes[index].type;
  2148. }
  2149. return MAGNITUDE_NONE;
  2150. }
  2151. double magnitudeValue(unsigned char index) {
  2152. if (index < _magnitudes.size()) {
  2153. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  2154. }
  2155. return DBL_MIN;
  2156. }
  2157. unsigned char magnitudeIndex(unsigned char index) {
  2158. if (index < _magnitudes.size()) {
  2159. return _magnitudes[index].index_global;
  2160. }
  2161. return 0;
  2162. }
  2163. String magnitudeDescription(unsigned char index) {
  2164. if (index < _magnitudes.size()) {
  2165. return _magnitudeDescription(_magnitudes[index]);
  2166. }
  2167. return String();
  2168. }
  2169. String magnitudeTopicIndex(unsigned char index) {
  2170. char topic[32] = {0};
  2171. if (index < _magnitudes.size()) {
  2172. sensor_magnitude_t magnitude = _magnitudes[index];
  2173. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  2174. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.index_global);
  2175. } else {
  2176. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  2177. }
  2178. }
  2179. return String(topic);
  2180. }
  2181. // -----------------------------------------------------------------------------
  2182. void _sensorBackwards() {
  2183. // Some keys from older versions were longer
  2184. moveSetting("powerUnits", "pwrUnits");
  2185. moveSetting("energyUnits", "eneUnits");
  2186. // Energy is now indexed (based on magnitude.index_global)
  2187. moveSetting("eneTotal", "eneTotal0");
  2188. // Update PZEM004T energy total across multiple devices
  2189. moveSettings("pzEneTotal", "eneTotal");
  2190. // Unit ID is no longer shared, drop when equal to Min_ or None
  2191. const char *keys[3] = {
  2192. "pwrUnits", "eneUnits", "tmpUnits"
  2193. };
  2194. for (auto* key : keys) {
  2195. const auto units = getSetting(key);
  2196. if (units.length() && (units.equals("0") || units.equals("1"))) {
  2197. delSetting(key);
  2198. }
  2199. }
  2200. }
  2201. void sensorSetup() {
  2202. // Settings backwards compatibility
  2203. _sensorBackwards();
  2204. // Load configured sensors and set up all of magnitudes
  2205. _sensorLoad();
  2206. _sensorInit();
  2207. // Configure based on settings
  2208. _sensorConfigure();
  2209. // Allow us to query key default
  2210. settingsRegisterDefaults({
  2211. [](const char* key) -> bool {
  2212. if (strncmp(key, "pwr", 3) == 0) return true;
  2213. return false;
  2214. },
  2215. _sensorQueryDefault
  2216. });
  2217. // Websockets integration, send sensor readings and configuration
  2218. #if WEB_SUPPORT
  2219. wsRegister()
  2220. .onVisible(_sensorWebSocketOnVisible)
  2221. .onConnected(_sensorWebSocketOnConnected)
  2222. .onData(_sensorWebSocketSendData)
  2223. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2224. #endif
  2225. // MQTT receive callback, atm only for energy reset
  2226. #if MQTT_SUPPORT
  2227. mqttRegister(_sensorMqttCallback);
  2228. #endif
  2229. // API
  2230. #if API_SUPPORT
  2231. _sensorAPISetup();
  2232. #endif
  2233. // Terminal
  2234. #if TERMINAL_SUPPORT
  2235. _sensorInitCommands();
  2236. #endif
  2237. // Main callbacks
  2238. espurnaRegisterLoop(sensorLoop);
  2239. espurnaRegisterReload(_sensorConfigure);
  2240. }
  2241. void sensorLoop() {
  2242. // Check if we still have uninitialized sensors
  2243. static unsigned long last_init = 0;
  2244. if (!_sensors_ready) {
  2245. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2246. last_init = millis();
  2247. _sensorInit();
  2248. }
  2249. }
  2250. if (_magnitudes.size() == 0) return;
  2251. // Tick hook, called every loop()
  2252. _sensorTick();
  2253. // Check if we should read new data
  2254. static unsigned long last_update = 0;
  2255. static unsigned long report_count = 0;
  2256. if (millis() - last_update > _sensor_read_interval) {
  2257. last_update = millis();
  2258. report_count = (report_count + 1) % _sensor_report_every;
  2259. double value_raw; // holds the raw value as the sensor returns it
  2260. double value_show; // holds the processed value applying units and decimals
  2261. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2262. // Pre-read hook, called every reading
  2263. _sensorPre();
  2264. // Get the first relay state
  2265. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2266. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2267. #endif
  2268. // Get readings
  2269. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  2270. sensor_magnitude_t magnitude = _magnitudes[i];
  2271. if (magnitude.sensor->status()) {
  2272. // -------------------------------------------------------------
  2273. // Instant value
  2274. // -------------------------------------------------------------
  2275. value_raw = magnitude.sensor->value(magnitude.slot);
  2276. // Completely remove spurious values if relay is OFF
  2277. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2278. switch (magnitude.type) {
  2279. case MAGNITUDE_POWER_ACTIVE:
  2280. case MAGNITUDE_POWER_REACTIVE:
  2281. case MAGNITUDE_POWER_APPARENT:
  2282. case MAGNITUDE_POWER_FACTOR:
  2283. case MAGNITUDE_CURRENT:
  2284. case MAGNITUDE_ENERGY_DELTA:
  2285. if (relay_off) {
  2286. value_raw = 0.0;
  2287. }
  2288. break;
  2289. default:
  2290. break;
  2291. }
  2292. #endif
  2293. // In addition to that, we also check that value is above a certain threshold
  2294. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2295. value_raw = 0.0;
  2296. }
  2297. _magnitudes[i].last = value_raw;
  2298. // -------------------------------------------------------------
  2299. // Processing (filters)
  2300. // -------------------------------------------------------------
  2301. magnitude.filter->add(value_raw);
  2302. // Special case for MovingAverageFilter
  2303. switch (magnitude.type) {
  2304. case MAGNITUDE_COUNT:
  2305. case MAGNITUDE_GEIGER_CPM:
  2306. case MAGNITUDE_GEIGER_SIEVERT:
  2307. value_raw = magnitude.filter->result();
  2308. break;
  2309. default:
  2310. break;
  2311. }
  2312. // -------------------------------------------------------------
  2313. // Procesing (units and decimals)
  2314. // -------------------------------------------------------------
  2315. value_show = _magnitudeProcess(magnitude, value_raw);
  2316. #if BROKER_SUPPORT
  2317. {
  2318. char buffer[64];
  2319. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2320. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2321. }
  2322. #endif
  2323. // -------------------------------------------------------------
  2324. // Debug
  2325. // -------------------------------------------------------------
  2326. #if SENSOR_DEBUG
  2327. {
  2328. char buffer[64];
  2329. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2330. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2331. _magnitudeDescription(magnitude).c_str(),
  2332. magnitudeTopic(magnitude.type).c_str(),
  2333. buffer,
  2334. _magnitudeUnits(magnitude).c_str()
  2335. );
  2336. }
  2337. #endif // SENSOR_DEBUG
  2338. // -------------------------------------------------------------------
  2339. // Report when
  2340. // - report_count overflows after reaching _sensor_report_every
  2341. // - when magnitude specifies max_change and we greater or equal to it
  2342. // -------------------------------------------------------------------
  2343. bool report = (0 == report_count);
  2344. if (magnitude.max_change > 0) {
  2345. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  2346. }
  2347. // Special case for energy, save readings to RAM and EEPROM
  2348. if (MAGNITUDE_ENERGY == magnitude.type) {
  2349. _magnitudeSaveEnergyTotal(magnitude, report);
  2350. }
  2351. if (report) {
  2352. value_filtered = magnitude.filter->result();
  2353. value_filtered = _magnitudeProcess(magnitude, value_filtered);
  2354. magnitude.filter->reset();
  2355. if (magnitude.filter->size() != _sensor_report_every) {
  2356. magnitude.filter->resize(_sensor_report_every);
  2357. }
  2358. // Check if there is a minimum change threshold to report
  2359. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  2360. _magnitudes[i].reported = value_filtered;
  2361. _sensorReport(i, value_filtered);
  2362. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  2363. } // if (report_count == 0)
  2364. } // if (magnitude.sensor->status())
  2365. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  2366. // Post-read hook, called every reading
  2367. _sensorPost();
  2368. // And report data to modules that don't specifically track them
  2369. #if WEB_SUPPORT
  2370. wsPost(_sensorWebSocketSendData);
  2371. #endif
  2372. #if THINGSPEAK_SUPPORT
  2373. if (report_count == 0) tspkFlush();
  2374. #endif
  2375. }
  2376. }
  2377. #endif // SENSOR_SUPPORT