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.

1268 lines
40 KiB

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