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.

2368 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->setSELCurrent(HLW8012_SEL_CURRENT);
  1240. _sensors.push_back(sensor);
  1241. }
  1242. #endif
  1243. #if LDR_SUPPORT
  1244. {
  1245. LDRSensor * sensor = new LDRSensor();
  1246. sensor->setSamples(LDR_SAMPLES);
  1247. sensor->setDelay(LDR_DELAY);
  1248. sensor->setType(LDR_TYPE);
  1249. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1250. sensor->setResistor(LDR_RESISTOR);
  1251. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1252. _sensors.push_back(sensor);
  1253. }
  1254. #endif
  1255. #if MHZ19_SUPPORT
  1256. {
  1257. MHZ19Sensor * sensor = new MHZ19Sensor();
  1258. sensor->setRX(MHZ19_RX_PIN);
  1259. sensor->setTX(MHZ19_TX_PIN);
  1260. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1261. _sensors.push_back(sensor);
  1262. }
  1263. #endif
  1264. #if MICS2710_SUPPORT
  1265. {
  1266. MICS2710Sensor * sensor = new MICS2710Sensor();
  1267. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1268. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1269. sensor->setR0(MICS2710_R0);
  1270. sensor->setRL(MICS2710_RL);
  1271. sensor->setRS(0);
  1272. _sensors.push_back(sensor);
  1273. }
  1274. #endif
  1275. #if MICS5525_SUPPORT
  1276. {
  1277. MICS5525Sensor * sensor = new MICS5525Sensor();
  1278. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1279. sensor->setR0(MICS5525_R0);
  1280. sensor->setRL(MICS5525_RL);
  1281. sensor->setRS(0);
  1282. _sensors.push_back(sensor);
  1283. }
  1284. #endif
  1285. #if NTC_SUPPORT
  1286. {
  1287. NTCSensor * sensor = new NTCSensor();
  1288. sensor->setSamples(NTC_SAMPLES);
  1289. sensor->setDelay(NTC_DELAY);
  1290. sensor->setUpstreamResistor(NTC_R_UP);
  1291. sensor->setDownstreamResistor(NTC_R_DOWN);
  1292. sensor->setBeta(NTC_BETA);
  1293. sensor->setR0(NTC_R0);
  1294. sensor->setT0(NTC_T0);
  1295. _sensors.push_back(sensor);
  1296. }
  1297. #endif
  1298. #if PMSX003_SUPPORT
  1299. {
  1300. PMSX003Sensor * sensor = new PMSX003Sensor();
  1301. #if PMS_USE_SOFT
  1302. sensor->setRX(PMS_RX_PIN);
  1303. sensor->setTX(PMS_TX_PIN);
  1304. #else
  1305. sensor->setSerial(& PMS_HW_PORT);
  1306. #endif
  1307. sensor->setType(PMS_TYPE);
  1308. _sensors.push_back(sensor);
  1309. }
  1310. #endif
  1311. #if PULSEMETER_SUPPORT
  1312. {
  1313. PulseMeterSensor * sensor = new PulseMeterSensor();
  1314. sensor->setGPIO(PULSEMETER_PIN);
  1315. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1316. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1317. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1318. _sensors.push_back(sensor);
  1319. }
  1320. #endif
  1321. #if PZEM004T_SUPPORT
  1322. {
  1323. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1324. if (!addresses.length()) {
  1325. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1326. return;
  1327. }
  1328. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1329. sensor->setAddresses(addresses.c_str());
  1330. if (getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1331. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1332. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1333. } else {
  1334. sensor->setSerial(& PZEM004T_HW_PORT);
  1335. }
  1336. _sensors.push_back(sensor);
  1337. #if TERMINAL_SUPPORT
  1338. pzem004tInitCommands();
  1339. #endif
  1340. }
  1341. #endif
  1342. #if SENSEAIR_SUPPORT
  1343. {
  1344. SenseAirSensor * sensor = new SenseAirSensor();
  1345. sensor->setRX(SENSEAIR_RX_PIN);
  1346. sensor->setTX(SENSEAIR_TX_PIN);
  1347. _sensors.push_back(sensor);
  1348. }
  1349. #endif
  1350. #if SDS011_SUPPORT
  1351. {
  1352. SDS011Sensor * sensor = new SDS011Sensor();
  1353. sensor->setRX(SDS011_RX_PIN);
  1354. sensor->setTX(SDS011_TX_PIN);
  1355. _sensors.push_back(sensor);
  1356. }
  1357. #endif
  1358. #if SHT3X_I2C_SUPPORT
  1359. {
  1360. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1361. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1362. _sensors.push_back(sensor);
  1363. }
  1364. #endif
  1365. #if SI7021_SUPPORT
  1366. {
  1367. SI7021Sensor * sensor = new SI7021Sensor();
  1368. sensor->setAddress(SI7021_ADDRESS);
  1369. _sensors.push_back(sensor);
  1370. }
  1371. #endif
  1372. #if T6613_SUPPORT
  1373. {
  1374. T6613Sensor * sensor = new T6613Sensor();
  1375. sensor->setRX(T6613_RX_PIN);
  1376. sensor->setTX(T6613_TX_PIN);
  1377. _sensors.push_back(sensor);
  1378. }
  1379. #endif
  1380. #if TMP3X_SUPPORT
  1381. {
  1382. TMP3XSensor * sensor = new TMP3XSensor();
  1383. sensor->setType(TMP3X_TYPE);
  1384. _sensors.push_back(sensor);
  1385. }
  1386. #endif
  1387. #if V9261F_SUPPORT
  1388. {
  1389. V9261FSensor * sensor = new V9261FSensor();
  1390. sensor->setRX(V9261F_PIN);
  1391. sensor->setInverted(V9261F_PIN_INVERSE);
  1392. _sensors.push_back(sensor);
  1393. }
  1394. #endif
  1395. #if MAX6675_SUPPORT
  1396. {
  1397. MAX6675Sensor * sensor = new MAX6675Sensor();
  1398. sensor->setCS(MAX6675_CS_PIN);
  1399. sensor->setSO(MAX6675_SO_PIN);
  1400. sensor->setSCK(MAX6675_SCK_PIN);
  1401. _sensors.push_back(sensor);
  1402. }
  1403. #endif
  1404. #if VEML6075_SUPPORT
  1405. {
  1406. VEML6075Sensor * sensor = new VEML6075Sensor();
  1407. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1408. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1409. _sensors.push_back(sensor);
  1410. }
  1411. #endif
  1412. #if VL53L1X_SUPPORT
  1413. {
  1414. VL53L1XSensor * sensor = new VL53L1XSensor();
  1415. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1416. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1417. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1418. _sensors.push_back(sensor);
  1419. }
  1420. #endif
  1421. #if EZOPH_SUPPORT
  1422. {
  1423. EZOPHSensor * sensor = new EZOPHSensor();
  1424. sensor->setRX(EZOPH_RX_PIN);
  1425. sensor->setTX(EZOPH_TX_PIN);
  1426. _sensors.push_back(sensor);
  1427. }
  1428. #endif
  1429. #if ADE7953_SUPPORT
  1430. {
  1431. ADE7953Sensor * sensor = new ADE7953Sensor();
  1432. sensor->setAddress(ADE7953_ADDRESS);
  1433. _sensors.push_back(sensor);
  1434. }
  1435. #endif
  1436. #if SI1145_SUPPORT
  1437. {
  1438. SI1145Sensor * sensor = new SI1145Sensor();
  1439. sensor->setAddress(SI1145_ADDRESS);
  1440. _sensors.push_back(sensor);
  1441. }
  1442. #endif
  1443. #if HDC1080_SUPPORT
  1444. {
  1445. HDC1080Sensor * sensor = new HDC1080Sensor();
  1446. sensor->setAddress(HDC1080_ADDRESS);
  1447. _sensors.push_back(sensor);
  1448. }
  1449. #endif
  1450. }
  1451. void _sensorReport(unsigned char index, double value) {
  1452. const auto& magnitude = _magnitudes.at(index);
  1453. // XXX: ensure that the received 'value' will fit here
  1454. // dtostrf 2nd arg only controls leading zeroes and the
  1455. // 3rd is only for the part after the dot
  1456. char buffer[64];
  1457. dtostrf(value, 1, magnitude.decimals, buffer);
  1458. #if BROKER_SUPPORT
  1459. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value, buffer);
  1460. #endif
  1461. #if MQTT_SUPPORT
  1462. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1463. #if SENSOR_PUBLISH_ADDRESSES
  1464. char topic[32];
  1465. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1466. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1467. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1468. } else {
  1469. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1470. }
  1471. #endif // SENSOR_PUBLISH_ADDRESSES
  1472. #endif // MQTT_SUPPORT
  1473. #if THINGSPEAK_SUPPORT
  1474. tspkEnqueueMeasurement(index, buffer);
  1475. #endif // THINGSPEAK_SUPPORT
  1476. #if DOMOTICZ_SUPPORT
  1477. domoticzSendMagnitude(magnitude.type, index, value, buffer);
  1478. #endif // DOMOTICZ_SUPPORT
  1479. }
  1480. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  1481. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  1482. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  1483. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  1484. _sensorReport(k, value);
  1485. return;
  1486. }
  1487. }
  1488. }
  1489. void _sensorInit() {
  1490. _sensors_ready = true;
  1491. _sensor_save_every = 0;
  1492. for (unsigned char i=0; i<_sensors.size(); i++) {
  1493. // Do not process an already initialized sensor
  1494. if (_sensors[i]->ready()) continue;
  1495. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  1496. // Force sensor to reload config
  1497. _sensors[i]->begin();
  1498. if (!_sensors[i]->ready()) {
  1499. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  1500. _sensors_ready = false;
  1501. continue;
  1502. }
  1503. // Initialize sensor magnitudes
  1504. for (unsigned char magnitude_index = 0; magnitude_index < _sensors[i]->count(); ++magnitude_index) {
  1505. const auto magnitude_type = _sensors[i]->type(magnitude_index);
  1506. _magnitudes.emplace_back(
  1507. magnitude_type, // specific type of the magnitude
  1508. magnitude_index, // index local to the sensor
  1509. sensor::Unit::None, // set up later, in configuration
  1510. _sensors[i] // bind the sensor to allow us to reference it later
  1511. );
  1512. if (MAGNITUDE_ENERGY == magnitude_type) {
  1513. _sensor_save_count.push_back(0);
  1514. }
  1515. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1516. magnitudeTopic(magnitude_type).c_str(),
  1517. sensor_magnitude_t::counts(magnitude_type)
  1518. );
  1519. }
  1520. // Hook callback
  1521. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1522. _sensorCallback(i, type, value);
  1523. });
  1524. // Custom initializations, based on IDs
  1525. switch (_sensors[i]->getID()) {
  1526. case SENSOR_MICS2710_ID:
  1527. case SENSOR_MICS5525_ID: {
  1528. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[i]);
  1529. sensor->setR0(getSetting("snsR0", sensor->getR0()));
  1530. sensor->setRS(getSetting("snsRS", sensor->getRS()));
  1531. sensor->setRL(getSetting("snsRL", sensor->getRL()));
  1532. break;
  1533. }
  1534. default:
  1535. break;
  1536. }
  1537. // TODO: compatibility proxy, fetch global key before indexed
  1538. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  1539. return getSetting({key, index}, getSetting(key, default_value));
  1540. };
  1541. if (_sensorIsEmon(_sensors[i])) {
  1542. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[i]);
  1543. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1544. sensor->resetEnergy(index, _sensorEnergyTotal(index));
  1545. sensor->setCurrentRatio(
  1546. get_ratio("pwrRatioC", index, sensor->getCurrentRatio(index))
  1547. );
  1548. sensor->setVoltageRatio(
  1549. get_ratio("pwrRatioV", index, sensor->getVoltageRatio(index))
  1550. );
  1551. sensor->setPowerRatio(
  1552. get_ratio("pwrRatioP", index, sensor->getPowerRatio(index))
  1553. );
  1554. sensor->setEnergyRatio(
  1555. get_ratio("pwrRatioE", index, sensor->getEnergyRatio(index))
  1556. );
  1557. sensor->setVoltage(
  1558. get_ratio("pwrVoltage", index, sensor->getVoltage(index))
  1559. );
  1560. }
  1561. }
  1562. }
  1563. }
  1564. namespace settings {
  1565. namespace internal {
  1566. template <>
  1567. sensor::Unit convert(const String& string) {
  1568. const int value = string.toInt();
  1569. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1570. return static_cast<sensor::Unit>(value);
  1571. }
  1572. return sensor::Unit::None;
  1573. }
  1574. } // ns settings::internal
  1575. } // ns settings
  1576. void _sensorConfigure() {
  1577. // General sensor settings for reporting and saving
  1578. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1579. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1580. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  1581. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  1582. // Per-magnitude min & max delta settings
  1583. // - min controls whether we report at all when report_count overflows
  1584. // - max will trigger report as soon as read value is greater than the specified delta
  1585. // (atm this works best for accumulated magnitudes, like energy)
  1586. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  1587. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  1588. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  1589. // Specific sensor settings
  1590. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  1591. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1592. {
  1593. if (getSetting("snsResetCalibration", false)) {
  1594. switch (_sensors[index]->getID()) {
  1595. case SENSOR_MICS2710_ID:
  1596. case SENSOR_MICS5525_ID: {
  1597. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  1598. sensor->calibrate();
  1599. setSetting("snsR0", sensor->getR0());
  1600. break;
  1601. }
  1602. default:
  1603. break;
  1604. }
  1605. }
  1606. }
  1607. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  1608. if (_sensorIsEmon(_sensors[index])) {
  1609. // TODO: ::isEmon() ?
  1610. double value;
  1611. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  1612. if ((value = getSetting("pwrExpectedC", 0.0))) {
  1613. sensor->expectedCurrent(value);
  1614. delSetting("pwrExpectedC");
  1615. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1616. }
  1617. if ((value = getSetting("pwrExpectedV", 0.0))) {
  1618. delSetting("pwrExpectedV");
  1619. sensor->expectedVoltage(value);
  1620. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1621. }
  1622. if ((value = getSetting("pwrExpectedP", 0.0))) {
  1623. delSetting("pwrExpectedP");
  1624. sensor->expectedPower(value);
  1625. setSetting("pwrRatioP", sensor->getPowerRatio());
  1626. }
  1627. if (getSetting("pwrResetE", false)) {
  1628. delSetting("pwrResetE");
  1629. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1630. sensor->resetEnergy(index);
  1631. _sensorResetEnergyTotal(index);
  1632. }
  1633. }
  1634. if (getSetting("pwrResetCalibration", false)) {
  1635. delSetting("pwrResetCalibration");
  1636. delSetting("pwrRatioC");
  1637. delSetting("pwrRatioV");
  1638. delSetting("pwrRatioP");
  1639. sensor->resetRatios();
  1640. }
  1641. sensor->setEnergyRatio(getSetting("pwrRatioE", sensor->getEnergyRatio()));
  1642. } // is emon?
  1643. }
  1644. // Update magnitude config, filter sizes and reset energy if needed
  1645. {
  1646. // TODO: instead of using global enum, have a local mapping?
  1647. const auto tmpUnits = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS);
  1648. const auto pwrUnits = getSetting("pwrUnits", SENSOR_POWER_UNITS);
  1649. const auto eneUnits = getSetting("eneUnits", SENSOR_ENERGY_UNITS);
  1650. // TODO: map MAGNITUDE_... type to a specific string? nvm the preprocessor flags, just focus on settings
  1651. const auto tmpCorrection = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION);
  1652. const auto humCorrection = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION);
  1653. const auto luxCorrection = getSetting("luxCorrection", SENSOR_LUX_CORRECTION);
  1654. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  1655. auto& magnitude = _magnitudes.at(index);
  1656. switch (magnitude.type) {
  1657. case MAGNITUDE_TEMPERATURE:
  1658. magnitude.units = _magnitudeUnitFilter(
  1659. magnitude,
  1660. getSetting({"tmpUnits", magnitude.global}, tmpUnits)
  1661. );
  1662. magnitude.correction = getSetting({"tmpCorrection", magnitude.global}, tmpCorrection);
  1663. break;
  1664. case MAGNITUDE_HUMIDITY:
  1665. magnitude.correction = getSetting({"humCorrection", magnitude.global}, humCorrection);
  1666. break;
  1667. case MAGNITUDE_POWER_ACTIVE:
  1668. magnitude.units = _magnitudeUnitFilter(
  1669. magnitude,
  1670. getSetting({"pwrUnits", magnitude.global}, pwrUnits)
  1671. );
  1672. break;
  1673. case MAGNITUDE_ENERGY:
  1674. magnitude.units = _magnitudeUnitFilter(
  1675. magnitude,
  1676. getSetting({"eneUnits", magnitude.global}, eneUnits)
  1677. );
  1678. break;
  1679. case MAGNITUDE_LUX:
  1680. magnitude.correction = getSetting({"luxCorrection", magnitude.global}, luxCorrection);
  1681. break;
  1682. default:
  1683. magnitude.units = magnitude.sensor->units(magnitude.local);
  1684. break;
  1685. }
  1686. // some sensors can override decimal values if sensor has more precision than default
  1687. {
  1688. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  1689. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  1690. magnitude.decimals = (unsigned char) decimals;
  1691. }
  1692. // adjust min & max change delta value to trigger report
  1693. // TODO: find a proper way to extend this to min/max of any magnitude
  1694. {
  1695. auto min_default = 0.0;
  1696. auto max_default = 0.0;
  1697. switch (magnitude.type) {
  1698. case MAGNITUDE_TEMPERATURE:
  1699. min_default = tmp_min_delta;
  1700. break;
  1701. case MAGNITUDE_HUMIDITY:
  1702. min_default = hum_min_delta;
  1703. break;
  1704. case MAGNITUDE_ENERGY:
  1705. max_default = ene_max_delta;
  1706. break;
  1707. default:
  1708. break;
  1709. }
  1710. magnitude.min_change = getSetting({"snsMinDelta", index}, min_default);
  1711. magnitude.max_change = getSetting({"snsMaxDelta", index}, max_default);
  1712. }
  1713. // in case we don't save energy periodically, purge existing value in ram & settings
  1714. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  1715. _sensorResetEnergyTotal(magnitude.global);
  1716. }
  1717. }
  1718. }
  1719. saveSettings();
  1720. }
  1721. // -----------------------------------------------------------------------------
  1722. // Public
  1723. // -----------------------------------------------------------------------------
  1724. unsigned char sensorCount() {
  1725. return _sensors.size();
  1726. }
  1727. unsigned char magnitudeCount() {
  1728. return _magnitudes.size();
  1729. }
  1730. String magnitudeName(unsigned char index) {
  1731. if (index < _magnitudes.size()) {
  1732. sensor_magnitude_t magnitude = _magnitudes[index];
  1733. return magnitude.sensor->slot(magnitude.local);
  1734. }
  1735. return String();
  1736. }
  1737. unsigned char magnitudeType(unsigned char index) {
  1738. if (index < _magnitudes.size()) {
  1739. return int(_magnitudes[index].type);
  1740. }
  1741. return MAGNITUDE_NONE;
  1742. }
  1743. double magnitudeValue(unsigned char index) {
  1744. if (index < _magnitudes.size()) {
  1745. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  1746. }
  1747. return DBL_MIN;
  1748. }
  1749. unsigned char magnitudeIndex(unsigned char index) {
  1750. if (index < _magnitudes.size()) {
  1751. return int(_magnitudes[index].global);
  1752. }
  1753. return 0;
  1754. }
  1755. String magnitudeTopicIndex(unsigned char index) {
  1756. char topic[32] = {0};
  1757. if (index < _magnitudes.size()) {
  1758. sensor_magnitude_t magnitude = _magnitudes[index];
  1759. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1760. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1761. } else {
  1762. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1763. }
  1764. }
  1765. return String(topic);
  1766. }
  1767. // -----------------------------------------------------------------------------
  1768. void _sensorBackwards() {
  1769. // Some keys from older versions were longer
  1770. moveSetting("powerUnits", "pwrUnits");
  1771. moveSetting("energyUnits", "eneUnits");
  1772. // Energy is now indexed (based on magnitude.global)
  1773. moveSetting("eneTotal", "eneTotal0");
  1774. // Update PZEM004T energy total across multiple devices
  1775. moveSettings("pzEneTotal", "eneTotal");
  1776. // Unit ID is no longer shared, drop when equal to Min_ or None
  1777. const char *keys[3] = {
  1778. "pwrUnits", "eneUnits", "tmpUnits"
  1779. };
  1780. for (auto* key : keys) {
  1781. const auto units = getSetting(key);
  1782. if (units.length() && (units.equals("0") || units.equals("1"))) {
  1783. delSetting(key);
  1784. }
  1785. }
  1786. }
  1787. void sensorSetup() {
  1788. // Settings backwards compatibility
  1789. _sensorBackwards();
  1790. // Load configured sensors and set up all of magnitudes
  1791. _sensorLoad();
  1792. _sensorInit();
  1793. // Configure based on settings
  1794. _sensorConfigure();
  1795. // Websockets integration, send sensor readings and configuration
  1796. #if WEB_SUPPORT
  1797. wsRegister()
  1798. .onVisible(_sensorWebSocketOnVisible)
  1799. .onConnected(_sensorWebSocketOnConnected)
  1800. .onData(_sensorWebSocketSendData)
  1801. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  1802. #endif
  1803. // MQTT receive callback, atm only for energy reset
  1804. #if MQTT_SUPPORT
  1805. mqttRegister(_sensorMqttCallback);
  1806. #endif
  1807. // API
  1808. #if API_SUPPORT
  1809. _sensorAPISetup();
  1810. #endif
  1811. // Terminal
  1812. #if TERMINAL_SUPPORT
  1813. _sensorInitCommands();
  1814. #endif
  1815. // Main callbacks
  1816. espurnaRegisterLoop(sensorLoop);
  1817. espurnaRegisterReload(_sensorConfigure);
  1818. }
  1819. void sensorLoop() {
  1820. // Check if we still have uninitialized sensors
  1821. static unsigned long last_init = 0;
  1822. if (!_sensors_ready) {
  1823. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1824. last_init = millis();
  1825. _sensorInit();
  1826. }
  1827. }
  1828. if (_magnitudes.size() == 0) return;
  1829. // Tick hook, called every loop()
  1830. _sensorTick();
  1831. // Check if we should read new data
  1832. static unsigned long last_update = 0;
  1833. static unsigned long report_count = 0;
  1834. if (millis() - last_update > _sensor_read_interval) {
  1835. last_update = millis();
  1836. report_count = (report_count + 1) % _sensor_report_every;
  1837. double value_raw; // holds the raw value as the sensor returns it
  1838. double value_show; // holds the processed value applying units and decimals
  1839. double value_filtered; // holds the processed value applying filters, and the units and decimals
  1840. // Pre-read hook, called every reading
  1841. _sensorPre();
  1842. // Get the first relay state
  1843. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1844. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1845. #endif
  1846. // Get readings
  1847. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1848. sensor_magnitude_t magnitude = _magnitudes[i];
  1849. if (magnitude.sensor->status()) {
  1850. // -------------------------------------------------------------
  1851. // Instant value
  1852. // -------------------------------------------------------------
  1853. value_raw = magnitude.sensor->value(magnitude.local);
  1854. // Completely remove spurious values if relay is OFF
  1855. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1856. switch (magnitude.type) {
  1857. case MAGNITUDE_POWER_ACTIVE:
  1858. case MAGNITUDE_POWER_REACTIVE:
  1859. case MAGNITUDE_POWER_APPARENT:
  1860. case MAGNITUDE_POWER_FACTOR:
  1861. case MAGNITUDE_CURRENT:
  1862. case MAGNITUDE_ENERGY_DELTA:
  1863. if (relay_off) {
  1864. value_raw = 0.0;
  1865. }
  1866. break;
  1867. default:
  1868. break;
  1869. }
  1870. #endif
  1871. _magnitudes[i].last = value_raw;
  1872. // -------------------------------------------------------------
  1873. // Processing (filters)
  1874. // -------------------------------------------------------------
  1875. magnitude.filter->add(value_raw);
  1876. // Special case for MovingAverageFilter
  1877. switch (magnitude.type) {
  1878. case MAGNITUDE_COUNT:
  1879. case MAGNITUDE_GEIGER_CPM:
  1880. case MAGNITUDE_GEIGER_SIEVERT:
  1881. value_raw = magnitude.filter->result();
  1882. break;
  1883. default:
  1884. break;
  1885. }
  1886. // -------------------------------------------------------------
  1887. // Procesing (units and decimals)
  1888. // -------------------------------------------------------------
  1889. value_show = _magnitudeProcess(magnitude, value_raw);
  1890. #if BROKER_SUPPORT
  1891. {
  1892. char buffer[64];
  1893. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1894. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value_show, buffer);
  1895. }
  1896. #endif
  1897. // -------------------------------------------------------------
  1898. // Debug
  1899. // -------------------------------------------------------------
  1900. #if SENSOR_DEBUG
  1901. {
  1902. char buffer[64];
  1903. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1904. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1905. magnitude.sensor->slot(magnitude.local).c_str(),
  1906. magnitudeTopic(magnitude.type).c_str(),
  1907. buffer,
  1908. _magnitudeUnits(magnitude).c_str()
  1909. );
  1910. }
  1911. #endif // SENSOR_DEBUG
  1912. // -------------------------------------------------------------------
  1913. // Report when
  1914. // - report_count overflows after reaching _sensor_report_every
  1915. // - when magnitude specifies max_change and we greater or equal to it
  1916. // -------------------------------------------------------------------
  1917. bool report = (0 == report_count);
  1918. if (magnitude.max_change > 0) {
  1919. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  1920. }
  1921. // Special case for energy, save readings to RAM and EEPROM
  1922. if (MAGNITUDE_ENERGY == magnitude.type) {
  1923. _magnitudeSaveEnergyTotal(magnitude, report);
  1924. }
  1925. if (report) {
  1926. value_filtered = magnitude.filter->result();
  1927. value_filtered = _magnitudeProcess(magnitude, value_filtered);
  1928. magnitude.filter->reset();
  1929. if (magnitude.filter->size() != _sensor_report_every) {
  1930. magnitude.filter->resize(_sensor_report_every);
  1931. }
  1932. // Check if there is a minimum change threshold to report
  1933. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  1934. _magnitudes[i].reported = value_filtered;
  1935. _sensorReport(i, value_filtered);
  1936. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  1937. } // if (report_count == 0)
  1938. } // if (magnitude.sensor->status())
  1939. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1940. // Post-read hook, called every reading
  1941. _sensorPost();
  1942. // And report data to modules that don't specifically track them
  1943. #if WEB_SUPPORT
  1944. wsPost(_sensorWebSocketSendData);
  1945. #endif
  1946. #if THINGSPEAK_SUPPORT
  1947. if (report_count == 0) tspkFlush();
  1948. #endif
  1949. }
  1950. }
  1951. #endif // SENSOR_SUPPORT