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.

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