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.

905 lines
29 KiB

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