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.

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