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
83 KiB

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