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.

1336 lines
43 KiB

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