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.

1270 lines
40 KiB

7 years ago
6 years ago
7 years ago
6 years ago
7 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 reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. double max_change; // Maximum 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.reported;
  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 SDS011_SUPPORT
  434. {
  435. SDS011Sensor * sensor = new SDS011Sensor();
  436. sensor->setRX(SDS011_RX_PIN);
  437. sensor->setTX(SDS011_TX_PIN);
  438. _sensors.push_back(sensor);
  439. }
  440. #endif
  441. #if NTC_SUPPORT
  442. {
  443. NTCSensor * sensor = new NTCSensor();
  444. sensor->setSamples(NTC_SAMPLES);
  445. sensor->setDelay(NTC_DELAY);
  446. sensor->setUpstreamResistor(NTC_R_UP);
  447. sensor->setDownstreamResistor(NTC_R_DOWN);
  448. sensor->setBeta(NTC_BETA);
  449. sensor->setR0(NTC_R0);
  450. sensor->setT0(NTC_T0);
  451. _sensors.push_back(sensor);
  452. }
  453. #endif
  454. #if SENSEAIR_SUPPORT
  455. {
  456. SenseAirSensor * sensor = new SenseAirSensor();
  457. sensor->setRX(SENSEAIR_RX_PIN);
  458. sensor->setTX(SENSEAIR_TX_PIN);
  459. _sensors.push_back(sensor);
  460. }
  461. #endif
  462. #if PMSX003_SUPPORT
  463. {
  464. PMSX003Sensor * sensor = new PMSX003Sensor();
  465. #if PMS_USE_SOFT
  466. sensor->setRX(PMS_RX_PIN);
  467. sensor->setTX(PMS_TX_PIN);
  468. #else
  469. sensor->setSerial(& PMS_HW_PORT);
  470. #endif
  471. sensor->setType(PMS_TYPE);
  472. _sensors.push_back(sensor);
  473. }
  474. #endif
  475. #if PZEM004T_SUPPORT
  476. {
  477. PZEM004TSensor * sensor = new PZEM004TSensor();
  478. #if PZEM004T_USE_SOFT
  479. sensor->setRX(PZEM004T_RX_PIN);
  480. sensor->setTX(PZEM004T_TX_PIN);
  481. #else
  482. sensor->setSerial(& PZEM004T_HW_PORT);
  483. #endif
  484. _sensors.push_back(sensor);
  485. }
  486. #endif
  487. #if SHT3X_I2C_SUPPORT
  488. {
  489. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  490. sensor->setAddress(SHT3X_I2C_ADDRESS);
  491. _sensors.push_back(sensor);
  492. }
  493. #endif
  494. #if SI7021_SUPPORT
  495. {
  496. SI7021Sensor * sensor = new SI7021Sensor();
  497. sensor->setAddress(SI7021_ADDRESS);
  498. _sensors.push_back(sensor);
  499. }
  500. #endif
  501. #if TMP3X_SUPPORT
  502. {
  503. TMP3XSensor * sensor = new TMP3XSensor();
  504. sensor->setType(TMP3X_TYPE);
  505. _sensors.push_back(sensor);
  506. }
  507. #endif
  508. #if V9261F_SUPPORT
  509. {
  510. V9261FSensor * sensor = new V9261FSensor();
  511. sensor->setRX(V9261F_PIN);
  512. sensor->setInverted(V9261F_PIN_INVERSE);
  513. _sensors.push_back(sensor);
  514. }
  515. #endif
  516. }
  517. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  518. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  519. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  520. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  521. _sensorReport(k, value);
  522. return;
  523. }
  524. }
  525. }
  526. void _sensorInit() {
  527. _sensors_ready = true;
  528. _sensor_save_every = getSetting("snsSave", 0).toInt();
  529. for (unsigned char i=0; i<_sensors.size(); i++) {
  530. // Do not process an already initialized sensor
  531. if (_sensors[i]->ready()) continue;
  532. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  533. // Force sensor to reload config
  534. _sensors[i]->begin();
  535. if (!_sensors[i]->ready()) {
  536. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  537. _sensors_ready = false;
  538. continue;
  539. }
  540. // Initialize magnitudes
  541. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  542. unsigned char type = _sensors[i]->type(k);
  543. sensor_magnitude_t new_magnitude;
  544. new_magnitude.sensor = _sensors[i];
  545. new_magnitude.local = k;
  546. new_magnitude.type = type;
  547. new_magnitude.global = _counts[type];
  548. new_magnitude.current = 0;
  549. new_magnitude.reported = 0;
  550. new_magnitude.min_change = 0;
  551. new_magnitude.max_change = 0;
  552. // TODO: find a proper way to extend this to min/max of any magnitude
  553. if (MAGNITUDE_ENERGY == type) {
  554. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  555. } else if (MAGNITUDE_TEMPERATURE == type) {
  556. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  557. } else if (MAGNITUDE_HUMIDITY == type) {
  558. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  559. }
  560. if (MAGNITUDE_ENERGY == type) {
  561. new_magnitude.filter = new LastFilter();
  562. } else if (MAGNITUDE_DIGITAL == type) {
  563. new_magnitude.filter = new MaxFilter();
  564. } 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.
  565. new_magnitude.filter = new MovingAverageFilter();
  566. } else {
  567. new_magnitude.filter = new MedianFilter();
  568. }
  569. new_magnitude.filter->resize(_sensor_report_every);
  570. _magnitudes.push_back(new_magnitude);
  571. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  572. _counts[type] = _counts[type] + 1;
  573. }
  574. // Hook callback
  575. _sensors[i]->onEvent([i](unsigned char type, double value) {
  576. _sensorCallback(i, type, value);
  577. });
  578. // Custom initializations
  579. #if EMON_ANALOG_SUPPORT
  580. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  581. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  582. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  583. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  584. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  585. if (value > 0) sensor->resetEnergy(0, value);
  586. }
  587. #endif // EMON_ANALOG_SUPPORT
  588. #if HLW8012_SUPPORT
  589. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  590. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  591. double value;
  592. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  593. if (value > 0) sensor->setCurrentRatio(value);
  594. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  595. if (value > 0) sensor->setVoltageRatio(value);
  596. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  597. if (value > 0) sensor->setPowerRatio(value);
  598. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  599. if (value > 0) sensor->resetEnergy(value);
  600. }
  601. #endif // HLW8012_SUPPORT
  602. #if CSE7766_SUPPORT
  603. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  604. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  605. double value;
  606. value = getSetting("pwrRatioC", 0).toFloat();
  607. if (value > 0) sensor->setCurrentRatio(value);
  608. value = getSetting("pwrRatioV", 0).toFloat();
  609. if (value > 0) sensor->setVoltageRatio(value);
  610. value = getSetting("pwrRatioP", 0).toFloat();
  611. if (value > 0) sensor->setPowerRatio(value);
  612. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  613. if (value > 0) sensor->resetEnergy(value);
  614. }
  615. #endif // CSE7766_SUPPORT
  616. }
  617. }
  618. void _sensorConfigure() {
  619. // General sensor settings
  620. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  621. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  622. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  623. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  624. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  625. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  626. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  627. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  628. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  629. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  630. // Specific sensor settings
  631. for (unsigned char i=0; i<_sensors.size(); i++) {
  632. #if EMON_ANALOG_SUPPORT
  633. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  634. double value;
  635. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  636. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  637. sensor->expectedPower(0, value);
  638. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  639. }
  640. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  641. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  642. delSetting("pwrRatioC");
  643. }
  644. if (getSetting("pwrResetE", 0).toInt() == 1) {
  645. sensor->resetEnergy();
  646. delSetting("eneTotal");
  647. _sensorResetTS();
  648. }
  649. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  650. }
  651. #endif // EMON_ANALOG_SUPPORT
  652. #if EMON_ADC121_SUPPORT
  653. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  654. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  655. if (getSetting("pwrResetE", 0).toInt() == 1) {
  656. sensor->resetEnergy();
  657. delSetting("eneTotal");
  658. _sensorResetTS();
  659. }
  660. }
  661. #endif
  662. #if EMON_ADS1X15_SUPPORT
  663. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  664. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  665. if (getSetting("pwrResetE", 0).toInt() == 1) {
  666. sensor->resetEnergy();
  667. delSetting("eneTotal");
  668. _sensorResetTS();
  669. }
  670. }
  671. #endif
  672. #if HLW8012_SUPPORT
  673. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  674. double value;
  675. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  676. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  677. sensor->expectedCurrent(value);
  678. setSetting("pwrRatioC", sensor->getCurrentRatio());
  679. }
  680. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  681. sensor->expectedVoltage(value);
  682. setSetting("pwrRatioV", sensor->getVoltageRatio());
  683. }
  684. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  685. sensor->expectedPower(value);
  686. setSetting("pwrRatioP", sensor->getPowerRatio());
  687. }
  688. if (getSetting("pwrResetE", 0).toInt() == 1) {
  689. sensor->resetEnergy();
  690. delSetting("eneTotal");
  691. _sensorResetTS();
  692. }
  693. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  694. sensor->resetRatios();
  695. delSetting("pwrRatioC");
  696. delSetting("pwrRatioV");
  697. delSetting("pwrRatioP");
  698. }
  699. }
  700. #endif // HLW8012_SUPPORT
  701. #if CSE7766_SUPPORT
  702. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  703. double value;
  704. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  705. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  706. sensor->expectedCurrent(value);
  707. setSetting("pwrRatioC", sensor->getCurrentRatio());
  708. }
  709. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  710. sensor->expectedVoltage(value);
  711. setSetting("pwrRatioV", sensor->getVoltageRatio());
  712. }
  713. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  714. sensor->expectedPower(value);
  715. setSetting("pwrRatioP", sensor->getPowerRatio());
  716. }
  717. if (getSetting("pwrResetE", 0).toInt() == 1) {
  718. sensor->resetEnergy();
  719. delSetting("eneTotal");
  720. _sensorResetTS();
  721. }
  722. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  723. sensor->resetRatios();
  724. delSetting("pwrRatioC");
  725. delSetting("pwrRatioV");
  726. delSetting("pwrRatioP");
  727. }
  728. }
  729. #endif // CSE7766_SUPPORT
  730. }
  731. // Update filter sizes
  732. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  733. _magnitudes[i].filter->resize(_sensor_report_every);
  734. }
  735. // General processing
  736. if (0 == _sensor_save_every) {
  737. delSetting("eneTotal");
  738. }
  739. // Save settings
  740. delSetting("pwrExpectedP");
  741. delSetting("pwrExpectedC");
  742. delSetting("pwrExpectedV");
  743. delSetting("pwrResetCalibration");
  744. delSetting("pwrResetE");
  745. saveSettings();
  746. }
  747. void _sensorReport(unsigned char index, double value) {
  748. sensor_magnitude_t magnitude = _magnitudes[index];
  749. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  750. char buffer[10];
  751. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  752. #if BROKER_SUPPORT
  753. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  754. #endif
  755. #if MQTT_SUPPORT
  756. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  757. #if SENSOR_PUBLISH_ADDRESSES
  758. char topic[32];
  759. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  760. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  761. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  762. } else {
  763. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  764. }
  765. #endif // SENSOR_PUBLISH_ADDRESSES
  766. #endif // MQTT_SUPPORT
  767. #if INFLUXDB_SUPPORT
  768. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  769. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  770. } else {
  771. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  772. }
  773. #endif // INFLUXDB_SUPPORT
  774. #if THINGSPEAK_SUPPORT
  775. tspkEnqueueMeasurement(index, buffer);
  776. #endif
  777. #if DOMOTICZ_SUPPORT
  778. {
  779. char key[15];
  780. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  781. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  782. int status;
  783. if (value > 70) {
  784. status = HUMIDITY_WET;
  785. } else if (value > 45) {
  786. status = HUMIDITY_COMFORTABLE;
  787. } else if (value > 30) {
  788. status = HUMIDITY_NORMAL;
  789. } else {
  790. status = HUMIDITY_DRY;
  791. }
  792. char status_buf[5];
  793. itoa(status, status_buf, 10);
  794. domoticzSend(key, buffer, status_buf);
  795. } else {
  796. domoticzSend(key, 0, buffer);
  797. }
  798. }
  799. #endif // DOMOTICZ_SUPPORT
  800. }
  801. // -----------------------------------------------------------------------------
  802. // Public
  803. // -----------------------------------------------------------------------------
  804. unsigned char sensorCount() {
  805. return _sensors.size();
  806. }
  807. unsigned char magnitudeCount() {
  808. return _magnitudes.size();
  809. }
  810. String magnitudeName(unsigned char index) {
  811. if (index < _magnitudes.size()) {
  812. sensor_magnitude_t magnitude = _magnitudes[index];
  813. return magnitude.sensor->slot(magnitude.local);
  814. }
  815. return String();
  816. }
  817. unsigned char magnitudeType(unsigned char index) {
  818. if (index < _magnitudes.size()) {
  819. return int(_magnitudes[index].type);
  820. }
  821. return MAGNITUDE_NONE;
  822. }
  823. unsigned char magnitudeIndex(unsigned char index) {
  824. if (index < _magnitudes.size()) {
  825. return int(_magnitudes[index].global);
  826. }
  827. return 0;
  828. }
  829. String magnitudeTopic(unsigned char type) {
  830. char buffer[16] = {0};
  831. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  832. return String(buffer);
  833. }
  834. String magnitudeTopicIndex(unsigned char index) {
  835. char topic[32] = {0};
  836. if (index < _magnitudes.size()) {
  837. sensor_magnitude_t magnitude = _magnitudes[index];
  838. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  839. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  840. } else {
  841. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  842. }
  843. }
  844. return String(topic);
  845. }
  846. String magnitudeUnits(unsigned char type) {
  847. char buffer[8] = {0};
  848. if (type < MAGNITUDE_MAX) {
  849. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  850. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  851. } else if (
  852. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  853. (_sensor_energy_units == ENERGY_KWH)) {
  854. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  855. } else if (
  856. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  857. (_sensor_power_units == POWER_KILOWATTS)) {
  858. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  859. } else {
  860. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  861. }
  862. }
  863. return String(buffer);
  864. }
  865. // -----------------------------------------------------------------------------
  866. void sensorSetup() {
  867. // Backwards compatibility
  868. moveSetting("powerUnits", "pwrUnits");
  869. moveSetting("energyUnits", "eneUnits");
  870. // Load sensors
  871. _sensorLoad();
  872. _sensorInit();
  873. // Configure stored values
  874. _sensorConfigure();
  875. // Websockets
  876. #if WEB_SUPPORT
  877. wsOnSendRegister(_sensorWebSocketStart);
  878. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  879. wsOnSendRegister(_sensorWebSocketSendData);
  880. #endif
  881. // API
  882. #if API_SUPPORT
  883. _sensorAPISetup();
  884. #endif
  885. // Terminal
  886. #if TERMINAL_SUPPORT
  887. _sensorInitCommands();
  888. #endif
  889. // Main callbacks
  890. espurnaRegisterLoop(sensorLoop);
  891. espurnaRegisterReload(_sensorConfigure);
  892. }
  893. void sensorLoop() {
  894. // Check if we still have uninitialized sensors
  895. static unsigned long last_init = 0;
  896. if (!_sensors_ready) {
  897. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  898. last_init = millis();
  899. _sensorInit();
  900. }
  901. }
  902. if (_magnitudes.size() == 0) return;
  903. // Tick hook
  904. _sensorTick();
  905. // Check if we should read new data
  906. static unsigned long last_update = 0;
  907. static unsigned long report_count = 0;
  908. static unsigned long save_count = 0;
  909. if (millis() - last_update > _sensor_read_interval) {
  910. last_update = millis();
  911. report_count = (report_count + 1) % _sensor_report_every;
  912. double current;
  913. double filtered;
  914. // Pre-read hook
  915. _sensorPre();
  916. // Get the first relay state
  917. #if SENSOR_POWER_CHECK_STATUS
  918. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  919. #endif
  920. // Get readings
  921. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  922. sensor_magnitude_t magnitude = _magnitudes[i];
  923. if (magnitude.sensor->status()) {
  924. // -------------------------------------------------------------
  925. // Instant value
  926. // -------------------------------------------------------------
  927. current = magnitude.sensor->value(magnitude.local);
  928. // Completely remove spurious values if relay is OFF
  929. #if SENSOR_POWER_CHECK_STATUS
  930. if (relay_off) {
  931. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  932. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  933. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  934. magnitude.type == MAGNITUDE_CURRENT ||
  935. magnitude.type == MAGNITUDE_ENERGY_DELTA
  936. ) {
  937. current = 0;
  938. }
  939. }
  940. #endif
  941. // -------------------------------------------------------------
  942. // Processing (filters)
  943. // -------------------------------------------------------------
  944. magnitude.filter->add(current);
  945. // Special case for MovingAvergaeFilter
  946. if (MAGNITUDE_COUNT == magnitude.type ||
  947. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  948. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  949. current = magnitude.filter->result();
  950. }
  951. current = _magnitudeProcess(magnitude.type, current);
  952. _magnitudes[i].current = current;
  953. // -------------------------------------------------------------
  954. // Debug
  955. // -------------------------------------------------------------
  956. #if SENSOR_DEBUG
  957. {
  958. char buffer[64];
  959. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  960. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  961. magnitude.sensor->slot(magnitude.local).c_str(),
  962. magnitudeTopic(magnitude.type).c_str(),
  963. buffer,
  964. magnitudeUnits(magnitude.type).c_str()
  965. );
  966. }
  967. #endif // SENSOR_DEBUG
  968. // -------------------------------------------------------------
  969. // Report
  970. // (we do it every _sensor_report_every readings)
  971. // -------------------------------------------------------------
  972. bool report = (0 == report_count);
  973. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  974. // for MAGNITUDE_ENERGY, filtered value is last value
  975. double value = _magnitudeProcess(magnitude.type, current);
  976. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  977. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  978. if (report) {
  979. filtered = magnitude.filter->result();
  980. filtered = _magnitudeProcess(magnitude.type, filtered);
  981. magnitude.filter->reset();
  982. // Check if there is a minimum change threshold to report
  983. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  984. _magnitudes[i].reported = filtered;
  985. _sensorReport(i, filtered);
  986. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  987. // -------------------------------------------------------------
  988. // Saving to EEPROM
  989. // (we do it every _sensor_save_every readings)
  990. // -------------------------------------------------------------
  991. if (_sensor_save_every > 0) {
  992. save_count = (save_count + 1) % _sensor_save_every;
  993. if (0 == save_count) {
  994. if (MAGNITUDE_ENERGY == magnitude.type) {
  995. setSetting("eneTotal", current);
  996. saveSettings();
  997. }
  998. } // if (0 == save_count)
  999. } // if (_sensor_save_every > 0)
  1000. } // if (report_count == 0)
  1001. } // if (magnitude.sensor->status())
  1002. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1003. // Post-read hook
  1004. _sensorPost();
  1005. #if WEB_SUPPORT
  1006. wsSend(_sensorWebSocketSendData);
  1007. #endif
  1008. #if THINGSPEAK_SUPPORT
  1009. if (report_count == 0) tspkFlush();
  1010. #endif
  1011. }
  1012. }
  1013. #endif // SENSOR_SUPPORT