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.

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