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.

785 lines
24 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. // -----------------------------------------------------------------------------
  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 _sensorConfigure() {
  329. for (unsigned char i=0; i<_sensors.size(); i++) {
  330. #if EMON_ANALOG_SUPPORT
  331. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  332. double value;
  333. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  334. if (value = getSetting("pwrExpectedP", 0).toInt() == 0) {
  335. value = getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat();
  336. if (value > 0) sensor->setCurrentRatio(0, value);
  337. } else {
  338. sensor->expectedPower(0, value);
  339. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  340. }
  341. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  342. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  343. delSetting("pwrRatioC");
  344. }
  345. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  346. }
  347. #endif // EMON_ANALOG_SUPPORT
  348. // Force sensor to reload config
  349. _sensors[i]->begin();
  350. #if HLW8012_SUPPORT
  351. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  352. double value;
  353. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  354. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  355. sensor->expectedCurrent(value);
  356. setSetting("pwrRatioC", sensor->getCurrentRatio());
  357. } else {
  358. value = getSetting("pwrRatioC", 0).toFloat();
  359. if (value > 0) sensor->setCurrentRatio(value);
  360. }
  361. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  362. sensor->expectedVoltage(value);
  363. setSetting("pwrRatioV", sensor->getVoltageRatio());
  364. } else {
  365. value = getSetting("pwrRatioV", 0).toFloat();
  366. if (value > 0) sensor->setVoltageRatio(value);
  367. }
  368. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  369. sensor->expectedPower(value);
  370. setSetting("pwrRatioP", sensor->getPowerRatio());
  371. } else {
  372. value = getSetting("pwrRatioP", 0).toFloat();
  373. if (value > 0) sensor->setPowerRatio(value);
  374. }
  375. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  376. sensor->resetRatios();
  377. delSetting("pwrRatioC");
  378. delSetting("pwrRatioV");
  379. delSetting("pwrRatioP");
  380. }
  381. }
  382. #endif // HLW8012_SUPPORT
  383. }
  384. // General sensor settings
  385. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  386. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  387. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  388. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  389. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  390. // Update filter sizes
  391. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  392. _magnitudes[i].filter->resize(_sensor_report_every);
  393. }
  394. // Save settings
  395. delSetting("pwrExpectedP");
  396. delSetting("pwrExpectedC");
  397. delSetting("pwrExpectedV");
  398. delSetting("pwrResetCalibration");
  399. //saveSettings();
  400. }
  401. void _magnitudesInit() {
  402. for (unsigned char i=0; i<_sensors.size(); i++) {
  403. BaseSensor * sensor = _sensors[i];
  404. DEBUG_MSG_P(PSTR("[SENSOR] %s\n"), sensor->description().c_str());
  405. if (sensor->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  406. for (unsigned char k=0; k<sensor->count(); k++) {
  407. unsigned char type = sensor->type(k);
  408. sensor_magnitude_t new_magnitude;
  409. new_magnitude.sensor = sensor;
  410. new_magnitude.local = k;
  411. new_magnitude.type = type;
  412. new_magnitude.global = _counts[type];
  413. new_magnitude.current = 0;
  414. new_magnitude.filtered = 0;
  415. new_magnitude.reported = 0;
  416. new_magnitude.min_change = 0;
  417. if (type == MAGNITUDE_DIGITAL) {
  418. new_magnitude.filter = new MaxFilter();
  419. } else if (type == MAGNITUDE_EVENTS) {
  420. new_magnitude.filter = new MovingAverageFilter();
  421. } else {
  422. new_magnitude.filter = new MedianFilter();
  423. }
  424. new_magnitude.filter->resize(_sensor_report_every);
  425. _magnitudes.push_back(new_magnitude);
  426. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  427. _counts[type] = _counts[type] + 1;
  428. }
  429. }
  430. }
  431. // -----------------------------------------------------------------------------
  432. // Public
  433. // -----------------------------------------------------------------------------
  434. unsigned char sensorCount() {
  435. return _sensors.size();
  436. }
  437. unsigned char magnitudeCount() {
  438. return _magnitudes.size();
  439. }
  440. String magnitudeName(unsigned char index) {
  441. if (index < _magnitudes.size()) {
  442. sensor_magnitude_t magnitude = _magnitudes[index];
  443. return magnitude.sensor->slot(magnitude.local);
  444. }
  445. return String();
  446. }
  447. unsigned char magnitudeType(unsigned char index) {
  448. if (index < _magnitudes.size()) {
  449. return int(_magnitudes[index].type);
  450. }
  451. return MAGNITUDE_NONE;
  452. }
  453. unsigned char magnitudeIndex(unsigned char index) {
  454. if (index < _magnitudes.size()) {
  455. return int(_magnitudes[index].global);
  456. }
  457. return 0;
  458. }
  459. String magnitudeTopic(unsigned char type) {
  460. char buffer[16] = {0};
  461. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  462. return String(buffer);
  463. }
  464. String magnitudeTopicIndex(unsigned char index) {
  465. char topic[32] = {0};
  466. if (index < _magnitudes.size()) {
  467. sensor_magnitude_t magnitude = _magnitudes[index];
  468. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  469. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  470. } else {
  471. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  472. }
  473. }
  474. return String(topic);
  475. }
  476. String magnitudeUnits(unsigned char type) {
  477. char buffer[8] = {0};
  478. if (type < MAGNITUDE_MAX) {
  479. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  480. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  481. } else {
  482. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  483. }
  484. }
  485. return String(buffer);
  486. }
  487. // -----------------------------------------------------------------------------
  488. void sensorSetup() {
  489. // Load sensors
  490. _sensorInit();
  491. // Configure stored values
  492. _sensorConfigure();
  493. // Load magnitudes
  494. _magnitudesInit();
  495. #if WEB_SUPPORT
  496. // Websockets
  497. wsOnSendRegister(_sensorWebSocketStart);
  498. wsOnSendRegister(_sensorWebSocketSendData);
  499. wsOnAfterParseRegister(_sensorConfigure);
  500. // API
  501. _sensorAPISetup();
  502. #endif
  503. #if TERMINAL_SUPPORT
  504. _sensorInitCommands();
  505. #endif
  506. // Register loop
  507. espurnaRegisterLoop(sensorLoop);
  508. }
  509. void sensorLoop() {
  510. static unsigned long last_update = 0;
  511. static unsigned long report_count = 0;
  512. if (_magnitudes.size() == 0) return;
  513. // Tick hook
  514. _sensorTick();
  515. // Check if we should read new data
  516. if (millis() - last_update > _sensor_read_interval) {
  517. last_update = millis();
  518. report_count = (report_count + 1) % _sensor_report_every;
  519. double current;
  520. double filtered;
  521. char buffer[64];
  522. // Pre-read hook
  523. _sensorPre();
  524. // Get readings
  525. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  526. sensor_magnitude_t magnitude = _magnitudes[i];
  527. if (magnitude.sensor->status()) {
  528. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  529. current = magnitude.sensor->value(magnitude.local);
  530. magnitude.filter->add(current);
  531. // Special case
  532. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  533. current = _magnitudeProcess(magnitude.type, current);
  534. _magnitudes[i].current = current;
  535. // Debug
  536. #if SENSOR_DEBUG
  537. {
  538. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  539. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  540. magnitude.sensor->slot(magnitude.local).c_str(),
  541. magnitudeTopic(magnitude.type).c_str(),
  542. buffer,
  543. magnitudeUnits(magnitude.type).c_str()
  544. );
  545. }
  546. #endif // SENSOR_DEBUG
  547. // Time to report (we do it every _sensor_report_every readings)
  548. if (report_count == 0) {
  549. filtered = magnitude.filter->result();
  550. magnitude.filter->reset();
  551. filtered = _magnitudeProcess(magnitude.type, filtered);
  552. _magnitudes[i].filtered = filtered;
  553. // Check if there is a minimum change threshold to report
  554. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  555. _magnitudes[i].reported = filtered;
  556. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  557. #if BROKER_SUPPORT
  558. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  559. #endif
  560. #if MQTT_SUPPORT
  561. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  562. #if SENSOR_PUBLISH_ADDRESSES
  563. char topic[32];
  564. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  565. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  566. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  567. } else {
  568. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  569. }
  570. #endif // SENSOR_PUBLISH_ADDRESSES
  571. #endif // MQTT_SUPPORT
  572. #if INFLUXDB_SUPPORT
  573. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  574. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  575. } else {
  576. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  577. }
  578. #endif // INFLUXDB_SUPPORT
  579. #if THINGSPEAK_SUPPORT
  580. tspkEnqueueMeasurement(i, buffer);
  581. #endif
  582. #if DOMOTICZ_SUPPORT
  583. {
  584. char key[15];
  585. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  586. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  587. int status;
  588. if (filtered > 70) {
  589. status = HUMIDITY_WET;
  590. } else if (filtered > 45) {
  591. status = HUMIDITY_COMFORTABLE;
  592. } else if (filtered > 30) {
  593. status = HUMIDITY_NORMAL;
  594. } else {
  595. status = HUMIDITY_DRY;
  596. }
  597. char status_buf[5];
  598. itoa(status, status_buf, 10);
  599. domoticzSend(key, buffer, status_buf);
  600. } else {
  601. domoticzSend(key, 0, buffer);
  602. }
  603. }
  604. #endif // DOMOTICZ_SUPPORT
  605. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  606. } // if (report_count == 0)
  607. } // if (magnitude.sensor->status())
  608. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  609. // Post-read hook
  610. _sensorPost();
  611. #if WEB_SUPPORT
  612. wsSend(_sensorWebSocketSendData);
  613. #endif
  614. #if THINGSPEAK_SUPPORT
  615. if (report_count == 0) tspkFlush();
  616. #endif
  617. }
  618. }
  619. #endif // SENSOR_SUPPORT