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.

885 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. _magnitudesInit(_sensors[i]);
  418. // Hook callback
  419. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  420. _sensorCallback(i, type, payload);
  421. });
  422. #if HLW8012_SUPPORT
  423. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  424. double value;
  425. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  426. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  427. sensor->expectedCurrent(value);
  428. setSetting("pwrRatioC", sensor->getCurrentRatio());
  429. } else {
  430. value = getSetting("pwrRatioC", 0).toFloat();
  431. if (value > 0) sensor->setCurrentRatio(value);
  432. }
  433. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  434. sensor->expectedVoltage(value);
  435. setSetting("pwrRatioV", sensor->getVoltageRatio());
  436. } else {
  437. value = getSetting("pwrRatioV", 0).toFloat();
  438. if (value > 0) sensor->setVoltageRatio(value);
  439. }
  440. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  441. sensor->expectedPower(value);
  442. setSetting("pwrRatioP", sensor->getPowerRatio());
  443. } else {
  444. value = getSetting("pwrRatioP", 0).toFloat();
  445. if (value > 0) sensor->setPowerRatio(value);
  446. }
  447. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  448. sensor->resetRatios();
  449. delSetting("pwrRatioC");
  450. delSetting("pwrRatioV");
  451. delSetting("pwrRatioP");
  452. }
  453. }
  454. #endif // HLW8012_SUPPORT
  455. }
  456. }
  457. void _magnitudesInit(BaseSensor * sensor) {
  458. for (unsigned char k=0; k<sensor->count(); k++) {
  459. unsigned char type = sensor->type(k);
  460. sensor_magnitude_t new_magnitude;
  461. new_magnitude.sensor = sensor;
  462. new_magnitude.local = k;
  463. new_magnitude.type = type;
  464. new_magnitude.global = _counts[type];
  465. new_magnitude.current = 0;
  466. new_magnitude.filtered = 0;
  467. new_magnitude.reported = 0;
  468. new_magnitude.min_change = 0;
  469. if (type == MAGNITUDE_DIGITAL) {
  470. new_magnitude.filter = new MaxFilter();
  471. } else if (type == MAGNITUDE_EVENTS) {
  472. new_magnitude.filter = new MovingAverageFilter();
  473. } else {
  474. new_magnitude.filter = new MedianFilter();
  475. }
  476. new_magnitude.filter->resize(_sensor_report_every);
  477. _magnitudes.push_back(new_magnitude);
  478. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  479. _counts[type] = _counts[type] + 1;
  480. }
  481. }
  482. void _sensorConfigure() {
  483. // General sensor settings
  484. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  485. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  486. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  487. _sensor_power_units = getSetting("powerUnits", SENSOR_POWER_UNITS).toInt();
  488. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  489. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  490. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  491. // Update filter sizes
  492. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  493. _magnitudes[i].filter->resize(_sensor_report_every);
  494. }
  495. // Save settings
  496. delSetting("pwrExpectedP");
  497. delSetting("pwrExpectedC");
  498. delSetting("pwrExpectedV");
  499. delSetting("pwrResetCalibration");
  500. //saveSettings();
  501. }
  502. // -----------------------------------------------------------------------------
  503. // Public
  504. // -----------------------------------------------------------------------------
  505. unsigned char sensorCount() {
  506. return _sensors.size();
  507. }
  508. unsigned char magnitudeCount() {
  509. return _magnitudes.size();
  510. }
  511. String magnitudeName(unsigned char index) {
  512. if (index < _magnitudes.size()) {
  513. sensor_magnitude_t magnitude = _magnitudes[index];
  514. return magnitude.sensor->slot(magnitude.local);
  515. }
  516. return String();
  517. }
  518. unsigned char magnitudeType(unsigned char index) {
  519. if (index < _magnitudes.size()) {
  520. return int(_magnitudes[index].type);
  521. }
  522. return MAGNITUDE_NONE;
  523. }
  524. unsigned char magnitudeIndex(unsigned char index) {
  525. if (index < _magnitudes.size()) {
  526. return int(_magnitudes[index].global);
  527. }
  528. return 0;
  529. }
  530. String magnitudeTopic(unsigned char type) {
  531. char buffer[16] = {0};
  532. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  533. return String(buffer);
  534. }
  535. String magnitudeTopicIndex(unsigned char index) {
  536. char topic[32] = {0};
  537. if (index < _magnitudes.size()) {
  538. sensor_magnitude_t magnitude = _magnitudes[index];
  539. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  540. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  541. } else {
  542. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  543. }
  544. }
  545. return String(topic);
  546. }
  547. String magnitudeUnits(unsigned char type) {
  548. char buffer[8] = {0};
  549. if (type < MAGNITUDE_MAX) {
  550. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  551. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  552. } else if (
  553. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  554. (_sensor_energy_units == ENERGY_KWH)) {
  555. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  556. } else if (
  557. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  558. (_sensor_power_units == POWER_KILOWATTS)) {
  559. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  560. } else {
  561. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  562. }
  563. }
  564. return String(buffer);
  565. }
  566. // -----------------------------------------------------------------------------
  567. void sensorSetup() {
  568. // Load sensors
  569. _sensorLoad();
  570. _sensorInit();
  571. // Configure stored values
  572. _sensorConfigure();
  573. #if WEB_SUPPORT
  574. // Websockets
  575. wsOnSendRegister(_sensorWebSocketStart);
  576. wsOnSendRegister(_sensorWebSocketSendData);
  577. wsOnAfterParseRegister(_sensorConfigure);
  578. // API
  579. _sensorAPISetup();
  580. #endif
  581. #if TERMINAL_SUPPORT
  582. _sensorInitCommands();
  583. #endif
  584. // Register loop
  585. espurnaRegisterLoop(sensorLoop);
  586. }
  587. void sensorLoop() {
  588. // Check if we still have uninitialized sensors
  589. static unsigned long last_init = 0;
  590. if (!_sensors_ready) {
  591. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  592. last_init = millis();
  593. _sensorInit();
  594. }
  595. }
  596. if (_magnitudes.size() == 0) return;
  597. // Tick hook
  598. _sensorTick();
  599. // Check if we should read new data
  600. static unsigned long last_update = 0;
  601. static unsigned long report_count = 0;
  602. if (millis() - last_update > _sensor_read_interval) {
  603. last_update = millis();
  604. report_count = (report_count + 1) % _sensor_report_every;
  605. double current;
  606. double filtered;
  607. char buffer[64];
  608. // Pre-read hook
  609. _sensorPre();
  610. // Get readings
  611. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  612. sensor_magnitude_t magnitude = _magnitudes[i];
  613. if (magnitude.sensor->status()) {
  614. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  615. current = magnitude.sensor->value(magnitude.local);
  616. magnitude.filter->add(current);
  617. // Special case
  618. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  619. current = _magnitudeProcess(magnitude.type, current);
  620. _magnitudes[i].current = current;
  621. // Debug
  622. #if SENSOR_DEBUG
  623. {
  624. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  625. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  626. magnitude.sensor->slot(magnitude.local).c_str(),
  627. magnitudeTopic(magnitude.type).c_str(),
  628. buffer,
  629. magnitudeUnits(magnitude.type).c_str()
  630. );
  631. }
  632. #endif // SENSOR_DEBUG
  633. // Time to report (we do it every _sensor_report_every readings)
  634. if (report_count == 0) {
  635. filtered = magnitude.filter->result();
  636. magnitude.filter->reset();
  637. filtered = _magnitudeProcess(magnitude.type, filtered);
  638. _magnitudes[i].filtered = filtered;
  639. // Check if there is a minimum change threshold to report
  640. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  641. _magnitudes[i].reported = filtered;
  642. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  643. #if BROKER_SUPPORT
  644. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  645. #endif
  646. #if MQTT_SUPPORT
  647. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  648. #if SENSOR_PUBLISH_ADDRESSES
  649. char topic[32];
  650. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  651. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  652. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  653. } else {
  654. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  655. }
  656. #endif // SENSOR_PUBLISH_ADDRESSES
  657. #endif // MQTT_SUPPORT
  658. #if INFLUXDB_SUPPORT
  659. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  660. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  661. } else {
  662. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  663. }
  664. #endif // INFLUXDB_SUPPORT
  665. #if THINGSPEAK_SUPPORT
  666. tspkEnqueueMeasurement(i, buffer);
  667. #endif
  668. #if DOMOTICZ_SUPPORT
  669. {
  670. char key[15];
  671. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  672. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  673. int status;
  674. if (filtered > 70) {
  675. status = HUMIDITY_WET;
  676. } else if (filtered > 45) {
  677. status = HUMIDITY_COMFORTABLE;
  678. } else if (filtered > 30) {
  679. status = HUMIDITY_NORMAL;
  680. } else {
  681. status = HUMIDITY_DRY;
  682. }
  683. char status_buf[5];
  684. itoa(status, status_buf, 10);
  685. domoticzSend(key, buffer, status_buf);
  686. } else {
  687. domoticzSend(key, 0, buffer);
  688. }
  689. }
  690. #endif // DOMOTICZ_SUPPORT
  691. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  692. } // if (report_count == 0)
  693. } // if (magnitude.sensor->status())
  694. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  695. // Post-read hook
  696. _sensorPost();
  697. #if WEB_SUPPORT
  698. wsSend(_sensorWebSocketSendData);
  699. #endif
  700. #if THINGSPEAK_SUPPORT
  701. if (report_count == 0) tspkFlush();
  702. #endif
  703. }
  704. }
  705. #endif // SENSOR_SUPPORT