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.

1065 lines
34 KiB

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