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.

1244 lines
39 KiB

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