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.

1165 lines
36 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if SENSOR_SUPPORT
  6. #include <vector>
  7. #include "filters/MaxFilter.h"
  8. #include "filters/MedianFilter.h"
  9. #include "filters/MovingAverageFilter.h"
  10. #include "sensors/BaseSensor.h"
  11. typedef struct {
  12. BaseSensor * sensor; // Sensor object
  13. BaseFilter * filter; // Filter object
  14. unsigned char local; // Local index in its provider
  15. unsigned char type; // Type of measurement
  16. unsigned char global; // Global index in its type
  17. double current; // Current (last) value, unfiltered
  18. double filtered; // Filtered (averaged) value
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. } sensor_magnitude_t;
  22. std::vector<BaseSensor *> _sensors;
  23. std::vector<sensor_magnitude_t> _magnitudes;
  24. bool _sensors_ready = false;
  25. unsigned char _counts[MAGNITUDE_MAX];
  26. bool _sensor_realtime = API_REAL_TIME_VALUES;
  27. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  28. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  29. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  30. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  31. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  32. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  33. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  34. 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 SONAR_SUPPORT
  394. {
  395. SonarSensor * sensor = new SonarSensor();
  396. sensor->setEcho(SONAR_ECHO);
  397. sensor->setIterations(SONAR_ITERATIONS);
  398. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  399. sensor->setTrigger(SONAR_TRIGGER);
  400. _sensors.push_back(sensor);
  401. }
  402. #endif
  403. #if HLW8012_SUPPORT
  404. {
  405. HLW8012Sensor * sensor = new HLW8012Sensor();
  406. sensor->setSEL(HLW8012_SEL_PIN);
  407. sensor->setCF(HLW8012_CF_PIN);
  408. sensor->setCF1(HLW8012_CF1_PIN);
  409. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  410. _sensors.push_back(sensor);
  411. }
  412. #endif
  413. #if MHZ19_SUPPORT
  414. {
  415. MHZ19Sensor * sensor = new MHZ19Sensor();
  416. sensor->setRX(MHZ19_RX_PIN);
  417. sensor->setTX(MHZ19_TX_PIN);
  418. _sensors.push_back(sensor);
  419. }
  420. #endif
  421. #if NTC_SUPPORT
  422. {
  423. NTCSensor * sensor = new NTCSensor();
  424. sensor->setSamples(NTC_SAMPLES);
  425. sensor->setDelay(NTC_DELAY);
  426. sensor->setUpstreamResistor(NTC_R_UP);
  427. sensor->setDownstreamResistor(NTC_R_DOWN);
  428. sensor->setBeta(NTC_BETA);
  429. sensor->setR0(NTC_R0);
  430. sensor->setT0(NTC_T0);
  431. _sensors.push_back(sensor);
  432. }
  433. #endif
  434. #if SENSEAIR_SUPPORT
  435. {
  436. SenseAirSensor * sensor = new SenseAirSensor();
  437. sensor->setRX(SENSEAIR_RX_PIN);
  438. sensor->setTX(SENSEAIR_TX_PIN);
  439. _sensors.push_back(sensor);
  440. }
  441. #endif
  442. #if PMSX003_SUPPORT
  443. {
  444. PMSX003Sensor * sensor = new PMSX003Sensor();
  445. sensor->setRX(PMS_RX_PIN);
  446. sensor->setTX(PMS_TX_PIN);
  447. sensor->setType(PMS_TYPE);
  448. _sensors.push_back(sensor);
  449. }
  450. #endif
  451. #if PZEM004T_SUPPORT
  452. {
  453. PZEM004TSensor * sensor = new PZEM004TSensor();
  454. #if PZEM004T_USE_SOFT
  455. sensor->setRX(PZEM004T_RX_PIN);
  456. sensor->setTX(PZEM004T_TX_PIN);
  457. #else
  458. sensor->setSerial(& PZEM004T_HW_PORT);
  459. #endif
  460. _sensors.push_back(sensor);
  461. }
  462. #endif
  463. #if SHT3X_I2C_SUPPORT
  464. {
  465. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  466. sensor->setAddress(SHT3X_I2C_ADDRESS);
  467. _sensors.push_back(sensor);
  468. }
  469. #endif
  470. #if SI7021_SUPPORT
  471. {
  472. SI7021Sensor * sensor = new SI7021Sensor();
  473. sensor->setAddress(SI7021_ADDRESS);
  474. _sensors.push_back(sensor);
  475. }
  476. #endif
  477. #if TMP3X_SUPPORT
  478. {
  479. TMP3XSensor * sensor = new TMP3XSensor();
  480. sensor->setType(TMP3X_TYPE);
  481. _sensors.push_back(sensor);
  482. }
  483. #endif
  484. #if V9261F_SUPPORT
  485. {
  486. V9261FSensor * sensor = new V9261FSensor();
  487. sensor->setRX(V9261F_PIN);
  488. sensor->setInverted(V9261F_PIN_INVERSE);
  489. _sensors.push_back(sensor);
  490. }
  491. #endif
  492. }
  493. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  494. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  495. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  496. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  497. _sensorReport(k, value);
  498. return;
  499. }
  500. }
  501. }
  502. void _sensorInit() {
  503. _sensors_ready = true;
  504. for (unsigned char i=0; i<_sensors.size(); i++) {
  505. // Do not process an already initialized sensor
  506. if (_sensors[i]->ready()) continue;
  507. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  508. // Force sensor to reload config
  509. _sensors[i]->begin();
  510. if (!_sensors[i]->ready()) {
  511. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  512. _sensors_ready = false;
  513. continue;
  514. }
  515. // Initialize magnitudes
  516. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  517. unsigned char type = _sensors[i]->type(k);
  518. sensor_magnitude_t new_magnitude;
  519. new_magnitude.sensor = _sensors[i];
  520. new_magnitude.local = k;
  521. new_magnitude.type = type;
  522. new_magnitude.global = _counts[type];
  523. new_magnitude.current = 0;
  524. new_magnitude.filtered = 0;
  525. new_magnitude.reported = 0;
  526. new_magnitude.min_change = 0;
  527. if (type == MAGNITUDE_DIGITAL) {
  528. new_magnitude.filter = new MaxFilter();
  529. } 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.
  530. new_magnitude.filter = new MovingAverageFilter();
  531. } else {
  532. new_magnitude.filter = new MedianFilter();
  533. }
  534. new_magnitude.filter->resize(_sensor_report_every);
  535. _magnitudes.push_back(new_magnitude);
  536. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  537. _counts[type] = _counts[type] + 1;
  538. }
  539. // Hook callback
  540. _sensors[i]->onEvent([i](unsigned char type, double value) {
  541. _sensorCallback(i, type, value);
  542. });
  543. // Custom initializations
  544. #if EMON_ANALOG_SUPPORT
  545. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  546. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  547. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  548. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  549. }
  550. #endif // EMON_ANALOG_SUPPORT
  551. #if HLW8012_SUPPORT
  552. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  553. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  554. double value;
  555. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  556. if (value > 0) sensor->setCurrentRatio(value);
  557. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  558. if (value > 0) sensor->setVoltageRatio(value);
  559. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  560. if (value > 0) sensor->setPowerRatio(value);
  561. }
  562. #endif // HLW8012_SUPPORT
  563. #if CSE7766_SUPPORT
  564. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  565. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  566. double value;
  567. value = getSetting("pwrRatioC", 0).toFloat();
  568. if (value > 0) sensor->setCurrentRatio(value);
  569. value = getSetting("pwrRatioV", 0).toFloat();
  570. if (value > 0) sensor->setVoltageRatio(value);
  571. value = getSetting("pwrRatioP", 0).toFloat();
  572. if (value > 0) sensor->setPowerRatio(value);
  573. }
  574. #endif // CSE7766_SUPPORT
  575. }
  576. }
  577. void _sensorConfigure() {
  578. // General sensor settings
  579. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  580. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  581. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  582. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  583. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  584. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  585. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  586. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  587. // Specific sensor settings
  588. for (unsigned char i=0; i<_sensors.size(); i++) {
  589. #if EMON_ANALOG_SUPPORT
  590. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  591. double value;
  592. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  593. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  594. sensor->expectedPower(0, value);
  595. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  596. }
  597. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  598. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  599. delSetting("pwrRatioC");
  600. }
  601. if (getSetting("pwrResetE", 0).toInt() == 1) {
  602. sensor->resetEnergy();
  603. _sensorReset();
  604. }
  605. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  606. }
  607. #endif // EMON_ANALOG_SUPPORT
  608. #if EMON_ADC121_SUPPORT
  609. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  610. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  611. if (getSetting("pwrResetE", 0).toInt() == 1) {
  612. sensor->resetEnergy();
  613. _sensorReset();
  614. }
  615. }
  616. #endif
  617. #if EMON_ADS1X15_SUPPORT
  618. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  619. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  620. if (getSetting("pwrResetE", 0).toInt() == 1) {
  621. sensor->resetEnergy();
  622. _sensorReset();
  623. }
  624. }
  625. #endif
  626. #if HLW8012_SUPPORT
  627. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  628. double value;
  629. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  630. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  631. sensor->expectedCurrent(value);
  632. setSetting("pwrRatioC", sensor->getCurrentRatio());
  633. }
  634. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  635. sensor->expectedVoltage(value);
  636. setSetting("pwrRatioV", sensor->getVoltageRatio());
  637. }
  638. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  639. sensor->expectedPower(value);
  640. setSetting("pwrRatioP", sensor->getPowerRatio());
  641. }
  642. if (getSetting("pwrResetE", 0).toInt() == 1) {
  643. sensor->resetEnergy();
  644. _sensorReset();
  645. }
  646. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  647. sensor->resetRatios();
  648. delSetting("pwrRatioC");
  649. delSetting("pwrRatioV");
  650. delSetting("pwrRatioP");
  651. }
  652. }
  653. #endif // HLW8012_SUPPORT
  654. #if CSE7766_SUPPORT
  655. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  656. double value;
  657. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  658. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  659. sensor->expectedCurrent(value);
  660. setSetting("pwrRatioC", sensor->getCurrentRatio());
  661. }
  662. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  663. sensor->expectedVoltage(value);
  664. setSetting("pwrRatioV", sensor->getVoltageRatio());
  665. }
  666. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  667. sensor->expectedPower(value);
  668. setSetting("pwrRatioP", sensor->getPowerRatio());
  669. }
  670. if (getSetting("pwrResetE", 0).toInt() == 1) {
  671. sensor->resetEnergy();
  672. _sensorReset();
  673. }
  674. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  675. sensor->resetRatios();
  676. delSetting("pwrRatioC");
  677. delSetting("pwrRatioV");
  678. delSetting("pwrRatioP");
  679. }
  680. }
  681. #endif // CSE7766_SUPPORT
  682. }
  683. // Update filter sizes
  684. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  685. _magnitudes[i].filter->resize(_sensor_report_every);
  686. }
  687. // Save settings
  688. delSetting("pwrExpectedP");
  689. delSetting("pwrExpectedC");
  690. delSetting("pwrExpectedV");
  691. delSetting("pwrResetCalibration");
  692. delSetting("pwrResetE");
  693. saveSettings();
  694. }
  695. void _sensorReport(unsigned char index, double value) {
  696. sensor_magnitude_t magnitude = _magnitudes[index];
  697. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  698. char buffer[10];
  699. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  700. #if BROKER_SUPPORT
  701. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  702. #endif
  703. #if MQTT_SUPPORT
  704. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  705. #if SENSOR_PUBLISH_ADDRESSES
  706. char topic[32];
  707. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  708. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  709. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  710. } else {
  711. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  712. }
  713. #endif // SENSOR_PUBLISH_ADDRESSES
  714. #endif // MQTT_SUPPORT
  715. #if INFLUXDB_SUPPORT
  716. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  717. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  718. } else {
  719. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  720. }
  721. #endif // INFLUXDB_SUPPORT
  722. #if THINGSPEAK_SUPPORT
  723. tspkEnqueueMeasurement(index, buffer);
  724. #endif
  725. #if DOMOTICZ_SUPPORT
  726. {
  727. char key[15];
  728. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  729. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  730. int status;
  731. if (value > 70) {
  732. status = HUMIDITY_WET;
  733. } else if (value > 45) {
  734. status = HUMIDITY_COMFORTABLE;
  735. } else if (value > 30) {
  736. status = HUMIDITY_NORMAL;
  737. } else {
  738. status = HUMIDITY_DRY;
  739. }
  740. char status_buf[5];
  741. itoa(status, status_buf, 10);
  742. domoticzSend(key, buffer, status_buf);
  743. } else {
  744. domoticzSend(key, 0, buffer);
  745. }
  746. }
  747. #endif // DOMOTICZ_SUPPORT
  748. }
  749. // -----------------------------------------------------------------------------
  750. // Public
  751. // -----------------------------------------------------------------------------
  752. unsigned char sensorCount() {
  753. return _sensors.size();
  754. }
  755. unsigned char magnitudeCount() {
  756. return _magnitudes.size();
  757. }
  758. String magnitudeName(unsigned char index) {
  759. if (index < _magnitudes.size()) {
  760. sensor_magnitude_t magnitude = _magnitudes[index];
  761. return magnitude.sensor->slot(magnitude.local);
  762. }
  763. return String();
  764. }
  765. unsigned char magnitudeType(unsigned char index) {
  766. if (index < _magnitudes.size()) {
  767. return int(_magnitudes[index].type);
  768. }
  769. return MAGNITUDE_NONE;
  770. }
  771. unsigned char magnitudeIndex(unsigned char index) {
  772. if (index < _magnitudes.size()) {
  773. return int(_magnitudes[index].global);
  774. }
  775. return 0;
  776. }
  777. String magnitudeTopic(unsigned char type) {
  778. char buffer[16] = {0};
  779. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  780. return String(buffer);
  781. }
  782. String magnitudeTopicIndex(unsigned char index) {
  783. char topic[32] = {0};
  784. if (index < _magnitudes.size()) {
  785. sensor_magnitude_t magnitude = _magnitudes[index];
  786. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  787. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  788. } else {
  789. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  790. }
  791. }
  792. return String(topic);
  793. }
  794. String magnitudeUnits(unsigned char type) {
  795. char buffer[8] = {0};
  796. if (type < MAGNITUDE_MAX) {
  797. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  798. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  799. } else if (
  800. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  801. (_sensor_energy_units == ENERGY_KWH)) {
  802. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  803. } else if (
  804. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  805. (_sensor_power_units == POWER_KILOWATTS)) {
  806. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  807. } else {
  808. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  809. }
  810. }
  811. return String(buffer);
  812. }
  813. // -----------------------------------------------------------------------------
  814. void sensorSetup() {
  815. // Backwards compatibility
  816. moveSetting("powerUnits", "pwrUnits");
  817. // Load sensors
  818. _sensorLoad();
  819. _sensorInit();
  820. // Configure stored values
  821. _sensorConfigure();
  822. #if WEB_SUPPORT
  823. // Websockets
  824. wsOnSendRegister(_sensorWebSocketStart);
  825. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  826. wsOnSendRegister(_sensorWebSocketSendData);
  827. wsOnAfterParseRegister(_sensorConfigure);
  828. // API
  829. _sensorAPISetup();
  830. #endif
  831. #if TERMINAL_SUPPORT
  832. _sensorInitCommands();
  833. #endif
  834. // Register loop
  835. espurnaRegisterLoop(sensorLoop);
  836. }
  837. void sensorLoop() {
  838. // Check if we still have uninitialized sensors
  839. static unsigned long last_init = 0;
  840. if (!_sensors_ready) {
  841. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  842. last_init = millis();
  843. _sensorInit();
  844. }
  845. }
  846. if (_magnitudes.size() == 0) return;
  847. // Tick hook
  848. _sensorTick();
  849. // Check if we should read new data
  850. static unsigned long last_update = 0;
  851. static unsigned long report_count = 0;
  852. if (millis() - last_update > _sensor_read_interval) {
  853. last_update = millis();
  854. report_count = (report_count + 1) % _sensor_report_every;
  855. double current;
  856. double filtered;
  857. // Pre-read hook
  858. _sensorPre();
  859. // Get the first relay state
  860. #if SENSOR_POWER_CHECK_STATUS
  861. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  862. #endif
  863. // Get readings
  864. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  865. sensor_magnitude_t magnitude = _magnitudes[i];
  866. if (magnitude.sensor->status()) {
  867. current = magnitude.sensor->value(magnitude.local);
  868. // Completely remove spurious values if relay is OFF
  869. #if SENSOR_POWER_CHECK_STATUS
  870. if (relay_off) {
  871. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  872. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  873. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  874. magnitude.type == MAGNITUDE_CURRENT ||
  875. magnitude.type == MAGNITUDE_ENERGY_DELTA
  876. ) {
  877. current = 0;
  878. }
  879. }
  880. #endif
  881. magnitude.filter->add(current);
  882. // Special case
  883. if (magnitude.type == MAGNITUDE_COUNT) {
  884. current = magnitude.filter->result();
  885. }
  886. current = _magnitudeProcess(magnitude.type, current);
  887. _magnitudes[i].current = current;
  888. // Debug
  889. #if SENSOR_DEBUG
  890. {
  891. char buffer[64];
  892. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  893. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  894. magnitude.sensor->slot(magnitude.local).c_str(),
  895. magnitudeTopic(magnitude.type).c_str(),
  896. buffer,
  897. magnitudeUnits(magnitude.type).c_str()
  898. );
  899. }
  900. #endif // SENSOR_DEBUG
  901. // Time to report (we do it every _sensor_report_every readings)
  902. if (report_count == 0) {
  903. filtered = magnitude.filter->result();
  904. magnitude.filter->reset();
  905. filtered = _magnitudeProcess(magnitude.type, filtered);
  906. _magnitudes[i].filtered = filtered;
  907. // Check if there is a minimum change threshold to report
  908. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  909. _magnitudes[i].reported = filtered;
  910. _sensorReport(i, filtered);
  911. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  912. } // if (report_count == 0)
  913. } // if (magnitude.sensor->status())
  914. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  915. // Post-read hook
  916. _sensorPost();
  917. #if WEB_SUPPORT
  918. wsSend(_sensorWebSocketSendData);
  919. #endif
  920. #if THINGSPEAK_SUPPORT
  921. if (report_count == 0) tspkFlush();
  922. #endif
  923. }
  924. }
  925. #endif // SENSOR_SUPPORT