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.

796 lines
25 KiB

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