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.

851 lines
27 KiB

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