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.

979 lines
31 KiB

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. #if AM2320_SUPPORT
  390. {
  391. AM2320Sensor * sensor = new AM2320Sensor();
  392. sensor->setAddress(AM2320_ADDRESS);
  393. _sensors.push_back(sensor);
  394. }
  395. #endif
  396. #if GUVAS12SD_SUPPORT
  397. {
  398. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  399. sensor->setGPIO(GUVAS12SD_PIN);
  400. _sensors.push_back(sensor);
  401. }
  402. #endif
  403. }
  404. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  405. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  406. }
  407. void _sensorInit() {
  408. _sensors_ready = true;
  409. for (unsigned char i=0; i<_sensors.size(); i++) {
  410. // Do not process an already initialized sensor
  411. if (_sensors[i]->ready()) continue;
  412. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  413. // Force sensor to reload config
  414. _sensors[i]->begin();
  415. if (!_sensors[i]->ready()) {
  416. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  417. _sensors_ready = false;
  418. continue;
  419. }
  420. // Initialize magnitudes
  421. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  422. unsigned char type = _sensors[i]->type(k);
  423. sensor_magnitude_t new_magnitude;
  424. new_magnitude.sensor = _sensors[i];
  425. new_magnitude.local = k;
  426. new_magnitude.type = type;
  427. new_magnitude.global = _counts[type];
  428. new_magnitude.current = 0;
  429. new_magnitude.filtered = 0;
  430. new_magnitude.reported = 0;
  431. new_magnitude.min_change = 0;
  432. if (type == MAGNITUDE_DIGITAL) {
  433. new_magnitude.filter = new MaxFilter();
  434. } else if (type == MAGNITUDE_EVENTS) {
  435. new_magnitude.filter = new MovingAverageFilter();
  436. } else {
  437. new_magnitude.filter = new MedianFilter();
  438. }
  439. new_magnitude.filter->resize(_sensor_report_every);
  440. _magnitudes.push_back(new_magnitude);
  441. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  442. _counts[type] = _counts[type] + 1;
  443. }
  444. // Hook callback
  445. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  446. _sensorCallback(i, type, payload);
  447. });
  448. // Custom initializations
  449. #if EMON_ANALOG_SUPPORT
  450. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  451. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  452. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  453. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  454. }
  455. #endif // EMON_ANALOG_SUPPORT
  456. #if HLW8012_SUPPORT
  457. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  458. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  459. double value;
  460. value = getSetting("pwrRatioC", 0).toFloat();
  461. if (value > 0) sensor->setCurrentRatio(value);
  462. value = getSetting("pwrRatioV", 0).toFloat();
  463. if (value > 0) sensor->setVoltageRatio(value);
  464. value = getSetting("pwrRatioP", 0).toFloat();
  465. if (value > 0) sensor->setPowerRatio(value);
  466. }
  467. #endif // HLW8012_SUPPORT
  468. }
  469. }
  470. void _sensorConfigure() {
  471. // General sensor settings
  472. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  473. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  474. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  475. _sensor_power_units = getSetting("powerUnits", SENSOR_POWER_UNITS).toInt();
  476. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  477. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  478. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  479. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  480. // Specific sensor settings
  481. for (unsigned char i=0; i<_sensors.size(); i++) {
  482. #if EMON_ANALOG_SUPPORT
  483. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  484. double value;
  485. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  486. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  487. sensor->expectedPower(0, value);
  488. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  489. }
  490. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  491. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  492. delSetting("pwrRatioC");
  493. }
  494. if (getSetting("pwrResetE", 0).toInt() == 1) {
  495. sensor->resetEnergy();
  496. }
  497. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  498. }
  499. #endif // EMON_ANALOG_SUPPORT
  500. #if EMON_ADC121_SUPPORT
  501. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  502. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  503. if (getSetting("pwrResetE", 0).toInt() == 1) {
  504. sensor->resetEnergy();
  505. }
  506. }
  507. #endif
  508. #if EMON_ADS1X15_SUPPORT
  509. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  510. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  511. if (getSetting("pwrResetE", 0).toInt() == 1) {
  512. sensor->resetEnergy();
  513. }
  514. }
  515. #endif
  516. #if HLW8012_SUPPORT
  517. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  518. double value;
  519. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  520. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  521. sensor->expectedCurrent(value);
  522. setSetting("pwrRatioC", sensor->getCurrentRatio());
  523. }
  524. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  525. sensor->expectedVoltage(value);
  526. setSetting("pwrRatioV", sensor->getVoltageRatio());
  527. }
  528. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  529. sensor->expectedPower(value);
  530. setSetting("pwrRatioP", sensor->getPowerRatio());
  531. }
  532. if (getSetting("pwrResetE", 0).toInt() == 1) {
  533. sensor->resetEnergy();
  534. }
  535. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  536. sensor->resetRatios();
  537. delSetting("pwrRatioC");
  538. delSetting("pwrRatioV");
  539. delSetting("pwrRatioP");
  540. }
  541. }
  542. #endif // HLW8012_SUPPORT
  543. }
  544. // Update filter sizes
  545. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  546. _magnitudes[i].filter->resize(_sensor_report_every);
  547. }
  548. // Save settings
  549. delSetting("pwrExpectedP");
  550. delSetting("pwrExpectedC");
  551. delSetting("pwrExpectedV");
  552. delSetting("pwrResetCalibration");
  553. delSetting("pwrResetE");
  554. saveSettings();
  555. }
  556. // -----------------------------------------------------------------------------
  557. // Public
  558. // -----------------------------------------------------------------------------
  559. unsigned char sensorCount() {
  560. return _sensors.size();
  561. }
  562. unsigned char magnitudeCount() {
  563. return _magnitudes.size();
  564. }
  565. String magnitudeName(unsigned char index) {
  566. if (index < _magnitudes.size()) {
  567. sensor_magnitude_t magnitude = _magnitudes[index];
  568. return magnitude.sensor->slot(magnitude.local);
  569. }
  570. return String();
  571. }
  572. unsigned char magnitudeType(unsigned char index) {
  573. if (index < _magnitudes.size()) {
  574. return int(_magnitudes[index].type);
  575. }
  576. return MAGNITUDE_NONE;
  577. }
  578. unsigned char magnitudeIndex(unsigned char index) {
  579. if (index < _magnitudes.size()) {
  580. return int(_magnitudes[index].global);
  581. }
  582. return 0;
  583. }
  584. String magnitudeTopic(unsigned char type) {
  585. char buffer[16] = {0};
  586. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  587. return String(buffer);
  588. }
  589. String magnitudeTopicIndex(unsigned char index) {
  590. char topic[32] = {0};
  591. if (index < _magnitudes.size()) {
  592. sensor_magnitude_t magnitude = _magnitudes[index];
  593. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  594. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  595. } else {
  596. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  597. }
  598. }
  599. return String(topic);
  600. }
  601. String magnitudeUnits(unsigned char type) {
  602. char buffer[8] = {0};
  603. if (type < MAGNITUDE_MAX) {
  604. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  605. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  606. } else if (
  607. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  608. (_sensor_energy_units == ENERGY_KWH)) {
  609. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  610. } else if (
  611. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  612. (_sensor_power_units == POWER_KILOWATTS)) {
  613. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  614. } else {
  615. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  616. }
  617. }
  618. return String(buffer);
  619. }
  620. // -----------------------------------------------------------------------------
  621. void sensorSetup() {
  622. // Load sensors
  623. _sensorLoad();
  624. _sensorInit();
  625. // Configure stored values
  626. _sensorConfigure();
  627. #if WEB_SUPPORT
  628. // Websockets
  629. wsOnSendRegister(_sensorWebSocketStart);
  630. wsOnSendRegister(_sensorWebSocketSendData);
  631. wsOnAfterParseRegister(_sensorConfigure);
  632. // API
  633. _sensorAPISetup();
  634. #endif
  635. #if TERMINAL_SUPPORT
  636. _sensorInitCommands();
  637. #endif
  638. // Register loop
  639. espurnaRegisterLoop(sensorLoop);
  640. }
  641. void sensorLoop() {
  642. // Check if we still have uninitialized sensors
  643. static unsigned long last_init = 0;
  644. if (!_sensors_ready) {
  645. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  646. last_init = millis();
  647. _sensorInit();
  648. }
  649. }
  650. if (_magnitudes.size() == 0) return;
  651. // Tick hook
  652. _sensorTick();
  653. // Check if we should read new data
  654. static unsigned long last_update = 0;
  655. static unsigned long report_count = 0;
  656. if (millis() - last_update > _sensor_read_interval) {
  657. last_update = millis();
  658. report_count = (report_count + 1) % _sensor_report_every;
  659. double current;
  660. double filtered;
  661. char buffer[64];
  662. // Pre-read hook
  663. _sensorPre();
  664. // Get the first relay state
  665. #if SENSOR_POWER_CHECK_STATUS
  666. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  667. #endif
  668. // Get readings
  669. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  670. sensor_magnitude_t magnitude = _magnitudes[i];
  671. if (magnitude.sensor->status()) {
  672. current = magnitude.sensor->value(magnitude.local);
  673. // Completely remove spurious values if relay is OFF
  674. #if SENSOR_POWER_CHECK_STATUS
  675. if (relay_off) {
  676. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  677. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  678. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  679. magnitude.type == MAGNITUDE_CURRENT ||
  680. magnitude.type == MAGNITUDE_ENERGY_DELTA
  681. ) {
  682. current = 0;
  683. }
  684. }
  685. #endif
  686. magnitude.filter->add(current);
  687. // Special case
  688. if (magnitude.type == MAGNITUDE_EVENTS) {
  689. current = magnitude.filter->result();
  690. }
  691. current = _magnitudeProcess(magnitude.type, current);
  692. _magnitudes[i].current = current;
  693. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  694. // Debug
  695. #if SENSOR_DEBUG
  696. {
  697. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  698. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  699. magnitude.sensor->slot(magnitude.local).c_str(),
  700. magnitudeTopic(magnitude.type).c_str(),
  701. buffer,
  702. magnitudeUnits(magnitude.type).c_str()
  703. );
  704. }
  705. #endif // SENSOR_DEBUG
  706. // Time to report (we do it every _sensor_report_every readings)
  707. if (report_count == 0) {
  708. filtered = magnitude.filter->result();
  709. magnitude.filter->reset();
  710. filtered = _magnitudeProcess(magnitude.type, filtered);
  711. _magnitudes[i].filtered = filtered;
  712. // Check if there is a minimum change threshold to report
  713. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  714. _magnitudes[i].reported = filtered;
  715. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  716. #if BROKER_SUPPORT
  717. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  718. #endif
  719. #if MQTT_SUPPORT
  720. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  721. #if SENSOR_PUBLISH_ADDRESSES
  722. char topic[32];
  723. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  724. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  725. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  726. } else {
  727. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  728. }
  729. #endif // SENSOR_PUBLISH_ADDRESSES
  730. #endif // MQTT_SUPPORT
  731. #if INFLUXDB_SUPPORT
  732. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  733. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  734. } else {
  735. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  736. }
  737. #endif // INFLUXDB_SUPPORT
  738. #if THINGSPEAK_SUPPORT
  739. tspkEnqueueMeasurement(i, buffer);
  740. #endif
  741. #if DOMOTICZ_SUPPORT
  742. {
  743. char key[15];
  744. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  745. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  746. int status;
  747. if (filtered > 70) {
  748. status = HUMIDITY_WET;
  749. } else if (filtered > 45) {
  750. status = HUMIDITY_COMFORTABLE;
  751. } else if (filtered > 30) {
  752. status = HUMIDITY_NORMAL;
  753. } else {
  754. status = HUMIDITY_DRY;
  755. }
  756. char status_buf[5];
  757. itoa(status, status_buf, 10);
  758. domoticzSend(key, buffer, status_buf);
  759. } else {
  760. domoticzSend(key, 0, buffer);
  761. }
  762. }
  763. #endif // DOMOTICZ_SUPPORT
  764. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  765. } // if (report_count == 0)
  766. } // if (magnitude.sensor->status())
  767. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  768. // Post-read hook
  769. _sensorPost();
  770. #if WEB_SUPPORT
  771. wsSend(_sensorWebSocketSendData);
  772. #endif
  773. #if THINGSPEAK_SUPPORT
  774. if (report_count == 0) tspkFlush();
  775. #endif
  776. }
  777. }
  778. #endif // SENSOR_SUPPORT