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.

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