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.

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