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.

1211 lines
38 KiB

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