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.

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