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.

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