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.

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