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.

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