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.

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