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.

1332 lines
42 KiB

7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2018 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. typedef struct {
  13. BaseSensor * sensor; // Sensor object
  14. BaseFilter * filter; // Filter object
  15. unsigned char local; // Local index in its provider
  16. unsigned char type; // Type of measurement
  17. unsigned char global; // Global index in its type
  18. double current; // Current (last) value, unfiltered
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. double max_change; // Maximum value change to report
  22. } sensor_magnitude_t;
  23. std::vector<BaseSensor *> _sensors;
  24. std::vector<sensor_magnitude_t> _magnitudes;
  25. bool _sensors_ready = false;
  26. unsigned char _counts[MAGNITUDE_MAX];
  27. bool _sensor_realtime = API_REAL_TIME_VALUES;
  28. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  29. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  30. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  31. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  32. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  33. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  34. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  35. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  36. String _sensor_energy_reset_ts = String();
  37. // -----------------------------------------------------------------------------
  38. // Private
  39. // -----------------------------------------------------------------------------
  40. unsigned char _magnitudeDecimals(unsigned char type) {
  41. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  42. if (type == MAGNITUDE_ENERGY ||
  43. type == MAGNITUDE_ENERGY_DELTA) {
  44. if (_sensor_energy_units == ENERGY_KWH) return 3;
  45. }
  46. if (type == MAGNITUDE_POWER_ACTIVE ||
  47. type == MAGNITUDE_POWER_APPARENT ||
  48. type == MAGNITUDE_POWER_REACTIVE) {
  49. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  50. }
  51. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  52. return 0;
  53. }
  54. double _magnitudeProcess(unsigned char type, double value) {
  55. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  56. if (type == MAGNITUDE_TEMPERATURE) {
  57. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  58. value = value + _sensor_temperature_correction;
  59. }
  60. if (type == MAGNITUDE_HUMIDITY) {
  61. value = constrain(value + _sensor_humidity_correction, 0, 100);
  62. }
  63. if (type == MAGNITUDE_ENERGY ||
  64. type == MAGNITUDE_ENERGY_DELTA) {
  65. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  66. }
  67. if (type == MAGNITUDE_POWER_ACTIVE ||
  68. type == MAGNITUDE_POWER_APPARENT ||
  69. type == MAGNITUDE_POWER_REACTIVE) {
  70. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  71. }
  72. return roundTo(value, _magnitudeDecimals(type));
  73. }
  74. // -----------------------------------------------------------------------------
  75. #if WEB_SUPPORT
  76. bool _sensorWebSocketOnReceive(const char * key, JsonVariant& value) {
  77. if (strncmp(key, "pwr", 3) == 0) return true;
  78. if (strncmp(key, "sns", 3) == 0) return true;
  79. if (strncmp(key, "tmp", 3) == 0) return true;
  80. if (strncmp(key, "hum", 3) == 0) return true;
  81. if (strncmp(key, "ene", 3) == 0) return true;
  82. return false;
  83. }
  84. void _sensorWebSocketSendData(JsonObject& root) {
  85. char buffer[10];
  86. bool hasTemperature = false;
  87. bool hasHumidity = false;
  88. bool hasMICS = false;
  89. JsonArray& list = root.createNestedArray("magnitudes");
  90. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  91. sensor_magnitude_t magnitude = _magnitudes[i];
  92. if (magnitude.type == MAGNITUDE_EVENT) continue;
  93. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  94. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  95. JsonObject& element = list.createNestedObject();
  96. element["index"] = int(magnitude.global);
  97. element["type"] = int(magnitude.type);
  98. element["value"] = String(buffer);
  99. element["units"] = magnitudeUnits(magnitude.type);
  100. element["error"] = magnitude.sensor->error();
  101. if (magnitude.type == MAGNITUDE_ENERGY) {
  102. if (_sensor_energy_reset_ts.length() == 0) _sensorResetTS();
  103. element["description"] = magnitude.sensor->slot(magnitude.local) + String(" (since ") + _sensor_energy_reset_ts + String(")");
  104. } else {
  105. element["description"] = magnitude.sensor->slot(magnitude.local);
  106. }
  107. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  108. if (magnitude.type == MAGNITUDE_HUMIDITY) hasHumidity = true;
  109. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  110. if (magnitude.type == MAGNITUDE_CO || magnitude.type == MAGNITUDE_NO2) hasMICS = true;
  111. #endif
  112. }
  113. if (hasTemperature) root["temperatureVisible"] = 1;
  114. if (hasHumidity) root["humidityVisible"] = 1;
  115. if (hasMICS) root["micsVisible"] = 1;
  116. }
  117. void _sensorWebSocketStart(JsonObject& root) {
  118. for (unsigned char i=0; i<_sensors.size(); i++) {
  119. BaseSensor * sensor = _sensors[i];
  120. #if EMON_ANALOG_SUPPORT
  121. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  122. root["emonVisible"] = 1;
  123. root["pwrVisible"] = 1;
  124. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  125. }
  126. #endif
  127. #if HLW8012_SUPPORT
  128. if (sensor->getID() == SENSOR_HLW8012_ID) {
  129. root["hlwVisible"] = 1;
  130. root["pwrVisible"] = 1;
  131. }
  132. #endif
  133. #if CSE7766_SUPPORT
  134. if (sensor->getID() == SENSOR_CSE7766_ID) {
  135. root["cseVisible"] = 1;
  136. root["pwrVisible"] = 1;
  137. }
  138. #endif
  139. #if V9261F_SUPPORT
  140. if (sensor->getID() == SENSOR_V9261F_ID) {
  141. root["pwrVisible"] = 1;
  142. }
  143. #endif
  144. #if ECH1560_SUPPORT
  145. if (sensor->getID() == SENSOR_ECH1560_ID) {
  146. root["pwrVisible"] = 1;
  147. }
  148. #endif
  149. #if PZEM004T_SUPPORT
  150. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  151. root["pzemVisible"] = 1;
  152. root["pwrVisible"] = 1;
  153. }
  154. #endif
  155. }
  156. if (_magnitudes.size() > 0) {
  157. root["snsVisible"] = 1;
  158. //root["apiRealTime"] = _sensor_realtime;
  159. root["pwrUnits"] = _sensor_power_units;
  160. root["eneUnits"] = _sensor_energy_units;
  161. root["tmpUnits"] = _sensor_temperature_units;
  162. root["tmpCorrection"] = _sensor_temperature_correction;
  163. root["humCorrection"] = _sensor_humidity_correction;
  164. root["snsRead"] = _sensor_read_interval / 1000;
  165. root["snsReport"] = _sensor_report_every;
  166. root["snsSave"] = _sensor_save_every;
  167. }
  168. /*
  169. // Sensors manifest
  170. JsonArray& manifest = root.createNestedArray("manifest");
  171. #if BMX280_SUPPORT
  172. BMX280Sensor::manifest(manifest);
  173. #endif
  174. // Sensors configuration
  175. JsonArray& sensors = root.createNestedArray("sensors");
  176. for (unsigned char i; i<_sensors.size(); i++) {
  177. JsonObject& sensor = sensors.createNestedObject();
  178. sensor["index"] = i;
  179. sensor["id"] = _sensors[i]->getID();
  180. _sensors[i]->getConfig(sensor);
  181. }
  182. */
  183. }
  184. #endif // WEB_SUPPORT
  185. #if API_SUPPORT
  186. void _sensorAPISetup() {
  187. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  188. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  189. String topic = magnitudeTopic(magnitude.type);
  190. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  191. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  192. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  193. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  194. double value = _sensor_realtime ? magnitude.current : magnitude.reported;
  195. dtostrf(value, 1-len, decimals, buffer);
  196. });
  197. }
  198. }
  199. #endif // API_SUPPORT
  200. #if TERMINAL_SUPPORT
  201. void _sensorInitCommands() {
  202. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  203. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  204. sensor_magnitude_t magnitude = _magnitudes[i];
  205. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  206. i,
  207. magnitudeTopic(magnitude.type).c_str(),
  208. magnitude.sensor->slot(magnitude.local).c_str(),
  209. magnitudeTopic(magnitude.type).c_str(),
  210. magnitude.global
  211. );
  212. }
  213. DEBUG_MSG_P(PSTR("+OK\n"));
  214. });
  215. }
  216. #endif
  217. void _sensorTick() {
  218. for (unsigned char i=0; i<_sensors.size(); i++) {
  219. _sensors[i]->tick();
  220. }
  221. }
  222. void _sensorPre() {
  223. for (unsigned char i=0; i<_sensors.size(); i++) {
  224. _sensors[i]->pre();
  225. if (!_sensors[i]->status()) {
  226. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  227. _sensors[i]->description().c_str(),
  228. _sensors[i]->error()
  229. );
  230. }
  231. }
  232. }
  233. void _sensorPost() {
  234. for (unsigned char i=0; i<_sensors.size(); i++) {
  235. _sensors[i]->post();
  236. }
  237. }
  238. void _sensorResetTS() {
  239. #if NTP_SUPPORT
  240. if (ntpSynced()) {
  241. if (_sensor_energy_reset_ts.length() == 0) {
  242. _sensor_energy_reset_ts = ntpDateTime(now() - millis() / 1000);
  243. } else {
  244. _sensor_energy_reset_ts = ntpDateTime(now());
  245. }
  246. } else {
  247. _sensor_energy_reset_ts = String();
  248. }
  249. setSetting("snsResetTS", _sensor_energy_reset_ts);
  250. #endif
  251. }
  252. // -----------------------------------------------------------------------------
  253. // Sensor initialization
  254. // -----------------------------------------------------------------------------
  255. void _sensorLoad() {
  256. /*
  257. This is temporal, in the future sensors will be initialized based on
  258. soft configuration (data stored in EEPROM config) so you will be able
  259. to define and configure new sensors on the fly
  260. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  261. loaded and initialized here. If you want to add new sensors of the same type
  262. just duplicate the block and change the arguments for the set* methods.
  263. Check the DHT block below for an example
  264. */
  265. #if AM2320_SUPPORT
  266. {
  267. AM2320Sensor * sensor = new AM2320Sensor();
  268. sensor->setAddress(AM2320_ADDRESS);
  269. _sensors.push_back(sensor);
  270. }
  271. #endif
  272. #if ANALOG_SUPPORT
  273. {
  274. AnalogSensor * sensor = new AnalogSensor();
  275. sensor->setSamples(ANALOG_SAMPLES);
  276. sensor->setDelay(ANALOG_DELAY);
  277. _sensors.push_back(sensor);
  278. }
  279. #endif
  280. #if BH1750_SUPPORT
  281. {
  282. BH1750Sensor * sensor = new BH1750Sensor();
  283. sensor->setAddress(BH1750_ADDRESS);
  284. sensor->setMode(BH1750_MODE);
  285. _sensors.push_back(sensor);
  286. }
  287. #endif
  288. #if BMX280_SUPPORT
  289. {
  290. BMX280Sensor * sensor = new BMX280Sensor();
  291. sensor->setAddress(BMX280_ADDRESS);
  292. _sensors.push_back(sensor);
  293. }
  294. #endif
  295. #if CSE7766_SUPPORT
  296. {
  297. CSE7766Sensor * sensor = new CSE7766Sensor();
  298. sensor->setRX(CSE7766_PIN);
  299. _sensors.push_back(sensor);
  300. }
  301. #endif
  302. #if DALLAS_SUPPORT
  303. {
  304. DallasSensor * sensor = new DallasSensor();
  305. sensor->setGPIO(DALLAS_PIN);
  306. _sensors.push_back(sensor);
  307. }
  308. #endif
  309. #if DHT_SUPPORT
  310. {
  311. DHTSensor * sensor = new DHTSensor();
  312. sensor->setGPIO(DHT_PIN);
  313. sensor->setType(DHT_TYPE);
  314. _sensors.push_back(sensor);
  315. }
  316. #endif
  317. /*
  318. // Example on how to add a second DHT sensor
  319. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  320. #if DHT_SUPPORT
  321. {
  322. DHTSensor * sensor = new DHTSensor();
  323. sensor->setGPIO(DHT2_PIN);
  324. sensor->setType(DHT2_TYPE);
  325. _sensors.push_back(sensor);
  326. }
  327. #endif
  328. */
  329. #if DIGITAL_SUPPORT
  330. {
  331. DigitalSensor * sensor = new DigitalSensor();
  332. sensor->setGPIO(DIGITAL_PIN);
  333. sensor->setMode(DIGITAL_PIN_MODE);
  334. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  335. _sensors.push_back(sensor);
  336. }
  337. #endif
  338. #if ECH1560_SUPPORT
  339. {
  340. ECH1560Sensor * sensor = new ECH1560Sensor();
  341. sensor->setCLK(ECH1560_CLK_PIN);
  342. sensor->setMISO(ECH1560_MISO_PIN);
  343. sensor->setInverted(ECH1560_INVERTED);
  344. _sensors.push_back(sensor);
  345. }
  346. #endif
  347. #if EMON_ADC121_SUPPORT
  348. {
  349. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  350. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  351. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  352. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  353. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  354. _sensors.push_back(sensor);
  355. }
  356. #endif
  357. #if EMON_ADS1X15_SUPPORT
  358. {
  359. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  360. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  361. sensor->setType(EMON_ADS1X15_TYPE);
  362. sensor->setMask(EMON_ADS1X15_MASK);
  363. sensor->setGain(EMON_ADS1X15_GAIN);
  364. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  365. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  366. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  367. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  368. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  369. _sensors.push_back(sensor);
  370. }
  371. #endif
  372. #if EMON_ANALOG_SUPPORT
  373. {
  374. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  375. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  376. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  377. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  378. _sensors.push_back(sensor);
  379. }
  380. #endif
  381. #if EVENTS_SUPPORT
  382. {
  383. EventSensor * sensor = new EventSensor();
  384. sensor->setGPIO(EVENTS_PIN);
  385. sensor->setTrigger(EVENTS_TRIGGER);
  386. sensor->setPinMode(EVENTS_PIN_MODE);
  387. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  388. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  389. _sensors.push_back(sensor);
  390. }
  391. #endif
  392. #if GEIGER_SUPPORT
  393. {
  394. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  395. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  396. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  397. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  398. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  399. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  400. _sensors.push_back(sensor);
  401. }
  402. #endif
  403. #if GUVAS12SD_SUPPORT
  404. {
  405. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  406. sensor->setGPIO(GUVAS12SD_PIN);
  407. _sensors.push_back(sensor);
  408. }
  409. #endif
  410. #if SONAR_SUPPORT
  411. {
  412. SonarSensor * sensor = new SonarSensor();
  413. sensor->setEcho(SONAR_ECHO);
  414. sensor->setIterations(SONAR_ITERATIONS);
  415. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  416. sensor->setTrigger(SONAR_TRIGGER);
  417. _sensors.push_back(sensor);
  418. }
  419. #endif
  420. #if HLW8012_SUPPORT
  421. {
  422. HLW8012Sensor * sensor = new HLW8012Sensor();
  423. sensor->setSEL(HLW8012_SEL_PIN);
  424. sensor->setCF(HLW8012_CF_PIN);
  425. sensor->setCF1(HLW8012_CF1_PIN);
  426. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  427. _sensors.push_back(sensor);
  428. }
  429. #endif
  430. #if MHZ19_SUPPORT
  431. {
  432. MHZ19Sensor * sensor = new MHZ19Sensor();
  433. sensor->setRX(MHZ19_RX_PIN);
  434. sensor->setTX(MHZ19_TX_PIN);
  435. _sensors.push_back(sensor);
  436. }
  437. #endif
  438. #if MICS2710_SUPPORT
  439. {
  440. MICS2710Sensor * sensor = new MICS2710Sensor();
  441. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  442. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  443. sensor->setRL(MICS2710_RL);
  444. _sensors.push_back(sensor);
  445. }
  446. #endif
  447. #if MICS5525_SUPPORT
  448. {
  449. MICS5525Sensor * sensor = new MICS5525Sensor();
  450. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  451. sensor->setRL(MICS5525_RL);
  452. _sensors.push_back(sensor);
  453. }
  454. #endif
  455. #if NTC_SUPPORT
  456. {
  457. NTCSensor * sensor = new NTCSensor();
  458. sensor->setSamples(NTC_SAMPLES);
  459. sensor->setDelay(NTC_DELAY);
  460. sensor->setUpstreamResistor(NTC_R_UP);
  461. sensor->setDownstreamResistor(NTC_R_DOWN);
  462. sensor->setBeta(NTC_BETA);
  463. sensor->setR0(NTC_R0);
  464. sensor->setT0(NTC_T0);
  465. _sensors.push_back(sensor);
  466. }
  467. #endif
  468. #if SENSEAIR_SUPPORT
  469. {
  470. SenseAirSensor * sensor = new SenseAirSensor();
  471. sensor->setRX(SENSEAIR_RX_PIN);
  472. sensor->setTX(SENSEAIR_TX_PIN);
  473. _sensors.push_back(sensor);
  474. }
  475. #endif
  476. #if SDS011_SUPPORT
  477. {
  478. SDS011Sensor * sensor = new SDS011Sensor();
  479. sensor->setRX(SDS011_RX_PIN);
  480. sensor->setTX(SDS011_TX_PIN);
  481. _sensors.push_back(sensor);
  482. }
  483. #endif
  484. #if PMSX003_SUPPORT
  485. {
  486. PMSX003Sensor * sensor = new PMSX003Sensor();
  487. #if PMS_USE_SOFT
  488. sensor->setRX(PMS_RX_PIN);
  489. sensor->setTX(PMS_TX_PIN);
  490. #else
  491. sensor->setSerial(& PMS_HW_PORT);
  492. #endif
  493. sensor->setType(PMS_TYPE);
  494. _sensors.push_back(sensor);
  495. }
  496. #endif
  497. #if PZEM004T_SUPPORT
  498. {
  499. PZEM004TSensor * sensor = new PZEM004TSensor();
  500. #if PZEM004T_USE_SOFT
  501. sensor->setRX(PZEM004T_RX_PIN);
  502. sensor->setTX(PZEM004T_TX_PIN);
  503. #else
  504. sensor->setSerial(& PZEM004T_HW_PORT);
  505. #endif
  506. _sensors.push_back(sensor);
  507. }
  508. #endif
  509. #if SHT3X_I2C_SUPPORT
  510. {
  511. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  512. sensor->setAddress(SHT3X_I2C_ADDRESS);
  513. _sensors.push_back(sensor);
  514. }
  515. #endif
  516. #if SI7021_SUPPORT
  517. {
  518. SI7021Sensor * sensor = new SI7021Sensor();
  519. sensor->setAddress(SI7021_ADDRESS);
  520. _sensors.push_back(sensor);
  521. }
  522. #endif
  523. #if TMP3X_SUPPORT
  524. {
  525. TMP3XSensor * sensor = new TMP3XSensor();
  526. sensor->setType(TMP3X_TYPE);
  527. _sensors.push_back(sensor);
  528. }
  529. #endif
  530. #if V9261F_SUPPORT
  531. {
  532. V9261FSensor * sensor = new V9261FSensor();
  533. sensor->setRX(V9261F_PIN);
  534. sensor->setInverted(V9261F_PIN_INVERSE);
  535. _sensors.push_back(sensor);
  536. }
  537. #endif
  538. }
  539. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  540. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  541. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  542. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  543. _sensorReport(k, value);
  544. return;
  545. }
  546. }
  547. }
  548. void _sensorInit() {
  549. _sensors_ready = true;
  550. _sensor_save_every = getSetting("snsSave", 0).toInt();
  551. for (unsigned char i=0; i<_sensors.size(); i++) {
  552. // Do not process an already initialized sensor
  553. if (_sensors[i]->ready()) continue;
  554. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  555. // Force sensor to reload config
  556. _sensors[i]->begin();
  557. if (!_sensors[i]->ready()) {
  558. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  559. _sensors_ready = false;
  560. continue;
  561. }
  562. // Initialize magnitudes
  563. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  564. unsigned char type = _sensors[i]->type(k);
  565. sensor_magnitude_t new_magnitude;
  566. new_magnitude.sensor = _sensors[i];
  567. new_magnitude.local = k;
  568. new_magnitude.type = type;
  569. new_magnitude.global = _counts[type];
  570. new_magnitude.current = 0;
  571. new_magnitude.reported = 0;
  572. new_magnitude.min_change = 0;
  573. new_magnitude.max_change = 0;
  574. // TODO: find a proper way to extend this to min/max of any magnitude
  575. if (MAGNITUDE_ENERGY == type) {
  576. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  577. } else if (MAGNITUDE_TEMPERATURE == type) {
  578. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  579. } else if (MAGNITUDE_HUMIDITY == type) {
  580. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  581. }
  582. if (MAGNITUDE_ENERGY == type) {
  583. new_magnitude.filter = new LastFilter();
  584. } else if (MAGNITUDE_DIGITAL == type) {
  585. new_magnitude.filter = new MaxFilter();
  586. } 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.
  587. new_magnitude.filter = new MovingAverageFilter();
  588. } else {
  589. new_magnitude.filter = new MedianFilter();
  590. }
  591. new_magnitude.filter->resize(_sensor_report_every);
  592. _magnitudes.push_back(new_magnitude);
  593. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  594. _counts[type] = _counts[type] + 1;
  595. }
  596. // Hook callback
  597. _sensors[i]->onEvent([i](unsigned char type, double value) {
  598. _sensorCallback(i, type, value);
  599. });
  600. // Custom initializations
  601. #if MICS2710_SUPPORT
  602. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  603. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  604. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  605. }
  606. #endif // MICS2710_SUPPORT
  607. #if MICS5525_SUPPORT
  608. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  609. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  610. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  611. }
  612. #endif // MICS5525_SUPPORT
  613. #if EMON_ANALOG_SUPPORT
  614. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  615. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  616. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  617. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  618. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  619. if (value > 0) sensor->resetEnergy(0, value);
  620. }
  621. #endif // EMON_ANALOG_SUPPORT
  622. #if HLW8012_SUPPORT
  623. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  624. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  625. double value;
  626. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  627. if (value > 0) sensor->setCurrentRatio(value);
  628. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  629. if (value > 0) sensor->setVoltageRatio(value);
  630. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  631. if (value > 0) sensor->setPowerRatio(value);
  632. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  633. if (value > 0) sensor->resetEnergy(value);
  634. }
  635. #endif // HLW8012_SUPPORT
  636. #if CSE7766_SUPPORT
  637. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  638. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  639. double value;
  640. value = getSetting("pwrRatioC", 0).toFloat();
  641. if (value > 0) sensor->setCurrentRatio(value);
  642. value = getSetting("pwrRatioV", 0).toFloat();
  643. if (value > 0) sensor->setVoltageRatio(value);
  644. value = getSetting("pwrRatioP", 0).toFloat();
  645. if (value > 0) sensor->setPowerRatio(value);
  646. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  647. if (value > 0) sensor->resetEnergy(value);
  648. }
  649. #endif // CSE7766_SUPPORT
  650. }
  651. }
  652. void _sensorConfigure() {
  653. // General sensor settings
  654. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  655. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  656. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  657. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  658. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  659. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  660. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  661. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  662. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  663. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  664. // Specific sensor settings
  665. for (unsigned char i=0; i<_sensors.size(); i++) {
  666. #if MICS2710_SUPPORT
  667. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  668. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  669. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  670. sensor->calibrate();
  671. setSetting("snsR0", sensor->getR0());
  672. }
  673. }
  674. #endif // MICS2710_SUPPORT
  675. #if MICS5525_SUPPORT
  676. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  677. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  678. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  679. sensor->calibrate();
  680. setSetting("snsR0", sensor->getR0());
  681. }
  682. }
  683. #endif // MICS5525_SUPPORT
  684. #if EMON_ANALOG_SUPPORT
  685. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  686. double value;
  687. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  688. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  689. sensor->expectedPower(0, value);
  690. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  691. }
  692. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  693. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  694. delSetting("pwrRatioC");
  695. }
  696. if (getSetting("pwrResetE", 0).toInt() == 1) {
  697. sensor->resetEnergy();
  698. delSetting("eneTotal");
  699. _sensorResetTS();
  700. }
  701. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  702. }
  703. #endif // EMON_ANALOG_SUPPORT
  704. #if EMON_ADC121_SUPPORT
  705. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  706. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  707. if (getSetting("pwrResetE", 0).toInt() == 1) {
  708. sensor->resetEnergy();
  709. delSetting("eneTotal");
  710. _sensorResetTS();
  711. }
  712. }
  713. #endif
  714. #if EMON_ADS1X15_SUPPORT
  715. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  716. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  717. if (getSetting("pwrResetE", 0).toInt() == 1) {
  718. sensor->resetEnergy();
  719. delSetting("eneTotal");
  720. _sensorResetTS();
  721. }
  722. }
  723. #endif
  724. #if HLW8012_SUPPORT
  725. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  726. double value;
  727. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  728. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  729. sensor->expectedCurrent(value);
  730. setSetting("pwrRatioC", sensor->getCurrentRatio());
  731. }
  732. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  733. sensor->expectedVoltage(value);
  734. setSetting("pwrRatioV", sensor->getVoltageRatio());
  735. }
  736. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  737. sensor->expectedPower(value);
  738. setSetting("pwrRatioP", sensor->getPowerRatio());
  739. }
  740. if (getSetting("pwrResetE", 0).toInt() == 1) {
  741. sensor->resetEnergy();
  742. delSetting("eneTotal");
  743. _sensorResetTS();
  744. }
  745. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  746. sensor->resetRatios();
  747. delSetting("pwrRatioC");
  748. delSetting("pwrRatioV");
  749. delSetting("pwrRatioP");
  750. }
  751. }
  752. #endif // HLW8012_SUPPORT
  753. #if CSE7766_SUPPORT
  754. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  755. double value;
  756. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  757. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  758. sensor->expectedCurrent(value);
  759. setSetting("pwrRatioC", sensor->getCurrentRatio());
  760. }
  761. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  762. sensor->expectedVoltage(value);
  763. setSetting("pwrRatioV", sensor->getVoltageRatio());
  764. }
  765. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  766. sensor->expectedPower(value);
  767. setSetting("pwrRatioP", sensor->getPowerRatio());
  768. }
  769. if (getSetting("pwrResetE", 0).toInt() == 1) {
  770. sensor->resetEnergy();
  771. delSetting("eneTotal");
  772. _sensorResetTS();
  773. }
  774. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  775. sensor->resetRatios();
  776. delSetting("pwrRatioC");
  777. delSetting("pwrRatioV");
  778. delSetting("pwrRatioP");
  779. }
  780. }
  781. #endif // CSE7766_SUPPORT
  782. }
  783. // Update filter sizes
  784. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  785. _magnitudes[i].filter->resize(_sensor_report_every);
  786. }
  787. // General processing
  788. if (0 == _sensor_save_every) {
  789. delSetting("eneTotal");
  790. }
  791. // Save settings
  792. delSetting("snsResetCalibration");
  793. delSetting("pwrExpectedP");
  794. delSetting("pwrExpectedC");
  795. delSetting("pwrExpectedV");
  796. delSetting("pwrResetCalibration");
  797. delSetting("pwrResetE");
  798. saveSettings();
  799. }
  800. void _sensorReport(unsigned char index, double value) {
  801. sensor_magnitude_t magnitude = _magnitudes[index];
  802. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  803. char buffer[10];
  804. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  805. #if BROKER_SUPPORT
  806. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  807. #endif
  808. #if MQTT_SUPPORT
  809. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  810. #if SENSOR_PUBLISH_ADDRESSES
  811. char topic[32];
  812. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  813. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  814. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  815. } else {
  816. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  817. }
  818. #endif // SENSOR_PUBLISH_ADDRESSES
  819. #endif // MQTT_SUPPORT
  820. #if INFLUXDB_SUPPORT
  821. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  822. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  823. } else {
  824. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  825. }
  826. #endif // INFLUXDB_SUPPORT
  827. #if THINGSPEAK_SUPPORT
  828. tspkEnqueueMeasurement(index, buffer);
  829. #endif
  830. #if DOMOTICZ_SUPPORT
  831. {
  832. char key[15];
  833. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  834. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  835. int status;
  836. if (value > 70) {
  837. status = HUMIDITY_WET;
  838. } else if (value > 45) {
  839. status = HUMIDITY_COMFORTABLE;
  840. } else if (value > 30) {
  841. status = HUMIDITY_NORMAL;
  842. } else {
  843. status = HUMIDITY_DRY;
  844. }
  845. char status_buf[5];
  846. itoa(status, status_buf, 10);
  847. domoticzSend(key, buffer, status_buf);
  848. } else {
  849. domoticzSend(key, 0, buffer);
  850. }
  851. }
  852. #endif // DOMOTICZ_SUPPORT
  853. }
  854. // -----------------------------------------------------------------------------
  855. // Public
  856. // -----------------------------------------------------------------------------
  857. unsigned char sensorCount() {
  858. return _sensors.size();
  859. }
  860. unsigned char magnitudeCount() {
  861. return _magnitudes.size();
  862. }
  863. String magnitudeName(unsigned char index) {
  864. if (index < _magnitudes.size()) {
  865. sensor_magnitude_t magnitude = _magnitudes[index];
  866. return magnitude.sensor->slot(magnitude.local);
  867. }
  868. return String();
  869. }
  870. unsigned char magnitudeType(unsigned char index) {
  871. if (index < _magnitudes.size()) {
  872. return int(_magnitudes[index].type);
  873. }
  874. return MAGNITUDE_NONE;
  875. }
  876. unsigned char magnitudeIndex(unsigned char index) {
  877. if (index < _magnitudes.size()) {
  878. return int(_magnitudes[index].global);
  879. }
  880. return 0;
  881. }
  882. String magnitudeTopic(unsigned char type) {
  883. char buffer[16] = {0};
  884. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  885. return String(buffer);
  886. }
  887. String magnitudeTopicIndex(unsigned char index) {
  888. char topic[32] = {0};
  889. if (index < _magnitudes.size()) {
  890. sensor_magnitude_t magnitude = _magnitudes[index];
  891. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  892. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  893. } else {
  894. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  895. }
  896. }
  897. return String(topic);
  898. }
  899. String magnitudeUnits(unsigned char type) {
  900. char buffer[8] = {0};
  901. if (type < MAGNITUDE_MAX) {
  902. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  903. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  904. } else if (
  905. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  906. (_sensor_energy_units == ENERGY_KWH)) {
  907. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  908. } else if (
  909. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  910. (_sensor_power_units == POWER_KILOWATTS)) {
  911. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  912. } else {
  913. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  914. }
  915. }
  916. return String(buffer);
  917. }
  918. // -----------------------------------------------------------------------------
  919. void sensorSetup() {
  920. // Backwards compatibility
  921. moveSetting("powerUnits", "pwrUnits");
  922. moveSetting("energyUnits", "eneUnits");
  923. // Load sensors
  924. _sensorLoad();
  925. _sensorInit();
  926. // Configure stored values
  927. _sensorConfigure();
  928. // Websockets
  929. #if WEB_SUPPORT
  930. wsOnSendRegister(_sensorWebSocketStart);
  931. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  932. wsOnSendRegister(_sensorWebSocketSendData);
  933. #endif
  934. // API
  935. #if API_SUPPORT
  936. _sensorAPISetup();
  937. #endif
  938. // Terminal
  939. #if TERMINAL_SUPPORT
  940. _sensorInitCommands();
  941. #endif
  942. // Main callbacks
  943. espurnaRegisterLoop(sensorLoop);
  944. espurnaRegisterReload(_sensorConfigure);
  945. }
  946. void sensorLoop() {
  947. // Check if we still have uninitialized sensors
  948. static unsigned long last_init = 0;
  949. if (!_sensors_ready) {
  950. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  951. last_init = millis();
  952. _sensorInit();
  953. }
  954. }
  955. if (_magnitudes.size() == 0) return;
  956. // Tick hook
  957. _sensorTick();
  958. // Check if we should read new data
  959. static unsigned long last_update = 0;
  960. static unsigned long report_count = 0;
  961. static unsigned long save_count = 0;
  962. if (millis() - last_update > _sensor_read_interval) {
  963. last_update = millis();
  964. report_count = (report_count + 1) % _sensor_report_every;
  965. double current;
  966. double filtered;
  967. // Pre-read hook
  968. _sensorPre();
  969. // Get the first relay state
  970. #if SENSOR_POWER_CHECK_STATUS
  971. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  972. #endif
  973. // Get readings
  974. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  975. sensor_magnitude_t magnitude = _magnitudes[i];
  976. if (magnitude.sensor->status()) {
  977. // -------------------------------------------------------------
  978. // Instant value
  979. // -------------------------------------------------------------
  980. current = magnitude.sensor->value(magnitude.local);
  981. // Completely remove spurious values if relay is OFF
  982. #if SENSOR_POWER_CHECK_STATUS
  983. if (relay_off) {
  984. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  985. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  986. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  987. magnitude.type == MAGNITUDE_CURRENT ||
  988. magnitude.type == MAGNITUDE_ENERGY_DELTA
  989. ) {
  990. current = 0;
  991. }
  992. }
  993. #endif
  994. // -------------------------------------------------------------
  995. // Processing (filters)
  996. // -------------------------------------------------------------
  997. magnitude.filter->add(current);
  998. // Special case for MovingAvergaeFilter
  999. if (MAGNITUDE_COUNT == magnitude.type ||
  1000. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1001. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1002. current = magnitude.filter->result();
  1003. }
  1004. current = _magnitudeProcess(magnitude.type, current);
  1005. _magnitudes[i].current = current;
  1006. // -------------------------------------------------------------
  1007. // Debug
  1008. // -------------------------------------------------------------
  1009. #if SENSOR_DEBUG
  1010. {
  1011. char buffer[64];
  1012. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1013. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1014. magnitude.sensor->slot(magnitude.local).c_str(),
  1015. magnitudeTopic(magnitude.type).c_str(),
  1016. buffer,
  1017. magnitudeUnits(magnitude.type).c_str()
  1018. );
  1019. }
  1020. #endif // SENSOR_DEBUG
  1021. // -------------------------------------------------------------
  1022. // Report
  1023. // (we do it every _sensor_report_every readings)
  1024. // -------------------------------------------------------------
  1025. bool report = (0 == report_count);
  1026. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1027. // for MAGNITUDE_ENERGY, filtered value is last value
  1028. double value = _magnitudeProcess(magnitude.type, current);
  1029. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1030. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1031. if (report) {
  1032. filtered = magnitude.filter->result();
  1033. filtered = _magnitudeProcess(magnitude.type, filtered);
  1034. magnitude.filter->reset();
  1035. // Check if there is a minimum change threshold to report
  1036. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1037. _magnitudes[i].reported = filtered;
  1038. _sensorReport(i, filtered);
  1039. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1040. // -------------------------------------------------------------
  1041. // Saving to EEPROM
  1042. // (we do it every _sensor_save_every readings)
  1043. // -------------------------------------------------------------
  1044. if (_sensor_save_every > 0) {
  1045. save_count = (save_count + 1) % _sensor_save_every;
  1046. if (0 == save_count) {
  1047. if (MAGNITUDE_ENERGY == magnitude.type) {
  1048. setSetting("eneTotal", current);
  1049. saveSettings();
  1050. }
  1051. } // if (0 == save_count)
  1052. } // if (_sensor_save_every > 0)
  1053. } // if (report_count == 0)
  1054. } // if (magnitude.sensor->status())
  1055. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1056. // Post-read hook
  1057. _sensorPost();
  1058. #if WEB_SUPPORT
  1059. wsSend(_sensorWebSocketSendData);
  1060. #endif
  1061. #if THINGSPEAK_SUPPORT
  1062. if (report_count == 0) tspkFlush();
  1063. #endif
  1064. }
  1065. }
  1066. #endif // SENSOR_SUPPORT