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.

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