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.

2201 lines
67 KiB

7 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. #if SENSOR_SUPPORT
  6. #include <vector>
  7. #include <float.h>
  8. #include "broker.h"
  9. #include "domoticz.h"
  10. #include "mqtt.h"
  11. #include "ntp.h"
  12. #include "relay.h"
  13. #include "sensor.h"
  14. #include "terminal.h"
  15. #include "ws.h"
  16. struct sensor_magnitude_t {
  17. private:
  18. static unsigned char _counts[MAGNITUDE_MAX];
  19. public:
  20. static unsigned char counts(unsigned char type) {
  21. return _counts[type];
  22. }
  23. sensor_magnitude_t();
  24. sensor_magnitude_t(unsigned char type, unsigned char local, sensor::Unit units, BaseSensor* sensor);
  25. BaseSensor * sensor; // Sensor object
  26. BaseFilter * filter; // Filter object
  27. unsigned char type; // Type of measurement
  28. unsigned char local; // Local index in its provider
  29. unsigned char global; // Global index in its type
  30. unsigned char decimals; // Number of decimals in textual representation
  31. sensor::Unit units; // Units of measurement
  32. double last; // Last raw value from sensor (unfiltered)
  33. double reported; // Last reported value
  34. double min_change; // Minimum value change to report
  35. double max_change; // Maximum value change to report
  36. double correction; // Value correction (applied when processing)
  37. };
  38. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX];
  39. namespace sensor {
  40. // Base units
  41. // TODO: implement through a single class and allow direct access to the ::value
  42. KWh::KWh() :
  43. value(0)
  44. {}
  45. KWh::KWh(uint32_t value) :
  46. value(value)
  47. {}
  48. Ws::Ws() :
  49. value(0)
  50. {}
  51. Ws::Ws(uint32_t value) :
  52. value(value)
  53. {}
  54. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  55. Energy::Energy(KWh kwh, Ws ws) :
  56. kwh(kwh)
  57. {
  58. *this += ws;
  59. }
  60. Energy::Energy(KWh kwh) :
  61. kwh(kwh),
  62. ws()
  63. {}
  64. Energy::Energy(Ws ws) :
  65. kwh()
  66. {
  67. *this += ws;
  68. }
  69. Energy::Energy(double raw) {
  70. *this = raw;
  71. }
  72. Energy& Energy::operator =(double raw) {
  73. double _wh;
  74. kwh = modf(raw, &_wh);
  75. ws = _wh * 3600.0;
  76. return *this;
  77. }
  78. Energy& Energy::operator +=(Ws _ws) {
  79. while (_ws.value >= KwhMultiplier) {
  80. _ws.value -= KwhMultiplier;
  81. ++kwh.value;
  82. }
  83. ws.value += _ws.value;
  84. while (ws.value >= KwhMultiplier) {
  85. ws.value -= KwhMultiplier;
  86. ++kwh.value;
  87. }
  88. return *this;
  89. }
  90. Energy Energy::operator +(Ws watt_s) {
  91. Energy result(*this);
  92. result += watt_s;
  93. return result;
  94. }
  95. Energy::operator bool() {
  96. return (kwh.value > 0) && (ws.value > 0);
  97. }
  98. Ws Energy::asWs() {
  99. auto _kwh = kwh.value;
  100. while (_kwh >= KwhLimit) {
  101. _kwh -= KwhLimit;
  102. }
  103. return (_kwh * KwhMultiplier) + ws.value;
  104. }
  105. double Energy::asDouble() {
  106. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  107. }
  108. void Energy::reset() {
  109. kwh.value = 0;
  110. ws.value = 0;
  111. }
  112. } // namespace sensor
  113. bool _sensorIsEmon(BaseSensor* sensor) {
  114. return sensor->type() & sensor::type::Emon;
  115. }
  116. // ---------------------------------------------------------------------------
  117. std::vector<BaseSensor *> _sensors;
  118. std::vector<sensor_magnitude_t> _magnitudes;
  119. bool _sensors_ready = false;
  120. bool _sensor_realtime = API_REAL_TIME_VALUES;
  121. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  122. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  123. // Energy persistence
  124. std::vector<unsigned char> _sensor_save_count;
  125. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  126. // -----------------------------------------------------------------------------
  127. // Private
  128. // -----------------------------------------------------------------------------
  129. sensor_magnitude_t::sensor_magnitude_t() :
  130. sensor(nullptr),
  131. filter(nullptr),
  132. type(0),
  133. local(0),
  134. global(0),
  135. decimals(0),
  136. units(sensor::Unit::None),
  137. last(0.0),
  138. reported(0.0),
  139. min_change(0.0),
  140. max_change(0.0),
  141. correction(0.0)
  142. {}
  143. sensor_magnitude_t::sensor_magnitude_t(unsigned char type, unsigned char local, sensor::Unit units, BaseSensor* sensor) :
  144. sensor(sensor),
  145. filter(nullptr),
  146. type(type),
  147. local(local),
  148. global(_counts[type]),
  149. decimals(0),
  150. units(units),
  151. last(0.0),
  152. reported(0.0),
  153. min_change(0.0),
  154. max_change(0.0),
  155. correction(0.0)
  156. {
  157. ++_counts[type];
  158. switch (type) {
  159. case MAGNITUDE_ENERGY:
  160. filter = new LastFilter();
  161. case MAGNITUDE_ENERGY_DELTA:
  162. filter = new SumFilter();
  163. case MAGNITUDE_DIGITAL:
  164. filter = new MaxFilter();
  165. // For geiger counting moving average filter is the most appropriate if needed at all.
  166. case MAGNITUDE_COUNT:
  167. case MAGNITUDE_GEIGER_CPM:
  168. case MAGNITUDE_GEIGER_SIEVERT:
  169. filter = new MovingAverageFilter();
  170. default:
  171. filter = new MedianFilter();
  172. }
  173. filter->resize(_sensor_report_every);
  174. }
  175. // Hardcoded decimals for each magnitude
  176. unsigned char _sensorUnitDecimals(sensor::Unit unit) {
  177. switch (unit) {
  178. case sensor::Unit::Celcius:
  179. case sensor::Unit::Farenheit:
  180. return 1;
  181. case sensor::Unit::Percentage:
  182. return 0;
  183. case sensor::Unit::Hectopascal:
  184. return 2;
  185. case sensor::Unit::Ampere:
  186. return 3;
  187. case sensor::Unit::Volt:
  188. return 0;
  189. case sensor::Unit::Watt:
  190. case sensor::Unit::Voltampere:
  191. case sensor::Unit::VoltampereReactive:
  192. return 0;
  193. case sensor::Unit::Kilowatt:
  194. case sensor::Unit::Kilovoltampere:
  195. case sensor::Unit::KilovoltampereReactive:
  196. return 3;
  197. case sensor::Unit::KilowattHour:
  198. return 3;
  199. case sensor::Unit::WattSecond:
  200. return 0;
  201. case sensor::Unit::CountsPerMinute:
  202. case sensor::Unit::MicrosievertPerHour:
  203. return 4;
  204. case sensor::Unit::Meter:
  205. return 3;
  206. case sensor::Unit::UltravioletIndex:
  207. return 3;
  208. case sensor::Unit::None:
  209. default:
  210. return 0;
  211. }
  212. }
  213. String magnitudeTopic(unsigned char type) {
  214. const __FlashStringHelper* result = nullptr;
  215. switch (type) {
  216. case MAGNITUDE_TEMPERATURE:
  217. result = F("temperature");
  218. break;
  219. case MAGNITUDE_HUMIDITY:
  220. result = F("humidity");
  221. break;
  222. case MAGNITUDE_PRESSURE:
  223. result = F("pressure");
  224. break;
  225. case MAGNITUDE_CURRENT:
  226. result = F("current");
  227. break;
  228. case MAGNITUDE_VOLTAGE:
  229. result = F("voltage");
  230. break;
  231. case MAGNITUDE_POWER_ACTIVE:
  232. result = F("power");
  233. break;
  234. case MAGNITUDE_POWER_APPARENT:
  235. result = F("apparent");
  236. break;
  237. case MAGNITUDE_POWER_REACTIVE:
  238. result = F("reactive");
  239. break;
  240. case MAGNITUDE_POWER_FACTOR:
  241. result = F("factor");
  242. break;
  243. case MAGNITUDE_ENERGY:
  244. result = F("energy");
  245. break;
  246. case MAGNITUDE_ENERGY_DELTA:
  247. result = F("energy_delta");
  248. break;
  249. case MAGNITUDE_ANALOG:
  250. result = F("analog");
  251. break;
  252. case MAGNITUDE_DIGITAL:
  253. result = F("digital");
  254. break;
  255. case MAGNITUDE_EVENT:
  256. result = F("event");
  257. break;
  258. case MAGNITUDE_PM1dot0:
  259. result = F("pm1dot0");
  260. break;
  261. case MAGNITUDE_PM2dot5:
  262. result = F("pm2dot5");
  263. break;
  264. case MAGNITUDE_PM10:
  265. result = F("pm10");
  266. break;
  267. case MAGNITUDE_CO2:
  268. result = F("co2");
  269. break;
  270. case MAGNITUDE_LUX:
  271. result = F("lux");
  272. break;
  273. case MAGNITUDE_UVA:
  274. result = F("uva");
  275. break;
  276. case MAGNITUDE_UVB:
  277. result = F("uvb");
  278. break;
  279. case MAGNITUDE_UVI:
  280. result = F("uvi");
  281. break;
  282. case MAGNITUDE_DISTANCE:
  283. result = F("distance");
  284. break;
  285. case MAGNITUDE_HCHO:
  286. result = F("hcho");
  287. break;
  288. case MAGNITUDE_GEIGER_CPM:
  289. result = F("ldr_cpm"); // local dose rate [Counts per minute]
  290. break;
  291. case MAGNITUDE_GEIGER_SIEVERT:
  292. result = F("ldr_uSvh"); // local dose rate [µSievert per hour]
  293. break;
  294. case MAGNITUDE_COUNT:
  295. result = F("count");
  296. break;
  297. case MAGNITUDE_NO2:
  298. result = F("no2");
  299. break;
  300. case MAGNITUDE_CO:
  301. result = F("co");
  302. break;
  303. case MAGNITUDE_RESISTANCE:
  304. result = F("resistance");
  305. break;
  306. case MAGNITUDE_PH:
  307. result = F("ph");
  308. break;
  309. case MAGNITUDE_NONE:
  310. default:
  311. result = F("unknown");
  312. break;
  313. }
  314. return String(result);
  315. }
  316. String magnitudeTopic(const sensor_magnitude_t& magnitude) {
  317. return magnitudeTopic(magnitude.type);
  318. }
  319. String magnitudeUnits(const sensor_magnitude_t& magnitude) {
  320. const __FlashStringHelper* result = nullptr;
  321. switch (magnitude.units) {
  322. case sensor::Unit::Farenheit:
  323. result = F("°F");
  324. break;
  325. case sensor::Unit::Celcius:
  326. result = F("°C");
  327. break;
  328. case sensor::Unit::Percentage:
  329. result = F("%");
  330. break;
  331. case sensor::Unit::Hectopascal:
  332. result = F("hPa");
  333. break;
  334. case sensor::Unit::Ampere:
  335. result = F("A");
  336. break;
  337. case sensor::Unit::Volt:
  338. result = F("V");
  339. break;
  340. case sensor::Unit::Watt:
  341. result = F("W");
  342. break;
  343. case sensor::Unit::Kilowatt:
  344. result = F("kW");
  345. break;
  346. case sensor::Unit::Voltampere:
  347. result = F("VA");
  348. break;
  349. case sensor::Unit::Kilovoltampere:
  350. result = F("kVA");
  351. break;
  352. case sensor::Unit::VoltampereReactive:
  353. result = F("VAR");
  354. break;
  355. case sensor::Unit::KilovoltampereReactive:
  356. result = F("kVAR");
  357. break;
  358. case sensor::Unit::Joule:
  359. //aka case sensor::Unit::WattSecond:
  360. result = F("J");
  361. break;
  362. case sensor::Unit::KilowattHour:
  363. result = F("kWh");
  364. break;
  365. case sensor::Unit::MicrogrammPerCubicMeter:
  366. result = F("µg/m³");
  367. break;
  368. case sensor::Unit::PartsPerMillion:
  369. result = F("ppm");
  370. break;
  371. case sensor::Unit::Lux:
  372. result = F("lux");
  373. break;
  374. case sensor::Unit::Ohm:
  375. result = F("ohm");
  376. break;
  377. case sensor::Unit::MilligrammPerCubicMeter:
  378. result = F("mg/m³");
  379. break;
  380. case sensor::Unit::CountsPerMinute:
  381. result = F("cpm");
  382. break;
  383. case sensor::Unit::MicrosievertPerHour:
  384. result = F("µSv/h");
  385. break;
  386. case sensor::Unit::Meter:
  387. result = F("m");
  388. break;
  389. case sensor::Unit::None:
  390. default:
  391. result = F("");
  392. break;
  393. }
  394. return String(result);
  395. }
  396. String magnitudeUnits(unsigned char index) {
  397. if (index >= magnitudeCount()) return String();
  398. return magnitudeUnits(_magnitudes[index]);
  399. }
  400. // Choose unit based on type of magnitude we use
  401. sensor::Unit _magnitudeUnitFilter(const sensor_magnitude_t& magnitude, sensor::Unit updated) {
  402. auto result = magnitude.units;
  403. switch (magnitude.type) {
  404. case MAGNITUDE_TEMPERATURE: {
  405. switch (updated) {
  406. case sensor::Unit::Celcius:
  407. case sensor::Unit::Farenheit:
  408. case sensor::Unit::Kelvin:
  409. result = updated;
  410. break;
  411. default:
  412. break;
  413. }
  414. break;
  415. }
  416. case MAGNITUDE_POWER_ACTIVE: {
  417. switch (updated) {
  418. case sensor::Unit::Kilowatt:
  419. case sensor::Unit::Watt:
  420. result = updated;
  421. break;
  422. default:
  423. break;
  424. }
  425. break;
  426. }
  427. case MAGNITUDE_ENERGY: {
  428. switch (updated) {
  429. case sensor::Unit::KilowattHour:
  430. case sensor::Unit::Joule:
  431. result = updated;
  432. break;
  433. default:
  434. break;
  435. }
  436. break;
  437. }
  438. }
  439. return result;
  440. };
  441. double _magnitudeProcess(const sensor_magnitude_t& magnitude, double value) {
  442. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  443. switch (magnitude.sensor->units(magnitude.local)) {
  444. case sensor::Unit::Celcius:
  445. if (magnitude.units == sensor::Unit::Farenheit) {
  446. value = (value * 1.8) + 32.0;
  447. } else if (magnitude.units == sensor::Unit::Kelvin) {
  448. value = value + 273.15;
  449. }
  450. break;
  451. case sensor::Unit::Percentage:
  452. value = constrain(value, 0.0, 100.0);
  453. break;
  454. case sensor::Unit::Watt:
  455. case sensor::Unit::Voltampere:
  456. case sensor::Unit::VoltampereReactive:
  457. if ((magnitude.units == sensor::Unit::Kilowatt)
  458. || (magnitude.units == sensor::Unit::Kilovoltampere)
  459. || (magnitude.units == sensor::Unit::KilovoltampereReactive)) {
  460. value = value / 1.0e+3;
  461. }
  462. break;
  463. case sensor::Unit::KilowattHour:
  464. // TODO: we may end up with inf at some point?
  465. if (magnitude.units == sensor::Unit::Joule) {
  466. value = value * 3.6e+6;
  467. }
  468. break;
  469. default:
  470. break;
  471. }
  472. value = value + magnitude.correction;
  473. return roundTo(value, magnitude.decimals);
  474. }
  475. // -----------------------------------------------------------------------------
  476. #if WEB_SUPPORT
  477. //void _sensorWebSocketMagnitudes(JsonObject& root, const String& ws_name, const String& conf_name) {
  478. template<typename T> void _sensorWebSocketMagnitudes(JsonObject& root, T prefix) {
  479. // ws produces flat list <prefix>Magnitudes
  480. const String ws_name = String(prefix) + "Magnitudes";
  481. // config uses <prefix>Magnitude<index> (cut 's')
  482. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  483. JsonObject& list = root.createNestedObject(ws_name);
  484. list["size"] = magnitudeCount();
  485. //JsonArray& name = list.createNestedArray("name");
  486. JsonArray& type = list.createNestedArray("type");
  487. JsonArray& index = list.createNestedArray("index");
  488. JsonArray& idx = list.createNestedArray("idx");
  489. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  490. //name.add(magnitudeName(i));
  491. type.add(magnitudeType(i));
  492. index.add(magnitudeIndex(i));
  493. idx.add(getSetting({conf_name, i}, 0));
  494. }
  495. }
  496. /*
  497. template<typename T> void _sensorWebSocketMagnitudes(JsonObject& root, T prefix) {
  498. // ws produces flat list <prefix>Magnitudes
  499. const String ws_name = String(prefix) + "Magnitudes";
  500. // config uses <prefix>Magnitude<index> (cut 's')
  501. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  502. _sensorWebSocketMagnitudes(root, ws_name, conf_name);
  503. }
  504. */
  505. bool _sensorWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  506. if (strncmp(key, "pwr", 3) == 0) return true;
  507. if (strncmp(key, "sns", 3) == 0) return true;
  508. if (strncmp(key, "tmp", 3) == 0) return true;
  509. if (strncmp(key, "hum", 3) == 0) return true;
  510. if (strncmp(key, "ene", 3) == 0) return true;
  511. if (strncmp(key, "lux", 3) == 0) return true;
  512. return false;
  513. }
  514. void _sensorWebSocketOnVisible(JsonObject& root) {
  515. root["snsVisible"] = 1;
  516. for (auto& magnitude : _magnitudes) {
  517. if (magnitude.type == MAGNITUDE_TEMPERATURE) root["temperatureVisible"] = 1;
  518. if (magnitude.type == MAGNITUDE_HUMIDITY) root["humidityVisible"] = 1;
  519. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  520. if (magnitude.type == MAGNITUDE_CO || magnitude.type == MAGNITUDE_NO2) root["micsVisible"] = 1;
  521. #endif
  522. }
  523. }
  524. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  525. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  526. uint8_t size = 0;
  527. JsonArray& index = magnitudes.createNestedArray("index");
  528. JsonArray& type = magnitudes.createNestedArray("type");
  529. JsonArray& units = magnitudes.createNestedArray("units");
  530. JsonArray& description = magnitudes.createNestedArray("description");
  531. for (unsigned char i=0; i<magnitudeCount(); i++) {
  532. auto& magnitude = _magnitudes[i];
  533. if (magnitude.type == MAGNITUDE_EVENT) continue;
  534. ++size;
  535. index.add<uint8_t>(magnitude.global);
  536. type.add<uint8_t>(magnitude.type);
  537. units.add(magnitudeUnits(magnitude));
  538. {
  539. String sensor_desc = magnitude.sensor->slot(magnitude.local);
  540. description.add(sensor_desc);
  541. }
  542. }
  543. magnitudes["size"] = size;
  544. }
  545. void _sensorWebSocketSendData(JsonObject& root) {
  546. char buffer[64];
  547. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  548. uint8_t size = 0;
  549. JsonArray& value = magnitudes.createNestedArray("value");
  550. JsonArray& error = magnitudes.createNestedArray("error");
  551. #if NTP_SUPPORT
  552. JsonArray& info = magnitudes.createNestedArray("info");
  553. #endif
  554. for (auto& magnitude : _magnitudes) {
  555. if (magnitude.type == MAGNITUDE_EVENT) continue;
  556. ++size;
  557. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  558. value.add(buffer);
  559. error.add(magnitude.sensor->error());
  560. #if NTP_SUPPORT
  561. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  562. String string = F("Last saved: ");
  563. string += getSetting({"eneTime", magnitude.global}, F("(unknown)"));
  564. info.add(string);
  565. } else {
  566. info.add((uint8_t)0);
  567. }
  568. #endif
  569. }
  570. magnitudes["size"] = size;
  571. }
  572. void _sensorWebSocketOnConnected(JsonObject& root) {
  573. for (unsigned char i=0; i<_sensors.size(); i++) {
  574. BaseSensor * sensor = _sensors[i];
  575. UNUSED(sensor);
  576. #if EMON_ANALOG_SUPPORT
  577. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  578. root["emonVisible"] = 1;
  579. root["pwrVisible"] = 1;
  580. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  581. }
  582. #endif
  583. #if HLW8012_SUPPORT
  584. if (sensor->getID() == SENSOR_HLW8012_ID) {
  585. root["hlwVisible"] = 1;
  586. root["pwrVisible"] = 1;
  587. }
  588. #endif
  589. #if CSE7766_SUPPORT
  590. if (sensor->getID() == SENSOR_CSE7766_ID) {
  591. root["cseVisible"] = 1;
  592. root["pwrVisible"] = 1;
  593. }
  594. #endif
  595. #if V9261F_SUPPORT
  596. if (sensor->getID() == SENSOR_V9261F_ID) {
  597. root["pwrVisible"] = 1;
  598. }
  599. #endif
  600. #if ECH1560_SUPPORT
  601. if (sensor->getID() == SENSOR_ECH1560_ID) {
  602. root["pwrVisible"] = 1;
  603. }
  604. #endif
  605. #if PZEM004T_SUPPORT
  606. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  607. root["pzemVisible"] = 1;
  608. root["pwrVisible"] = 1;
  609. }
  610. #endif
  611. #if PULSEMETER_SUPPORT
  612. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  613. root["pmVisible"] = 1;
  614. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  615. }
  616. #endif
  617. }
  618. if (sensor_magnitude_t::counts(MAGNITUDE_TEMPERATURE)) {
  619. root["tmpCorrection"] = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION);
  620. }
  621. if (sensor_magnitude_t::counts(MAGNITUDE_HUMIDITY)) {
  622. root["humCorrection"] = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION);
  623. }
  624. if (sensor_magnitude_t::counts(MAGNITUDE_LUX)) {
  625. root["luxCorrection"] = getSetting("luxCorrection", SENSOR_LUX_CORRECTION);
  626. }
  627. if (magnitudeCount()) {
  628. root["snsRead"] = _sensor_read_interval / 1000;
  629. root["snsReport"] = _sensor_report_every;
  630. root["snsSave"] = _sensor_save_every;
  631. _sensorWebSocketMagnitudesConfig(root);
  632. }
  633. }
  634. #endif // WEB_SUPPORT
  635. #if API_SUPPORT
  636. void _sensorAPISetup() {
  637. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  638. auto& magnitude = _magnitudes.at(magnitude_id);
  639. String topic = magnitudeTopic(magnitude.type);
  640. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) topic = topic + "/" + String(magnitude.global);
  641. api_get_callback_f get_cb = [&magnitude](char * buffer, size_t len) {
  642. double value = _sensor_realtime ? magnitude.last : magnitude.reported;
  643. dtostrf(value, 1, magnitude.decimals, buffer);
  644. };
  645. api_put_callback_f put_cb = nullptr;
  646. if (magnitude.type == MAGNITUDE_ENERGY) {
  647. put_cb = [&magnitude](const char* payload) {
  648. _sensorApiResetEnergy(magnitude, payload);
  649. };
  650. }
  651. apiRegister(topic.c_str(), get_cb, put_cb);
  652. }
  653. }
  654. #endif // API_SUPPORT == 1
  655. #if MQTT_SUPPORT
  656. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  657. static const auto energy_topic = magnitudeTopic(MAGNITUDE_ENERGY);
  658. switch (type) {
  659. case MQTT_MESSAGE_EVENT: {
  660. String t = mqttMagnitude((char *) topic);
  661. if (!t.startsWith(energy_topic)) break;
  662. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  663. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  664. for (auto& magnitude : _magnitudes) {
  665. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  666. if (index != magnitude.global) continue;
  667. _sensorApiResetEnergy(magnitude, payload);
  668. break;
  669. }
  670. }
  671. case MQTT_CONNECT_EVENT: {
  672. for (auto& magnitude : _magnitudes) {
  673. if (MAGNITUDE_ENERGY == magnitude.type) {
  674. const String topic = energy_topic + "/+";
  675. mqttSubscribe(topic.c_str());
  676. break;
  677. }
  678. }
  679. }
  680. case MQTT_DISCONNECT_EVENT:
  681. default:
  682. break;
  683. }
  684. }
  685. #endif // MQTT_SUPPORT == 1
  686. #if TERMINAL_SUPPORT
  687. void _sensorInitCommands() {
  688. terminalRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  689. char last[64];
  690. char reported[64];
  691. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  692. auto& magnitude = _magnitudes.at(index);
  693. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  694. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  695. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  696. index,
  697. magnitudeTopic(magnitude.type).c_str(), magnitude.global,
  698. magnitude.sensor->slot(magnitude.local).c_str(),
  699. last, reported
  700. );
  701. }
  702. terminalOK();
  703. });
  704. }
  705. #endif // TERMINAL_SUPPORT == 1
  706. void _sensorTick() {
  707. for (auto* sensor : _sensors) {
  708. sensor->tick();
  709. }
  710. }
  711. void _sensorPre() {
  712. for (auto* sensor : _sensors) {
  713. sensor->pre();
  714. if (!sensor->status()) {
  715. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  716. sensor->description().c_str(),
  717. sensor->error()
  718. );
  719. }
  720. }
  721. }
  722. void _sensorPost() {
  723. for (auto* sensor : _sensors) {
  724. sensor->post();
  725. }
  726. }
  727. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  728. return sensor::Energy {
  729. sensor::KWh { Rtcmem->energy[index].kwh },
  730. sensor::Ws { Rtcmem->energy[index].ws }
  731. };
  732. }
  733. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  734. Rtcmem->energy[index].kwh = source.kwh.value;
  735. Rtcmem->energy[index].ws = source.ws.value;
  736. }
  737. sensor::Energy _sensorParseEnergy(const String& value) {
  738. sensor::Energy result;
  739. const bool separator = value.indexOf('+') > 0;
  740. if (value.length() && (separator > 0)) {
  741. const String before = value.substring(0, separator);
  742. const String after = value.substring(separator + 1);
  743. result.kwh = strtoul(before.c_str(), nullptr, 10);
  744. result.ws = strtoul(after.c_str(), nullptr, 10);
  745. }
  746. return result;
  747. }
  748. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  749. if (!payload || !strlen(payload)) return;
  750. if (payload[0] != '0') return;
  751. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  752. auto energy = _sensorParseEnergy(payload);
  753. sensor->resetEnergy(magnitude.global, energy);
  754. }
  755. sensor::Energy _sensorEnergyTotal(unsigned char index) {
  756. sensor::Energy result;
  757. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  758. result = _sensorRtcmemLoadEnergy(index);
  759. } else if (_sensor_save_every > 0) {
  760. result = _sensorParseEnergy(getSetting({"eneTotal", index}));
  761. }
  762. return result;
  763. }
  764. sensor::Energy sensorEnergyTotal() {
  765. return _sensorEnergyTotal(0);
  766. }
  767. void _sensorResetEnergyTotal(unsigned char index) {
  768. delSetting({"eneTotal", index});
  769. delSetting({"eneTime", index});
  770. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  771. Rtcmem->energy[index].kwh = 0;
  772. Rtcmem->energy[index].ws = 0;
  773. }
  774. }
  775. void _magnitudeSaveEnergyTotal(sensor_magnitude_t& magnitude, bool persistent) {
  776. if (magnitude.type != MAGNITUDE_ENERGY) return;
  777. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  778. const auto energy = sensor->totalEnergy();
  779. // Always save to RTCMEM
  780. if (magnitude.global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  781. _sensorRtcmemSaveEnergy(magnitude.global, energy);
  782. }
  783. // Save to EEPROM every '_sensor_save_every' readings
  784. // Format is `<kwh>+<ws>`, value without `+` is treated as `<ws>`
  785. if (persistent && _sensor_save_every) {
  786. _sensor_save_count[magnitude.global] =
  787. (_sensor_save_count[magnitude.global] + 1) % _sensor_save_every;
  788. if (0 == _sensor_save_count[magnitude.global]) {
  789. const String total = String(energy.kwh.value) + "+" + String(energy.ws.value);
  790. setSetting({"eneTotal", magnitude.global}, total);
  791. #if NTP_SUPPORT
  792. if (ntpSynced()) setSetting({"eneTime", magnitude.global}, ntpDateTime());
  793. #endif
  794. }
  795. }
  796. }
  797. // -----------------------------------------------------------------------------
  798. // Sensor initialization
  799. // -----------------------------------------------------------------------------
  800. void _sensorLoad() {
  801. /*
  802. This is temporal, in the future sensors will be initialized based on
  803. soft configuration (data stored in EEPROM config) so you will be able
  804. to define and configure new sensors on the fly
  805. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  806. loaded and initialized here. If you want to add new sensors of the same type
  807. just duplicate the block and change the arguments for the set* methods.
  808. For example, how to add a second DHT sensor:
  809. #if DHT_SUPPORT
  810. {
  811. DHTSensor * sensor = new DHTSensor();
  812. sensor->setGPIO(DHT2_PIN);
  813. sensor->setType(DHT2_TYPE);
  814. _sensors.push_back(sensor);
  815. }
  816. #endif
  817. DHT2_PIN and DHT2_TYPE should be globally accessible:
  818. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  819. - in custom.h, as `#define ...`
  820. */
  821. #if AM2320_SUPPORT
  822. {
  823. AM2320Sensor * sensor = new AM2320Sensor();
  824. sensor->setAddress(AM2320_ADDRESS);
  825. _sensors.push_back(sensor);
  826. }
  827. #endif
  828. #if ANALOG_SUPPORT
  829. {
  830. AnalogSensor * sensor = new AnalogSensor();
  831. sensor->setSamples(ANALOG_SAMPLES);
  832. sensor->setDelay(ANALOG_DELAY);
  833. //CICM For analog scaling
  834. sensor->setFactor(ANALOG_FACTOR);
  835. sensor->setOffset(ANALOG_OFFSET);
  836. _sensors.push_back(sensor);
  837. }
  838. #endif
  839. #if BH1750_SUPPORT
  840. {
  841. BH1750Sensor * sensor = new BH1750Sensor();
  842. sensor->setAddress(BH1750_ADDRESS);
  843. sensor->setMode(BH1750_MODE);
  844. _sensors.push_back(sensor);
  845. }
  846. #endif
  847. #if BMP180_SUPPORT
  848. {
  849. BMP180Sensor * sensor = new BMP180Sensor();
  850. sensor->setAddress(BMP180_ADDRESS);
  851. _sensors.push_back(sensor);
  852. }
  853. #endif
  854. #if BMX280_SUPPORT
  855. {
  856. // Support up to two sensors with full auto-discovery.
  857. const unsigned char number = constrain(getSetting<int>("bmx280Number", BMX280_NUMBER), 1, 2);
  858. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  859. // otherwise choose the other unnamed sensor address
  860. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  861. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  862. const decltype(first) address_map[2] { first, second };
  863. for (unsigned char n=0; n < number; ++n) {
  864. BMX280Sensor * sensor = new BMX280Sensor();
  865. sensor->setAddress(address_map[n]);
  866. _sensors.push_back(sensor);
  867. }
  868. }
  869. #endif
  870. #if CSE7766_SUPPORT
  871. {
  872. CSE7766Sensor * sensor = new CSE7766Sensor();
  873. sensor->setRX(CSE7766_PIN);
  874. _sensors.push_back(sensor);
  875. }
  876. #endif
  877. #if DALLAS_SUPPORT
  878. {
  879. DallasSensor * sensor = new DallasSensor();
  880. sensor->setGPIO(DALLAS_PIN);
  881. _sensors.push_back(sensor);
  882. }
  883. #endif
  884. #if DHT_SUPPORT
  885. {
  886. DHTSensor * sensor = new DHTSensor();
  887. sensor->setGPIO(DHT_PIN);
  888. sensor->setType(DHT_TYPE);
  889. _sensors.push_back(sensor);
  890. }
  891. #endif
  892. #if DIGITAL_SUPPORT
  893. {
  894. auto getPin = [](unsigned char index) -> int {
  895. switch (index) {
  896. case 0: return DIGITAL1_PIN;
  897. case 1: return DIGITAL2_PIN;
  898. case 2: return DIGITAL3_PIN;
  899. case 3: return DIGITAL4_PIN;
  900. case 4: return DIGITAL5_PIN;
  901. case 5: return DIGITAL6_PIN;
  902. case 6: return DIGITAL7_PIN;
  903. case 7: return DIGITAL8_PIN;
  904. default: return GPIO_NONE;
  905. }
  906. };
  907. auto getDefaultState = [](unsigned char index) -> int {
  908. switch (index) {
  909. case 0: return DIGITAL1_DEFAULT_STATE;
  910. case 1: return DIGITAL2_DEFAULT_STATE;
  911. case 2: return DIGITAL3_DEFAULT_STATE;
  912. case 3: return DIGITAL4_DEFAULT_STATE;
  913. case 4: return DIGITAL5_DEFAULT_STATE;
  914. case 5: return DIGITAL6_DEFAULT_STATE;
  915. case 6: return DIGITAL7_DEFAULT_STATE;
  916. case 7: return DIGITAL8_DEFAULT_STATE;
  917. default: return 1;
  918. }
  919. };
  920. auto getMode = [](unsigned char index) -> int {
  921. switch (index) {
  922. case 0: return DIGITAL1_PIN_MODE;
  923. case 1: return DIGITAL2_PIN_MODE;
  924. case 2: return DIGITAL3_PIN_MODE;
  925. case 3: return DIGITAL4_PIN_MODE;
  926. case 4: return DIGITAL5_PIN_MODE;
  927. case 5: return DIGITAL6_PIN_MODE;
  928. case 6: return DIGITAL7_PIN_MODE;
  929. case 7: return DIGITAL8_PIN_MODE;
  930. default: return INPUT_PULLUP;
  931. }
  932. };
  933. for (unsigned char index = 0; index < GpioPins; ++index) {
  934. const auto pin = getPin(index);
  935. if (pin == GPIO_NONE) break;
  936. DigitalSensor * sensor = new DigitalSensor();
  937. sensor->setGPIO(pin);
  938. sensor->setMode(getMode(index));
  939. sensor->setDefault(getDefaultState(index));
  940. _sensors.push_back(sensor);
  941. }
  942. }
  943. #endif
  944. #if ECH1560_SUPPORT
  945. {
  946. ECH1560Sensor * sensor = new ECH1560Sensor();
  947. sensor->setCLK(ECH1560_CLK_PIN);
  948. sensor->setMISO(ECH1560_MISO_PIN);
  949. sensor->setInverted(ECH1560_INVERTED);
  950. _sensors.push_back(sensor);
  951. }
  952. #endif
  953. #if EMON_ADC121_SUPPORT
  954. {
  955. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  956. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  957. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  958. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  959. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  960. _sensors.push_back(sensor);
  961. }
  962. #endif
  963. #if EMON_ADS1X15_SUPPORT
  964. {
  965. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  966. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  967. sensor->setType(EMON_ADS1X15_TYPE);
  968. sensor->setMask(EMON_ADS1X15_MASK);
  969. sensor->setGain(EMON_ADS1X15_GAIN);
  970. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  971. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  972. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  973. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  974. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  975. _sensors.push_back(sensor);
  976. }
  977. #endif
  978. #if EMON_ANALOG_SUPPORT
  979. {
  980. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  981. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  982. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  983. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  984. _sensors.push_back(sensor);
  985. }
  986. #endif
  987. #if EVENTS_SUPPORT
  988. {
  989. #if (EVENTS1_PIN != GPIO_NONE)
  990. {
  991. EventSensor * sensor = new EventSensor();
  992. sensor->setGPIO(EVENTS1_PIN);
  993. sensor->setTrigger(EVENTS1_TRIGGER);
  994. sensor->setPinMode(EVENTS1_PIN_MODE);
  995. sensor->setDebounceTime(EVENTS1_DEBOUNCE);
  996. sensor->setInterruptMode(EVENTS1_INTERRUPT_MODE);
  997. _sensors.push_back(sensor);
  998. }
  999. #endif
  1000. #if (EVENTS2_PIN != GPIO_NONE)
  1001. {
  1002. EventSensor * sensor = new EventSensor();
  1003. sensor->setGPIO(EVENTS2_PIN);
  1004. sensor->setTrigger(EVENTS2_TRIGGER);
  1005. sensor->setPinMode(EVENTS2_PIN_MODE);
  1006. sensor->setDebounceTime(EVENTS2_DEBOUNCE);
  1007. sensor->setInterruptMode(EVENTS2_INTERRUPT_MODE);
  1008. _sensors.push_back(sensor);
  1009. }
  1010. #endif
  1011. #if (EVENTS3_PIN != GPIO_NONE)
  1012. {
  1013. EventSensor * sensor = new EventSensor();
  1014. sensor->setGPIO(EVENTS3_PIN);
  1015. sensor->setTrigger(EVENTS3_TRIGGER);
  1016. sensor->setPinMode(EVENTS3_PIN_MODE);
  1017. sensor->setDebounceTime(EVENTS3_DEBOUNCE);
  1018. sensor->setInterruptMode(EVENTS3_INTERRUPT_MODE);
  1019. _sensors.push_back(sensor);
  1020. }
  1021. #endif
  1022. #if (EVENTS4_PIN != GPIO_NONE)
  1023. {
  1024. EventSensor * sensor = new EventSensor();
  1025. sensor->setGPIO(EVENTS4_PIN);
  1026. sensor->setTrigger(EVENTS4_TRIGGER);
  1027. sensor->setPinMode(EVENTS4_PIN_MODE);
  1028. sensor->setDebounceTime(EVENTS4_DEBOUNCE);
  1029. sensor->setInterruptMode(EVENTS4_INTERRUPT_MODE);
  1030. _sensors.push_back(sensor);
  1031. }
  1032. #endif
  1033. #if (EVENTS5_PIN != GPIO_NONE)
  1034. {
  1035. EventSensor * sensor = new EventSensor();
  1036. sensor->setGPIO(EVENTS5_PIN);
  1037. sensor->setTrigger(EVENTS5_TRIGGER);
  1038. sensor->setPinMode(EVENTS5_PIN_MODE);
  1039. sensor->setDebounceTime(EVENTS5_DEBOUNCE);
  1040. sensor->setInterruptMode(EVENTS5_INTERRUPT_MODE);
  1041. _sensors.push_back(sensor);
  1042. }
  1043. #endif
  1044. #if (EVENTS6_PIN != GPIO_NONE)
  1045. {
  1046. EventSensor * sensor = new EventSensor();
  1047. sensor->setGPIO(EVENTS6_PIN);
  1048. sensor->setTrigger(EVENTS6_TRIGGER);
  1049. sensor->setPinMode(EVENTS6_PIN_MODE);
  1050. sensor->setDebounceTime(EVENTS6_DEBOUNCE);
  1051. sensor->setInterruptMode(EVENTS6_INTERRUPT_MODE);
  1052. _sensors.push_back(sensor);
  1053. }
  1054. #endif
  1055. #if (EVENTS7_PIN != GPIO_NONE)
  1056. {
  1057. EventSensor * sensor = new EventSensor();
  1058. sensor->setGPIO(EVENTS7_PIN);
  1059. sensor->setTrigger(EVENTS7_TRIGGER);
  1060. sensor->setPinMode(EVENTS7_PIN_MODE);
  1061. sensor->setDebounceTime(EVENTS7_DEBOUNCE);
  1062. sensor->setInterruptMode(EVENTS7_INTERRUPT_MODE);
  1063. _sensors.push_back(sensor);
  1064. }
  1065. #endif
  1066. #if (EVENTS8_PIN != GPIO_NONE)
  1067. {
  1068. EventSensor * sensor = new EventSensor();
  1069. sensor->setGPIO(EVENTS8_PIN);
  1070. sensor->setTrigger(EVENTS8_TRIGGER);
  1071. sensor->setPinMode(EVENTS8_PIN_MODE);
  1072. sensor->setDebounceTime(EVENTS8_DEBOUNCE);
  1073. sensor->setInterruptMode(EVENTS8_INTERRUPT_MODE);
  1074. _sensors.push_back(sensor);
  1075. }
  1076. #endif
  1077. }
  1078. #endif
  1079. #if GEIGER_SUPPORT
  1080. {
  1081. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1082. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1083. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1084. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1085. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1086. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1087. _sensors.push_back(sensor);
  1088. }
  1089. #endif
  1090. #if GUVAS12SD_SUPPORT
  1091. {
  1092. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1093. sensor->setGPIO(GUVAS12SD_PIN);
  1094. _sensors.push_back(sensor);
  1095. }
  1096. #endif
  1097. #if SONAR_SUPPORT
  1098. {
  1099. SonarSensor * sensor = new SonarSensor();
  1100. sensor->setEcho(SONAR_ECHO);
  1101. sensor->setIterations(SONAR_ITERATIONS);
  1102. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1103. sensor->setTrigger(SONAR_TRIGGER);
  1104. _sensors.push_back(sensor);
  1105. }
  1106. #endif
  1107. #if HLW8012_SUPPORT
  1108. {
  1109. HLW8012Sensor * sensor = new HLW8012Sensor();
  1110. sensor->setSEL(getSetting("snsHlw8012SelGPIO", HLW8012_SEL_PIN));
  1111. sensor->setCF(getSetting("snsHlw8012CfGPIO", HLW8012_CF_PIN));
  1112. sensor->setCF1(getSetting("snsHlw8012Cf1GPIO", HLW8012_CF1_PIN));
  1113. sensor->setCurrentRatio(HLW8012_CURRENT_RATIO);
  1114. sensor->setVoltageRatio(HLW8012_VOLTAGE_RATIO);
  1115. sensor->setPowerRatio(HLW8012_POWER_RATIO);
  1116. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1117. _sensors.push_back(sensor);
  1118. }
  1119. #endif
  1120. #if LDR_SUPPORT
  1121. {
  1122. LDRSensor * sensor = new LDRSensor();
  1123. sensor->setSamples(LDR_SAMPLES);
  1124. sensor->setDelay(LDR_DELAY);
  1125. sensor->setType(LDR_TYPE);
  1126. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1127. sensor->setResistor(LDR_RESISTOR);
  1128. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1129. _sensors.push_back(sensor);
  1130. }
  1131. #endif
  1132. #if MHZ19_SUPPORT
  1133. {
  1134. MHZ19Sensor * sensor = new MHZ19Sensor();
  1135. sensor->setRX(MHZ19_RX_PIN);
  1136. sensor->setTX(MHZ19_TX_PIN);
  1137. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1138. _sensors.push_back(sensor);
  1139. }
  1140. #endif
  1141. #if MICS2710_SUPPORT
  1142. {
  1143. MICS2710Sensor * sensor = new MICS2710Sensor();
  1144. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1145. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1146. sensor->setR0(MICS2710_R0);
  1147. sensor->setRL(MICS2710_RL);
  1148. sensor->setRS(0);
  1149. _sensors.push_back(sensor);
  1150. }
  1151. #endif
  1152. #if MICS5525_SUPPORT
  1153. {
  1154. MICS5525Sensor * sensor = new MICS5525Sensor();
  1155. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1156. sensor->setR0(MICS5525_R0);
  1157. sensor->setRL(MICS5525_RL);
  1158. sensor->setRS(0);
  1159. _sensors.push_back(sensor);
  1160. }
  1161. #endif
  1162. #if NTC_SUPPORT
  1163. {
  1164. NTCSensor * sensor = new NTCSensor();
  1165. sensor->setSamples(NTC_SAMPLES);
  1166. sensor->setDelay(NTC_DELAY);
  1167. sensor->setUpstreamResistor(NTC_R_UP);
  1168. sensor->setDownstreamResistor(NTC_R_DOWN);
  1169. sensor->setBeta(NTC_BETA);
  1170. sensor->setR0(NTC_R0);
  1171. sensor->setT0(NTC_T0);
  1172. _sensors.push_back(sensor);
  1173. }
  1174. #endif
  1175. #if PMSX003_SUPPORT
  1176. {
  1177. PMSX003Sensor * sensor = new PMSX003Sensor();
  1178. #if PMS_USE_SOFT
  1179. sensor->setRX(PMS_RX_PIN);
  1180. sensor->setTX(PMS_TX_PIN);
  1181. #else
  1182. sensor->setSerial(& PMS_HW_PORT);
  1183. #endif
  1184. sensor->setType(PMS_TYPE);
  1185. _sensors.push_back(sensor);
  1186. }
  1187. #endif
  1188. #if PULSEMETER_SUPPORT
  1189. {
  1190. PulseMeterSensor * sensor = new PulseMeterSensor();
  1191. sensor->setGPIO(PULSEMETER_PIN);
  1192. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1193. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1194. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1195. _sensors.push_back(sensor);
  1196. }
  1197. #endif
  1198. #if PZEM004T_SUPPORT
  1199. {
  1200. String addresses = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1201. if (!addresses.length()) {
  1202. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  1203. return;
  1204. }
  1205. PZEM004TSensor * sensor = PZEM004TSensor::create();
  1206. sensor->setAddresses(addresses.c_str());
  1207. if (getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1208. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1209. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1210. } else {
  1211. sensor->setSerial(& PZEM004T_HW_PORT);
  1212. }
  1213. _sensors.push_back(sensor);
  1214. #if TERMINAL_SUPPORT
  1215. pzem004tInitCommands();
  1216. #endif
  1217. }
  1218. #endif
  1219. #if SENSEAIR_SUPPORT
  1220. {
  1221. SenseAirSensor * sensor = new SenseAirSensor();
  1222. sensor->setRX(SENSEAIR_RX_PIN);
  1223. sensor->setTX(SENSEAIR_TX_PIN);
  1224. _sensors.push_back(sensor);
  1225. }
  1226. #endif
  1227. #if SDS011_SUPPORT
  1228. {
  1229. SDS011Sensor * sensor = new SDS011Sensor();
  1230. sensor->setRX(SDS011_RX_PIN);
  1231. sensor->setTX(SDS011_TX_PIN);
  1232. _sensors.push_back(sensor);
  1233. }
  1234. #endif
  1235. #if SHT3X_I2C_SUPPORT
  1236. {
  1237. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1238. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1239. _sensors.push_back(sensor);
  1240. }
  1241. #endif
  1242. #if SI7021_SUPPORT
  1243. {
  1244. SI7021Sensor * sensor = new SI7021Sensor();
  1245. sensor->setAddress(SI7021_ADDRESS);
  1246. _sensors.push_back(sensor);
  1247. }
  1248. #endif
  1249. #if T6613_SUPPORT
  1250. {
  1251. T6613Sensor * sensor = new T6613Sensor();
  1252. sensor->setRX(T6613_RX_PIN);
  1253. sensor->setTX(T6613_TX_PIN);
  1254. _sensors.push_back(sensor);
  1255. }
  1256. #endif
  1257. #if TMP3X_SUPPORT
  1258. {
  1259. TMP3XSensor * sensor = new TMP3XSensor();
  1260. sensor->setType(TMP3X_TYPE);
  1261. _sensors.push_back(sensor);
  1262. }
  1263. #endif
  1264. #if V9261F_SUPPORT
  1265. {
  1266. V9261FSensor * sensor = new V9261FSensor();
  1267. sensor->setRX(V9261F_PIN);
  1268. sensor->setInverted(V9261F_PIN_INVERSE);
  1269. _sensors.push_back(sensor);
  1270. }
  1271. #endif
  1272. #if MAX6675_SUPPORT
  1273. {
  1274. MAX6675Sensor * sensor = new MAX6675Sensor();
  1275. sensor->setCS(MAX6675_CS_PIN);
  1276. sensor->setSO(MAX6675_SO_PIN);
  1277. sensor->setSCK(MAX6675_SCK_PIN);
  1278. _sensors.push_back(sensor);
  1279. }
  1280. #endif
  1281. #if VEML6075_SUPPORT
  1282. {
  1283. VEML6075Sensor * sensor = new VEML6075Sensor();
  1284. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1285. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1286. _sensors.push_back(sensor);
  1287. }
  1288. #endif
  1289. #if VL53L1X_SUPPORT
  1290. {
  1291. VL53L1XSensor * sensor = new VL53L1XSensor();
  1292. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1293. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1294. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1295. _sensors.push_back(sensor);
  1296. }
  1297. #endif
  1298. #if EZOPH_SUPPORT
  1299. {
  1300. EZOPHSensor * sensor = new EZOPHSensor();
  1301. sensor->setRX(EZOPH_RX_PIN);
  1302. sensor->setTX(EZOPH_TX_PIN);
  1303. _sensors.push_back(sensor);
  1304. }
  1305. #endif
  1306. #if ADE7953_SUPPORT
  1307. {
  1308. ADE7953Sensor * sensor = new ADE7953Sensor();
  1309. sensor->setAddress(ADE7953_ADDRESS);
  1310. _sensors.push_back(sensor);
  1311. }
  1312. #endif
  1313. #if SI1145_SUPPORT
  1314. {
  1315. SI1145Sensor * sensor = new SI1145Sensor();
  1316. sensor->setAddress(SI1145_ADDRESS);
  1317. _sensors.push_back(sensor);
  1318. }
  1319. #endif
  1320. #if HDC1080_SUPPORT
  1321. {
  1322. HDC1080Sensor * sensor = new HDC1080Sensor();
  1323. sensor->setAddress(HDC1080_ADDRESS);
  1324. _sensors.push_back(sensor);
  1325. }
  1326. #endif
  1327. }
  1328. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  1329. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  1330. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  1331. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  1332. _sensorReport(k, value);
  1333. return;
  1334. }
  1335. }
  1336. }
  1337. void _sensorInit() {
  1338. _sensors_ready = true;
  1339. _sensor_save_every = 0;
  1340. for (unsigned char i=0; i<_sensors.size(); i++) {
  1341. // Do not process an already initialized sensor
  1342. if (_sensors[i]->ready()) continue;
  1343. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  1344. // Force sensor to reload config
  1345. _sensors[i]->begin();
  1346. if (!_sensors[i]->ready()) {
  1347. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  1348. _sensors_ready = false;
  1349. continue;
  1350. }
  1351. // Initialize sensor magnitudes
  1352. for (unsigned char magnitude_index = 0; magnitude_index < _sensors[i]->count(); ++magnitude_index) {
  1353. const auto magnitude_type = _sensors[i]->type(magnitude_index);
  1354. _magnitudes.emplace_back(
  1355. magnitude_type, // specific type of the magnitude
  1356. magnitude_index, // index local to the sensor
  1357. sensor::Unit::None, // set up later, in configuration
  1358. _sensors[i] // bind the sensor to allow us to reference it later
  1359. );
  1360. if (MAGNITUDE_ENERGY == magnitude_type) {
  1361. _sensor_save_count.push_back(0);
  1362. }
  1363. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  1364. magnitudeTopic(magnitude_type).c_str(),
  1365. sensor_magnitude_t::counts(magnitude_type)
  1366. );
  1367. }
  1368. // Hook callback
  1369. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1370. _sensorCallback(i, type, value);
  1371. });
  1372. // Custom initializations, based on IDs
  1373. switch (_sensors[i]->getID()) {
  1374. case SENSOR_MICS2710_ID:
  1375. case SENSOR_MICS5525_ID: {
  1376. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[i]);
  1377. sensor->setR0(getSetting("snsR0", sensor->getR0()));
  1378. sensor->setRS(getSetting("snsRS", sensor->getRS()));
  1379. sensor->setRL(getSetting("snsRL", sensor->getRL()));
  1380. break;
  1381. }
  1382. default:
  1383. break;
  1384. }
  1385. // TODO: compatibility proxy, fetch global key before indexed
  1386. auto get_ratio = [](const char* key, unsigned char index, double default_value) -> double {
  1387. return getSetting({key, index}, getSetting(key, default_value));
  1388. };
  1389. if (_sensorIsEmon(_sensors[i])) {
  1390. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[i]);
  1391. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1392. sensor->resetEnergy(index, _sensorEnergyTotal(index));
  1393. sensor->setCurrentRatio(
  1394. get_ratio("pwrRatioC", index, sensor->getCurrentRatio(index))
  1395. );
  1396. sensor->setVoltageRatio(
  1397. get_ratio("pwrRatioV", index, sensor->getVoltageRatio(index))
  1398. );
  1399. sensor->setPowerRatio(
  1400. get_ratio("pwrRatioP", index, sensor->getPowerRatio(index))
  1401. );
  1402. sensor->setEnergyRatio(
  1403. get_ratio("pwrRatioE", index, sensor->getEnergyRatio(index))
  1404. );
  1405. sensor->setVoltage(
  1406. get_ratio("pwrVoltage", index, sensor->getVoltage(index))
  1407. );
  1408. }
  1409. }
  1410. }
  1411. }
  1412. namespace settings {
  1413. namespace internal {
  1414. template <>
  1415. sensor::Unit convert(const String& string) {
  1416. const int value = string.toInt();
  1417. if ((value > static_cast<int>(sensor::Unit::Min_)) && (value < static_cast<int>(sensor::Unit::Max_))) {
  1418. return static_cast<sensor::Unit>(value);
  1419. }
  1420. return sensor::Unit::None;
  1421. }
  1422. } // ns settings::internal
  1423. } // ns settings
  1424. void _sensorConfigure() {
  1425. // General sensor settings for reporting and saving
  1426. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1427. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1428. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  1429. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  1430. // Per-magnitude min & max delta settings
  1431. // - min controls whether we report at all when report_count overflows
  1432. // - max will trigger report as soon as read value is greater than the specified delta
  1433. // (atm this works best for accumulated magnitudes, like energy)
  1434. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  1435. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  1436. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  1437. // Specific sensor settings
  1438. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  1439. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1440. {
  1441. if (getSetting("snsResetCalibration", false)) {
  1442. switch (_sensors[index]->getID()) {
  1443. case SENSOR_MICS2710_ID:
  1444. case SENSOR_MICS5525_ID: {
  1445. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  1446. sensor->calibrate();
  1447. setSetting("snsR0", sensor->getR0());
  1448. break;
  1449. }
  1450. default:
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  1456. if (_sensorIsEmon(_sensors[index])) {
  1457. // TODO: ::isEmon() ?
  1458. double value;
  1459. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  1460. if ((value = getSetting("pwrExpectedC", 0.0))) {
  1461. sensor->expectedCurrent(value);
  1462. delSetting("pwrExpectedC");
  1463. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1464. }
  1465. if ((value = getSetting("pwrExpectedV", 0.0))) {
  1466. delSetting("pwrExpectedV");
  1467. sensor->expectedVoltage(value);
  1468. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1469. }
  1470. if ((value = getSetting("pwrExpectedP", 0.0))) {
  1471. delSetting("pwrExpectedP");
  1472. sensor->expectedPower(value);
  1473. setSetting("pwrRatioP", sensor->getPowerRatio());
  1474. }
  1475. if (getSetting("pwrResetE", false)) {
  1476. delSetting("pwrResetE");
  1477. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  1478. sensor->resetEnergy(index);
  1479. _sensorResetEnergyTotal(index);
  1480. }
  1481. }
  1482. if (getSetting("pwrResetCalibration", false)) {
  1483. delSetting("pwrResetCalibration");
  1484. delSetting("pwrRatioC");
  1485. delSetting("pwrRatioV");
  1486. delSetting("pwrRatioP");
  1487. sensor->resetRatios();
  1488. }
  1489. sensor->setEnergyRatio(getSetting("pwrRatioE", sensor->getEnergyRatio()));
  1490. } // is emon?
  1491. }
  1492. // Update magnitude config, filter sizes and reset energy if needed
  1493. {
  1494. // TODO: instead of using global enum, have a local mapping?
  1495. const auto tmpUnits = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS);
  1496. const auto pwrUnits = getSetting("pwrUnits", SENSOR_POWER_UNITS);
  1497. const auto eneUnits = getSetting("eneUnits", SENSOR_ENERGY_UNITS);
  1498. // TODO: map MAGNITUDE_... type to a specific string? nvm the preprocessor flags, just focus on settings
  1499. const auto tmpCorrection = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION);
  1500. const auto humCorrection = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION);
  1501. const auto luxCorrection = getSetting("luxCorrection", SENSOR_LUX_CORRECTION);
  1502. for (unsigned char index = 0; index < _magnitudes.size(); ++index) {
  1503. auto& magnitude = _magnitudes.at(index);
  1504. switch (magnitude.type) {
  1505. case MAGNITUDE_TEMPERATURE:
  1506. magnitude.units = _magnitudeUnitFilter(
  1507. magnitude,
  1508. getSetting({"tmpUnits", magnitude.global}, tmpUnits)
  1509. );
  1510. magnitude.correction = getSetting({"tmpCorrection", magnitude.global}, tmpCorrection);
  1511. break;
  1512. case MAGNITUDE_HUMIDITY:
  1513. magnitude.correction = getSetting({"humCorrection", magnitude.global}, humCorrection);
  1514. break;
  1515. case MAGNITUDE_POWER_ACTIVE:
  1516. magnitude.units = _magnitudeUnitFilter(
  1517. magnitude,
  1518. getSetting({"pwrUnits", magnitude.global}, pwrUnits)
  1519. );
  1520. break;
  1521. case MAGNITUDE_ENERGY:
  1522. magnitude.units = _magnitudeUnitFilter(
  1523. magnitude,
  1524. getSetting({"eneUnits", magnitude.global}, eneUnits)
  1525. );
  1526. break;
  1527. case MAGNITUDE_LUX:
  1528. magnitude.correction = getSetting({"luxCorrection", magnitude.global}, luxCorrection);
  1529. break;
  1530. default:
  1531. magnitude.units = magnitude.sensor->units(magnitude.local);
  1532. break;
  1533. }
  1534. // some sensors can override decimal values if sensor has more precision than default
  1535. {
  1536. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  1537. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  1538. magnitude.decimals = (unsigned char) decimals;
  1539. }
  1540. // adjust min & max change delta value to trigger report
  1541. // TODO: find a proper way to extend this to min/max of any magnitude
  1542. {
  1543. auto min_default = 0.0;
  1544. auto max_default = 0.0;
  1545. switch (magnitude.type) {
  1546. case MAGNITUDE_TEMPERATURE:
  1547. min_default = tmp_min_delta;
  1548. break;
  1549. case MAGNITUDE_HUMIDITY:
  1550. min_default = hum_min_delta;
  1551. break;
  1552. case MAGNITUDE_ENERGY:
  1553. max_default = ene_max_delta;
  1554. break;
  1555. default:
  1556. break;
  1557. }
  1558. magnitude.min_change = getSetting({"snsMinDelta", index}, min_default);
  1559. magnitude.max_change = getSetting({"snsMaxDelta", index}, max_default);
  1560. }
  1561. // in case we don't save energy periodically, purge existing value in ram & settings
  1562. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  1563. _sensorResetEnergyTotal(magnitude.global);
  1564. }
  1565. }
  1566. }
  1567. saveSettings();
  1568. }
  1569. void _sensorReport(unsigned char index, double value) {
  1570. const auto& magnitude = _magnitudes.at(index);
  1571. // XXX: ensure that the received 'value' will fit here
  1572. // dtostrf 2nd arg only controls leading zeroes and the
  1573. // 3rd is only for the part after the dot
  1574. char buffer[64];
  1575. dtostrf(value, 1, magnitude.decimals, buffer);
  1576. #if BROKER_SUPPORT
  1577. SensorReportBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value, buffer);
  1578. #endif
  1579. #if MQTT_SUPPORT
  1580. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1581. #if SENSOR_PUBLISH_ADDRESSES
  1582. char topic[32];
  1583. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1584. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1585. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1586. } else {
  1587. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1588. }
  1589. #endif // SENSOR_PUBLISH_ADDRESSES
  1590. #endif // MQTT_SUPPORT
  1591. #if THINGSPEAK_SUPPORT
  1592. tspkEnqueueMeasurement(index, buffer);
  1593. #endif // THINGSPEAK_SUPPORT
  1594. #if DOMOTICZ_SUPPORT
  1595. domoticzSendMagnitude(magnitude.type, index, value, buffer);
  1596. #endif // DOMOTICZ_SUPPORT
  1597. }
  1598. // -----------------------------------------------------------------------------
  1599. // Public
  1600. // -----------------------------------------------------------------------------
  1601. unsigned char sensorCount() {
  1602. return _sensors.size();
  1603. }
  1604. unsigned char magnitudeCount() {
  1605. return _magnitudes.size();
  1606. }
  1607. String magnitudeName(unsigned char index) {
  1608. if (index < _magnitudes.size()) {
  1609. sensor_magnitude_t magnitude = _magnitudes[index];
  1610. return magnitude.sensor->slot(magnitude.local);
  1611. }
  1612. return String();
  1613. }
  1614. unsigned char magnitudeType(unsigned char index) {
  1615. if (index < _magnitudes.size()) {
  1616. return int(_magnitudes[index].type);
  1617. }
  1618. return MAGNITUDE_NONE;
  1619. }
  1620. double magnitudeValue(unsigned char index) {
  1621. if (index < _magnitudes.size()) {
  1622. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  1623. }
  1624. return DBL_MIN;
  1625. }
  1626. unsigned char magnitudeIndex(unsigned char index) {
  1627. if (index < _magnitudes.size()) {
  1628. return int(_magnitudes[index].global);
  1629. }
  1630. return 0;
  1631. }
  1632. String magnitudeTopicIndex(unsigned char index) {
  1633. char topic[32] = {0};
  1634. if (index < _magnitudes.size()) {
  1635. sensor_magnitude_t magnitude = _magnitudes[index];
  1636. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  1637. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1638. } else {
  1639. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1640. }
  1641. }
  1642. return String(topic);
  1643. }
  1644. // -----------------------------------------------------------------------------
  1645. void _sensorBackwards() {
  1646. // Some keys from older versions were longer
  1647. moveSetting("powerUnits", "pwrUnits");
  1648. moveSetting("energyUnits", "eneUnits");
  1649. // Energy is now indexed (based on magnitude.global)
  1650. moveSetting("eneTotal", "eneTotal0");
  1651. // Update PZEM004T energy total across multiple devices
  1652. moveSettings("pzEneTotal", "eneTotal");
  1653. // Unit ID is no longer shared, drop when equal to Min_ or None
  1654. const char *keys[3] = {
  1655. "pwrUnits", "eneUnits", "tmpUnits"
  1656. };
  1657. for (auto* key : keys) {
  1658. const auto units = getSetting(key);
  1659. if (units.length() && (units.equals("0") || units.equals("1"))) {
  1660. delSetting(key);
  1661. }
  1662. }
  1663. }
  1664. void sensorSetup() {
  1665. // Settings backwards compatibility
  1666. _sensorBackwards();
  1667. // Load configured sensors and set up all of magnitudes
  1668. _sensorLoad();
  1669. _sensorInit();
  1670. // Configure based on settings
  1671. _sensorConfigure();
  1672. // Websockets integration, send sensor readings and configuration
  1673. #if WEB_SUPPORT
  1674. wsRegister()
  1675. .onVisible(_sensorWebSocketOnVisible)
  1676. .onConnected(_sensorWebSocketOnConnected)
  1677. .onData(_sensorWebSocketSendData)
  1678. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  1679. #endif
  1680. // MQTT receive callback, atm only for energy reset
  1681. #if MQTT_SUPPORT
  1682. mqttRegister(_sensorMqttCallback);
  1683. #endif
  1684. // API
  1685. #if API_SUPPORT
  1686. _sensorAPISetup();
  1687. #endif
  1688. // Terminal
  1689. #if TERMINAL_SUPPORT
  1690. _sensorInitCommands();
  1691. #endif
  1692. // Main callbacks
  1693. espurnaRegisterLoop(sensorLoop);
  1694. espurnaRegisterReload(_sensorConfigure);
  1695. }
  1696. void sensorLoop() {
  1697. // Check if we still have uninitialized sensors
  1698. static unsigned long last_init = 0;
  1699. if (!_sensors_ready) {
  1700. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1701. last_init = millis();
  1702. _sensorInit();
  1703. }
  1704. }
  1705. if (_magnitudes.size() == 0) return;
  1706. // Tick hook, called every loop()
  1707. _sensorTick();
  1708. // Check if we should read new data
  1709. static unsigned long last_update = 0;
  1710. static unsigned long report_count = 0;
  1711. if (millis() - last_update > _sensor_read_interval) {
  1712. last_update = millis();
  1713. report_count = (report_count + 1) % _sensor_report_every;
  1714. double value_raw; // holds the raw value as the sensor returns it
  1715. double value_show; // holds the processed value applying units and decimals
  1716. double value_filtered; // holds the processed value applying filters, and the units and decimals
  1717. // Pre-read hook, called every reading
  1718. _sensorPre();
  1719. // Get the first relay state
  1720. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1721. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1722. #endif
  1723. // Get readings
  1724. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1725. sensor_magnitude_t magnitude = _magnitudes[i];
  1726. if (magnitude.sensor->status()) {
  1727. // -------------------------------------------------------------
  1728. // Instant value
  1729. // -------------------------------------------------------------
  1730. value_raw = magnitude.sensor->value(magnitude.local);
  1731. // Completely remove spurious values if relay is OFF
  1732. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  1733. switch (magnitude.type) {
  1734. case MAGNITUDE_POWER_ACTIVE:
  1735. case MAGNITUDE_POWER_REACTIVE:
  1736. case MAGNITUDE_POWER_APPARENT:
  1737. case MAGNITUDE_POWER_FACTOR:
  1738. case MAGNITUDE_CURRENT:
  1739. case MAGNITUDE_ENERGY_DELTA:
  1740. if (relay_off) {
  1741. value_raw = 0.0;
  1742. }
  1743. break;
  1744. default:
  1745. break;
  1746. }
  1747. #endif
  1748. _magnitudes[i].last = value_raw;
  1749. // -------------------------------------------------------------
  1750. // Processing (filters)
  1751. // -------------------------------------------------------------
  1752. magnitude.filter->add(value_raw);
  1753. // Special case for MovingAverageFilter
  1754. switch (magnitude.type) {
  1755. case MAGNITUDE_COUNT:
  1756. case MAGNITUDE_GEIGER_CPM:
  1757. case MAGNITUDE_GEIGER_SIEVERT:
  1758. value_raw = magnitude.filter->result();
  1759. break;
  1760. default:
  1761. break;
  1762. }
  1763. // -------------------------------------------------------------
  1764. // Procesing (units and decimals)
  1765. // -------------------------------------------------------------
  1766. value_show = _magnitudeProcess(magnitude, value_raw);
  1767. #if BROKER_SUPPORT
  1768. {
  1769. char buffer[64];
  1770. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1771. SensorReadBroker::Publish(magnitudeTopic(magnitude.type), magnitude.global, value_show, buffer);
  1772. }
  1773. #endif
  1774. // -------------------------------------------------------------
  1775. // Debug
  1776. // -------------------------------------------------------------
  1777. #if SENSOR_DEBUG
  1778. {
  1779. char buffer[64];
  1780. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1781. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1782. magnitude.sensor->slot(magnitude.local).c_str(),
  1783. magnitudeTopic(magnitude.type).c_str(),
  1784. buffer,
  1785. magnitudeUnits(magnitude).c_str()
  1786. );
  1787. }
  1788. #endif // SENSOR_DEBUG
  1789. // -------------------------------------------------------------------
  1790. // Report when
  1791. // - report_count overflows after reaching _sensor_report_every
  1792. // - when magnitude specifies max_change and we greater or equal to it
  1793. // -------------------------------------------------------------------
  1794. bool report = (0 == report_count);
  1795. if (magnitude.max_change > 0) {
  1796. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  1797. }
  1798. // Special case for energy, save readings to RAM and EEPROM
  1799. if (MAGNITUDE_ENERGY == magnitude.type) {
  1800. _magnitudeSaveEnergyTotal(magnitude, report);
  1801. }
  1802. if (report) {
  1803. value_filtered = magnitude.filter->result();
  1804. value_filtered = _magnitudeProcess(magnitude, value_filtered);
  1805. magnitude.filter->reset();
  1806. if (magnitude.filter->size() != _sensor_report_every) {
  1807. magnitude.filter->resize(_sensor_report_every);
  1808. }
  1809. // Check if there is a minimum change threshold to report
  1810. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  1811. _magnitudes[i].reported = value_filtered;
  1812. _sensorReport(i, value_filtered);
  1813. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  1814. } // if (report_count == 0)
  1815. } // if (magnitude.sensor->status())
  1816. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1817. // Post-read hook, called every reading
  1818. _sensorPost();
  1819. // And report data to modules that don't specifically track them
  1820. #if WEB_SUPPORT
  1821. wsPost(_sensorWebSocketSendData);
  1822. #endif
  1823. #if THINGSPEAK_SUPPORT
  1824. if (report_count == 0) tspkFlush();
  1825. #endif
  1826. }
  1827. }
  1828. #endif // SENSOR_SUPPORT