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.

1340 lines
43 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. #if VEML6075_SUPPORT
  539. {
  540. VEML6075Sensor * sensor = new VEML6075Sensor();
  541. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  542. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  543. _sensors.push_back(sensor);
  544. }
  545. #endif
  546. }
  547. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  548. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  549. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  550. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  551. _sensorReport(k, value);
  552. return;
  553. }
  554. }
  555. }
  556. void _sensorInit() {
  557. _sensors_ready = true;
  558. _sensor_save_every = getSetting("snsSave", 0).toInt();
  559. for (unsigned char i=0; i<_sensors.size(); i++) {
  560. // Do not process an already initialized sensor
  561. if (_sensors[i]->ready()) continue;
  562. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  563. // Force sensor to reload config
  564. _sensors[i]->begin();
  565. if (!_sensors[i]->ready()) {
  566. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  567. _sensors_ready = false;
  568. continue;
  569. }
  570. // Initialize magnitudes
  571. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  572. unsigned char type = _sensors[i]->type(k);
  573. sensor_magnitude_t new_magnitude;
  574. new_magnitude.sensor = _sensors[i];
  575. new_magnitude.local = k;
  576. new_magnitude.type = type;
  577. new_magnitude.global = _counts[type];
  578. new_magnitude.current = 0;
  579. new_magnitude.reported = 0;
  580. new_magnitude.min_change = 0;
  581. new_magnitude.max_change = 0;
  582. // TODO: find a proper way to extend this to min/max of any magnitude
  583. if (MAGNITUDE_ENERGY == type) {
  584. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  585. } else if (MAGNITUDE_TEMPERATURE == type) {
  586. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  587. } else if (MAGNITUDE_HUMIDITY == type) {
  588. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  589. }
  590. if (MAGNITUDE_ENERGY == type) {
  591. new_magnitude.filter = new LastFilter();
  592. } else if (MAGNITUDE_DIGITAL == type) {
  593. new_magnitude.filter = new MaxFilter();
  594. } 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.
  595. new_magnitude.filter = new MovingAverageFilter();
  596. } else {
  597. new_magnitude.filter = new MedianFilter();
  598. }
  599. new_magnitude.filter->resize(_sensor_report_every);
  600. _magnitudes.push_back(new_magnitude);
  601. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  602. _counts[type] = _counts[type] + 1;
  603. }
  604. // Hook callback
  605. _sensors[i]->onEvent([i](unsigned char type, double value) {
  606. _sensorCallback(i, type, value);
  607. });
  608. // Custom initializations
  609. #if MICS2710_SUPPORT
  610. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  611. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  612. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  613. }
  614. #endif // MICS2710_SUPPORT
  615. #if MICS5525_SUPPORT
  616. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  617. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  618. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  619. }
  620. #endif // MICS5525_SUPPORT
  621. #if EMON_ANALOG_SUPPORT
  622. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  623. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  624. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  625. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  626. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  627. if (value > 0) sensor->resetEnergy(0, value);
  628. }
  629. #endif // EMON_ANALOG_SUPPORT
  630. #if HLW8012_SUPPORT
  631. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  632. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  633. double value;
  634. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  635. if (value > 0) sensor->setCurrentRatio(value);
  636. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  637. if (value > 0) sensor->setVoltageRatio(value);
  638. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  639. if (value > 0) sensor->setPowerRatio(value);
  640. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  641. if (value > 0) sensor->resetEnergy(value);
  642. }
  643. #endif // HLW8012_SUPPORT
  644. #if CSE7766_SUPPORT
  645. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  646. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  647. double value;
  648. value = getSetting("pwrRatioC", 0).toFloat();
  649. if (value > 0) sensor->setCurrentRatio(value);
  650. value = getSetting("pwrRatioV", 0).toFloat();
  651. if (value > 0) sensor->setVoltageRatio(value);
  652. value = getSetting("pwrRatioP", 0).toFloat();
  653. if (value > 0) sensor->setPowerRatio(value);
  654. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  655. if (value > 0) sensor->resetEnergy(value);
  656. }
  657. #endif // CSE7766_SUPPORT
  658. }
  659. }
  660. void _sensorConfigure() {
  661. // General sensor settings
  662. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  663. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  664. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  665. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  666. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  667. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  668. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  669. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  670. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  671. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  672. // Specific sensor settings
  673. for (unsigned char i=0; i<_sensors.size(); i++) {
  674. #if MICS2710_SUPPORT
  675. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  676. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  677. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  678. sensor->calibrate();
  679. setSetting("snsR0", sensor->getR0());
  680. }
  681. }
  682. #endif // MICS2710_SUPPORT
  683. #if MICS5525_SUPPORT
  684. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  685. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  686. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  687. sensor->calibrate();
  688. setSetting("snsR0", sensor->getR0());
  689. }
  690. }
  691. #endif // MICS5525_SUPPORT
  692. #if EMON_ANALOG_SUPPORT
  693. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  694. double value;
  695. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  696. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  697. sensor->expectedPower(0, value);
  698. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  699. }
  700. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  701. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  702. delSetting("pwrRatioC");
  703. }
  704. if (getSetting("pwrResetE", 0).toInt() == 1) {
  705. sensor->resetEnergy();
  706. delSetting("eneTotal");
  707. _sensorResetTS();
  708. }
  709. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  710. }
  711. #endif // EMON_ANALOG_SUPPORT
  712. #if EMON_ADC121_SUPPORT
  713. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  714. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  715. if (getSetting("pwrResetE", 0).toInt() == 1) {
  716. sensor->resetEnergy();
  717. delSetting("eneTotal");
  718. _sensorResetTS();
  719. }
  720. }
  721. #endif
  722. #if EMON_ADS1X15_SUPPORT
  723. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  724. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  725. if (getSetting("pwrResetE", 0).toInt() == 1) {
  726. sensor->resetEnergy();
  727. delSetting("eneTotal");
  728. _sensorResetTS();
  729. }
  730. }
  731. #endif
  732. #if HLW8012_SUPPORT
  733. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  734. double value;
  735. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  736. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  737. sensor->expectedCurrent(value);
  738. setSetting("pwrRatioC", sensor->getCurrentRatio());
  739. }
  740. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  741. sensor->expectedVoltage(value);
  742. setSetting("pwrRatioV", sensor->getVoltageRatio());
  743. }
  744. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  745. sensor->expectedPower(value);
  746. setSetting("pwrRatioP", sensor->getPowerRatio());
  747. }
  748. if (getSetting("pwrResetE", 0).toInt() == 1) {
  749. sensor->resetEnergy();
  750. delSetting("eneTotal");
  751. _sensorResetTS();
  752. }
  753. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  754. sensor->resetRatios();
  755. delSetting("pwrRatioC");
  756. delSetting("pwrRatioV");
  757. delSetting("pwrRatioP");
  758. }
  759. }
  760. #endif // HLW8012_SUPPORT
  761. #if CSE7766_SUPPORT
  762. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  763. double value;
  764. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  765. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  766. sensor->expectedCurrent(value);
  767. setSetting("pwrRatioC", sensor->getCurrentRatio());
  768. }
  769. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  770. sensor->expectedVoltage(value);
  771. setSetting("pwrRatioV", sensor->getVoltageRatio());
  772. }
  773. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  774. sensor->expectedPower(value);
  775. setSetting("pwrRatioP", sensor->getPowerRatio());
  776. }
  777. if (getSetting("pwrResetE", 0).toInt() == 1) {
  778. sensor->resetEnergy();
  779. delSetting("eneTotal");
  780. _sensorResetTS();
  781. }
  782. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  783. sensor->resetRatios();
  784. delSetting("pwrRatioC");
  785. delSetting("pwrRatioV");
  786. delSetting("pwrRatioP");
  787. }
  788. }
  789. #endif // CSE7766_SUPPORT
  790. }
  791. // Update filter sizes
  792. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  793. _magnitudes[i].filter->resize(_sensor_report_every);
  794. }
  795. // General processing
  796. if (0 == _sensor_save_every) {
  797. delSetting("eneTotal");
  798. }
  799. // Save settings
  800. delSetting("snsResetCalibration");
  801. delSetting("pwrExpectedP");
  802. delSetting("pwrExpectedC");
  803. delSetting("pwrExpectedV");
  804. delSetting("pwrResetCalibration");
  805. delSetting("pwrResetE");
  806. saveSettings();
  807. }
  808. void _sensorReport(unsigned char index, double value) {
  809. sensor_magnitude_t magnitude = _magnitudes[index];
  810. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  811. char buffer[10];
  812. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  813. #if BROKER_SUPPORT
  814. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  815. #endif
  816. #if MQTT_SUPPORT
  817. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  818. #if SENSOR_PUBLISH_ADDRESSES
  819. char topic[32];
  820. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  821. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  822. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  823. } else {
  824. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  825. }
  826. #endif // SENSOR_PUBLISH_ADDRESSES
  827. #endif // MQTT_SUPPORT
  828. #if INFLUXDB_SUPPORT
  829. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  830. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  831. } else {
  832. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  833. }
  834. #endif // INFLUXDB_SUPPORT
  835. #if THINGSPEAK_SUPPORT
  836. tspkEnqueueMeasurement(index, buffer);
  837. #endif
  838. #if DOMOTICZ_SUPPORT
  839. {
  840. char key[15];
  841. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  842. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  843. int status;
  844. if (value > 70) {
  845. status = HUMIDITY_WET;
  846. } else if (value > 45) {
  847. status = HUMIDITY_COMFORTABLE;
  848. } else if (value > 30) {
  849. status = HUMIDITY_NORMAL;
  850. } else {
  851. status = HUMIDITY_DRY;
  852. }
  853. char status_buf[5];
  854. itoa(status, status_buf, 10);
  855. domoticzSend(key, buffer, status_buf);
  856. } else {
  857. domoticzSend(key, 0, buffer);
  858. }
  859. }
  860. #endif // DOMOTICZ_SUPPORT
  861. }
  862. // -----------------------------------------------------------------------------
  863. // Public
  864. // -----------------------------------------------------------------------------
  865. unsigned char sensorCount() {
  866. return _sensors.size();
  867. }
  868. unsigned char magnitudeCount() {
  869. return _magnitudes.size();
  870. }
  871. String magnitudeName(unsigned char index) {
  872. if (index < _magnitudes.size()) {
  873. sensor_magnitude_t magnitude = _magnitudes[index];
  874. return magnitude.sensor->slot(magnitude.local);
  875. }
  876. return String();
  877. }
  878. unsigned char magnitudeType(unsigned char index) {
  879. if (index < _magnitudes.size()) {
  880. return int(_magnitudes[index].type);
  881. }
  882. return MAGNITUDE_NONE;
  883. }
  884. unsigned char magnitudeIndex(unsigned char index) {
  885. if (index < _magnitudes.size()) {
  886. return int(_magnitudes[index].global);
  887. }
  888. return 0;
  889. }
  890. String magnitudeTopic(unsigned char type) {
  891. char buffer[16] = {0};
  892. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  893. return String(buffer);
  894. }
  895. String magnitudeTopicIndex(unsigned char index) {
  896. char topic[32] = {0};
  897. if (index < _magnitudes.size()) {
  898. sensor_magnitude_t magnitude = _magnitudes[index];
  899. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  900. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  901. } else {
  902. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  903. }
  904. }
  905. return String(topic);
  906. }
  907. String magnitudeUnits(unsigned char type) {
  908. char buffer[8] = {0};
  909. if (type < MAGNITUDE_MAX) {
  910. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  911. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  912. } else if (
  913. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  914. (_sensor_energy_units == ENERGY_KWH)) {
  915. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  916. } else if (
  917. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  918. (_sensor_power_units == POWER_KILOWATTS)) {
  919. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  920. } else {
  921. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  922. }
  923. }
  924. return String(buffer);
  925. }
  926. // -----------------------------------------------------------------------------
  927. void sensorSetup() {
  928. // Backwards compatibility
  929. moveSetting("powerUnits", "pwrUnits");
  930. moveSetting("energyUnits", "eneUnits");
  931. // Load sensors
  932. _sensorLoad();
  933. _sensorInit();
  934. // Configure stored values
  935. _sensorConfigure();
  936. // Websockets
  937. #if WEB_SUPPORT
  938. wsOnSendRegister(_sensorWebSocketStart);
  939. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  940. wsOnSendRegister(_sensorWebSocketSendData);
  941. #endif
  942. // API
  943. #if API_SUPPORT
  944. _sensorAPISetup();
  945. #endif
  946. // Terminal
  947. #if TERMINAL_SUPPORT
  948. _sensorInitCommands();
  949. #endif
  950. // Main callbacks
  951. espurnaRegisterLoop(sensorLoop);
  952. espurnaRegisterReload(_sensorConfigure);
  953. }
  954. void sensorLoop() {
  955. // Check if we still have uninitialized sensors
  956. static unsigned long last_init = 0;
  957. if (!_sensors_ready) {
  958. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  959. last_init = millis();
  960. _sensorInit();
  961. }
  962. }
  963. if (_magnitudes.size() == 0) return;
  964. // Tick hook
  965. _sensorTick();
  966. // Check if we should read new data
  967. static unsigned long last_update = 0;
  968. static unsigned long report_count = 0;
  969. static unsigned long save_count = 0;
  970. if (millis() - last_update > _sensor_read_interval) {
  971. last_update = millis();
  972. report_count = (report_count + 1) % _sensor_report_every;
  973. double current;
  974. double filtered;
  975. // Pre-read hook
  976. _sensorPre();
  977. // Get the first relay state
  978. #if SENSOR_POWER_CHECK_STATUS
  979. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  980. #endif
  981. // Get readings
  982. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  983. sensor_magnitude_t magnitude = _magnitudes[i];
  984. if (magnitude.sensor->status()) {
  985. // -------------------------------------------------------------
  986. // Instant value
  987. // -------------------------------------------------------------
  988. current = magnitude.sensor->value(magnitude.local);
  989. // Completely remove spurious values if relay is OFF
  990. #if SENSOR_POWER_CHECK_STATUS
  991. if (relay_off) {
  992. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  993. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  994. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  995. magnitude.type == MAGNITUDE_CURRENT ||
  996. magnitude.type == MAGNITUDE_ENERGY_DELTA
  997. ) {
  998. current = 0;
  999. }
  1000. }
  1001. #endif
  1002. // -------------------------------------------------------------
  1003. // Processing (filters)
  1004. // -------------------------------------------------------------
  1005. magnitude.filter->add(current);
  1006. // Special case for MovingAvergaeFilter
  1007. if (MAGNITUDE_COUNT == magnitude.type ||
  1008. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1009. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1010. current = magnitude.filter->result();
  1011. }
  1012. current = _magnitudeProcess(magnitude.type, current);
  1013. _magnitudes[i].current = current;
  1014. // -------------------------------------------------------------
  1015. // Debug
  1016. // -------------------------------------------------------------
  1017. #if SENSOR_DEBUG
  1018. {
  1019. char buffer[64];
  1020. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1021. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1022. magnitude.sensor->slot(magnitude.local).c_str(),
  1023. magnitudeTopic(magnitude.type).c_str(),
  1024. buffer,
  1025. magnitudeUnits(magnitude.type).c_str()
  1026. );
  1027. }
  1028. #endif // SENSOR_DEBUG
  1029. // -------------------------------------------------------------
  1030. // Report
  1031. // (we do it every _sensor_report_every readings)
  1032. // -------------------------------------------------------------
  1033. bool report = (0 == report_count);
  1034. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1035. // for MAGNITUDE_ENERGY, filtered value is last value
  1036. double value = _magnitudeProcess(magnitude.type, current);
  1037. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1038. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1039. if (report) {
  1040. filtered = magnitude.filter->result();
  1041. filtered = _magnitudeProcess(magnitude.type, filtered);
  1042. magnitude.filter->reset();
  1043. // Check if there is a minimum change threshold to report
  1044. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1045. _magnitudes[i].reported = filtered;
  1046. _sensorReport(i, filtered);
  1047. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1048. // -------------------------------------------------------------
  1049. // Saving to EEPROM
  1050. // (we do it every _sensor_save_every readings)
  1051. // -------------------------------------------------------------
  1052. if (_sensor_save_every > 0) {
  1053. save_count = (save_count + 1) % _sensor_save_every;
  1054. if (0 == save_count) {
  1055. if (MAGNITUDE_ENERGY == magnitude.type) {
  1056. setSetting("eneTotal", current);
  1057. saveSettings();
  1058. }
  1059. } // if (0 == save_count)
  1060. } // if (_sensor_save_every > 0)
  1061. } // if (report_count == 0)
  1062. } // if (magnitude.sensor->status())
  1063. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1064. // Post-read hook
  1065. _sensorPost();
  1066. #if WEB_SUPPORT
  1067. wsSend(_sensorWebSocketSendData);
  1068. #endif
  1069. #if THINGSPEAK_SUPPORT
  1070. if (report_count == 0) tspkFlush();
  1071. #endif
  1072. }
  1073. }
  1074. #endif // SENSOR_SUPPORT