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.

2835 lines
84 KiB

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