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.

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