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.

1167 lines
36 KiB

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