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.

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