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.

1858 lines
61 KiB

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