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.

914 lines
29 KiB

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