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.

704 lines
23 KiB

7 years ago
7 years ago
7 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <vector>
  6. #include "filters/MaxFilter.h"
  7. #include "filters/MedianFilter.h"
  8. #include "filters/MovingAverageFilter.h"
  9. #include "sensors/BaseSensor.h"
  10. typedef struct {
  11. BaseSensor * sensor;
  12. unsigned char local; // Local index in its provider
  13. magnitude_t type; // Type of measurement
  14. unsigned char global; // Global index in its type
  15. double current; // Current (last) value, unfiltered
  16. double filtered; // Filtered (averaged) value
  17. double reported; // Last reported value
  18. double min_change; // Minimum value change to report
  19. BaseFilter * filter; // Filter object
  20. } sensor_magnitude_t;
  21. std::vector<BaseSensor *> _sensors;
  22. std::vector<sensor_magnitude_t> _magnitudes;
  23. unsigned char _counts[MAGNITUDE_MAX];
  24. bool _sensor_realtime = API_REAL_TIME_VALUES;
  25. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  26. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  27. // -----------------------------------------------------------------------------
  28. // Private
  29. // -----------------------------------------------------------------------------
  30. String _sensorTopic(magnitude_t type) {
  31. if (type == MAGNITUDE_TEMPERATURE) return String(MAGNITUDE_TEMPERATURE_TOPIC);
  32. if (type == MAGNITUDE_HUMIDITY) return String(MAGNITUDE_HUMIDITY_TOPIC);
  33. if (type == MAGNITUDE_PRESSURE) return String(MAGNITUDE_PRESSURE_TOPIC);
  34. if (type == MAGNITUDE_CURRENT) return String(MAGNITUDE_CURRENT_TOPIC);
  35. if (type == MAGNITUDE_VOLTAGE) return String(MAGNITUDE_VOLTAGE_TOPIC);
  36. if (type == MAGNITUDE_POWER_ACTIVE) return String(MAGNITUDE_ACTIVE_POWER_TOPIC);
  37. if (type == MAGNITUDE_POWER_APPARENT) return String(MAGNITUDE_APPARENT_POWER_TOPIC);
  38. if (type == MAGNITUDE_POWER_REACTIVE) return String(MAGNITUDE_REACTIVE_POWER_TOPIC);
  39. if (type == MAGNITUDE_POWER_FACTOR) return String(MAGNITUDE_POWER_FACTOR_TOPIC);
  40. if (type == MAGNITUDE_ENERGY) return String(MAGNITUDE_ENERGY_TOPIC);
  41. if (type == MAGNITUDE_ENERGY_DELTA) return String(MAGNITUDE_ENERGY_DELTA_TOPIC);
  42. if (type == MAGNITUDE_ANALOG) return String(MAGNITUDE_ANALOG_TOPIC);
  43. if (type == MAGNITUDE_DIGITAL) return String(MAGNITUDE_DIGITAL_TOPIC);
  44. if (type == MAGNITUDE_EVENTS) return String(MAGNITUDE_EVENTS_TOPIC);
  45. if (type == MAGNITUDE_PM1dot0) return String(MAGNITUDE_PM1dot0_TOPIC);
  46. if (type == MAGNITUDE_PM2dot5) return String(MAGNITUDE_PM2dot5_TOPIC);
  47. if (type == MAGNITUDE_PM10) return String(MAGNITUDE_PM10_TOPIC);
  48. if (type == MAGNITUDE_CO2) return String(MAGNITUDE_CO2_TOPIC);
  49. return String(MAGNITUDE_UNKNOWN_TOPIC);
  50. }
  51. unsigned char _sensorDecimals(magnitude_t type) {
  52. if (type == MAGNITUDE_TEMPERATURE) return MAGNITUDE_TEMPERATURE_DECIMALS;
  53. if (type == MAGNITUDE_HUMIDITY) return MAGNITUDE_HUMIDITY_DECIMALS;
  54. if (type == MAGNITUDE_PRESSURE) return MAGNITUDE_PRESSURE_DECIMALS;
  55. if (type == MAGNITUDE_CURRENT) return MAGNITUDE_CURRENT_DECIMALS;
  56. if (type == MAGNITUDE_VOLTAGE) return MAGNITUDE_VOLTAGE_DECIMALS;
  57. if (type == MAGNITUDE_POWER_ACTIVE) return MAGNITUDE_POWER_DECIMALS;
  58. if (type == MAGNITUDE_POWER_APPARENT) return MAGNITUDE_POWER_DECIMALS;
  59. if (type == MAGNITUDE_POWER_REACTIVE) return MAGNITUDE_POWER_DECIMALS;
  60. if (type == MAGNITUDE_POWER_FACTOR) return MAGNITUDE_POWER_FACTOR_DECIMALS;
  61. if (type == MAGNITUDE_ENERGY) return MAGNITUDE_ENERGY_DECIMALS;
  62. if (type == MAGNITUDE_ENERGY_DELTA) return MAGNITUDE_ENERGY_DECIMALS;
  63. if (type == MAGNITUDE_ANALOG) return MAGNITUDE_ANALOG_DECIMALS;
  64. if (type == MAGNITUDE_EVENTS) return MAGNITUDE_EVENTS_DECIMALS;
  65. if (type == MAGNITUDE_PM1dot0) return MAGNITUDE_PM1dot0_DECIMALS;
  66. if (type == MAGNITUDE_PM2dot5) return MAGNITUDE_PM2dot5_DECIMALS;
  67. if (type == MAGNITUDE_PM10) return MAGNITUDE_PM10_DECIMALS;
  68. if (type == MAGNITUDE_CO2) return MAGNITUDE_CO2_DECIMALS;
  69. return 0;
  70. }
  71. String _sensorUnits(magnitude_t type) {
  72. if (type == MAGNITUDE_TEMPERATURE) return (_sensor_temperature_units == TMP_CELSIUS) ? String("C") : String("F");
  73. if (type == MAGNITUDE_HUMIDITY) return String("%");
  74. if (type == MAGNITUDE_PRESSURE) return String("hPa");
  75. if (type == MAGNITUDE_CURRENT) return String("A");
  76. if (type == MAGNITUDE_VOLTAGE) return String("V");
  77. if (type == MAGNITUDE_POWER_ACTIVE) return String("W");
  78. if (type == MAGNITUDE_POWER_APPARENT) return String("W");
  79. if (type == MAGNITUDE_POWER_REACTIVE) return String("W");
  80. if (type == MAGNITUDE_POWER_FACTOR) return String("%");
  81. if (type == MAGNITUDE_ENERGY) return String("J");
  82. if (type == MAGNITUDE_ENERGY_DELTA) return String("J");
  83. if (type == MAGNITUDE_EVENTS) return String("/min");
  84. if (type == MAGNITUDE_PM1dot0) return String("µg/m3");
  85. if (type == MAGNITUDE_PM2dot5) return String("µg/m3");
  86. if (type == MAGNITUDE_PM10) return String("µg/m3");
  87. if (type == MAGNITUDE_CO2) return String("ppm");
  88. return String();
  89. }
  90. double _sensorProcess(magnitude_t type, double value) {
  91. if (type == MAGNITUDE_TEMPERATURE) {
  92. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  93. value = value + _sensor_temperature_correction;
  94. }
  95. return roundTo(value, _sensorDecimals(type));
  96. }
  97. #if WEB_SUPPORT
  98. void _sensorWebSocketSendData(JsonObject& root) {
  99. char buffer[10];
  100. bool hasTemperature = false;
  101. JsonArray& list = root.createNestedArray("magnitudes");
  102. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  103. sensor_magnitude_t magnitude = _magnitudes[i];
  104. unsigned char decimals = _sensorDecimals(magnitude.type);
  105. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  106. JsonObject& element = list.createNestedObject();
  107. element["index"] = int(magnitude.global);
  108. element["type"] = int(magnitude.type);
  109. element["value"] = String(buffer);
  110. element["units"] = _sensorUnits(magnitude.type);
  111. element["description"] = magnitude.sensor->slot(magnitude.local);
  112. element["error"] = magnitude.sensor->error();
  113. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  114. }
  115. //root["apiRealTime"] = _sensor_realtime;
  116. root["tmpUnits"] = _sensor_temperature_units;
  117. root["tmpCorrection"] = _sensor_temperature_correction;
  118. if (hasTemperature) root["temperatureVisible"] = 1;
  119. }
  120. void _sensorWebSocketStart(JsonObject& root) {
  121. bool hasSensors = false;
  122. for (unsigned char i=0; i<_sensors.size(); i++) {
  123. BaseSensor * sensor = _sensors[i];
  124. #if EMON_ANALOG_SUPPORT
  125. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  126. root["emonVisible"] = 1;
  127. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  128. hasSensors = true;
  129. }
  130. #endif
  131. #if HLW8012_SUPPORT
  132. if (sensor->getID() == SENSOR_HLW8012_ID) {
  133. root["hlwVisible"] = 1;
  134. hasSensors = true;
  135. }
  136. #endif
  137. }
  138. if (hasSensors) root["sensorsVisible"] = 1;
  139. /*
  140. // Sensors manifest
  141. JsonArray& manifest = root.createNestedArray("manifest");
  142. #if BMX280_SUPPORT
  143. BMX280Sensor::manifest(manifest);
  144. #endif
  145. // Sensors configuration
  146. JsonArray& sensors = root.createNestedArray("sensors");
  147. for (unsigned char i; i<_sensors.size(); i++) {
  148. JsonObject& sensor = sensors.createNestedObject();
  149. sensor["index"] = i;
  150. sensor["id"] = _sensors[i]->getID();
  151. _sensors[i]->getConfig(sensor);
  152. }
  153. */
  154. }
  155. void _sensorAPISetup() {
  156. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  157. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  158. String topic = _sensorTopic(magnitude.type);
  159. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  160. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  161. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  162. unsigned char decimals = _sensorDecimals(magnitude.type);
  163. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  164. dtostrf(value, 1-len, decimals, buffer);
  165. });
  166. }
  167. }
  168. #endif
  169. void _sensorTick() {
  170. for (unsigned char i=0; i<_sensors.size(); i++) {
  171. _sensors[i]->tick();
  172. }
  173. }
  174. void _sensorPre() {
  175. for (unsigned char i=0; i<_sensors.size(); i++) {
  176. _sensors[i]->pre();
  177. if (!_sensors[i]->status()) {
  178. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  179. _sensors[i]->description().c_str(),
  180. _sensors[i]->error()
  181. );
  182. }
  183. }
  184. }
  185. void _sensorPost() {
  186. for (unsigned char i=0; i<_sensors.size(); i++) {
  187. _sensors[i]->post();
  188. }
  189. }
  190. // -----------------------------------------------------------------------------
  191. // Sensor initialization
  192. // -----------------------------------------------------------------------------
  193. void _sensorInit() {
  194. #if ANALOG_SUPPORT
  195. {
  196. AnalogSensor * sensor = new AnalogSensor();
  197. _sensors.push_back(sensor);
  198. }
  199. #endif
  200. #if BMX280_SUPPORT
  201. {
  202. BMX280Sensor * sensor = new BMX280Sensor();
  203. sensor->setAddress(BMX280_ADDRESS);
  204. _sensors.push_back(sensor);
  205. }
  206. #endif
  207. #if DALLAS_SUPPORT
  208. {
  209. DallasSensor * sensor = new DallasSensor();
  210. sensor->setGPIO(DALLAS_PIN);
  211. _sensors.push_back(sensor);
  212. }
  213. #endif
  214. #if DHT_SUPPORT
  215. {
  216. DHTSensor * sensor = new DHTSensor();
  217. sensor->setGPIO(DHT_PIN);
  218. sensor->setType(DHT_TYPE);
  219. _sensors.push_back(sensor);
  220. }
  221. #endif
  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. double value;
  335. for (unsigned char i=0; i<_sensors.size(); i++) {
  336. #if EMON_ANALOG_SUPPORT
  337. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  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. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  358. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  359. sensor->expectedCurrent(value);
  360. setSetting("pwrRatioC", sensor->getCurrentRatio());
  361. } else {
  362. value = getSetting("pwrRatioC", 0).toFloat();
  363. if (value > 0) sensor->setCurrentRatio(value);
  364. }
  365. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  366. sensor->expectedVoltage(value);
  367. setSetting("pwrRatioV", sensor->getVoltageRatio());
  368. } else {
  369. value = getSetting("pwrRatioV", 0).toFloat();
  370. if (value > 0) sensor->setVoltageRatio(value);
  371. }
  372. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  373. sensor->expectedPower(value);
  374. setSetting("pwrRatioP", sensor->getPowerRatio());
  375. } else {
  376. value = getSetting("pwrRatioP", 0).toFloat();
  377. if (value > 0) sensor->setPowerRatio(value);
  378. }
  379. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  380. sensor->resetRatios();
  381. delSetting("pwrRatioC");
  382. delSetting("pwrRatioV");
  383. delSetting("pwrRatioP");
  384. }
  385. }
  386. #endif // HLW8012_SUPPORT
  387. }
  388. // General sensor settings
  389. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  390. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  391. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  392. // Save settings
  393. delSetting("pwrExpectedP");
  394. delSetting("pwrExpectedC");
  395. delSetting("pwrExpectedV");
  396. delSetting("pwrResetCalibration");
  397. //saveSettings();
  398. }
  399. void _magnitudesInit() {
  400. for (unsigned char i=0; i<_sensors.size(); i++) {
  401. BaseSensor * sensor = _sensors[i];
  402. DEBUG_MSG("[SENSOR] %s\n", sensor->description().c_str());
  403. if (sensor->error() != 0) DEBUG_MSG("[SENSOR] -> ERROR %d\n", sensor->error());
  404. for (unsigned char k=0; k<sensor->count(); k++) {
  405. magnitude_t type = sensor->type(k);
  406. sensor_magnitude_t new_magnitude;
  407. new_magnitude.sensor = sensor;
  408. new_magnitude.local = k;
  409. new_magnitude.type = type;
  410. new_magnitude.global = _counts[type];
  411. new_magnitude.current = 0;
  412. new_magnitude.filtered = 0;
  413. new_magnitude.reported = 0;
  414. new_magnitude.min_change = 0;
  415. if (type == MAGNITUDE_DIGITAL) {
  416. new_magnitude.filter = new MaxFilter();
  417. } else if (type == MAGNITUDE_EVENTS) {
  418. new_magnitude.filter = new MovingAverageFilter();
  419. } else {
  420. new_magnitude.filter = new MedianFilter();
  421. }
  422. _magnitudes.push_back(new_magnitude);
  423. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  424. _counts[type] = _counts[type] + 1;
  425. }
  426. }
  427. }
  428. // -----------------------------------------------------------------------------
  429. // Public
  430. // -----------------------------------------------------------------------------
  431. unsigned char sensorCount() {
  432. return _sensors.size();
  433. }
  434. unsigned char magnitudeCount() {
  435. return _magnitudes.size();
  436. }
  437. String magnitudeName(unsigned char index) {
  438. if (index < _magnitudes.size()) {
  439. sensor_magnitude_t magnitude = _magnitudes[index];
  440. return magnitude.sensor->slot(magnitude.local);
  441. }
  442. return String();
  443. }
  444. unsigned char magnitudeType(unsigned char index) {
  445. if (index < _magnitudes.size()) {
  446. return int(_magnitudes[index].type);
  447. }
  448. return MAGNITUDE_NONE;
  449. }
  450. unsigned char magnitudeIndex(unsigned char index) {
  451. if (index < _magnitudes.size()) {
  452. return int(_magnitudes[index].global);
  453. }
  454. return 0;
  455. }
  456. // -----------------------------------------------------------------------------
  457. void sensorSetup() {
  458. // Load sensors
  459. _sensorInit();
  460. // Configure stored values
  461. _sensorConfigure();
  462. // Load magnitudes
  463. _magnitudesInit();
  464. #if WEB_SUPPORT
  465. // Websockets
  466. wsOnSendRegister(_sensorWebSocketStart);
  467. wsOnSendRegister(_sensorWebSocketSendData);
  468. wsOnAfterParseRegister(_sensorConfigure);
  469. // API
  470. _sensorAPISetup();
  471. #endif
  472. }
  473. void sensorLoop() {
  474. static unsigned long last_update = 0;
  475. static unsigned long report_count = 0;
  476. // Tick hook
  477. _sensorTick();
  478. // Check if we should read new data
  479. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  480. last_update = millis();
  481. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  482. double current;
  483. double filtered;
  484. char buffer[64];
  485. // Pre-read hook
  486. _sensorPre();
  487. // Get readings
  488. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  489. sensor_magnitude_t magnitude = _magnitudes[i];
  490. if (magnitude.sensor->status()) {
  491. unsigned char decimals = _sensorDecimals(magnitude.type);
  492. current = magnitude.sensor->value(magnitude.local);
  493. magnitude.filter->add(current);
  494. // Special case
  495. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  496. current = _sensorProcess(magnitude.type, current);
  497. _magnitudes[i].current = current;
  498. // Debug
  499. #if SENSOR_DEBUG
  500. {
  501. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  502. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  503. magnitude.sensor->slot(magnitude.local).c_str(),
  504. _sensorTopic(magnitude.type).c_str(),
  505. buffer,
  506. _sensorUnits(magnitude.type).c_str()
  507. );
  508. }
  509. #endif
  510. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  511. if (report_count == 0) {
  512. filtered = magnitude.filter->result();
  513. magnitude.filter->reset();
  514. filtered = _sensorProcess(magnitude.type, filtered);
  515. _magnitudes[i].filtered = filtered;
  516. // Check if there is a minimum change threshold to report
  517. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  518. _magnitudes[i].reported = filtered;
  519. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  520. #if MQTT_SUPPORT
  521. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  522. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  523. } else {
  524. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  525. }
  526. #endif
  527. #if INFLUXDB_SUPPORT
  528. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  529. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  530. } else {
  531. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  532. }
  533. #endif
  534. #if DOMOTICZ_SUPPORT
  535. {
  536. char key[15];
  537. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  538. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  539. int status;
  540. if (filtered > 70) {
  541. status = HUMIDITY_WET;
  542. } else if (filtered > 45) {
  543. status = HUMIDITY_COMFORTABLE;
  544. } else if (filtered > 30) {
  545. status = HUMIDITY_NORMAL;
  546. } else {
  547. status = HUMIDITY_DRY;
  548. }
  549. char status_buf[5];
  550. itoa(status, status_buf, 10);
  551. domoticzSend(key, buffer, status_buf);
  552. } else {
  553. domoticzSend(key, 0, buffer);
  554. }
  555. }
  556. #endif
  557. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  558. } // if (report_count == 0)
  559. } // if (magnitude.sensor->status())
  560. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  561. // Post-read hook
  562. _sensorPost();
  563. #if WEB_SUPPORT
  564. wsSend(_sensorWebSocketSendData);
  565. #endif
  566. }
  567. }