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.

775 lines
24 KiB

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