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.

1365 lines
44 KiB

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