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.

806 lines
25 KiB

7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if SENSOR_SUPPORT
  6. #include <vector>
  7. #include "filters/MaxFilter.h"
  8. #include "filters/MedianFilter.h"
  9. #include "filters/MovingAverageFilter.h"
  10. #include "sensors/BaseSensor.h"
  11. typedef struct {
  12. BaseSensor * sensor; // Sensor object
  13. BaseFilter * filter; // Filter object
  14. unsigned char local; // Local index in its provider
  15. unsigned char type; // Type of measurement
  16. unsigned char global; // Global index in its type
  17. double current; // Current (last) value, unfiltered
  18. double filtered; // Filtered (averaged) value
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. } sensor_magnitude_t;
  22. std::vector<BaseSensor *> _sensors;
  23. std::vector<sensor_magnitude_t> _magnitudes;
  24. unsigned char _counts[MAGNITUDE_MAX];
  25. bool _sensor_realtime = API_REAL_TIME_VALUES;
  26. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  27. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  28. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  29. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  30. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  31. // -----------------------------------------------------------------------------
  32. // Private
  33. // -----------------------------------------------------------------------------
  34. unsigned char _magnitudeDecimals(unsigned char type) {
  35. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  36. return 0;
  37. }
  38. double _magnitudeProcess(unsigned char type, double value) {
  39. if (type == MAGNITUDE_TEMPERATURE) {
  40. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  41. value = value + _sensor_temperature_correction;
  42. }
  43. if (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) {
  44. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  45. }
  46. return roundTo(value, _magnitudeDecimals(type));
  47. }
  48. // -----------------------------------------------------------------------------
  49. #if WEB_SUPPORT
  50. void _sensorWebSocketSendData(JsonObject& root) {
  51. char buffer[10];
  52. bool hasTemperature = false;
  53. JsonArray& list = root.createNestedArray("magnitudes");
  54. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  55. sensor_magnitude_t magnitude = _magnitudes[i];
  56. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  57. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  58. JsonObject& element = list.createNestedObject();
  59. element["index"] = int(magnitude.global);
  60. element["type"] = int(magnitude.type);
  61. element["value"] = String(buffer);
  62. element["units"] = magnitudeUnits(magnitude.type);
  63. element["description"] = magnitude.sensor->slot(magnitude.local);
  64. element["error"] = magnitude.sensor->error();
  65. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  66. }
  67. if (hasTemperature) root["temperatureVisible"] = 1;
  68. }
  69. void _sensorWebSocketStart(JsonObject& root) {
  70. for (unsigned char i=0; i<_sensors.size(); i++) {
  71. BaseSensor * sensor = _sensors[i];
  72. #if EMON_ANALOG_SUPPORT
  73. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  74. root["emonVisible"] = 1;
  75. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  76. }
  77. #endif
  78. #if HLW8012_SUPPORT
  79. if (sensor->getID() == SENSOR_HLW8012_ID) {
  80. root["hlwVisible"] = 1;
  81. }
  82. #endif
  83. }
  84. if (_magnitudes.size() > 0) {
  85. root["sensorsVisible"] = 1;
  86. //root["apiRealTime"] = _sensor_realtime;
  87. root["tmpUnits"] = _sensor_temperature_units;
  88. root["energyUnits"] = _sensor_energy_units;
  89. root["tmpCorrection"] = _sensor_temperature_correction;
  90. root["snsRead"] = _sensor_read_interval / 1000;
  91. root["snsReport"] = _sensor_report_every;
  92. }
  93. /*
  94. // Sensors manifest
  95. JsonArray& manifest = root.createNestedArray("manifest");
  96. #if BMX280_SUPPORT
  97. BMX280Sensor::manifest(manifest);
  98. #endif
  99. // Sensors configuration
  100. JsonArray& sensors = root.createNestedArray("sensors");
  101. for (unsigned char i; i<_sensors.size(); i++) {
  102. JsonObject& sensor = sensors.createNestedObject();
  103. sensor["index"] = i;
  104. sensor["id"] = _sensors[i]->getID();
  105. _sensors[i]->getConfig(sensor);
  106. }
  107. */
  108. }
  109. void _sensorAPISetup() {
  110. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  111. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  112. String topic = magnitudeTopic(magnitude.type);
  113. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  114. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  115. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  116. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  117. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  118. dtostrf(value, 1-len, decimals, buffer);
  119. });
  120. }
  121. }
  122. #endif
  123. #if TERMINAL_SUPPORT
  124. void _sensorInitCommands() {
  125. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  126. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  127. sensor_magnitude_t magnitude = _magnitudes[i];
  128. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  129. i,
  130. magnitudeTopic(magnitude.type).c_str(),
  131. magnitude.sensor->slot(magnitude.local).c_str(),
  132. magnitudeTopic(magnitude.type).c_str(),
  133. magnitude.global
  134. );
  135. }
  136. DEBUG_MSG_P(PSTR("+OK\n"));
  137. });
  138. }
  139. #endif
  140. void _sensorTick() {
  141. for (unsigned char i=0; i<_sensors.size(); i++) {
  142. _sensors[i]->tick();
  143. }
  144. }
  145. void _sensorPre() {
  146. for (unsigned char i=0; i<_sensors.size(); i++) {
  147. _sensors[i]->pre();
  148. if (!_sensors[i]->status()) {
  149. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  150. _sensors[i]->description().c_str(),
  151. _sensors[i]->error()
  152. );
  153. }
  154. }
  155. }
  156. void _sensorPost() {
  157. for (unsigned char i=0; i<_sensors.size(); i++) {
  158. _sensors[i]->post();
  159. }
  160. }
  161. // -----------------------------------------------------------------------------
  162. // Sensor initialization
  163. // -----------------------------------------------------------------------------
  164. void _sensorInit() {
  165. /*
  166. This is temporal, in the future sensors will be initialized based on
  167. soft configuration (data stored in EEPROM config) so you will be able
  168. to define and configure new sensors on the fly
  169. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  170. loaded and initialized here. If you want to add new sensors of the same type
  171. just duplicate the block and change the arguments for the set* methods.
  172. Check the DHT block below for an example
  173. */
  174. #if ANALOG_SUPPORT
  175. {
  176. AnalogSensor * sensor = new AnalogSensor();
  177. _sensors.push_back(sensor);
  178. }
  179. #endif
  180. #if BH1750_SUPPORT
  181. {
  182. BH1750Sensor * sensor = new BH1750Sensor();
  183. sensor->setAddress(BH1750_ADDRESS);
  184. sensor->setMode(BH1750_MODE);
  185. _sensors.push_back(sensor);
  186. }
  187. #endif
  188. #if BMX280_SUPPORT
  189. {
  190. BMX280Sensor * sensor = new BMX280Sensor();
  191. sensor->setAddress(BMX280_ADDRESS);
  192. _sensors.push_back(sensor);
  193. }
  194. #endif
  195. #if DALLAS_SUPPORT
  196. {
  197. DallasSensor * sensor = new DallasSensor();
  198. sensor->setGPIO(DALLAS_PIN);
  199. _sensors.push_back(sensor);
  200. }
  201. #endif
  202. #if DHT_SUPPORT
  203. {
  204. DHTSensor * sensor = new DHTSensor();
  205. sensor->setGPIO(DHT_PIN);
  206. sensor->setType(DHT_TYPE);
  207. _sensors.push_back(sensor);
  208. }
  209. #endif
  210. /*
  211. // Example on how to add a second DHT sensor
  212. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  213. #if DHT_SUPPORT
  214. {
  215. DHTSensor * sensor = new DHTSensor();
  216. sensor->setGPIO(DHT2_PIN);
  217. sensor->setType(DHT2_TYPE);
  218. _sensors.push_back(sensor);
  219. }
  220. #endif
  221. */
  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 _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  334. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  335. }
  336. void _sensorConfigure() {
  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. double value;
  341. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  342. if (value = (getSetting("pwrExpectedP", 0).toInt() == 0)) {
  343. value = getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat();
  344. if (value > 0) sensor->setCurrentRatio(0, value);
  345. } else {
  346. sensor->expectedPower(0, value);
  347. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  348. }
  349. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  350. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  351. delSetting("pwrRatioC");
  352. }
  353. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  354. }
  355. #endif // EMON_ANALOG_SUPPORT
  356. // Force sensor to reload config
  357. _sensors[i]->begin();
  358. // Hook callback
  359. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  360. _sensorCallback(i, type, payload);
  361. });
  362. #if HLW8012_SUPPORT
  363. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  364. double value;
  365. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  366. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  367. sensor->expectedCurrent(value);
  368. setSetting("pwrRatioC", sensor->getCurrentRatio());
  369. } else {
  370. value = getSetting("pwrRatioC", 0).toFloat();
  371. if (value > 0) sensor->setCurrentRatio(value);
  372. }
  373. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  374. sensor->expectedVoltage(value);
  375. setSetting("pwrRatioV", sensor->getVoltageRatio());
  376. } else {
  377. value = getSetting("pwrRatioV", 0).toFloat();
  378. if (value > 0) sensor->setVoltageRatio(value);
  379. }
  380. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  381. sensor->expectedPower(value);
  382. setSetting("pwrRatioP", sensor->getPowerRatio());
  383. } else {
  384. value = getSetting("pwrRatioP", 0).toFloat();
  385. if (value > 0) sensor->setPowerRatio(value);
  386. }
  387. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  388. sensor->resetRatios();
  389. delSetting("pwrRatioC");
  390. delSetting("pwrRatioV");
  391. delSetting("pwrRatioP");
  392. }
  393. }
  394. #endif // HLW8012_SUPPORT
  395. }
  396. // General sensor settings
  397. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  398. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  399. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  400. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  401. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  402. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  403. // Update filter sizes
  404. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  405. _magnitudes[i].filter->resize(_sensor_report_every);
  406. }
  407. // Save settings
  408. delSetting("pwrExpectedP");
  409. delSetting("pwrExpectedC");
  410. delSetting("pwrExpectedV");
  411. delSetting("pwrResetCalibration");
  412. //saveSettings();
  413. }
  414. void _magnitudesInit() {
  415. for (unsigned char i=0; i<_sensors.size(); i++) {
  416. BaseSensor * sensor = _sensors[i];
  417. DEBUG_MSG_P(PSTR("[SENSOR] %s\n"), sensor->description().c_str());
  418. if (sensor->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  419. for (unsigned char k=0; k<sensor->count(); k++) {
  420. unsigned char type = sensor->type(k);
  421. sensor_magnitude_t new_magnitude;
  422. new_magnitude.sensor = sensor;
  423. new_magnitude.local = k;
  424. new_magnitude.type = type;
  425. new_magnitude.global = _counts[type];
  426. new_magnitude.current = 0;
  427. new_magnitude.filtered = 0;
  428. new_magnitude.reported = 0;
  429. new_magnitude.min_change = 0;
  430. if (type == MAGNITUDE_DIGITAL) {
  431. new_magnitude.filter = new MaxFilter();
  432. } else if (type == MAGNITUDE_EVENTS) {
  433. new_magnitude.filter = new MovingAverageFilter();
  434. } else {
  435. new_magnitude.filter = new MedianFilter();
  436. }
  437. new_magnitude.filter->resize(_sensor_report_every);
  438. _magnitudes.push_back(new_magnitude);
  439. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  440. _counts[type] = _counts[type] + 1;
  441. }
  442. }
  443. }
  444. // -----------------------------------------------------------------------------
  445. // Public
  446. // -----------------------------------------------------------------------------
  447. unsigned char sensorCount() {
  448. return _sensors.size();
  449. }
  450. unsigned char magnitudeCount() {
  451. return _magnitudes.size();
  452. }
  453. String magnitudeName(unsigned char index) {
  454. if (index < _magnitudes.size()) {
  455. sensor_magnitude_t magnitude = _magnitudes[index];
  456. return magnitude.sensor->slot(magnitude.local);
  457. }
  458. return String();
  459. }
  460. unsigned char magnitudeType(unsigned char index) {
  461. if (index < _magnitudes.size()) {
  462. return int(_magnitudes[index].type);
  463. }
  464. return MAGNITUDE_NONE;
  465. }
  466. unsigned char magnitudeIndex(unsigned char index) {
  467. if (index < _magnitudes.size()) {
  468. return int(_magnitudes[index].global);
  469. }
  470. return 0;
  471. }
  472. String magnitudeTopic(unsigned char type) {
  473. char buffer[16] = {0};
  474. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  475. return String(buffer);
  476. }
  477. String magnitudeTopicIndex(unsigned char index) {
  478. char topic[32] = {0};
  479. if (index < _magnitudes.size()) {
  480. sensor_magnitude_t magnitude = _magnitudes[index];
  481. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  482. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  483. } else {
  484. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  485. }
  486. }
  487. return String(topic);
  488. }
  489. String magnitudeUnits(unsigned char type) {
  490. char buffer[8] = {0};
  491. if (type < MAGNITUDE_MAX) {
  492. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  493. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  494. } else if ((type == MAGNITUDE_ENERGY) && (_sensor_energy_units == ENERGY_KWH)) {
  495. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  496. } else if ((type == MAGNITUDE_ENERGY_DELTA) && (_sensor_energy_units == ENERGY_KWH)) {
  497. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  498. } else {
  499. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  500. }
  501. }
  502. return String(buffer);
  503. }
  504. // -----------------------------------------------------------------------------
  505. void sensorSetup() {
  506. // Load sensors
  507. _sensorInit();
  508. // Configure stored values
  509. _sensorConfigure();
  510. // Load magnitudes
  511. _magnitudesInit();
  512. #if WEB_SUPPORT
  513. // Websockets
  514. wsOnSendRegister(_sensorWebSocketStart);
  515. wsOnSendRegister(_sensorWebSocketSendData);
  516. wsOnAfterParseRegister(_sensorConfigure);
  517. // API
  518. _sensorAPISetup();
  519. #endif
  520. #if TERMINAL_SUPPORT
  521. _sensorInitCommands();
  522. #endif
  523. // Register loop
  524. espurnaRegisterLoop(sensorLoop);
  525. }
  526. void sensorLoop() {
  527. static unsigned long last_update = 0;
  528. static unsigned long report_count = 0;
  529. if (_magnitudes.size() == 0) return;
  530. // Tick hook
  531. _sensorTick();
  532. // Check if we should read new data
  533. if (millis() - last_update > _sensor_read_interval) {
  534. last_update = millis();
  535. report_count = (report_count + 1) % _sensor_report_every;
  536. double current;
  537. double filtered;
  538. char buffer[64];
  539. // Pre-read hook
  540. _sensorPre();
  541. // Get readings
  542. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  543. sensor_magnitude_t magnitude = _magnitudes[i];
  544. if (magnitude.sensor->status()) {
  545. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  546. current = magnitude.sensor->value(magnitude.local);
  547. magnitude.filter->add(current);
  548. // Special case
  549. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  550. current = _magnitudeProcess(magnitude.type, current);
  551. _magnitudes[i].current = current;
  552. // Debug
  553. #if SENSOR_DEBUG
  554. {
  555. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  556. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  557. magnitude.sensor->slot(magnitude.local).c_str(),
  558. magnitudeTopic(magnitude.type).c_str(),
  559. buffer,
  560. magnitudeUnits(magnitude.type).c_str()
  561. );
  562. }
  563. #endif // SENSOR_DEBUG
  564. // Time to report (we do it every _sensor_report_every readings)
  565. if (report_count == 0) {
  566. filtered = magnitude.filter->result();
  567. magnitude.filter->reset();
  568. filtered = _magnitudeProcess(magnitude.type, filtered);
  569. _magnitudes[i].filtered = filtered;
  570. // Check if there is a minimum change threshold to report
  571. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  572. _magnitudes[i].reported = filtered;
  573. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  574. #if BROKER_SUPPORT
  575. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  576. #endif
  577. #if MQTT_SUPPORT
  578. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  579. #if SENSOR_PUBLISH_ADDRESSES
  580. char topic[32];
  581. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  582. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  583. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  584. } else {
  585. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  586. }
  587. #endif // SENSOR_PUBLISH_ADDRESSES
  588. #endif // MQTT_SUPPORT
  589. #if INFLUXDB_SUPPORT
  590. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  591. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  592. } else {
  593. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  594. }
  595. #endif // INFLUXDB_SUPPORT
  596. #if THINGSPEAK_SUPPORT
  597. tspkEnqueueMeasurement(i, buffer);
  598. #endif
  599. #if DOMOTICZ_SUPPORT
  600. {
  601. char key[15];
  602. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  603. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  604. int status;
  605. if (filtered > 70) {
  606. status = HUMIDITY_WET;
  607. } else if (filtered > 45) {
  608. status = HUMIDITY_COMFORTABLE;
  609. } else if (filtered > 30) {
  610. status = HUMIDITY_NORMAL;
  611. } else {
  612. status = HUMIDITY_DRY;
  613. }
  614. char status_buf[5];
  615. itoa(status, status_buf, 10);
  616. domoticzSend(key, buffer, status_buf);
  617. } else {
  618. domoticzSend(key, 0, buffer);
  619. }
  620. }
  621. #endif // DOMOTICZ_SUPPORT
  622. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  623. } // if (report_count == 0)
  624. } // if (magnitude.sensor->status())
  625. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  626. // Post-read hook
  627. _sensorPost();
  628. #if WEB_SUPPORT
  629. wsSend(_sensorWebSocketSendData);
  630. #endif
  631. #if THINGSPEAK_SUPPORT
  632. if (report_count == 0) tspkFlush();
  633. #endif
  634. }
  635. }
  636. #endif // SENSOR_SUPPORT