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.

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