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.

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