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.

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