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.

1163 lines
36 KiB

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