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.

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