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.

791 lines
25 KiB

7 years ago
7 years ago
7 years ago
7 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/MaxFilter.h"
  8. #include "filters/MedianFilter.h"
  9. #include "filters/MovingAverageFilter.h"
  10. #include "sensors/BaseSensor.h"
  11. typedef struct {
  12. BaseSensor * sensor; // Sensor object
  13. BaseFilter * filter; // Filter object
  14. unsigned char local; // Local index in its provider
  15. unsigned char type; // Type of measurement
  16. unsigned char global; // Global index in its type
  17. double current; // Current (last) value, unfiltered
  18. double filtered; // Filtered (averaged) value
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. } sensor_magnitude_t;
  22. std::vector<BaseSensor *> _sensors;
  23. std::vector<sensor_magnitude_t> _magnitudes;
  24. unsigned char _counts[MAGNITUDE_MAX];
  25. bool _sensor_realtime = API_REAL_TIME_VALUES;
  26. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  27. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  28. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  29. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  30. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  31. // -----------------------------------------------------------------------------
  32. // Private
  33. // -----------------------------------------------------------------------------
  34. unsigned char _magnitudeDecimals(unsigned char type) {
  35. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  36. return 0;
  37. }
  38. double _magnitudeProcess(unsigned char type, double value) {
  39. if (type == MAGNITUDE_TEMPERATURE) {
  40. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  41. value = value + _sensor_temperature_correction;
  42. }
  43. if (type == MAGNITUDE_HUMIDITY) {
  44. value = value + _sensor_humidity_correction;
  45. }
  46. return roundTo(value, _magnitudeDecimals(type));
  47. }
  48. // -----------------------------------------------------------------------------
  49. #if WEB_SUPPORT
  50. void _sensorWebSocketSendData(JsonObject& root) {
  51. char buffer[10];
  52. bool hasTemperature = false;
  53. JsonArray& list = root.createNestedArray("magnitudes");
  54. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  55. sensor_magnitude_t magnitude = _magnitudes[i];
  56. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  57. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  58. JsonObject& element = list.createNestedObject();
  59. element["index"] = int(magnitude.global);
  60. element["type"] = int(magnitude.type);
  61. element["value"] = String(buffer);
  62. element["units"] = magnitudeUnits(magnitude.type);
  63. element["description"] = magnitude.sensor->slot(magnitude.local);
  64. element["error"] = magnitude.sensor->error();
  65. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  66. }
  67. if (hasTemperature) root["temperatureVisible"] = 1;
  68. }
  69. void _sensorWebSocketStart(JsonObject& root) {
  70. for (unsigned char i=0; i<_sensors.size(); i++) {
  71. BaseSensor * sensor = _sensors[i];
  72. #if EMON_ANALOG_SUPPORT
  73. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  74. root["emonVisible"] = 1;
  75. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  76. }
  77. #endif
  78. #if HLW8012_SUPPORT
  79. if (sensor->getID() == SENSOR_HLW8012_ID) {
  80. root["hlwVisible"] = 1;
  81. }
  82. #endif
  83. }
  84. if (_magnitudes.size() > 0) {
  85. root["sensorsVisible"] = 1;
  86. //root["apiRealTime"] = _sensor_realtime;
  87. root["tmpUnits"] = _sensor_temperature_units;
  88. root["tmpCorrection"] = _sensor_temperature_correction;
  89. root["humCorrection"] = _sensor_humidity_correction;
  90. root["snsRead"] = _sensor_read_interval / 1000;
  91. root["snsReport"] = _sensor_report_every;
  92. }
  93. /*
  94. // Sensors manifest
  95. JsonArray& manifest = root.createNestedArray("manifest");
  96. #if BMX280_SUPPORT
  97. BMX280Sensor::manifest(manifest);
  98. #endif
  99. // Sensors configuration
  100. JsonArray& sensors = root.createNestedArray("sensors");
  101. for (unsigned char i; i<_sensors.size(); i++) {
  102. JsonObject& sensor = sensors.createNestedObject();
  103. sensor["index"] = i;
  104. sensor["id"] = _sensors[i]->getID();
  105. _sensors[i]->getConfig(sensor);
  106. }
  107. */
  108. }
  109. void _sensorAPISetup() {
  110. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  111. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  112. String topic = magnitudeTopic(magnitude.type);
  113. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  114. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  115. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  116. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  117. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  118. dtostrf(value, 1-len, decimals, buffer);
  119. });
  120. }
  121. }
  122. #endif
  123. #if TERMINAL_SUPPORT
  124. void _sensorInitCommands() {
  125. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  126. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  127. sensor_magnitude_t magnitude = _magnitudes[i];
  128. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  129. i,
  130. magnitudeTopic(magnitude.type).c_str(),
  131. magnitude.sensor->slot(magnitude.local).c_str(),
  132. magnitudeTopic(magnitude.type).c_str(),
  133. magnitude.global
  134. );
  135. }
  136. DEBUG_MSG_P(PSTR("+OK\n"));
  137. });
  138. }
  139. #endif
  140. void _sensorTick() {
  141. for (unsigned char i=0; i<_sensors.size(); i++) {
  142. _sensors[i]->tick();
  143. }
  144. }
  145. void _sensorPre() {
  146. for (unsigned char i=0; i<_sensors.size(); i++) {
  147. _sensors[i]->pre();
  148. if (!_sensors[i]->status()) {
  149. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  150. _sensors[i]->description().c_str(),
  151. _sensors[i]->error()
  152. );
  153. }
  154. }
  155. }
  156. void _sensorPost() {
  157. for (unsigned char i=0; i<_sensors.size(); i++) {
  158. _sensors[i]->post();
  159. }
  160. }
  161. // -----------------------------------------------------------------------------
  162. // Sensor initialization
  163. // -----------------------------------------------------------------------------
  164. void _sensorInit() {
  165. /*
  166. This is temporal, in the future sensors will be initialized based on
  167. soft configuration (data stored in EEPROM config) so you will be able
  168. to define and configure new sensors on the fly
  169. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  170. loaded and initialized here. If you want to add new sensors of the same type
  171. just duplicate the block and change the arguments for the set* methods.
  172. Check the DHT block below for an example
  173. */
  174. #if ANALOG_SUPPORT
  175. {
  176. AnalogSensor * sensor = new AnalogSensor();
  177. _sensors.push_back(sensor);
  178. }
  179. #endif
  180. #if BH1750_SUPPORT
  181. {
  182. BH1750Sensor * sensor = new BH1750Sensor();
  183. sensor->setAddress(BH1750_ADDRESS);
  184. sensor->setMode(BH1750_MODE);
  185. _sensors.push_back(sensor);
  186. }
  187. #endif
  188. #if BMX280_SUPPORT
  189. {
  190. BMX280Sensor * sensor = new BMX280Sensor();
  191. sensor->setAddress(BMX280_ADDRESS);
  192. _sensors.push_back(sensor);
  193. }
  194. #endif
  195. #if DALLAS_SUPPORT
  196. {
  197. DallasSensor * sensor = new DallasSensor();
  198. sensor->setGPIO(DALLAS_PIN);
  199. _sensors.push_back(sensor);
  200. }
  201. #endif
  202. #if DHT_SUPPORT
  203. {
  204. DHTSensor * sensor = new DHTSensor();
  205. sensor->setGPIO(DHT_PIN);
  206. sensor->setType(DHT_TYPE);
  207. _sensors.push_back(sensor);
  208. }
  209. #endif
  210. /*
  211. // Example on how to add a second DHT sensor
  212. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  213. #if DHT_SUPPORT
  214. {
  215. DHTSensor * sensor = new DHTSensor();
  216. sensor->setGPIO(DHT2_PIN);
  217. sensor->setType(DHT2_TYPE);
  218. _sensors.push_back(sensor);
  219. }
  220. #endif
  221. */
  222. #if DIGITAL_SUPPORT
  223. {
  224. DigitalSensor * sensor = new DigitalSensor();
  225. sensor->setGPIO(DIGITAL_PIN);
  226. sensor->setMode(DIGITAL_PIN_MODE);
  227. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  228. _sensors.push_back(sensor);
  229. }
  230. #endif
  231. #if ECH1560_SUPPORT
  232. {
  233. ECH1560Sensor * sensor = new ECH1560Sensor();
  234. sensor->setCLK(ECH1560_CLK_PIN);
  235. sensor->setMISO(ECH1560_MISO_PIN);
  236. sensor->setInverted(ECH1560_INVERTED);
  237. _sensors.push_back(sensor);
  238. }
  239. #endif
  240. #if EMON_ADC121_SUPPORT
  241. {
  242. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  243. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  244. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  245. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  246. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  247. _sensors.push_back(sensor);
  248. }
  249. #endif
  250. #if EMON_ADS1X15_SUPPORT
  251. {
  252. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  253. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  254. sensor->setType(EMON_ADS1X15_TYPE);
  255. sensor->setMask(EMON_ADS1X15_MASK);
  256. sensor->setGain(EMON_ADS1X15_GAIN);
  257. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  258. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  259. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  260. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  261. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  262. _sensors.push_back(sensor);
  263. }
  264. #endif
  265. #if EMON_ANALOG_SUPPORT
  266. {
  267. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  268. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  269. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  270. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  271. _sensors.push_back(sensor);
  272. }
  273. #endif
  274. #if EVENTS_SUPPORT
  275. {
  276. EventSensor * sensor = new EventSensor();
  277. sensor->setGPIO(EVENTS_PIN);
  278. sensor->setMode(EVENTS_PIN_MODE);
  279. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  280. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  281. _sensors.push_back(sensor);
  282. }
  283. #endif
  284. #if HLW8012_SUPPORT
  285. {
  286. HLW8012Sensor * sensor = new HLW8012Sensor();
  287. sensor->setSEL(HLW8012_SEL_PIN);
  288. sensor->setCF(HLW8012_CF_PIN);
  289. sensor->setCF1(HLW8012_CF1_PIN);
  290. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  291. _sensors.push_back(sensor);
  292. }
  293. #endif
  294. #if MHZ19_SUPPORT
  295. {
  296. MHZ19Sensor * sensor = new MHZ19Sensor();
  297. sensor->setRX(MHZ19_RX_PIN);
  298. sensor->setTX(MHZ19_TX_PIN);
  299. _sensors.push_back(sensor);
  300. }
  301. #endif
  302. #if PMSX003_SUPPORT
  303. {
  304. PMSX003Sensor * sensor = new PMSX003Sensor();
  305. sensor->setRX(PMS_RX_PIN);
  306. sensor->setTX(PMS_TX_PIN);
  307. _sensors.push_back(sensor);
  308. }
  309. #endif
  310. #if SHT3X_I2C_SUPPORT
  311. {
  312. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  313. sensor->setAddress(SHT3X_I2C_ADDRESS);
  314. _sensors.push_back(sensor);
  315. }
  316. #endif
  317. #if SI7021_SUPPORT
  318. {
  319. SI7021Sensor * sensor = new SI7021Sensor();
  320. sensor->setAddress(SI7021_ADDRESS);
  321. _sensors.push_back(sensor);
  322. }
  323. #endif
  324. #if V9261F_SUPPORT
  325. {
  326. V9261FSensor * sensor = new V9261FSensor();
  327. sensor->setRX(V9261F_PIN);
  328. sensor->setInverted(V9261F_PIN_INVERSE);
  329. _sensors.push_back(sensor);
  330. }
  331. #endif
  332. }
  333. void _sensorConfigure() {
  334. for (unsigned char i=0; i<_sensors.size(); i++) {
  335. #if EMON_ANALOG_SUPPORT
  336. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  337. double value;
  338. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  339. if (value = getSetting("pwrExpectedP", 0).toInt() == 0) {
  340. value = getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat();
  341. if (value > 0) sensor->setCurrentRatio(0, value);
  342. } else {
  343. sensor->expectedPower(0, value);
  344. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  345. }
  346. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  347. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  348. delSetting("pwrRatioC");
  349. }
  350. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  351. }
  352. #endif // EMON_ANALOG_SUPPORT
  353. // Force sensor to reload config
  354. _sensors[i]->begin();
  355. #if HLW8012_SUPPORT
  356. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  357. double value;
  358. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  359. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  360. sensor->expectedCurrent(value);
  361. setSetting("pwrRatioC", sensor->getCurrentRatio());
  362. } else {
  363. value = getSetting("pwrRatioC", 0).toFloat();
  364. if (value > 0) sensor->setCurrentRatio(value);
  365. }
  366. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  367. sensor->expectedVoltage(value);
  368. setSetting("pwrRatioV", sensor->getVoltageRatio());
  369. } else {
  370. value = getSetting("pwrRatioV", 0).toFloat();
  371. if (value > 0) sensor->setVoltageRatio(value);
  372. }
  373. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  374. sensor->expectedPower(value);
  375. setSetting("pwrRatioP", sensor->getPowerRatio());
  376. } else {
  377. value = getSetting("pwrRatioP", 0).toFloat();
  378. if (value > 0) sensor->setPowerRatio(value);
  379. }
  380. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  381. sensor->resetRatios();
  382. delSetting("pwrRatioC");
  383. delSetting("pwrRatioV");
  384. delSetting("pwrRatioP");
  385. }
  386. }
  387. #endif // HLW8012_SUPPORT
  388. }
  389. // General sensor settings
  390. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  391. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  392. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  393. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  394. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  395. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  396. // Update filter sizes
  397. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  398. _magnitudes[i].filter->resize(_sensor_report_every);
  399. }
  400. // Save settings
  401. delSetting("pwrExpectedP");
  402. delSetting("pwrExpectedC");
  403. delSetting("pwrExpectedV");
  404. delSetting("pwrResetCalibration");
  405. //saveSettings();
  406. }
  407. void _magnitudesInit() {
  408. for (unsigned char i=0; i<_sensors.size(); i++) {
  409. BaseSensor * sensor = _sensors[i];
  410. DEBUG_MSG_P(PSTR("[SENSOR] %s\n"), sensor->description().c_str());
  411. if (sensor->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  412. for (unsigned char k=0; k<sensor->count(); k++) {
  413. unsigned char type = sensor->type(k);
  414. sensor_magnitude_t new_magnitude;
  415. new_magnitude.sensor = sensor;
  416. new_magnitude.local = k;
  417. new_magnitude.type = type;
  418. new_magnitude.global = _counts[type];
  419. new_magnitude.current = 0;
  420. new_magnitude.filtered = 0;
  421. new_magnitude.reported = 0;
  422. new_magnitude.min_change = 0;
  423. if (type == MAGNITUDE_DIGITAL) {
  424. new_magnitude.filter = new MaxFilter();
  425. } else if (type == MAGNITUDE_EVENTS) {
  426. new_magnitude.filter = new MovingAverageFilter();
  427. } else {
  428. new_magnitude.filter = new MedianFilter();
  429. }
  430. new_magnitude.filter->resize(_sensor_report_every);
  431. _magnitudes.push_back(new_magnitude);
  432. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  433. _counts[type] = _counts[type] + 1;
  434. }
  435. }
  436. }
  437. // -----------------------------------------------------------------------------
  438. // Public
  439. // -----------------------------------------------------------------------------
  440. unsigned char sensorCount() {
  441. return _sensors.size();
  442. }
  443. unsigned char magnitudeCount() {
  444. return _magnitudes.size();
  445. }
  446. String magnitudeName(unsigned char index) {
  447. if (index < _magnitudes.size()) {
  448. sensor_magnitude_t magnitude = _magnitudes[index];
  449. return magnitude.sensor->slot(magnitude.local);
  450. }
  451. return String();
  452. }
  453. unsigned char magnitudeType(unsigned char index) {
  454. if (index < _magnitudes.size()) {
  455. return int(_magnitudes[index].type);
  456. }
  457. return MAGNITUDE_NONE;
  458. }
  459. unsigned char magnitudeIndex(unsigned char index) {
  460. if (index < _magnitudes.size()) {
  461. return int(_magnitudes[index].global);
  462. }
  463. return 0;
  464. }
  465. String magnitudeTopic(unsigned char type) {
  466. char buffer[16] = {0};
  467. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  468. return String(buffer);
  469. }
  470. String magnitudeTopicIndex(unsigned char index) {
  471. char topic[32] = {0};
  472. if (index < _magnitudes.size()) {
  473. sensor_magnitude_t magnitude = _magnitudes[index];
  474. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  475. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  476. } else {
  477. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  478. }
  479. }
  480. return String(topic);
  481. }
  482. String magnitudeUnits(unsigned char type) {
  483. char buffer[8] = {0};
  484. if (type < MAGNITUDE_MAX) {
  485. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  486. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  487. } else {
  488. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  489. }
  490. }
  491. return String(buffer);
  492. }
  493. // -----------------------------------------------------------------------------
  494. void sensorSetup() {
  495. // Load sensors
  496. _sensorInit();
  497. // Configure stored values
  498. _sensorConfigure();
  499. // Load magnitudes
  500. _magnitudesInit();
  501. #if WEB_SUPPORT
  502. // Websockets
  503. wsOnSendRegister(_sensorWebSocketStart);
  504. wsOnSendRegister(_sensorWebSocketSendData);
  505. wsOnAfterParseRegister(_sensorConfigure);
  506. // API
  507. _sensorAPISetup();
  508. #endif
  509. #if TERMINAL_SUPPORT
  510. _sensorInitCommands();
  511. #endif
  512. // Register loop
  513. espurnaRegisterLoop(sensorLoop);
  514. }
  515. void sensorLoop() {
  516. static unsigned long last_update = 0;
  517. static unsigned long report_count = 0;
  518. if (_magnitudes.size() == 0) return;
  519. // Tick hook
  520. _sensorTick();
  521. // Check if we should read new data
  522. if (millis() - last_update > _sensor_read_interval) {
  523. last_update = millis();
  524. report_count = (report_count + 1) % _sensor_report_every;
  525. double current;
  526. double filtered;
  527. char buffer[64];
  528. // Pre-read hook
  529. _sensorPre();
  530. // Get readings
  531. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  532. sensor_magnitude_t magnitude = _magnitudes[i];
  533. if (magnitude.sensor->status()) {
  534. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  535. current = magnitude.sensor->value(magnitude.local);
  536. magnitude.filter->add(current);
  537. // Special case
  538. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  539. current = _magnitudeProcess(magnitude.type, current);
  540. _magnitudes[i].current = current;
  541. // Debug
  542. #if SENSOR_DEBUG
  543. {
  544. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  545. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  546. magnitude.sensor->slot(magnitude.local).c_str(),
  547. magnitudeTopic(magnitude.type).c_str(),
  548. buffer,
  549. magnitudeUnits(magnitude.type).c_str()
  550. );
  551. }
  552. #endif // SENSOR_DEBUG
  553. // Time to report (we do it every _sensor_report_every readings)
  554. if (report_count == 0) {
  555. filtered = magnitude.filter->result();
  556. magnitude.filter->reset();
  557. filtered = _magnitudeProcess(magnitude.type, filtered);
  558. _magnitudes[i].filtered = filtered;
  559. // Check if there is a minimum change threshold to report
  560. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  561. _magnitudes[i].reported = filtered;
  562. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  563. #if BROKER_SUPPORT
  564. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  565. #endif
  566. #if MQTT_SUPPORT
  567. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  568. #if SENSOR_PUBLISH_ADDRESSES
  569. char topic[32];
  570. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  571. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  572. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  573. } else {
  574. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  575. }
  576. #endif // SENSOR_PUBLISH_ADDRESSES
  577. #endif // MQTT_SUPPORT
  578. #if INFLUXDB_SUPPORT
  579. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  580. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  581. } else {
  582. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  583. }
  584. #endif // INFLUXDB_SUPPORT
  585. #if THINGSPEAK_SUPPORT
  586. tspkEnqueueMeasurement(i, buffer);
  587. #endif
  588. #if DOMOTICZ_SUPPORT
  589. {
  590. char key[15];
  591. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  592. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  593. int status;
  594. if (filtered > 70) {
  595. status = HUMIDITY_WET;
  596. } else if (filtered > 45) {
  597. status = HUMIDITY_COMFORTABLE;
  598. } else if (filtered > 30) {
  599. status = HUMIDITY_NORMAL;
  600. } else {
  601. status = HUMIDITY_DRY;
  602. }
  603. char status_buf[5];
  604. itoa(status, status_buf, 10);
  605. domoticzSend(key, buffer, status_buf);
  606. } else {
  607. domoticzSend(key, 0, buffer);
  608. }
  609. }
  610. #endif // DOMOTICZ_SUPPORT
  611. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  612. } // if (report_count == 0)
  613. } // if (magnitude.sensor->status())
  614. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  615. // Post-read hook
  616. _sensorPost();
  617. #if WEB_SUPPORT
  618. wsSend(_sensorWebSocketSendData);
  619. #endif
  620. #if THINGSPEAK_SUPPORT
  621. if (report_count == 0) tspkFlush();
  622. #endif
  623. }
  624. }
  625. #endif // SENSOR_SUPPORT