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.

1169 lines
36 KiB

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