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.

2371 lines
70 KiB

7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "sensor.h"
  6. #if SENSOR_SUPPORT
  7. #include <vector>
  8. #include <float.h>
  9. #include "api.h"
  10. #include "broker.h"
  11. #include "domoticz.h"
  12. #include "i2c.h"
  13. #include "mqtt.h"
  14. #include "ntp.h"
  15. #include "relay.h"
  16. #include "terminal.h"
  17. #include "thingspeak.h"
  18. #include "rtcmem.h"
  19. #include "ws.h"
  20. //--------------------------------------------------------------------------------
  21. // TODO: namespace { ... } ? sensor ctors need to work though
  22. #include "filters/LastFilter.h"
  23. #include "filters/MaxFilter.h"
  24. #include "filters/MedianFilter.h"
  25. #include "filters/MovingAverageFilter.h"
  26. #include "filters/SumFilter.h"
  27. #include "sensors/BaseSensor.h"
  28. #include "sensors/BaseEmonSensor.h"
  29. #include "sensors/BaseAnalogSensor.h"
  30. #if AM2320_SUPPORT
  31. #include "sensors/AM2320Sensor.h"
  32. #endif
  33. #if ANALOG_SUPPORT
  34. #include "sensors/AnalogSensor.h"
  35. #endif
  36. #if BH1750_SUPPORT
  37. #include "sensors/BH1750Sensor.h"
  38. #endif
  39. #if BMP180_SUPPORT
  40. #include "sensors/BMP180Sensor.h"
  41. #endif
  42. #if BMX280_SUPPORT
  43. #include "sensors/BMX280Sensor.h"
  44. #endif
  45. #if CSE7766_SUPPORT
  46. #include "sensors/CSE7766Sensor.h"
  47. #endif
  48. #if DALLAS_SUPPORT
  49. #include "sensors/DallasSensor.h"
  50. #endif
  51. #if DHT_SUPPORT
  52. #include "sensors/DHTSensor.h"
  53. #endif
  54. #if DIGITAL_SUPPORT
  55. #include "sensors/DigitalSensor.h"
  56. #endif
  57. #if ECH1560_SUPPORT
  58. #include "sensors/ECH1560Sensor.h"
  59. #endif
  60. #if EMON_ADC121_SUPPORT
  61. #include "sensors/EmonADC121Sensor.h"
  62. #endif
  63. #if EMON_ADS1X15_SUPPORT
  64. #include "sensors/EmonADS1X15Sensor.h"
  65. #endif
  66. #if EMON_ANALOG_SUPPORT
  67. #include "sensors/EmonAnalogSensor.h"
  68. #endif
  69. #if EVENTS_SUPPORT
  70. #include "sensors/EventSensor.h"
  71. #endif
  72. #if EZOPH_SUPPORT
  73. #include "sensors/EZOPHSensor.h"
  74. #endif
  75. #if GEIGER_SUPPORT
  76. #include "sensors/GeigerSensor.h"
  77. #endif
  78. #if GUVAS12SD_SUPPORT
  79. #include "sensors/GUVAS12SDSensor.h"
  80. #endif
  81. #if HLW8012_SUPPORT
  82. #include "sensors/HLW8012Sensor.h"
  83. #endif
  84. #if LDR_SUPPORT
  85. #include "sensors/LDRSensor.h"
  86. #endif
  87. #if MAX6675_SUPPORT
  88. #include "sensors/MAX6675Sensor.h"
  89. #endif
  90. #if MICS2710_SUPPORT
  91. #include "sensors/MICS2710Sensor.h"
  92. #endif
  93. #if MICS5525_SUPPORT
  94. #include "sensors/MICS5525Sensor.h"
  95. #endif
  96. #if MHZ19_SUPPORT
  97. #include "sensors/MHZ19Sensor.h"
  98. #endif
  99. #if NTC_SUPPORT
  100. #include "sensors/NTCSensor.h"
  101. #endif
  102. #if SDS011_SUPPORT
  103. #include "sensors/SDS011Sensor.h"
  104. #endif
  105. #if SENSEAIR_SUPPORT
  106. #include "sensors/SenseAirSensor.h"
  107. #endif
  108. #if PMSX003_SUPPORT
  109. #include "sensors/PMSX003Sensor.h"
  110. #endif
  111. #if PULSEMETER_SUPPORT
  112. #include "sensors/PulseMeterSensor.h"
  113. #endif
  114. #if PZEM004T_SUPPORT
  115. #include "sensors/PZEM004TSensor.h"
  116. #endif
  117. #if SHT3X_I2C_SUPPORT
  118. #include "sensors/SHT3XI2CSensor.h"
  119. #endif
  120. #if SI7021_SUPPORT
  121. #include "sensors/SI7021Sensor.h"
  122. #endif
  123. #if SONAR_SUPPORT
  124. #include "sensors/SonarSensor.h"
  125. #endif
  126. #if T6613_SUPPORT
  127. #include "sensors/T6613Sensor.h"
  128. #endif
  129. #if TMP3X_SUPPORT
  130. #include "sensors/TMP3XSensor.h"
  131. #endif
  132. #if V9261F_SUPPORT
  133. #include "sensors/V9261FSensor.h"
  134. #endif
  135. #if VEML6075_SUPPORT
  136. #include "sensors/VEML6075Sensor.h"
  137. #endif
  138. #if VL53L1X_SUPPORT
  139. #include "sensors/VL53L1XSensor.h"
  140. #endif
  141. #if ADE7953_SUPPORT
  142. #include "sensors/ADE7953Sensor.h"
  143. #endif
  144. #if SI1145_SUPPORT
  145. #include "sensors/SI1145Sensor.h"
  146. #endif
  147. #if HDC1080_SUPPORT
  148. #include "sensors/HDC1080Sensor.h"
  149. #endif
  150. //--------------------------------------------------------------------------------
  151. struct sensor_magnitude_t {
  152. private:
  153. static unsigned char _counts[MAGNITUDE_MAX];
  154. public:
  155. static unsigned char counts(unsigned char type) {
  156. return _counts[type];
  157. }
  158. sensor_magnitude_t();
  159. sensor_magnitude_t(unsigned char type, unsigned char local, sensor::Unit units, BaseSensor* sensor);
  160. BaseSensor * sensor; // Sensor object
  161. BaseFilter * filter; // Filter object
  162. unsigned char type; // Type of measurement
  163. unsigned char local; // Local index in its provider
  164. unsigned char global; // Global index in its type
  165. unsigned char decimals; // Number of decimals in textual representation
  166. sensor::Unit units; // Units of measurement
  167. double last; // Last raw value from sensor (unfiltered)
  168. double reported; // Last reported value
  169. double min_change; // Minimum value change to report
  170. double max_change; // Maximum value change to report
  171. double correction; // Value correction (applied when processing)
  172. };
  173. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX];
  174. namespace sensor {
  175. // Base units
  176. // TODO: implement through a single class and allow direct access to the ::value
  177. KWh::KWh() :
  178. value(0)
  179. {}
  180. KWh::KWh(uint32_t value) :
  181. value(value)
  182. {}
  183. Ws::Ws() :
  184. value(0)
  185. {}
  186. Ws::Ws(uint32_t value) :
  187. value(value)
  188. {}
  189. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  190. Energy::Energy(KWh kwh, Ws ws) :
  191. kwh(kwh)
  192. {
  193. *this += ws;
  194. }
  195. Energy::Energy(KWh kwh) :
  196. kwh(kwh),
  197. ws()
  198. {}
  199. Energy::Energy(Ws ws) :
  200. kwh()
  201. {
  202. *this += ws;
  203. }
  204. Energy::Energy(double raw) {
  205. *this = raw;
  206. }
  207. Energy& Energy::operator =(double raw) {
  208. double _wh;
  209. kwh = modf(raw, &_wh);
  210. ws = _wh * 3600.0;
  211. return *this;
  212. }
  213. Energy& Energy::operator +=(Ws _ws) {
  214. while (_ws.value >= KwhMultiplier) {
  215. _ws.value -= KwhMultiplier;
  216. ++kwh.value;
  217. }
  218. ws.value += _ws.value;
  219. while (ws.value >= KwhMultiplier) {
  220. ws.value -= KwhMultiplier;
  221. ++kwh.value;
  222. }
  223. return *this;
  224. }
  225. Energy Energy::operator +(Ws watt_s) {
  226. Energy result(*this);
  227. result += watt_s;
  228. return result;
  229. }
  230. Energy::operator bool() {
  231. return (kwh.value > 0) && (ws.value > 0);
  232. }
  233. Ws Energy::asWs() {
  234. auto _kwh = kwh.value;
  235. while (_kwh >= KwhLimit) {
  236. _kwh -= KwhLimit;
  237. }
  238. return (_kwh * KwhMultiplier) + ws.value;
  239. }
  240. double Energy::asDouble() {
  241. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  242. }
  243. void Energy::reset() {
  244. kwh.value = 0;
  245. ws.value = 0;
  246. }
  247. } // namespace sensor
  248. // -----------------------------------------------------------------------------
  249. // Energy persistence
  250. // -----------------------------------------------------------------------------
  251. std::vector<unsigned char> _sensor_save_count;
  252. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  253. bool _sensorIsEmon(BaseSensor* sensor) {
  254. return sensor->type() & sensor::type::Emon;
  255. }
  256. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  257. return sensor::Energy {
  258. sensor::KWh { Rtcmem->energy[index].kwh },
  259. sensor::Ws { Rtcmem->energy[index].ws }
  260. };
  261. }
  262. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  263. Rtcmem->energy[index].kwh = source.kwh.value;
  264. Rtcmem->energy[index].ws = source.ws.value;
  265. }
  266. sensor::Energy _sensorParseEnergy(const String& value) {
  267. sensor::Energy result;
  268. const bool separator = value.indexOf('+') > 0;
  269. if (value.length() && (separator > 0)) {
  270. const String before = value.substring(0, separator);
  271. const String after = value.substring(separator + 1);
  272. result.kwh = strtoul(before.c_str(), nullptr, 10);
  273. result.ws = strtoul(after.c_str(), nullptr, 10);
  274. }
  275. return result;
  276. }
  277. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  278. if (!payload || !strlen(payload)) return;
  279. if (payload[0] != '0') return;
  280. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  281. auto energy = _sensorParseEnergy(payload);
  282. sensor->resetEnergy(magnitude.global, energy);
  283. }
  284. sensor::Energy _sensorEnergyTotal(unsigned char index) {
  285. sensor::Energy result;
  286. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  287. result = _sensorRtcmemLoadEnergy(index);
  288. } else if (_sensor_save_every > 0) {
  289. result = _sensorParseEnergy(getSetting({"eneTotal", index}));
  290. }
  291. return result;
  292. }
  293. sensor::Energy sensorEnergyTotal() {
  294. return _sensorEnergyTotal(0);
  295. }
  296. void _sensorResetEnergyTotal(unsigned char index) {
  297. delSetting({"eneTotal", index});
  298. delSetting({"eneTime", index});
  299. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  300. Rtcmem->energy[index].kwh = 0;
  301. Rtcmem->energy[index].ws = 0;
  302. }
  303. }
  304. void _magnitudeSaveEnergyTotal(sensor_magnitude_t& magnitude, bool persistent) {
  305. if (magnitude.type != MAGNITUDE_ENERGY) return;
  306. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  307. const auto energy = sensor->totalEnergy();
  308. // Always save to RTCMEM
  309. if (magnitude.global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  310. _sensorRtcmemSaveEnergy(magnitude.global, energy);
  311. }
  312. // Save to EEPROM every '_sensor_save_every' readings
  313. // Format is `<kwh>+<ws>`, value without `+` is treated as `<ws>`
  314. if (persistent && _sensor_save_every) {
  315. _sensor_save_count[magnitude.global] =
  316. (_sensor_save_count[magnitude.global] + 1) % _sensor_save_every;
  317. if (0 == _sensor_save_count[magnitude.global]) {
  318. const String total = String(energy.kwh.value) + "+" + String(energy.ws.value);
  319. setSetting({"eneTotal", magnitude.global}, total);
  320. #if NTP_SUPPORT
  321. if (ntpSynced()) setSetting({"eneTime", magnitude.global}, ntpDateTime());
  322. #endif
  323. }
  324. }
  325. }
  326. // ---------------------------------------------------------------------------
  327. std::vector<BaseSensor *> _sensors;
  328. std::vector<sensor_magnitude_t> _magnitudes;
  329. bool _sensors_ready = false;
  330. bool _sensor_realtime = API_REAL_TIME_VALUES;
  331. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  332. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  333. // -----------------------------------------------------------------------------
  334. // Private
  335. // -----------------------------------------------------------------------------
  336. sensor_magnitude_t::sensor_magnitude_t() :
  337. sensor(nullptr),
  338. filter(nullptr),
  339. type(0),
  340. local(0),
  341. global(0),
  342. decimals(0),
  343. units(sensor::Unit::None),
  344. last(0.0),
  345. reported(0.0),
  346. min_change(0.0),
  347. max_change(0.0),
  348. correction(0.0)
  349. {}
  350. sensor_magnitude_t::sensor_magnitude_t(unsigned char type, unsigned char local, sensor::Unit units, BaseSensor* sensor) :
  351. sensor(sensor),
  352. filter(nullptr),
  353. type(type),
  354. local(local),
  355. global(_counts[type]),
  356. decimals(0),
  357. units(units),
  358. last(0.0),
  359. reported(0.0),
  360. min_change(0.0),
  361. max_change(0.0),
  362. correction(0.0)
  363. {
  364. ++_counts[type];
  365. switch (type) {
  366. case MAGNITUDE_ENERGY:
  367. filter = new LastFilter();
  368. case MAGNITUDE_ENERGY_DELTA:
  369. filter = new SumFilter();
  370. case MAGNITUDE_DIGITAL:
  371. filter = new MaxFilter();
  372. // For geiger counting moving average filter is the most appropriate if needed at all.
  373. case MAGNITUDE_COUNT:
  374. case MAGNITUDE_GEIGER_CPM:
  375. case MAGNITUDE_GEIGER_SIEVERT:
  376. filter = new MovingAverageFilter();
  377. default:
  378. filter = new MedianFilter();
  379. }
  380. filter->resize(_sensor_report_every);
  381. }
  382. // Hardcoded decimals for each magnitude
  383. unsigned char _sensorUnitDecimals(sensor::Unit unit) {
  384. switch (unit) {
  385. case sensor::Unit::Celcius:
  386. case sensor::Unit::Farenheit:
  387. return 1;
  388. case sensor::Unit::Percentage:
  389. return 0;
  390. case sensor::Unit::Hectopascal:
  391. return 2;
  392. case sensor::Unit::Ampere:
  393. return 3;
  394. case sensor::Unit::Volt:
  395. return 0;
  396. case sensor::Unit::Watt:
  397. case sensor::Unit::Voltampere:
  398. case sensor::Unit::VoltampereReactive:
  399. return 0;
  400. case sensor::Unit::Kilowatt:
  401. case sensor::Unit::Kilovoltampere:
  402. case sensor::Unit::KilovoltampereReactive:
  403. return 3;
  404. case sensor::Unit::KilowattHour:
  405. return 3;
  406. case sensor::Unit::WattSecond:
  407. return 0;
  408. case sensor::Unit::CountsPerMinute:
  409. case sensor::Unit::MicrosievertPerHour:
  410. return 4;
  411. case sensor::Unit::Meter:
  412. return 3;
  413. case sensor::Unit::UltravioletIndex:
  414. return 3;
  415. case sensor::Unit::None:
  416. default:
  417. return 0;
  418. }
  419. }
  420. String magnitudeTopic(unsigned char type) {
  421. const __FlashStringHelper* result = nullptr;
  422. switch (type) {
  423. case MAGNITUDE_TEMPERATURE:
  424. result = F("temperature");
  425. break;
  426. case MAGNITUDE_HUMIDITY:
  427. result = F("humidity");
  428. break;
  429. case MAGNITUDE_PRESSURE:
  430. result = F("pressure");
  431. break;
  432. case MAGNITUDE_CURRENT:
  433. result = F("current");
  434. break;
  435. case MAGNITUDE_VOLTAGE:
  436. result = F("voltage");
  437. break;
  438. case MAGNITUDE_POWER_ACTIVE:
  439. result = F("power");
  440. break;
  441. case MAGNITUDE_POWER_APPARENT:
  442. result = F("apparent");
  443. break;
  444. case MAGNITUDE_POWER_REACTIVE:
  445. result = F("reactive");
  446. break;
  447. case MAGNITUDE_POWER_FACTOR:
  448. result = F("factor");
  449. break;
  450. case MAGNITUDE_ENERGY:
  451. result = F("energy");
  452. break;
  453. case MAGNITUDE_ENERGY_DELTA:
  454. result = F("energy_delta");
  455. break;
  456. case MAGNITUDE_ANALOG:
  457. result = F("analog");
  458. break;
  459. case MAGNITUDE_DIGITAL:
  460. result = F("digital");
  461. break;
  462. case MAGNITUDE_EVENT:
  463. result = F("event");
  464. break;
  465. case MAGNITUDE_PM1dot0:
  466. result = F("pm1dot0");
  467. break;
  468. case MAGNITUDE_PM2dot5:
  469. result = F("pm2dot5");
  470. break;
  471. case MAGNITUDE_PM10:
  472. result = F("pm10");
  473. break;
  474. case MAGNITUDE_CO2:
  475. result = F("co2");
  476. break;
  477. case MAGNITUDE_LUX:
  478. result = F("lux");
  479. break;
  480. case MAGNITUDE_UVA:
  481. result = F("uva");
  482. break;
  483. case MAGNITUDE_UVB:
  484. result = F("uvb");
  485. break;
  486. case MAGNITUDE_UVI:
  487. result = F("uvi");
  488. break;
  489. case MAGNITUDE_DISTANCE:
  490. result = F("distance");
  491. break;
  492. case MAGNITUDE_HCHO:
  493. result = F("hcho");
  494. break;
  495. case MAGNITUDE_GEIGER_CPM:
  496. result = F("ldr_cpm"); // local dose rate [Counts per minute]
  497. break;
  498. case MAGNITUDE_GEIGER_SIEVERT:
  499. result = F("ldr_uSvh"); // local dose rate [µSievert per hour]
  500. break;
  501. case MAGNITUDE_COUNT:
  502. result = F("count");
  503. break;
  504. case MAGNITUDE_NO2:
  505. result = F("no2");
  506. break;
  507. case MAGNITUDE_CO:
  508. result = F("co");
  509. break;
  510. case MAGNITUDE_RESISTANCE:
  511. result = F("resistance");
  512. break;
  513. case MAGNITUDE_PH:
  514. result = F("ph");
  515. break;
  516. case MAGNITUDE_NONE:
  517. default:
  518. result = F("unknown");
  519. break;
  520. }
  521. return String(result);
  522. }
  523. String _magnitudeTopic(const sensor_magnitude_t& magnitude) {
  524. return magnitudeTopic(magnitude.type);
  525. }
  526. String _magnitudeUnits(const sensor_magnitude_t& magnitude) {
  527. const __FlashStringHelper* result = nullptr;
  528. switch (magnitude.units) {
  529. case sensor::Unit::Farenheit:
  530. result = F("°F");
  531. break;
  532. case sensor::Unit::Celcius:
  533. result = F("°C");
  534. break;
  535. case sensor::Unit::Percentage:
  536. result = F("%");
  537. break;
  538. case sensor::Unit::Hectopascal:
  539. result = F("hPa");
  540. break;
  541. case sensor::Unit::Ampere:
  542. result = F("A");
  543. break;
  544. case sensor::Unit::Volt:
  545. result = F("V");
  546. break;
  547. case sensor::Unit::Watt:
  548. result = F("W");
  549. break;
  550. case sensor::Unit::Kilowatt:
  551. result = F("kW");
  552. break;
  553. case sensor::Unit::Voltampere:
  554. result = F("VA");
  555. break;
  556. case sensor::Unit::Kilovoltampere:
  557. result = F("kVA");
  558. break;
  559. case sensor::Unit::VoltampereReactive:
  560. result = F("VAR");
  561. break;
  562. case sensor::Unit::KilovoltampereReactive:
  563. result = F("kVAR");
  564. break;
  565. case sensor::Unit::Joule:
  566. //aka case sensor::Unit::WattSecond:
  567. result = F("J");
  568. break;
  569. case sensor::Unit::KilowattHour:
  570. result = F("kWh");
  571. break;
  572. case sensor::Unit::MicrogrammPerCubicMeter:
  573. result = F("µg/m³");
  574. break;
  575. case sensor::Unit::PartsPerMillion:
  576. result = F("ppm");
  577. break;
  578. case sensor::Unit::Lux:
  579. result = F("lux");
  580. break;
  581. case sensor::Unit::Ohm:
  582. result = F("ohm");
  583. break;
  584. case sensor::Unit::MilligrammPerCubicMeter:
  585. result = F("mg/m³");
  586. break;
  587. case sensor::Unit::CountsPerMinute:
  588. result = F("cpm");
  589. break;
  590. case sensor::Unit::MicrosievertPerHour:
  591. result = F("µSv/h");
  592. break;
  593. case sensor::Unit::Meter:
  594. result = F("m");
  595. break;
  596. case sensor::Unit::None:
  597. default:
  598. result = F("");
  599. break;
  600. }
  601. return String(result);
  602. }
  603. String magnitudeUnits(unsigned char index) {
  604. if (index >= magnitudeCount()) return String();
  605. return _magnitudeUnits(_magnitudes[index]);
  606. }
  607. // Choose unit based on type of magnitude we use
  608. sensor::Unit _magnitudeUnitFilter(const sensor_magnitude_t& magnitude, sensor::Unit updated) {
  609. auto result = magnitude.units;
  610. switch (magnitude.type) {
  611. case MAGNITUDE_TEMPERATURE: {
  612. switch (updated) {
  613. case sensor::Unit::Celcius:
  614. case sensor::Unit::Farenheit:
  615. case sensor::Unit::Kelvin:
  616. result = updated;
  617. break;
  618. default:
  619. break;
  620. }
  621. break;
  622. }
  623. case MAGNITUDE_POWER_ACTIVE: {
  624. switch (updated) {
  625. case sensor::Unit::Kilowatt:
  626. case sensor::Unit::Watt:
  627. result = updated;
  628. break;
  629. default:
  630. break;
  631. }
  632. break;
  633. }
  634. case MAGNITUDE_ENERGY: {
  635. switch (updated) {
  636. case sensor::Unit::KilowattHour:
  637. case sensor::Unit::Joule:
  638. result = updated;
  639. break;
  640. default:
  641. break;
  642. }
  643. break;
  644. }
  645. }
  646. return result;
  647. };
  648. double _magnitudeProcess(const sensor_magnitude_t& magnitude, double value) {
  649. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  650. switch (magnitude.sensor->units(magnitude.local)) {
  651. case sensor::Unit::Celcius:
  652. if (magnitude.units == sensor::Unit::Farenheit) {
  653. value = (value * 1.8) + 32.0;
  654. } else if (magnitude.units == sensor::Unit::Kelvin) {
  655. value = value + 273.15;
  656. }
  657. break;
  658. case sensor::Unit::Percentage:
  659. value = constrain(value, 0.0, 100.0);
  660. break;
  661. case sensor::Unit::Watt:
  662. case sensor::Unit::Voltampere:
  663. case sensor::Unit::VoltampereReactive:
  664. if ((magnitude.units == sensor::Unit::Kilowatt)
  665. || (magnitude.units == sensor::Unit::Kilovoltampere)
  666. || (magnitude.units == sensor::Unit::KilovoltampereReactive)) {
  667. value = value / 1.0e+3;
  668. }
  669. break;
  670. case sensor::Unit::KilowattHour:
  671. // TODO: we may end up with inf at some point?
  672. if (magnitude.units == sensor::Unit::Joule) {
  673. value = value * 3.6e+6;
  674. }
  675. break;
  676. default:
  677. break;
  678. }
  679. value = value + magnitude.correction;
  680. return roundTo(value, magnitude.decimals);
  681. }
  682. // -----------------------------------------------------------------------------
  683. #if WEB_SUPPORT
  684. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  685. void sensorWebSocketMagnitudes(JsonObject& root, const String& prefix) {
  686. // ws produces flat list <prefix>Magnitudes
  687. const String ws_name = prefix + "Magnitudes";
  688. // config uses <prefix>Magnitude<index> (cut 's')
  689. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  690. JsonObject& list = root.createNestedObject(ws_name);
  691. list["size"] = magnitudeCount();
  692. JsonArray& type = list.createNestedArray("type");
  693. JsonArray& index = list.createNestedArray("index");
  694. JsonArray& idx = list.createNestedArray("idx");
  695. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  696. type.add(magnitudeType(i));
  697. index.add(magnitudeIndex(i));
  698. idx.add(getSetting({conf_name, i}, 0));
  699. }
  700. }
  701. bool _sensorWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  702. if (strncmp(key, "pwr", 3) == 0) return true;
  703. if (strncmp(key, "sns", 3) == 0) return true;
  704. if (strncmp(key, "tmp", 3) == 0) return true;
  705. if (strncmp(key, "hum", 3) == 0) return true;
  706. if (strncmp(key, "ene", 3) == 0) return true;
  707. if (strncmp(key, "lux", 3) == 0) return true;
  708. return false;
  709. }
  710. void _sensorWebSocketOnVisible(JsonObject& root) {
  711. root["snsVisible"] = 1;
  712. for (auto& magnitude : _magnitudes) {
  713. if (magnitude.type == MAGNITUDE_TEMPERATURE) root["temperatureVisible"] = 1;
  714. if (magnitude.type == MAGNITUDE_HUMIDITY) root["humidityVisible"] = 1;
  715. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  716. if (magnitude.type == MAGNITUDE_CO || magnitude.type == MAGNITUDE_NO2) root["micsVisible"] = 1;
  717. #endif
  718. }
  719. }
  720. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  721. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  722. uint8_t size = 0;
  723. JsonArray& index = magnitudes.createNestedArray("index");
  724. JsonArray& type = magnitudes.createNestedArray("type");
  725. JsonArray& units = magnitudes.createNestedArray("units");
  726. JsonArray& description = magnitudes.createNestedArray("description");
  727. for (unsigned char i=0; i<magnitudeCount(); i++) {
  728. auto& magnitude = _magnitudes[i];
  729. if (magnitude.type == MAGNITUDE_EVENT) continue;
  730. ++size;
  731. index.add<uint8_t>(magnitude.global);
  732. type.add<uint8_t>(magnitude.type);
  733. units.add(_magnitudeUnits(magnitude));
  734. {
  735. String sensor_desc = magnitude.sensor->slot(magnitude.local);
  736. description.add(sensor_desc);
  737. }
  738. }
  739. magnitudes["size"] = size;
  740. }
  741. void _sensorWebSocketSendData(JsonObject& root) {
  742. char buffer[64];
  743. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  744. uint8_t size = 0;
  745. JsonArray& value = magnitudes.createNestedArray("value");
  746. JsonArray& error = magnitudes.createNestedArray("error");
  747. #if NTP_SUPPORT
  748. JsonArray& info = magnitudes.createNestedArray("info");
  749. #endif
  750. for (auto& magnitude : _magnitudes) {
  751. if (magnitude.type == MAGNITUDE_EVENT) continue;
  752. ++size;
  753. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  754. value.add(buffer);
  755. error.add(magnitude.sensor->error());
  756. #if NTP_SUPPORT
  757. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  758. String string = F("Last saved: ");
  759. string += getSetting({"eneTime", magnitude.global}, F("(unknown)"));
  760. info.add(string);
  761. } else {
  762. info.add((uint8_t)0);
  763. }
  764. #endif
  765. }
  766. magnitudes["size"] = size;
  767. }
  768. void _sensorWebSocketOnConnected(JsonObject& root) {
  769. for (unsigned char i=0; i<_sensors.size(); i++) {
  770. BaseSensor * sensor = _sensors[i];
  771. UNUSED(sensor);
  772. #if EMON_ANALOG_SUPPORT
  773. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  774. root["emonVisible"] = 1;
  775. root["pwrVisible"] = 1;
  776. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  777. }
  778. #endif
  779. #if HLW8012_SUPPORT
  780. if (sensor->getID() == SENSOR_HLW8012_ID) {
  781. root["hlwVisible"] = 1;
  782. root["pwrVisible"] = 1;
  783. }
  784. #endif
  785. #if CSE7766_SUPPORT
  786. if (sensor->getID() == SENSOR_CSE7766_ID) {
  787. root["cseVisible"] = 1;
  788. root["pwrVisible"] = 1;
  789. }
  790. #endif
  791. #if V9261F_SUPPORT
  792. if (sensor->getID() == SENSOR_V9261F_ID) {
  793. root["pwrVisible"] = 1;
  794. }
  795. #endif
  796. #if ECH1560_SUPPORT
  797. if (sensor->getID() == SENSOR_ECH1560_ID) {
  798. root["pwrVisible"] = 1;
  799. }
  800. #endif
  801. #if PZEM004T_SUPPORT
  802. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  803. root["pzemVisible"] = 1;
  804. root["pwrVisible"] = 1;
  805. }
  806. #endif
  807. #if PULSEMETER_SUPPORT
  808. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  809. root["pmVisible"] = 1;
  810. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  811. }
  812. #endif
  813. }
  814. if (sensor_magnitude_t::counts(MAGNITUDE_TEMPERATURE)) {
  815. root["tmpCorrection"] = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION);
  816. }
  817. if (sensor_magnitude_t::counts(MAGNITUDE_HUMIDITY)) {
  818. root["humCorrection"] = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION);
  819. }
  820. if (sensor_magnitude_t::counts(MAGNITUDE_LUX)) {
  821. root["luxCorrection"] = getSetting("luxCorrection", SENSOR_LUX_CORRECTION);
  822. }
  823. if (magnitudeCount()) {
  824. root["snsRead"] = _sensor_read_interval / 1000;
  825. root["snsReport"] = _sensor_report_every;
  826. root["snsSave"] = _sensor_save_every;
  827. _sensorWebSocketMagnitudesConfig(root);
  828. }
  829. }
  830. #endif // WEB_SUPPORT
  831. #if API_SUPPORT
  832. void _sensorAPISetup() {
  833. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  834. auto& magnitude = _magnitudes.at(magnitude_id);
  835. String topic = magnitudeTopic(magnitude.type);
  836. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) topic = topic + "/" + String(magnitude.global);
  837. api_get_callback_f get_cb = [&magnitude](char * buffer, size_t len) {
  838. double value = _sensor_realtime ? magnitude.last : magnitude.reported;
  839. dtostrf(value, 1, magnitude.decimals, buffer);
  840. };
  841. api_put_callback_f put_cb = nullptr;
  842. if (magnitude.type == MAGNITUDE_ENERGY) {
  843. put_cb = [&magnitude](const char* payload) {
  844. _sensorApiResetEnergy(magnitude, payload);
  845. };
  846. }
  847. apiRegister(topic.c_str(), get_cb, put_cb);
  848. }
  849. }
  850. #endif // API_SUPPORT == 1
  851. #if MQTT_SUPPORT
  852. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  853. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  854. switch (type) {
  855. case MQTT_MESSAGE_EVENT: {
  856. String t = mqttMagnitude((char *) topic);
  857. if (!t.startsWith(energy_topic)) break;
  858. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  859. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  860. for (auto& magnitude : _magnitudes) {
  861. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  862. if (index != magnitude.global) continue;
  863. _sensorApiResetEnergy(magnitude, payload);
  864. break;
  865. }
  866. }
  867. case MQTT_CONNECT_EVENT: {
  868. for (auto& magnitude : _magnitudes) {
  869. if (MAGNITUDE_ENERGY == magnitude.type) {
  870. const String topic = energy_topic + "/+";
  871. mqttSubscribe(topic.c_str());
  872. break;
  873. }
  874. }
  875. }
  876. case MQTT_DISCONNECT_EVENT:
  877. default:
  878. break;
  879. }
  880. }
  881. #endif // MQTT_SUPPORT == 1
  882. #if TERMINAL_SUPPORT
  883. void _sensorInitCommands() {
  884. terminalRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  885. char last[64];
  886. char reported[64];
  887. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  888. auto& magnitude = _magnitudes.at(index);
  889. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  890. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  891. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  892. index,
  893. magnitudeTopic(magnitude.type).c_str(), magnitude.global,
  894. magnitude.sensor->slot(magnitude.local).c_str(),
  895. last, reported
  896. );
  897. }
  898. terminalOK();
  899. });
  900. }
  901. #endif // TERMINAL_SUPPORT == 1
  902. void _sensorTick() {
  903. for (auto* sensor : _sensors) {
  904. sensor->tick();
  905. }
  906. }
  907. void _sensorPre() {
  908. for (auto* sensor : _sensors) {
  909. sensor->pre();
  910. if (!sensor->status()) {
  911. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  912. sensor->description().c_str(),
  913. sensor->error()
  914. );
  915. }
  916. }
  917. }
  918. void _sensorPost() {
  919. for (auto* sensor : _sensors) {
  920. sensor->post();
  921. }
  922. }
  923. // -----------------------------------------------------------------------------
  924. // Sensor initialization
  925. // -----------------------------------------------------------------------------
  926. void _sensorLoad() {
  927. /*
  928. This is temporal, in the future sensors will be initialized based on
  929. soft configuration (data stored in EEPROM config) so you will be able
  930. to define and configure new sensors on the fly
  931. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  932. loaded and initialized here. If you want to add new sensors of the same type
  933. just duplicate the block and change the arguments for the set* methods.
  934. For example, how to add a second DHT sensor:
  935. #if DHT_SUPPORT
  936. {
  937. DHTSensor * sensor = new DHTSensor();
  938. sensor->setGPIO(DHT2_PIN);
  939. sensor->setType(DHT2_TYPE);
  940. _sensors.push_back(sensor);
  941. }
  942. #endif
  943. DHT2_PIN and DHT2_TYPE should be globally accessible:
  944. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  945. - in custom.h, as `#define ...`
  946. */
  947. #if AM2320_SUPPORT
  948. {
  949. AM2320Sensor * sensor = new AM2320Sensor();
  950. sensor->setAddress(AM2320_ADDRESS);
  951. _sensors.push_back(sensor);
  952. }
  953. #endif
  954. #if ANALOG_SUPPORT
  955. {
  956. AnalogSensor * sensor = new AnalogSensor();
  957. sensor->setSamples(ANALOG_SAMPLES);
  958. sensor->setDelay(ANALOG_DELAY);
  959. //CICM For analog scaling
  960. sensor->setFactor(ANALOG_FACTOR);
  961. sensor->setOffset(ANALOG_OFFSET);
  962. _sensors.push_back(sensor);
  963. }
  964. #endif
  965. #if BH1750_SUPPORT
  966. {
  967. BH1750Sensor * sensor = new BH1750Sensor();
  968. sensor->setAddress(BH1750_ADDRESS);
  969. sensor->setMode(BH1750_MODE);
  970. _sensors.push_back(sensor);
  971. }
  972. #endif
  973. #if BMP180_SUPPORT
  974. {
  975. BMP180Sensor * sensor = new BMP180Sensor();
  976. sensor->setAddress(BMP180_ADDRESS);
  977. _sensors.push_back(sensor);
  978. }
  979. #endif
  980. #if BMX280_SUPPORT
  981. {
  982. // Support up to two sensors with full auto-discovery.
  983. const unsigned char number = constrain(getSetting<int>("bmx280Number", BMX280_NUMBER), 1, 2);
  984. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  985. // otherwise choose the other unnamed sensor address
  986. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  987. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  988. const decltype(first) address_map[2] { first, second };
  989. for (unsigned char n=0; n < number; ++n) {
  990. BMX280Sensor * sensor = new BMX280Sensor();
  991. sensor->setAddress(address_map[n]);
  992. _sensors.push_back(sensor);
  993. }
  994. }
  995. #endif
  996. #if CSE7766_SUPPORT
  997. {
  998. CSE7766Sensor * sensor = new CSE7766Sensor();
  999. sensor->setRX(CSE7766_PIN);
  1000. _sensors.push_back(sensor);
  1001. }
  1002. #endif
  1003. #if DALLAS_SUPPORT
  1004. {
  1005. DallasSensor * sensor = new DallasSensor();
  1006. sensor->setGPIO(DALLAS_PIN);
  1007. _sensors.push_back(sensor);
  1008. }
  1009. #endif
  1010. #if DHT_SUPPORT
  1011. {
  1012. DHTSensor * sensor = new DHTSensor();
  1013. sensor->setGPIO(DHT_PIN);
  1014. sensor->setType(DHT_TYPE);
  1015. _sensors.push_back(sensor);
  1016. }
  1017. #endif
  1018. #if DIGITAL_SUPPORT
  1019. {
  1020. auto getPin = [](unsigned char index) -> int {
  1021. switch (index) {
  1022. case 0: return DIGITAL1_PIN;
  1023. case 1: return DIGITAL2_PIN;
  1024. case 2: return DIGITAL3_PIN;
  1025. case 3: return DIGITAL4_PIN;
  1026. case 4: return DIGITAL5_PIN;
  1027. case 5: return DIGITAL6_PIN;
  1028. case 6: return DIGITAL7_PIN;
  1029. case 7: return DIGITAL8_PIN;
  1030. default: return GPIO_NONE;
  1031. }
  1032. };
  1033. auto getDefaultState = [](unsigned char index) -> int {
  1034. switch (index) {
  1035. case 0: return DIGITAL1_DEFAULT_STATE;
  1036. case 1: return DIGITAL2_DEFAULT_STATE;
  1037. case 2: return DIGITAL3_DEFAULT_STATE;
  1038. case 3: return DIGITAL4_DEFAULT_STATE;
  1039. case 4: return DIGITAL5_DEFAULT_STATE;
  1040. case 5: return DIGITAL6_DEFAULT_STATE;
  1041. case 6: return DIGITAL7_DEFAULT_STATE;
  1042. case 7: return DIGITAL8_DEFAULT_STATE;
  1043. default: return 1;
  1044. }
  1045. };
  1046. auto getMode = [](unsigned char index) -> int {
  1047. switch (index) {
  1048. case 0: return DIGITAL1_PIN_MODE;
  1049. case 1: return DIGITAL2_PIN_MODE;
  1050. case 2: return DIGITAL3_PIN_MODE;
  1051. case 3: return DIGITAL4_PIN_MODE;
  1052. case 4: return DIGITAL5_PIN_MODE;
  1053. case 5: return DIGITAL6_PIN_MODE;
  1054. case 6: return DIGITAL7_PIN_MODE;
  1055. case 7: return DIGITAL8_PIN_MODE;
  1056. default: return INPUT_PULLUP;
  1057. }
  1058. };
  1059. for (unsigned char index = 0; index < GpioPins; ++index) {
  1060. const auto pin = getPin(index);
  1061. if (pin == GPIO_NONE) break;
  1062. DigitalSensor * sensor = new DigitalSensor();
  1063. sensor->setGPIO(pin);
  1064. sensor->setMode(getMode(index));
  1065. sensor->setDefault(getDefaultState(index));
  1066. _sensors.push_back(sensor);
  1067. }
  1068. }
  1069. #endif
  1070. #if ECH1560_SUPPORT
  1071. {
  1072. ECH1560Sensor * sensor = new ECH1560Sensor();
  1073. sensor->setCLK(ECH1560_CLK_PIN);
  1074. sensor->setMISO(ECH1560_MISO_PIN);
  1075. sensor->setInverted(ECH1560_INVERTED);
  1076. _sensors.push_back(sensor);
  1077. }
  1078. #endif
  1079. #if EMON_ADC121_SUPPORT
  1080. {
  1081. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1082. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1083. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1084. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1085. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1086. _sensors.push_back(sensor);
  1087. }
  1088. #endif
  1089. #if EMON_ADS1X15_SUPPORT
  1090. {
  1091. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  1092. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  1093. sensor->setType(EMON_ADS1X15_TYPE);
  1094. sensor->setMask(EMON_ADS1X15_MASK);
  1095. sensor->setGain(EMON_ADS1X15_GAIN);
  1096. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1097. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1098. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  1099. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  1100. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  1101. _sensors.push_back(sensor);
  1102. }
  1103. #endif
  1104. #if EMON_ANALOG_SUPPORT
  1105. {
  1106. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  1107. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1108. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  1109. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1110. _sensors.push_back(sensor);
  1111. }
  1112. #endif
  1113. #if EVENTS_SUPPORT
  1114. {
  1115. #if (EVENTS1_PIN != GPIO_NONE)
  1116. {
  1117. EventSensor * sensor = new EventSensor();
  1118. sensor->setGPIO(EVENTS1_PIN);
  1119. sensor->setTrigger(EVENTS1_TRIGGER);
  1120. sensor->setPinMode(EVENTS1_PIN_MODE);
  1121. sensor->setDebounceTime(EVENTS1_DEBOUNCE);
  1122. sensor->setInterruptMode(EVENTS1_INTERRUPT_MODE);
  1123. _sensors.push_back(sensor);
  1124. }
  1125. #endif
  1126. #if (EVENTS2_PIN != GPIO_NONE)
  1127. {
  1128. EventSensor * sensor = new EventSensor();
  1129. sensor->setGPIO(EVENTS2_PIN);
  1130. sensor->setTrigger(EVENTS2_TRIGGER);
  1131. sensor->setPinMode(EVENTS2_PIN_MODE);
  1132. sensor->setDebounceTime(EVENTS2_DEBOUNCE);
  1133. sensor->setInterruptMode(EVENTS2_INTERRUPT_MODE);
  1134. _sensors.push_back(sensor);
  1135. }
  1136. #endif
  1137. #if (EVENTS3_PIN != GPIO_NONE)
  1138. {
  1139. EventSensor * sensor = new EventSensor();
  1140. sensor->setGPIO(EVENTS3_PIN);
  1141. sensor->setTrigger(EVENTS3_TRIGGER);
  1142. sensor->setPinMode(EVENTS3_PIN_MODE);
  1143. sensor->setDebounceTime(EVENTS3_DEBOUNCE);
  1144. sensor->setInterruptMode(EVENTS3_INTERRUPT_MODE);
  1145. _sensors.push_back(sensor);
  1146. }
  1147. #endif
  1148. #if (EVENTS4_PIN != GPIO_NONE)
  1149. {
  1150. EventSensor * sensor = new EventSensor();
  1151. sensor->setGPIO(EVENTS4_PIN);
  1152. sensor->setTrigger(EVENTS4_TRIGGER);
  1153. sensor->setPinMode(EVENTS4_PIN_MODE);
  1154. sensor->setDebounceTime(EVENTS4_DEBOUNCE);
  1155. sensor->setInterruptMode(EVENTS4_INTERRUPT_MODE);
  1156. _sensors.push_back(sensor);
  1157. }
  1158. #endif
  1159. #if (EVENTS5_PIN != GPIO_NONE)
  1160. {
  1161. EventSensor * sensor = new EventSensor();
  1162. sensor->setGPIO(EVENTS5_PIN);
  1163. sensor->setTrigger(EVENTS5_TRIGGER);
  1164. sensor->setPinMode(EVENTS5_PIN_MODE);
  1165. sensor->setDebounceTime(EVENTS5_DEBOUNCE);
  1166. sensor->setInterruptMode(EVENTS5_INTERRUPT_MODE);
  1167. _sensors.push_back(sensor);
  1168. }
  1169. #endif
  1170. #if (EVENTS6_PIN != GPIO_NONE)
  1171. {
  1172. EventSensor * sensor = new EventSensor();
  1173. sensor->setGPIO(EVENTS6_PIN);
  1174. sensor->setTrigger(EVENTS6_TRIGGER);
  1175. sensor->setPinMode(EVENTS6_PIN_MODE);
  1176. sensor->setDebounceTime(EVENTS6_DEBOUNCE);
  1177. sensor->setInterruptMode(EVENTS6_INTERRUPT_MODE);
  1178. _sensors.push_back(sensor);
  1179. }
  1180. #endif
  1181. #if (EVENTS7_PIN != GPIO_NONE)
  1182. {
  1183. EventSensor * sensor = new EventSensor();
  1184. sensor->setGPIO(EVENTS7_PIN);
  1185. sensor->setTrigger(EVENTS7_TRIGGER);
  1186. sensor->setPinMode(EVENTS7_PIN_MODE);
  1187. sensor->setDebounceTime(EVENTS7_DEBOUNCE);
  1188. sensor->setInterruptMode(EVENTS7_INTERRUPT_MODE);
  1189. _sensors.push_back(sensor);
  1190. }
  1191. #endif
  1192. #if (EVENTS8_PIN != GPIO_NONE)
  1193. {
  1194. EventSensor * sensor = new EventSensor();
  1195. sensor->setGPIO(EVENTS8_PIN);
  1196. sensor->setTrigger(EVENTS8_TRIGGER);
  1197. sensor->setPinMode(EVENTS8_PIN_MODE);
  1198. sensor->setDebounceTime(EVENTS8_DEBOUNCE);
  1199. sensor->setInterruptMode(EVENTS8_INTERRUPT_MODE);
  1200. _sensors.push_back(sensor);
  1201. }
  1202. #endif
  1203. }
  1204. #endif
  1205. #if GEIGER_SUPPORT
  1206. {
  1207. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1208. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1209. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1210. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1211. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1212. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1213. _sensors.push_back(sensor);
  1214. }
  1215. #endif
  1216. #if GUVAS12SD_SUPPORT
  1217. {
  1218. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1219. sensor->setGPIO(GUVAS12SD_PIN);
  1220. _sensors.push_back(sensor);
  1221. }
  1222. #endif
  1223. #if SONAR_SUPPORT
  1224. {
  1225. SonarSensor * sensor = new SonarSensor();
  1226. sensor->setEcho(SONAR_ECHO);
  1227. sensor->setIterations(SONAR_ITERATIONS);
  1228. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1229. sensor->setTrigger(SONAR_TRIGGER);
  1230. _sensors.push_back(sensor);
  1231. }
  1232. #endif
  1233. #if HLW8012_SUPPORT
  1234. {
  1235. HLW8012Sensor * sensor = new HLW8012Sensor();
  1236. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1237. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1238. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1239. sensor->setCurrentRatio(HLW8012_CURRENT_RATIO);
  1240. sensor->setVoltageRatio(HLW8012_VOLTAGE_RATIO);
  1241. sensor->setPowerRatio(HLW8012_POWER_RATIO);
  1242. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1243. _sensors.push_back(sensor);
  1244. }
  1245. #endif
  1246. #if LDR_SUPPORT
  1247. {
  1248. LDRSensor * sensor = new LDRSensor();
  1249. sensor->setSamples(LDR_SAMPLES);
  1250. sensor->setDelay(LDR_DELAY);
  1251. sensor->setType(LDR_TYPE);
  1252. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1253. sensor->setResistor(LDR_RESISTOR);
  1254. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1255. _sensors.push_back(sensor);
  1256. }
  1257. #endif
  1258. #if MHZ19_SUPPORT
  1259. {
  1260. MHZ19Sensor * sensor = new MHZ19Sensor();
  1261. sensor->setRX(MHZ19_RX_PIN);
  1262. sensor->setTX(MHZ19_TX_PIN);
  1263. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1264. _sensors.push_back(sensor);
  1265. }
  1266. #endif
  1267. #if MICS2710_SUPPORT
  1268. {
  1269. MICS2710Sensor * sensor = new MICS2710Sensor();
  1270. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1271. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1272. sensor->setR0(MICS2710_R0);
  1273. sensor->setRL(MICS2710_RL);
  1274. sensor->setRS(0);
  1275. _sensors.push_back(sensor);
  1276. }
  1277. #endif
  1278. #if MICS5525_SUPPORT
  1279. {
  1280. MICS5525Sensor * sensor = new MICS5525Sensor();
  1281. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1282. sensor->setR0(MICS5525_R0);
  1283. sensor->setRL(MICS5525_RL);
  1284. sensor->setRS(0);
  1285. _sensors.push_back(sensor);
  1286. }
  1287. #endif
  1288. #if NTC_SUPPORT
  1289. {
  1290. NTCSensor * sensor = new NTCSensor();
  1291. sensor->setSamples(NTC_SAMPLES);
  1292. sensor->setDelay(NTC_DELAY);
  1293. sensor->setUpstreamResistor(NTC_R_UP);
  1294. sensor->setDownstreamResistor(NTC_R_DOWN);
  1295. sensor->setBeta(NTC_BETA);
  1296. sensor->setR0(NTC_R0);
  1297. sensor->setT0(NTC_T0);
  1298. _sensors.push_back(sensor);
  1299. }
  1300. #endif
  1301. #if PMSX003_SUPPORT
  1302. {
  1303. PMSX003Sensor * sensor = new PMSX003Sensor();
  1304. #if PMS_USE_SOFT
  1305. sensor->setRX(PMS_RX_PIN);
  1306. sensor->setTX(PMS_TX_PIN);
  1307. #else
  1308. sensor->setSerial(& PMS_HW_PORT);
  1309. #endif
  1310. sensor->setType(PMS_TYPE);
  1311. _sensors.push_back(sensor);
  1312. }
  1313. #endif
  1314. #if PULSEMETER_SUPPORT
  1315. {
  1316. PulseMeterSensor * sensor = new PulseMeterSensor();
  1317. sensor->setGPIO(PULSEMETER_PIN);
  1318. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1319. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1320. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1321. _sensors.push_back(sensor);
  1322. }
  1323. #endif
  1324. #if PZEM004T_SUPPORT
  1325. {
  1326. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1327. if (!addresses.length()) {
  1328. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1329. return;
  1330. }
  1331. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1332. sensor->setAddresses(addresses.c_str());
  1333. if (getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1334. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1335. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1336. } else {
  1337. sensor->setSerial(& PZEM004T_HW_PORT);
  1338. }
  1339. _sensors.push_back(sensor);
  1340. #if TERMINAL_SUPPORT
  1341. pzem004tInitCommands();
  1342. #endif
  1343. }
  1344. #endif
  1345. #if SENSEAIR_SUPPORT
  1346. {
  1347. SenseAirSensor * sensor = new SenseAirSensor();
  1348. sensor->setRX(SENSEAIR_RX_PIN);
  1349. sensor->setTX(SENSEAIR_TX_PIN);
  1350. _sensors.push_back(sensor);
  1351. }
  1352. #endif
  1353. #if SDS011_SUPPORT
  1354. {
  1355. SDS011Sensor * sensor = new SDS011Sensor();
  1356. sensor->setRX(SDS011_RX_PIN);
  1357. sensor->setTX(SDS011_TX_PIN);
  1358. _sensors.push_back(sensor);
  1359. }
  1360. #endif
  1361. #if SHT3X_I2C_SUPPORT
  1362. {
  1363. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1364. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1365. _sensors.push_back(sensor);
  1366. }
  1367. #endif
  1368. #if SI7021_SUPPORT
  1369. {
  1370. SI7021Sensor * sensor = new SI7021Sensor();
  1371. sensor->setAddress(SI7021_ADDRESS);
  1372. _sensors.push_back(sensor);
  1373. }
  1374. #endif
  1375. #if T6613_SUPPORT
  1376. {
  1377. T6613Sensor * sensor = new T6613Sensor();
  1378. sensor->setRX(T6613_RX_PIN);
  1379. sensor->setTX(T6613_TX_PIN);
  1380. _sensors.push_back(sensor);
  1381. }
  1382. #endif
  1383. #if TMP3X_SUPPORT
  1384. {
  1385. TMP3XSensor * sensor = new TMP3XSensor();
  1386. sensor->setType(TMP3X_TYPE);
  1387. _sensors.push_back(sensor);
  1388. }
  1389. #endif
  1390. #if V9261F_SUPPORT
  1391. {
  1392. V9261FSensor * sensor = new V9261FSensor();
  1393. sensor->setRX(V9261F_PIN);
  1394. sensor->setInverted(V9261F_PIN_INVERSE);
  1395. _sensors.push_back(sensor);
  1396. }
  1397. #endif
  1398. #if MAX6675_SUPPORT
  1399. {
  1400. MAX6675Sensor * sensor = new MAX6675Sensor();
  1401. sensor->setCS(MAX6675_CS_PIN);
  1402. sensor->setSO(MAX6675_SO_PIN);
  1403. sensor->setSCK(MAX6675_SCK_PIN);
  1404. _sensors.push_back(sensor);
  1405. }
  1406. #endif
  1407. #if VEML6075_SUPPORT
  1408. {
  1409. VEML6075Sensor * sensor = new VEML6075Sensor();
  1410. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1411. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1412. _sensors.push_back(sensor);
  1413. }
  1414. #endif
  1415. #if VL53L1X_SUPPORT
  1416. {
  1417. VL53L1XSensor * sensor = new VL53L1XSensor();
  1418. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1419. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1420. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1421. _sensors.push_back(sensor);
  1422. }
  1423. #endif
  1424. #if EZOPH_SUPPORT
  1425. {
  1426. EZOPHSensor * sensor = new EZOPHSensor();
  1427. sensor->setRX(EZOPH_RX_PIN);
  1428. sensor->setTX(EZOPH_TX_PIN);
  1429. _sensors.push_back(sensor);
  1430. }
  1431. #endif
  1432. #if ADE7953_SUPPORT
  1433. {
  1434. ADE7953Sensor * sensor = new ADE7953Sensor();
  1435. sensor->setAddress(ADE7953_ADDRESS);
  1436. _sensors.push_back(sensor);
  1437. }
  1438. #endif
  1439. #if SI1145_SUPPORT
  1440. {
  1441. SI1145Sensor * sensor = new SI1145Sensor();
  1442. sensor->setAddress(SI1145_ADDRESS);
  1443. _sensors.push_back(sensor);
  1444. }
  1445. #endif
  1446. #if HDC1080_SUPPORT
  1447. {
  1448. HDC1080Sensor * sensor = new HDC1080Sensor();
  1449. sensor->setAddress(HDC1080_ADDRESS);
  1450. _sensors.push_back(sensor);
  1451. }
  1452. #endif
  1453. }
  1454. void _sensorReport(unsigned char index, double value) {
  1455. const auto& magnitude = _magnitudes.at(index);
  1456. // XXX: ensure that the received 'value' will fit here
  1457. // dtostrf 2nd arg only controls leading zeroes and the
  1458. // 3rd is only for the part after the dot
  1459. char buffer[64];
  1460. dtostrf(value, 1, magnitude.decimals, buffer);
  1461. #if BROKER_SUPPORT
  1462. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value, buffer);
  1463. #endif
  1464. #if MQTT_SUPPORT
  1465. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1466. #if SENSOR_PUBLISH_ADDRESSES
  1467. char topic[32];
  1468. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1469. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1470. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1471. } else {
  1472. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1473. }
  1474. #endif // SENSOR_PUBLISH_ADDRESSES
  1475. #endif // MQTT_SUPPORT
  1476. #if THINGSPEAK_SUPPORT
  1477. tspkEnqueueMeasurement(index, buffer);
  1478. #endif // THINGSPEAK_SUPPORT
  1479. #if DOMOTICZ_SUPPORT
  1480. domoticzSendMagnitude(magnitude.type, index, value, buffer);
  1481. #endif // DOMOTICZ_SUPPORT
  1482. }
  1483. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  1484. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  1485. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  1486. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  1487. _sensorReport(k, value);
  1488. return;
  1489. }
  1490. }
  1491. }
  1492. void _sensorInit() {
  1493. _sensors_ready = true;
  1494. _sensor_save_every = 0;
  1495. for (unsigned char i=0; i<_sensors.size(); i++) {
  1496. // Do not process an already initialized sensor
  1497. if (_sensors[i]->ready()) continue;
  1498. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  1499. // Force sensor to reload config
  1500. _sensors[i]->begin();
  1501. if (!_sensors[i]->ready()) {
  1502. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  1503. _sensors_ready = false;
  1504. continue;
  1505. }
  1506. // Initialize sensor magnitudes
  1507. for (unsigned char magnitude_index = 0; magnitude_index < _sensors[i]->count(); ++magnitude_index) {
  1508. const auto magnitude_type = _sensors[i]->type(magnitude_index);
  1509. _magnitudes.emplace_back(
  1510. magnitude_type, // specific type of the magnitude
  1511. magnitude_index, // index local to the sensor
  1512. sensor::Unit::None, // set up later, in configuration
  1513. _sensors[i] // bind the sensor to allow us to reference it later
  1514. );
  1515. if (MAGNITUDE_ENERGY == magnitude_type) {
  1516. _sensor_save_count.push_back(0);
  1517. }
  1518. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1519. magnitudeTopic(magnitude_type).c_str(),
  1520. sensor_magnitude_t::counts(magnitude_type)
  1521. );
  1522. }
  1523. // Hook callback
  1524. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1525. _sensorCallback(i, type, value);
  1526. });
  1527. // Custom initializations, based on IDs
  1528. switch (_sensors[i]->getID()) {
  1529. case SENSOR_MICS2710_ID:
  1530. case SENSOR_MICS5525_ID: {
  1531. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[i]);
  1532. sensor->setR0(getSetting("snsR0", sensor->getR0()));
  1533. sensor->setRS(getSetting("snsRS", sensor->getRS()));
  1534. sensor->setRL(getSetting("snsRL", sensor->getRL()));
  1535. break;
  1536. }
  1537. default:
  1538. break;
  1539. }
  1540. // TODO: compatibility proxy, fetch global key before indexed
  1541. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  1542. return getSetting({key, index}, getSetting(key, default_value));
  1543. };
  1544. if (_sensorIsEmon(_sensors[i])) {
  1545. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[i]);
  1546. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1547. sensor->resetEnergy(index, _sensorEnergyTotal(index));
  1548. sensor->setCurrentRatio(
  1549. get_ratio("pwrRatioC", index, sensor->getCurrentRatio(index))
  1550. );
  1551. sensor->setVoltageRatio(
  1552. get_ratio("pwrRatioV", index, sensor->getVoltageRatio(index))
  1553. );
  1554. sensor->setPowerRatio(
  1555. get_ratio("pwrRatioP", index, sensor->getPowerRatio(index))
  1556. );
  1557. sensor->setEnergyRatio(
  1558. get_ratio("pwrRatioE", index, sensor->getEnergyRatio(index))
  1559. );
  1560. sensor->setVoltage(
  1561. get_ratio("pwrVoltage", index, sensor->getVoltage(index))
  1562. );
  1563. }
  1564. }
  1565. }
  1566. }
  1567. namespace settings {
  1568. namespace internal {
  1569. template <>
  1570. sensor::Unit convert(const String& string) {
  1571. const int value = string.toInt();
  1572. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1573. return static_cast<sensor::Unit>(value);
  1574. }
  1575. return sensor::Unit::None;
  1576. }
  1577. } // ns settings::internal
  1578. } // ns settings
  1579. void _sensorConfigure() {
  1580. // General sensor settings for reporting and saving
  1581. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1582. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1583. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  1584. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  1585. // Per-magnitude min & max delta settings
  1586. // - min controls whether we report at all when report_count overflows
  1587. // - max will trigger report as soon as read value is greater than the specified delta
  1588. // (atm this works best for accumulated magnitudes, like energy)
  1589. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  1590. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  1591. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  1592. // Specific sensor settings
  1593. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  1594. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1595. {
  1596. if (getSetting("snsResetCalibration", false)) {
  1597. switch (_sensors[index]->getID()) {
  1598. case SENSOR_MICS2710_ID:
  1599. case SENSOR_MICS5525_ID: {
  1600. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  1601. sensor->calibrate();
  1602. setSetting("snsR0", sensor->getR0());
  1603. break;
  1604. }
  1605. default:
  1606. break;
  1607. }
  1608. }
  1609. }
  1610. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  1611. if (_sensorIsEmon(_sensors[index])) {
  1612. // TODO: ::isEmon() ?
  1613. double value;
  1614. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  1615. if ((value = getSetting("pwrExpectedC", 0.0))) {
  1616. sensor->expectedCurrent(value);
  1617. delSetting("pwrExpectedC");
  1618. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1619. }
  1620. if ((value = getSetting("pwrExpectedV", 0.0))) {
  1621. delSetting("pwrExpectedV");
  1622. sensor->expectedVoltage(value);
  1623. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1624. }
  1625. if ((value = getSetting("pwrExpectedP", 0.0))) {
  1626. delSetting("pwrExpectedP");
  1627. sensor->expectedPower(value);
  1628. setSetting("pwrRatioP", sensor->getPowerRatio());
  1629. }
  1630. if (getSetting("pwrResetE", false)) {
  1631. delSetting("pwrResetE");
  1632. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1633. sensor->resetEnergy(index);
  1634. _sensorResetEnergyTotal(index);
  1635. }
  1636. }
  1637. if (getSetting("pwrResetCalibration", false)) {
  1638. delSetting("pwrResetCalibration");
  1639. delSetting("pwrRatioC");
  1640. delSetting("pwrRatioV");
  1641. delSetting("pwrRatioP");
  1642. sensor->resetRatios();
  1643. }
  1644. sensor->setEnergyRatio(getSetting("pwrRatioE", sensor->getEnergyRatio()));
  1645. } // is emon?
  1646. }
  1647. // Update magnitude config, filter sizes and reset energy if needed
  1648. {
  1649. // TODO: instead of using global enum, have a local mapping?
  1650. const auto tmpUnits = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS);
  1651. const auto pwrUnits = getSetting("pwrUnits", SENSOR_POWER_UNITS);
  1652. const auto eneUnits = getSetting("eneUnits", SENSOR_ENERGY_UNITS);
  1653. // TODO: map MAGNITUDE_... type to a specific string? nvm the preprocessor flags, just focus on settings
  1654. const auto tmpCorrection = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION);
  1655. const auto humCorrection = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION);
  1656. const auto luxCorrection = getSetting("luxCorrection", SENSOR_LUX_CORRECTION);
  1657. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  1658. auto& magnitude = _magnitudes.at(index);
  1659. switch (magnitude.type) {
  1660. case MAGNITUDE_TEMPERATURE:
  1661. magnitude.units = _magnitudeUnitFilter(
  1662. magnitude,
  1663. getSetting({"tmpUnits", magnitude.global}, tmpUnits)
  1664. );
  1665. magnitude.correction = getSetting({"tmpCorrection", magnitude.global}, tmpCorrection);
  1666. break;
  1667. case MAGNITUDE_HUMIDITY:
  1668. magnitude.correction = getSetting({"humCorrection", magnitude.global}, humCorrection);
  1669. break;
  1670. case MAGNITUDE_POWER_ACTIVE:
  1671. magnitude.units = _magnitudeUnitFilter(
  1672. magnitude,
  1673. getSetting({"pwrUnits", magnitude.global}, pwrUnits)
  1674. );
  1675. break;
  1676. case MAGNITUDE_ENERGY:
  1677. magnitude.units = _magnitudeUnitFilter(
  1678. magnitude,
  1679. getSetting({"eneUnits", magnitude.global}, eneUnits)
  1680. );
  1681. break;
  1682. case MAGNITUDE_LUX:
  1683. magnitude.correction = getSetting({"luxCorrection", magnitude.global}, luxCorrection);
  1684. break;
  1685. default:
  1686. magnitude.units = magnitude.sensor->units(magnitude.local);
  1687. break;
  1688. }
  1689. // some sensors can override decimal values if sensor has more precision than default
  1690. {
  1691. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  1692. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  1693. magnitude.decimals = (unsigned char) decimals;
  1694. }
  1695. // adjust min & max change delta value to trigger report
  1696. // TODO: find a proper way to extend this to min/max of any magnitude
  1697. {
  1698. auto min_default = 0.0;
  1699. auto max_default = 0.0;
  1700. switch (magnitude.type) {
  1701. case MAGNITUDE_TEMPERATURE:
  1702. min_default = tmp_min_delta;
  1703. break;
  1704. case MAGNITUDE_HUMIDITY:
  1705. min_default = hum_min_delta;
  1706. break;
  1707. case MAGNITUDE_ENERGY:
  1708. max_default = ene_max_delta;
  1709. break;
  1710. default:
  1711. break;
  1712. }
  1713. magnitude.min_change = getSetting({"snsMinDelta", index}, min_default);
  1714. magnitude.max_change = getSetting({"snsMaxDelta", index}, max_default);
  1715. }
  1716. // in case we don't save energy periodically, purge existing value in ram & settings
  1717. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  1718. _sensorResetEnergyTotal(magnitude.global);
  1719. }
  1720. }
  1721. }
  1722. saveSettings();
  1723. }
  1724. // -----------------------------------------------------------------------------
  1725. // Public
  1726. // -----------------------------------------------------------------------------
  1727. unsigned char sensorCount() {
  1728. return _sensors.size();
  1729. }
  1730. unsigned char magnitudeCount() {
  1731. return _magnitudes.size();
  1732. }
  1733. String magnitudeName(unsigned char index) {
  1734. if (index < _magnitudes.size()) {
  1735. sensor_magnitude_t magnitude = _magnitudes[index];
  1736. return magnitude.sensor->slot(magnitude.local);
  1737. }
  1738. return String();
  1739. }
  1740. unsigned char magnitudeType(unsigned char index) {
  1741. if (index < _magnitudes.size()) {
  1742. return int(_magnitudes[index].type);
  1743. }
  1744. return MAGNITUDE_NONE;
  1745. }
  1746. double magnitudeValue(unsigned char index) {
  1747. if (index < _magnitudes.size()) {
  1748. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  1749. }
  1750. return DBL_MIN;
  1751. }
  1752. unsigned char magnitudeIndex(unsigned char index) {
  1753. if (index < _magnitudes.size()) {
  1754. return int(_magnitudes[index].global);
  1755. }
  1756. return 0;
  1757. }
  1758. String magnitudeTopicIndex(unsigned char index) {
  1759. char topic[32] = {0};
  1760. if (index < _magnitudes.size()) {
  1761. sensor_magnitude_t magnitude = _magnitudes[index];
  1762. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1763. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1764. } else {
  1765. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1766. }
  1767. }
  1768. return String(topic);
  1769. }
  1770. // -----------------------------------------------------------------------------
  1771. void _sensorBackwards() {
  1772. // Some keys from older versions were longer
  1773. moveSetting("powerUnits", "pwrUnits");
  1774. moveSetting("energyUnits", "eneUnits");
  1775. // Energy is now indexed (based on magnitude.global)
  1776. moveSetting("eneTotal", "eneTotal0");
  1777. // Update PZEM004T energy total across multiple devices
  1778. moveSettings("pzEneTotal", "eneTotal");
  1779. // Unit ID is no longer shared, drop when equal to Min_ or None
  1780. const char *keys[3] = {
  1781. "pwrUnits", "eneUnits", "tmpUnits"
  1782. };
  1783. for (auto* key : keys) {
  1784. const auto units = getSetting(key);
  1785. if (units.length() && (units.equals("0") || units.equals("1"))) {
  1786. delSetting(key);
  1787. }
  1788. }
  1789. }
  1790. void sensorSetup() {
  1791. // Settings backwards compatibility
  1792. _sensorBackwards();
  1793. // Load configured sensors and set up all of magnitudes
  1794. _sensorLoad();
  1795. _sensorInit();
  1796. // Configure based on settings
  1797. _sensorConfigure();
  1798. // Websockets integration, send sensor readings and configuration
  1799. #if WEB_SUPPORT
  1800. wsRegister()
  1801. .onVisible(_sensorWebSocketOnVisible)
  1802. .onConnected(_sensorWebSocketOnConnected)
  1803. .onData(_sensorWebSocketSendData)
  1804. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  1805. #endif
  1806. // MQTT receive callback, atm only for energy reset
  1807. #if MQTT_SUPPORT
  1808. mqttRegister(_sensorMqttCallback);
  1809. #endif
  1810. // API
  1811. #if API_SUPPORT
  1812. _sensorAPISetup();
  1813. #endif
  1814. // Terminal
  1815. #if TERMINAL_SUPPORT
  1816. _sensorInitCommands();
  1817. #endif
  1818. // Main callbacks
  1819. espurnaRegisterLoop(sensorLoop);
  1820. espurnaRegisterReload(_sensorConfigure);
  1821. }
  1822. void sensorLoop() {
  1823. // Check if we still have uninitialized sensors
  1824. static unsigned long last_init = 0;
  1825. if (!_sensors_ready) {
  1826. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1827. last_init = millis();
  1828. _sensorInit();
  1829. }
  1830. }
  1831. if (_magnitudes.size() == 0) return;
  1832. // Tick hook, called every loop()
  1833. _sensorTick();
  1834. // Check if we should read new data
  1835. static unsigned long last_update = 0;
  1836. static unsigned long report_count = 0;
  1837. if (millis() - last_update > _sensor_read_interval) {
  1838. last_update = millis();
  1839. report_count = (report_count + 1) % _sensor_report_every;
  1840. double value_raw; // holds the raw value as the sensor returns it
  1841. double value_show; // holds the processed value applying units and decimals
  1842. double value_filtered; // holds the processed value applying filters, and the units and decimals
  1843. // Pre-read hook, called every reading
  1844. _sensorPre();
  1845. // Get the first relay state
  1846. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1847. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1848. #endif
  1849. // Get readings
  1850. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1851. sensor_magnitude_t magnitude = _magnitudes[i];
  1852. if (magnitude.sensor->status()) {
  1853. // -------------------------------------------------------------
  1854. // Instant value
  1855. // -------------------------------------------------------------
  1856. value_raw = magnitude.sensor->value(magnitude.local);
  1857. // Completely remove spurious values if relay is OFF
  1858. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1859. switch (magnitude.type) {
  1860. case MAGNITUDE_POWER_ACTIVE:
  1861. case MAGNITUDE_POWER_REACTIVE:
  1862. case MAGNITUDE_POWER_APPARENT:
  1863. case MAGNITUDE_POWER_FACTOR:
  1864. case MAGNITUDE_CURRENT:
  1865. case MAGNITUDE_ENERGY_DELTA:
  1866. if (relay_off) {
  1867. value_raw = 0.0;
  1868. }
  1869. break;
  1870. default:
  1871. break;
  1872. }
  1873. #endif
  1874. _magnitudes[i].last = value_raw;
  1875. // -------------------------------------------------------------
  1876. // Processing (filters)
  1877. // -------------------------------------------------------------
  1878. magnitude.filter->add(value_raw);
  1879. // Special case for MovingAverageFilter
  1880. switch (magnitude.type) {
  1881. case MAGNITUDE_COUNT:
  1882. case MAGNITUDE_GEIGER_CPM:
  1883. case MAGNITUDE_GEIGER_SIEVERT:
  1884. value_raw = magnitude.filter->result();
  1885. break;
  1886. default:
  1887. break;
  1888. }
  1889. // -------------------------------------------------------------
  1890. // Procesing (units and decimals)
  1891. // -------------------------------------------------------------
  1892. value_show = _magnitudeProcess(magnitude, value_raw);
  1893. #if BROKER_SUPPORT
  1894. {
  1895. char buffer[64];
  1896. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1897. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value_show, buffer);
  1898. }
  1899. #endif
  1900. // -------------------------------------------------------------
  1901. // Debug
  1902. // -------------------------------------------------------------
  1903. #if SENSOR_DEBUG
  1904. {
  1905. char buffer[64];
  1906. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1907. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1908. magnitude.sensor->slot(magnitude.local).c_str(),
  1909. magnitudeTopic(magnitude.type).c_str(),
  1910. buffer,
  1911. _magnitudeUnits(magnitude).c_str()
  1912. );
  1913. }
  1914. #endif // SENSOR_DEBUG
  1915. // -------------------------------------------------------------------
  1916. // Report when
  1917. // - report_count overflows after reaching _sensor_report_every
  1918. // - when magnitude specifies max_change and we greater or equal to it
  1919. // -------------------------------------------------------------------
  1920. bool report = (0 == report_count);
  1921. if (magnitude.max_change > 0) {
  1922. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  1923. }
  1924. // Special case for energy, save readings to RAM and EEPROM
  1925. if (MAGNITUDE_ENERGY == magnitude.type) {
  1926. _magnitudeSaveEnergyTotal(magnitude, report);
  1927. }
  1928. if (report) {
  1929. value_filtered = magnitude.filter->result();
  1930. value_filtered = _magnitudeProcess(magnitude, value_filtered);
  1931. magnitude.filter->reset();
  1932. if (magnitude.filter->size() != _sensor_report_every) {
  1933. magnitude.filter->resize(_sensor_report_every);
  1934. }
  1935. // Check if there is a minimum change threshold to report
  1936. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  1937. _magnitudes[i].reported = value_filtered;
  1938. _sensorReport(i, value_filtered);
  1939. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  1940. } // if (report_count == 0)
  1941. } // if (magnitude.sensor->status())
  1942. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1943. // Post-read hook, called every reading
  1944. _sensorPost();
  1945. // And report data to modules that don't specifically track them
  1946. #if WEB_SUPPORT
  1947. wsPost(_sensorWebSocketSendData);
  1948. #endif
  1949. #if THINGSPEAK_SUPPORT
  1950. if (report_count == 0) tspkFlush();
  1951. #endif
  1952. }
  1953. }
  1954. #endif // SENSOR_SUPPORT