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.

1218 lines
42 KiB

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