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.

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