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.

1161 lines
37 KiB

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