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.

2468 lines
74 KiB

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