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.

1554 lines
51 KiB

6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 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. #include <float.h>
  13. typedef struct {
  14. BaseSensor * sensor; // Sensor object
  15. BaseFilter * filter; // Filter object
  16. unsigned char local; // Local index in its provider
  17. unsigned char type; // Type of measurement
  18. unsigned char decimals; // Number of decimals in textual representation
  19. unsigned char global; // Global index in its type
  20. double current; // Current (last) value, unfiltered
  21. double reported; // Last reported value
  22. double min_change; // Minimum value change to report
  23. double max_change; // Maximum value change to report
  24. } sensor_magnitude_t;
  25. std::vector<BaseSensor *> _sensors;
  26. std::vector<sensor_magnitude_t> _magnitudes;
  27. bool _sensors_ready = false;
  28. unsigned char _counts[MAGNITUDE_MAX];
  29. bool _sensor_realtime = API_REAL_TIME_VALUES;
  30. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  31. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  32. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  33. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  34. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  35. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  36. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  37. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  38. #if PZEM004T_SUPPORT
  39. PZEM004TSensor *pzem004t_sensor;
  40. #endif
  41. String _sensor_energy_reset_ts = String();
  42. // -----------------------------------------------------------------------------
  43. // Private
  44. // -----------------------------------------------------------------------------
  45. unsigned char _magnitudeDecimals(unsigned char type) {
  46. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  47. if (type == MAGNITUDE_ANALOG) return ANALOG_DECIMALS;
  48. if (type == MAGNITUDE_ENERGY ||
  49. type == MAGNITUDE_ENERGY_DELTA) {
  50. if (_sensor_energy_units == ENERGY_KWH) return 3;
  51. }
  52. if (type == MAGNITUDE_POWER_ACTIVE ||
  53. type == MAGNITUDE_POWER_APPARENT ||
  54. type == MAGNITUDE_POWER_REACTIVE) {
  55. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  56. }
  57. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  58. return 0;
  59. }
  60. double _magnitudeProcess(unsigned char type, unsigned char decimals, double value) {
  61. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  62. if (type == MAGNITUDE_TEMPERATURE) {
  63. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  64. value = value + _sensor_temperature_correction;
  65. }
  66. if (type == MAGNITUDE_HUMIDITY) {
  67. value = constrain(value + _sensor_humidity_correction, 0, 100);
  68. }
  69. if (type == MAGNITUDE_ENERGY ||
  70. type == MAGNITUDE_ENERGY_DELTA) {
  71. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  72. }
  73. if (type == MAGNITUDE_POWER_ACTIVE ||
  74. type == MAGNITUDE_POWER_APPARENT ||
  75. type == MAGNITUDE_POWER_REACTIVE) {
  76. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  77. }
  78. return roundTo(value, decimals);
  79. }
  80. // -----------------------------------------------------------------------------
  81. #if WEB_SUPPORT
  82. template<typename T> void _sensorWebSocketMagnitudes(JsonObject& root, T prefix) {
  83. // ws produces flat list <prefix>Magnitudes
  84. String ws_name = String(prefix);
  85. ws_name.concat("Magnitudes");
  86. // config uses <prefix>Magnitude<index> (cut 's')
  87. String conf_name = ws_name.substring(0, ws_name.length() - 1);
  88. JsonObject& list = root.createNestedObject(ws_name);
  89. list["size"] = magnitudeCount();
  90. JsonArray& name = list.createNestedArray("name");
  91. JsonArray& type = list.createNestedArray("type");
  92. JsonArray& index = list.createNestedArray("index");
  93. JsonArray& idx = list.createNestedArray("idx");
  94. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  95. name.add(magnitudeName(i));
  96. type.add(magnitudeType(i));
  97. index.add(magnitudeIndex(i));
  98. idx.add(getSetting(conf_name, i, 0).toInt());
  99. }
  100. }
  101. bool _sensorWebSocketOnReceive(const char * key, JsonVariant& value) {
  102. if (strncmp(key, "pwr", 3) == 0) return true;
  103. if (strncmp(key, "sns", 3) == 0) return true;
  104. if (strncmp(key, "tmp", 3) == 0) return true;
  105. if (strncmp(key, "hum", 3) == 0) return true;
  106. if (strncmp(key, "ene", 3) == 0) return true;
  107. return false;
  108. }
  109. void _sensorWebSocketSendData(JsonObject& root) {
  110. char buffer[10];
  111. bool hasTemperature = false;
  112. bool hasHumidity = false;
  113. bool hasMICS = false;
  114. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  115. uint8_t size = 0;
  116. JsonArray& index = magnitudes.createNestedArray("index");
  117. JsonArray& type = magnitudes.createNestedArray("type");
  118. JsonArray& value = magnitudes.createNestedArray("value");
  119. JsonArray& units = magnitudes.createNestedArray("units");
  120. JsonArray& error = magnitudes.createNestedArray("error");
  121. JsonArray& description = magnitudes.createNestedArray("description");
  122. for (unsigned char i=0; i<magnitudeCount(); i++) {
  123. sensor_magnitude_t magnitude = _magnitudes[i];
  124. if (magnitude.type == MAGNITUDE_EVENT) continue;
  125. ++size;
  126. unsigned char decimals = magnitude.decimals;
  127. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  128. index.add<uint8_t>(magnitude.global);
  129. type.add<uint8_t>(magnitude.type);
  130. value.add(buffer);
  131. units.add(magnitudeUnits(magnitude.type));
  132. error.add(magnitude.sensor->error());
  133. if (magnitude.type == MAGNITUDE_ENERGY) {
  134. if (_sensor_energy_reset_ts.length() == 0) _sensorResetTS();
  135. description.add(magnitude.sensor->slot(magnitude.local) + String(" (since ") + _sensor_energy_reset_ts + String(")"));
  136. } else {
  137. description.add(magnitude.sensor->slot(magnitude.local));
  138. }
  139. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  140. if (magnitude.type == MAGNITUDE_HUMIDITY) hasHumidity = true;
  141. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  142. if (magnitude.type == MAGNITUDE_CO || magnitude.type == MAGNITUDE_NO2) hasMICS = true;
  143. #endif
  144. }
  145. magnitudes["size"] = size;
  146. if (hasTemperature) root["temperatureVisible"] = 1;
  147. if (hasHumidity) root["humidityVisible"] = 1;
  148. if (hasMICS) root["micsVisible"] = 1;
  149. }
  150. void _sensorWebSocketStart(JsonObject& root) {
  151. for (unsigned char i=0; i<_sensors.size(); i++) {
  152. BaseSensor * sensor = _sensors[i];
  153. #if EMON_ANALOG_SUPPORT
  154. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  155. root["emonVisible"] = 1;
  156. root["pwrVisible"] = 1;
  157. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  158. }
  159. #endif
  160. #if HLW8012_SUPPORT
  161. if (sensor->getID() == SENSOR_HLW8012_ID) {
  162. root["hlwVisible"] = 1;
  163. root["pwrVisible"] = 1;
  164. }
  165. #endif
  166. #if CSE7766_SUPPORT
  167. if (sensor->getID() == SENSOR_CSE7766_ID) {
  168. root["cseVisible"] = 1;
  169. root["pwrVisible"] = 1;
  170. }
  171. #endif
  172. #if V9261F_SUPPORT
  173. if (sensor->getID() == SENSOR_V9261F_ID) {
  174. root["pwrVisible"] = 1;
  175. }
  176. #endif
  177. #if ECH1560_SUPPORT
  178. if (sensor->getID() == SENSOR_ECH1560_ID) {
  179. root["pwrVisible"] = 1;
  180. }
  181. #endif
  182. #if PZEM004T_SUPPORT
  183. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  184. root["pzemVisible"] = 1;
  185. root["pwrVisible"] = 1;
  186. }
  187. #endif
  188. #if PULSEMETER_SUPPORT
  189. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  190. root["pmVisible"] = 1;
  191. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  192. }
  193. #endif
  194. }
  195. if (magnitudeCount()) {
  196. root["snsVisible"] = 1;
  197. //root["apiRealTime"] = _sensor_realtime;
  198. root["pwrUnits"] = _sensor_power_units;
  199. root["eneUnits"] = _sensor_energy_units;
  200. root["tmpUnits"] = _sensor_temperature_units;
  201. root["tmpCorrection"] = _sensor_temperature_correction;
  202. root["humCorrection"] = _sensor_humidity_correction;
  203. root["snsRead"] = _sensor_read_interval / 1000;
  204. root["snsReport"] = _sensor_report_every;
  205. root["snsSave"] = _sensor_save_every;
  206. }
  207. /*
  208. // Sensors manifest
  209. JsonArray& manifest = root.createNestedArray("manifest");
  210. #if BMX280_SUPPORT
  211. BMX280Sensor::manifest(manifest);
  212. #endif
  213. // Sensors configuration
  214. JsonArray& sensors = root.createNestedArray("sensors");
  215. for (unsigned char i; i<_sensors.size(); i++) {
  216. JsonObject& sensor = sensors.createNestedObject();
  217. sensor["index"] = i;
  218. sensor["id"] = _sensors[i]->getID();
  219. _sensors[i]->getConfig(sensor);
  220. }
  221. */
  222. }
  223. #endif // WEB_SUPPORT
  224. #if API_SUPPORT
  225. void _sensorAPISetup() {
  226. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  227. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  228. String topic = magnitudeTopic(magnitude.type);
  229. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  230. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  231. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  232. unsigned char decimals = magnitude.decimals;
  233. double value = _sensor_realtime ? magnitude.current : magnitude.reported;
  234. dtostrf(value, 1-len, decimals, buffer);
  235. });
  236. }
  237. }
  238. #endif // API_SUPPORT
  239. #if TERMINAL_SUPPORT
  240. void _sensorInitCommands() {
  241. terminalRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  242. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  243. sensor_magnitude_t magnitude = _magnitudes[i];
  244. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  245. i,
  246. magnitudeTopic(magnitude.type).c_str(),
  247. magnitude.sensor->slot(magnitude.local).c_str(),
  248. magnitudeTopic(magnitude.type).c_str(),
  249. magnitude.global
  250. );
  251. }
  252. terminalOK();
  253. });
  254. #if PZEM004T_SUPPORT
  255. terminalRegisterCommand(F("PZ.ADDRESS"), [](Embedis* e) {
  256. if (e->argc == 1) {
  257. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  258. unsigned char dev_count = pzem004t_sensor->getAddressesCount();
  259. for(unsigned char dev = 0; dev < dev_count; dev++) {
  260. DEBUG_MSG_P(PSTR("Device %d/%s\n"), dev, pzem004t_sensor->getAddress(dev).c_str());
  261. }
  262. terminalOK();
  263. } else if(e->argc == 2) {
  264. IPAddress addr;
  265. if (addr.fromString(String(e->argv[1]))) {
  266. if(pzem004t_sensor->setDeviceAddress(&addr)) {
  267. terminalOK();
  268. }
  269. } else {
  270. terminalError(F("Invalid address argument"));
  271. }
  272. } else {
  273. terminalError(F("Wrong arguments"));
  274. }
  275. });
  276. terminalRegisterCommand(F("PZ.RESET"), [](Embedis* e) {
  277. if(e->argc > 2) {
  278. terminalError(F("Wrong arguments"));
  279. } else {
  280. unsigned char init = e->argc == 2 ? String(e->argv[1]).toInt() : 0;
  281. unsigned char limit = e->argc == 2 ? init +1 : pzem004t_sensor->getAddressesCount();
  282. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  283. for(unsigned char dev = init; dev < limit; dev++) {
  284. float offset = pzem004t_sensor->resetEnergy(dev);
  285. setSetting("pzEneTotal", dev, offset);
  286. DEBUG_MSG_P(PSTR("Device %d/%s - Offset: %s\n"), dev, pzem004t_sensor->getAddress(dev).c_str(), String(offset).c_str());
  287. }
  288. terminalOK();
  289. }
  290. });
  291. terminalRegisterCommand(F("PZ.VALUE"), [](Embedis* e) {
  292. if(e->argc > 2) {
  293. terminalError(F("Wrong arguments"));
  294. } else {
  295. unsigned char init = e->argc == 2 ? String(e->argv[1]).toInt() : 0;
  296. unsigned char limit = e->argc == 2 ? init +1 : pzem004t_sensor->getAddressesCount();
  297. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  298. for(unsigned char dev = init; dev < limit; dev++) {
  299. DEBUG_MSG_P(PSTR("Device %d/%s - Current: %s Voltage: %s Power: %s Energy: %s\n"), //
  300. dev,
  301. pzem004t_sensor->getAddress(dev).c_str(),
  302. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_CURRENT_INDEX)).c_str(),
  303. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_VOLTAGE_INDEX)).c_str(),
  304. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_POWER_ACTIVE_INDEX)).c_str(),
  305. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_ENERGY_INDEX)).c_str());
  306. }
  307. terminalOK();
  308. }
  309. });
  310. #endif
  311. }
  312. #endif
  313. void _sensorTick() {
  314. for (unsigned char i=0; i<_sensors.size(); i++) {
  315. _sensors[i]->tick();
  316. }
  317. }
  318. void _sensorPre() {
  319. for (unsigned char i=0; i<_sensors.size(); i++) {
  320. _sensors[i]->pre();
  321. if (!_sensors[i]->status()) {
  322. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  323. _sensors[i]->description().c_str(),
  324. _sensors[i]->error()
  325. );
  326. }
  327. }
  328. }
  329. void _sensorPost() {
  330. for (unsigned char i=0; i<_sensors.size(); i++) {
  331. _sensors[i]->post();
  332. }
  333. }
  334. void _sensorResetTS() {
  335. #if NTP_SUPPORT
  336. if (ntpSynced()) {
  337. if (_sensor_energy_reset_ts.length() == 0) {
  338. _sensor_energy_reset_ts = ntpDateTime(now() - millis() / 1000);
  339. } else {
  340. _sensor_energy_reset_ts = ntpDateTime(now());
  341. }
  342. } else {
  343. _sensor_energy_reset_ts = String();
  344. }
  345. setSetting("snsResetTS", _sensor_energy_reset_ts);
  346. #endif
  347. }
  348. // -----------------------------------------------------------------------------
  349. // Sensor initialization
  350. // -----------------------------------------------------------------------------
  351. void _sensorLoad() {
  352. /*
  353. This is temporal, in the future sensors will be initialized based on
  354. soft configuration (data stored in EEPROM config) so you will be able
  355. to define and configure new sensors on the fly
  356. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  357. loaded and initialized here. If you want to add new sensors of the same type
  358. just duplicate the block and change the arguments for the set* methods.
  359. Check the DHT block below for an example
  360. */
  361. #if AM2320_SUPPORT
  362. {
  363. AM2320Sensor * sensor = new AM2320Sensor();
  364. sensor->setAddress(AM2320_ADDRESS);
  365. _sensors.push_back(sensor);
  366. }
  367. #endif
  368. #if ANALOG_SUPPORT
  369. {
  370. AnalogSensor * sensor = new AnalogSensor();
  371. sensor->setSamples(ANALOG_SAMPLES);
  372. sensor->setDelay(ANALOG_DELAY);
  373. //CICM For analog scaling
  374. sensor->setFactor(ANALOG_FACTOR);
  375. sensor->setOffset(ANALOG_OFFSET);
  376. _sensors.push_back(sensor);
  377. }
  378. #endif
  379. #if BH1750_SUPPORT
  380. {
  381. BH1750Sensor * sensor = new BH1750Sensor();
  382. sensor->setAddress(BH1750_ADDRESS);
  383. sensor->setMode(BH1750_MODE);
  384. _sensors.push_back(sensor);
  385. }
  386. #endif
  387. #if BMP180_SUPPORT
  388. {
  389. BMP180Sensor * sensor = new BMP180Sensor();
  390. sensor->setAddress(BMP180_ADDRESS);
  391. _sensors.push_back(sensor);
  392. }
  393. #endif
  394. #if BMX280_SUPPORT
  395. {
  396. BMX280Sensor * sensor = new BMX280Sensor();
  397. sensor->setAddress(BMX280_ADDRESS);
  398. _sensors.push_back(sensor);
  399. #if (BMX280_NUMBER == 2)
  400. // Up to two BME sensors allowed on one I2C bus
  401. BMX280Sensor * sensor2 = new BMX280Sensor();
  402. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  403. // otherwise choose the other unnamed sensor address
  404. sensor->setAddress( (BMX280_ADDRESS == 0x00) ? 0x00 : (0x76 + 0x77 - BMX280_ADDRESS));
  405. _sensors.push_back(sensor2);
  406. #endif
  407. }
  408. #endif
  409. #if CSE7766_SUPPORT
  410. {
  411. CSE7766Sensor * sensor = new CSE7766Sensor();
  412. sensor->setRX(CSE7766_PIN);
  413. _sensors.push_back(sensor);
  414. }
  415. #endif
  416. #if DALLAS_SUPPORT
  417. {
  418. DallasSensor * sensor = new DallasSensor();
  419. sensor->setGPIO(DALLAS_PIN);
  420. _sensors.push_back(sensor);
  421. }
  422. #endif
  423. #if DHT_SUPPORT
  424. {
  425. DHTSensor * sensor = new DHTSensor();
  426. sensor->setGPIO(DHT_PIN);
  427. sensor->setType(DHT_TYPE);
  428. _sensors.push_back(sensor);
  429. }
  430. #endif
  431. /*
  432. // Example on how to add a second DHT sensor
  433. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  434. #if DHT_SUPPORT
  435. {
  436. DHTSensor * sensor = new DHTSensor();
  437. sensor->setGPIO(DHT2_PIN);
  438. sensor->setType(DHT2_TYPE);
  439. _sensors.push_back(sensor);
  440. }
  441. #endif
  442. */
  443. #if DIGITAL_SUPPORT
  444. {
  445. DigitalSensor * sensor = new DigitalSensor();
  446. sensor->setGPIO(DIGITAL_PIN);
  447. sensor->setMode(DIGITAL_PIN_MODE);
  448. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  449. _sensors.push_back(sensor);
  450. }
  451. #endif
  452. #if ECH1560_SUPPORT
  453. {
  454. ECH1560Sensor * sensor = new ECH1560Sensor();
  455. sensor->setCLK(ECH1560_CLK_PIN);
  456. sensor->setMISO(ECH1560_MISO_PIN);
  457. sensor->setInverted(ECH1560_INVERTED);
  458. _sensors.push_back(sensor);
  459. }
  460. #endif
  461. #if EMON_ADC121_SUPPORT
  462. {
  463. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  464. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  465. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  466. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  467. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  468. _sensors.push_back(sensor);
  469. }
  470. #endif
  471. #if EMON_ADS1X15_SUPPORT
  472. {
  473. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  474. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  475. sensor->setType(EMON_ADS1X15_TYPE);
  476. sensor->setMask(EMON_ADS1X15_MASK);
  477. sensor->setGain(EMON_ADS1X15_GAIN);
  478. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  479. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  480. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  481. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  482. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  483. _sensors.push_back(sensor);
  484. }
  485. #endif
  486. #if EMON_ANALOG_SUPPORT
  487. {
  488. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  489. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  490. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  491. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  492. _sensors.push_back(sensor);
  493. }
  494. #endif
  495. #if EVENTS_SUPPORT
  496. {
  497. EventSensor * sensor = new EventSensor();
  498. sensor->setGPIO(EVENTS_PIN);
  499. sensor->setTrigger(EVENTS_TRIGGER);
  500. sensor->setPinMode(EVENTS_PIN_MODE);
  501. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  502. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  503. _sensors.push_back(sensor);
  504. }
  505. #endif
  506. #if GEIGER_SUPPORT
  507. {
  508. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  509. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  510. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  511. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  512. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  513. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  514. _sensors.push_back(sensor);
  515. }
  516. #endif
  517. #if GUVAS12SD_SUPPORT
  518. {
  519. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  520. sensor->setGPIO(GUVAS12SD_PIN);
  521. _sensors.push_back(sensor);
  522. }
  523. #endif
  524. #if SONAR_SUPPORT
  525. {
  526. SonarSensor * sensor = new SonarSensor();
  527. sensor->setEcho(SONAR_ECHO);
  528. sensor->setIterations(SONAR_ITERATIONS);
  529. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  530. sensor->setTrigger(SONAR_TRIGGER);
  531. _sensors.push_back(sensor);
  532. }
  533. #endif
  534. #if HLW8012_SUPPORT
  535. {
  536. HLW8012Sensor * sensor = new HLW8012Sensor();
  537. sensor->setSEL(HLW8012_SEL_PIN);
  538. sensor->setCF(HLW8012_CF_PIN);
  539. sensor->setCF1(HLW8012_CF1_PIN);
  540. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  541. _sensors.push_back(sensor);
  542. }
  543. #endif
  544. #if MHZ19_SUPPORT
  545. {
  546. MHZ19Sensor * sensor = new MHZ19Sensor();
  547. sensor->setRX(MHZ19_RX_PIN);
  548. sensor->setTX(MHZ19_TX_PIN);
  549. if (getSetting("mhz19CalibrateAuto", 0).toInt() == 1)
  550. sensor->setCalibrateAuto(true);
  551. _sensors.push_back(sensor);
  552. }
  553. #endif
  554. #if MICS2710_SUPPORT
  555. {
  556. MICS2710Sensor * sensor = new MICS2710Sensor();
  557. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  558. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  559. sensor->setRL(MICS2710_RL);
  560. _sensors.push_back(sensor);
  561. }
  562. #endif
  563. #if MICS5525_SUPPORT
  564. {
  565. MICS5525Sensor * sensor = new MICS5525Sensor();
  566. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  567. sensor->setRL(MICS5525_RL);
  568. _sensors.push_back(sensor);
  569. }
  570. #endif
  571. #if NTC_SUPPORT
  572. {
  573. NTCSensor * sensor = new NTCSensor();
  574. sensor->setSamples(NTC_SAMPLES);
  575. sensor->setDelay(NTC_DELAY);
  576. sensor->setUpstreamResistor(NTC_R_UP);
  577. sensor->setDownstreamResistor(NTC_R_DOWN);
  578. sensor->setBeta(NTC_BETA);
  579. sensor->setR0(NTC_R0);
  580. sensor->setT0(NTC_T0);
  581. _sensors.push_back(sensor);
  582. }
  583. #endif
  584. #if PMSX003_SUPPORT
  585. {
  586. PMSX003Sensor * sensor = new PMSX003Sensor();
  587. #if PMS_USE_SOFT
  588. sensor->setRX(PMS_RX_PIN);
  589. sensor->setTX(PMS_TX_PIN);
  590. #else
  591. sensor->setSerial(& PMS_HW_PORT);
  592. #endif
  593. sensor->setType(PMS_TYPE);
  594. _sensors.push_back(sensor);
  595. }
  596. #endif
  597. #if PULSEMETER_SUPPORT
  598. {
  599. PulseMeterSensor * sensor = new PulseMeterSensor();
  600. sensor->setGPIO(PULSEMETER_PIN);
  601. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  602. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  603. _sensors.push_back(sensor);
  604. }
  605. #endif
  606. #if PZEM004T_SUPPORT
  607. {
  608. PZEM004TSensor * sensor = pzem004t_sensor = new PZEM004TSensor();
  609. #if PZEM004T_USE_SOFT
  610. sensor->setRX(PZEM004T_RX_PIN);
  611. sensor->setTX(PZEM004T_TX_PIN);
  612. #else
  613. sensor->setSerial(& PZEM004T_HW_PORT);
  614. #endif
  615. sensor->setAddresses(PZEM004T_ADDRESSES);
  616. // Read saved energy offset
  617. unsigned char dev_count = sensor->getAddressesCount();
  618. for(unsigned char dev = 0; dev < dev_count; dev++) {
  619. float value = getSetting("pzEneTotal", dev, 0).toFloat();
  620. if (value > 0) sensor->resetEnergy(dev, value);
  621. }
  622. _sensors.push_back(sensor);
  623. }
  624. #endif
  625. #if SENSEAIR_SUPPORT
  626. {
  627. SenseAirSensor * sensor = new SenseAirSensor();
  628. sensor->setRX(SENSEAIR_RX_PIN);
  629. sensor->setTX(SENSEAIR_TX_PIN);
  630. _sensors.push_back(sensor);
  631. }
  632. #endif
  633. #if SDS011_SUPPORT
  634. {
  635. SDS011Sensor * sensor = new SDS011Sensor();
  636. sensor->setRX(SDS011_RX_PIN);
  637. sensor->setTX(SDS011_TX_PIN);
  638. _sensors.push_back(sensor);
  639. }
  640. #endif
  641. #if SHT3X_I2C_SUPPORT
  642. {
  643. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  644. sensor->setAddress(SHT3X_I2C_ADDRESS);
  645. _sensors.push_back(sensor);
  646. }
  647. #endif
  648. #if SI7021_SUPPORT
  649. {
  650. SI7021Sensor * sensor = new SI7021Sensor();
  651. sensor->setAddress(SI7021_ADDRESS);
  652. _sensors.push_back(sensor);
  653. }
  654. #endif
  655. #if TMP3X_SUPPORT
  656. {
  657. TMP3XSensor * sensor = new TMP3XSensor();
  658. sensor->setType(TMP3X_TYPE);
  659. _sensors.push_back(sensor);
  660. }
  661. #endif
  662. #if V9261F_SUPPORT
  663. {
  664. V9261FSensor * sensor = new V9261FSensor();
  665. sensor->setRX(V9261F_PIN);
  666. sensor->setInverted(V9261F_PIN_INVERSE);
  667. _sensors.push_back(sensor);
  668. }
  669. #endif
  670. #if MAX6675_SUPPORT
  671. {
  672. MAX6675Sensor * sensor = new MAX6675Sensor();
  673. sensor->setCS(MAX6675_CS_PIN);
  674. sensor->setSO(MAX6675_SO_PIN);
  675. sensor->setSCK(MAX6675_SCK_PIN);
  676. _sensors.push_back(sensor);
  677. }
  678. #endif
  679. #if VEML6075_SUPPORT
  680. {
  681. VEML6075Sensor * sensor = new VEML6075Sensor();
  682. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  683. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  684. _sensors.push_back(sensor);
  685. }
  686. #endif
  687. #if VL53L1X_SUPPORT
  688. {
  689. VL53L1XSensor * sensor = new VL53L1XSensor();
  690. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  691. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  692. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  693. _sensors.push_back(sensor);
  694. }
  695. #endif
  696. #if EZOPH_SUPPORT
  697. {
  698. EZOPHSensor * sensor = new EZOPHSensor();
  699. sensor->setRX(EZOPH_RX_PIN);
  700. sensor->setTX(EZOPH_TX_PIN);
  701. _sensors.push_back(sensor);
  702. }
  703. #endif
  704. }
  705. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  706. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  707. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  708. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  709. _sensorReport(k, value);
  710. return;
  711. }
  712. }
  713. }
  714. void _sensorInit() {
  715. _sensors_ready = true;
  716. _sensor_save_every = getSetting("snsSave", 0).toInt();
  717. for (unsigned char i=0; i<_sensors.size(); i++) {
  718. // Do not process an already initialized sensor
  719. if (_sensors[i]->ready()) continue;
  720. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  721. // Force sensor to reload config
  722. _sensors[i]->begin();
  723. if (!_sensors[i]->ready()) {
  724. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  725. _sensors_ready = false;
  726. continue;
  727. }
  728. // Initialize magnitudes
  729. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  730. unsigned char type = _sensors[i]->type(k);
  731. signed char decimals = _sensors[i]->decimals(type);
  732. if (decimals < 0) decimals = _magnitudeDecimals(type);
  733. sensor_magnitude_t new_magnitude;
  734. new_magnitude.sensor = _sensors[i];
  735. new_magnitude.local = k;
  736. new_magnitude.type = type;
  737. new_magnitude.decimals = (unsigned char) decimals;
  738. new_magnitude.global = _counts[type];
  739. new_magnitude.current = 0;
  740. new_magnitude.reported = 0;
  741. new_magnitude.min_change = 0;
  742. new_magnitude.max_change = 0;
  743. // TODO: find a proper way to extend this to min/max of any magnitude
  744. if (MAGNITUDE_ENERGY == type) {
  745. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  746. } else if (MAGNITUDE_TEMPERATURE == type) {
  747. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  748. } else if (MAGNITUDE_HUMIDITY == type) {
  749. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  750. }
  751. if (MAGNITUDE_ENERGY == type) {
  752. new_magnitude.filter = new LastFilter();
  753. } else if (MAGNITUDE_DIGITAL == type) {
  754. new_magnitude.filter = new MaxFilter();
  755. } 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.
  756. new_magnitude.filter = new MovingAverageFilter();
  757. } else {
  758. new_magnitude.filter = new MedianFilter();
  759. }
  760. new_magnitude.filter->resize(_sensor_report_every);
  761. _magnitudes.push_back(new_magnitude);
  762. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  763. _counts[type] = _counts[type] + 1;
  764. }
  765. // Hook callback
  766. _sensors[i]->onEvent([i](unsigned char type, double value) {
  767. _sensorCallback(i, type, value);
  768. });
  769. // Custom initializations
  770. #if MICS2710_SUPPORT
  771. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  772. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  773. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  774. }
  775. #endif // MICS2710_SUPPORT
  776. #if MICS5525_SUPPORT
  777. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  778. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  779. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  780. }
  781. #endif // MICS5525_SUPPORT
  782. #if EMON_ANALOG_SUPPORT
  783. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  784. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  785. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  786. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  787. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  788. if (value > 0) sensor->resetEnergy(0, value);
  789. }
  790. #endif // EMON_ANALOG_SUPPORT
  791. #if HLW8012_SUPPORT
  792. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  793. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  794. double value;
  795. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  796. if (value > 0) sensor->setCurrentRatio(value);
  797. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  798. if (value > 0) sensor->setVoltageRatio(value);
  799. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  800. if (value > 0) sensor->setPowerRatio(value);
  801. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  802. if (value > 0) sensor->resetEnergy(value);
  803. }
  804. #endif // HLW8012_SUPPORT
  805. #if CSE7766_SUPPORT
  806. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  807. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  808. double value;
  809. value = getSetting("pwrRatioC", 0).toFloat();
  810. if (value > 0) sensor->setCurrentRatio(value);
  811. value = getSetting("pwrRatioV", 0).toFloat();
  812. if (value > 0) sensor->setVoltageRatio(value);
  813. value = getSetting("pwrRatioP", 0).toFloat();
  814. if (value > 0) sensor->setPowerRatio(value);
  815. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  816. if (value > 0) sensor->resetEnergy(value);
  817. }
  818. #endif // CSE7766_SUPPORT
  819. #if PULSEMETER_SUPPORT
  820. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  821. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  822. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  823. }
  824. #endif // PULSEMETER_SUPPORT
  825. }
  826. }
  827. void _sensorConfigure() {
  828. // General sensor settings
  829. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  830. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  831. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  832. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  833. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  834. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  835. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  836. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  837. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  838. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  839. // Specific sensor settings
  840. for (unsigned char i=0; i<_sensors.size(); i++) {
  841. #if MICS2710_SUPPORT
  842. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  843. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  844. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  845. sensor->calibrate();
  846. setSetting("snsR0", sensor->getR0());
  847. }
  848. }
  849. #endif // MICS2710_SUPPORT
  850. #if MICS5525_SUPPORT
  851. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  852. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  853. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  854. sensor->calibrate();
  855. setSetting("snsR0", sensor->getR0());
  856. }
  857. }
  858. #endif // MICS5525_SUPPORT
  859. #if EMON_ANALOG_SUPPORT
  860. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  861. double value;
  862. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  863. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  864. sensor->expectedPower(0, value);
  865. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  866. }
  867. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  868. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  869. delSetting("pwrRatioC");
  870. }
  871. if (getSetting("pwrResetE", 0).toInt() == 1) {
  872. sensor->resetEnergy();
  873. delSetting("eneTotal");
  874. _sensorResetTS();
  875. }
  876. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  877. }
  878. #endif // EMON_ANALOG_SUPPORT
  879. #if EMON_ADC121_SUPPORT
  880. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  881. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  882. if (getSetting("pwrResetE", 0).toInt() == 1) {
  883. sensor->resetEnergy();
  884. delSetting("eneTotal");
  885. _sensorResetTS();
  886. }
  887. }
  888. #endif
  889. #if EMON_ADS1X15_SUPPORT
  890. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  891. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  892. if (getSetting("pwrResetE", 0).toInt() == 1) {
  893. sensor->resetEnergy();
  894. delSetting("eneTotal");
  895. _sensorResetTS();
  896. }
  897. }
  898. #endif
  899. #if HLW8012_SUPPORT
  900. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  901. double value;
  902. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  903. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  904. sensor->expectedCurrent(value);
  905. setSetting("pwrRatioC", sensor->getCurrentRatio());
  906. }
  907. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  908. sensor->expectedVoltage(value);
  909. setSetting("pwrRatioV", sensor->getVoltageRatio());
  910. }
  911. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  912. sensor->expectedPower(value);
  913. setSetting("pwrRatioP", sensor->getPowerRatio());
  914. }
  915. if (getSetting("pwrResetE", 0).toInt() == 1) {
  916. sensor->resetEnergy();
  917. delSetting("eneTotal");
  918. _sensorResetTS();
  919. }
  920. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  921. sensor->resetRatios();
  922. delSetting("pwrRatioC");
  923. delSetting("pwrRatioV");
  924. delSetting("pwrRatioP");
  925. }
  926. }
  927. #endif // HLW8012_SUPPORT
  928. #if CSE7766_SUPPORT
  929. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  930. double value;
  931. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  932. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  933. sensor->expectedCurrent(value);
  934. setSetting("pwrRatioC", sensor->getCurrentRatio());
  935. }
  936. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  937. sensor->expectedVoltage(value);
  938. setSetting("pwrRatioV", sensor->getVoltageRatio());
  939. }
  940. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  941. sensor->expectedPower(value);
  942. setSetting("pwrRatioP", sensor->getPowerRatio());
  943. }
  944. if (getSetting("pwrResetE", 0).toInt() == 1) {
  945. sensor->resetEnergy();
  946. delSetting("eneTotal");
  947. _sensorResetTS();
  948. }
  949. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  950. sensor->resetRatios();
  951. delSetting("pwrRatioC");
  952. delSetting("pwrRatioV");
  953. delSetting("pwrRatioP");
  954. }
  955. }
  956. #endif // CSE7766_SUPPORT
  957. #if PULSEMETER_SUPPORT
  958. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  959. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  960. if (getSetting("pwrResetE", 0).toInt() == 1) {
  961. sensor->resetEnergy();
  962. delSetting("eneTotal");
  963. _sensorResetTS();
  964. }
  965. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  966. }
  967. #endif // PULSEMETER_SUPPORT
  968. #if PZEM004T_SUPPORT
  969. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  970. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  971. if (getSetting("pwrResetE", 0).toInt() == 1) {
  972. unsigned char dev_count = sensor->getAddressesCount();
  973. for(unsigned char dev = 0; dev < dev_count; dev++) {
  974. sensor->resetEnergy(dev, 0);
  975. delSetting("pzEneTotal", dev);
  976. }
  977. _sensorResetTS();
  978. }
  979. }
  980. #endif // PZEM004T_SUPPORT
  981. }
  982. // Update filter sizes
  983. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  984. _magnitudes[i].filter->resize(_sensor_report_every);
  985. }
  986. // General processing
  987. if (0 == _sensor_save_every) {
  988. delSetting("eneTotal");
  989. }
  990. // Save settings
  991. delSetting("snsResetCalibration");
  992. delSetting("pwrExpectedP");
  993. delSetting("pwrExpectedC");
  994. delSetting("pwrExpectedV");
  995. delSetting("pwrResetCalibration");
  996. delSetting("pwrResetE");
  997. saveSettings();
  998. }
  999. void _sensorReport(unsigned char index, double value) {
  1000. sensor_magnitude_t magnitude = _magnitudes[index];
  1001. unsigned char decimals = magnitude.decimals;
  1002. char buffer[10];
  1003. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  1004. #if BROKER_SUPPORT
  1005. brokerPublish(BROKER_MSG_TYPE_SENSOR ,magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  1006. #endif
  1007. #if MQTT_SUPPORT
  1008. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1009. #if SENSOR_PUBLISH_ADDRESSES
  1010. char topic[32];
  1011. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1012. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1013. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1014. } else {
  1015. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1016. }
  1017. #endif // SENSOR_PUBLISH_ADDRESSES
  1018. #endif // MQTT_SUPPORT
  1019. #if THINGSPEAK_SUPPORT
  1020. tspkEnqueueMeasurement(index, buffer);
  1021. #endif
  1022. #if DOMOTICZ_SUPPORT
  1023. {
  1024. char key[15];
  1025. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  1026. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  1027. int status;
  1028. if (value > 70) {
  1029. status = HUMIDITY_WET;
  1030. } else if (value > 45) {
  1031. status = HUMIDITY_COMFORTABLE;
  1032. } else if (value > 30) {
  1033. status = HUMIDITY_NORMAL;
  1034. } else {
  1035. status = HUMIDITY_DRY;
  1036. }
  1037. char status_buf[5];
  1038. itoa(status, status_buf, 10);
  1039. domoticzSend(key, buffer, status_buf);
  1040. } else {
  1041. domoticzSend(key, 0, buffer);
  1042. }
  1043. }
  1044. #endif // DOMOTICZ_SUPPORT
  1045. }
  1046. // -----------------------------------------------------------------------------
  1047. // Public
  1048. // -----------------------------------------------------------------------------
  1049. unsigned char sensorCount() {
  1050. return _sensors.size();
  1051. }
  1052. unsigned char magnitudeCount() {
  1053. return _magnitudes.size();
  1054. }
  1055. String magnitudeName(unsigned char index) {
  1056. if (index < _magnitudes.size()) {
  1057. sensor_magnitude_t magnitude = _magnitudes[index];
  1058. return magnitude.sensor->slot(magnitude.local);
  1059. }
  1060. return String();
  1061. }
  1062. unsigned char magnitudeType(unsigned char index) {
  1063. if (index < _magnitudes.size()) {
  1064. return int(_magnitudes[index].type);
  1065. }
  1066. return MAGNITUDE_NONE;
  1067. }
  1068. double magnitudeValue(unsigned char index) {
  1069. if (index < _magnitudes.size()) {
  1070. return _sensor_realtime ? _magnitudes[index].current : _magnitudes[index].reported;
  1071. }
  1072. return DBL_MIN;
  1073. }
  1074. unsigned char magnitudeIndex(unsigned char index) {
  1075. if (index < _magnitudes.size()) {
  1076. return int(_magnitudes[index].global);
  1077. }
  1078. return 0;
  1079. }
  1080. String magnitudeTopic(unsigned char type) {
  1081. char buffer[16] = {0};
  1082. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1083. return String(buffer);
  1084. }
  1085. String magnitudeTopicIndex(unsigned char index) {
  1086. char topic[32] = {0};
  1087. if (index < _magnitudes.size()) {
  1088. sensor_magnitude_t magnitude = _magnitudes[index];
  1089. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1090. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1091. } else {
  1092. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1093. }
  1094. }
  1095. return String(topic);
  1096. }
  1097. String magnitudeUnits(unsigned char type) {
  1098. char buffer[8] = {0};
  1099. if (type < MAGNITUDE_MAX) {
  1100. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1101. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1102. } else if (
  1103. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1104. (_sensor_energy_units == ENERGY_KWH)) {
  1105. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1106. } else if (
  1107. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1108. (_sensor_power_units == POWER_KILOWATTS)) {
  1109. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1110. } else {
  1111. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1112. }
  1113. }
  1114. return String(buffer);
  1115. }
  1116. // -----------------------------------------------------------------------------
  1117. void sensorSetup() {
  1118. // Backwards compatibility
  1119. moveSetting("powerUnits", "pwrUnits");
  1120. moveSetting("energyUnits", "eneUnits");
  1121. // Load sensors
  1122. _sensorLoad();
  1123. _sensorInit();
  1124. // Configure stored values
  1125. _sensorConfigure();
  1126. // Websockets
  1127. #if WEB_SUPPORT
  1128. wsOnSendRegister(_sensorWebSocketStart);
  1129. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1130. wsOnSendRegister(_sensorWebSocketSendData);
  1131. #endif
  1132. // API
  1133. #if API_SUPPORT
  1134. _sensorAPISetup();
  1135. #endif
  1136. // Terminal
  1137. #if TERMINAL_SUPPORT
  1138. _sensorInitCommands();
  1139. #endif
  1140. // Main callbacks
  1141. espurnaRegisterLoop(sensorLoop);
  1142. espurnaRegisterReload(_sensorConfigure);
  1143. }
  1144. void sensorLoop() {
  1145. // Check if we still have uninitialized sensors
  1146. static unsigned long last_init = 0;
  1147. if (!_sensors_ready) {
  1148. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1149. last_init = millis();
  1150. _sensorInit();
  1151. }
  1152. }
  1153. if (_magnitudes.size() == 0) return;
  1154. // Tick hook
  1155. _sensorTick();
  1156. // Check if we should read new data
  1157. static unsigned long last_update = 0;
  1158. static unsigned long report_count = 0;
  1159. static unsigned long save_count = 0;
  1160. if (millis() - last_update > _sensor_read_interval) {
  1161. last_update = millis();
  1162. report_count = (report_count + 1) % _sensor_report_every;
  1163. double current;
  1164. double filtered;
  1165. // Pre-read hook
  1166. _sensorPre();
  1167. // Get the first relay state
  1168. #if SENSOR_POWER_CHECK_STATUS
  1169. bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1170. #endif
  1171. // Get readings
  1172. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1173. sensor_magnitude_t magnitude = _magnitudes[i];
  1174. if (magnitude.sensor->status()) {
  1175. // -------------------------------------------------------------
  1176. // Instant value
  1177. // -------------------------------------------------------------
  1178. current = magnitude.sensor->value(magnitude.local);
  1179. // Completely remove spurious values if relay is OFF
  1180. #if SENSOR_POWER_CHECK_STATUS
  1181. if (relay_off) {
  1182. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1183. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1184. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1185. magnitude.type == MAGNITUDE_CURRENT ||
  1186. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1187. ) {
  1188. current = 0;
  1189. }
  1190. }
  1191. #endif
  1192. // -------------------------------------------------------------
  1193. // Processing (filters)
  1194. // -------------------------------------------------------------
  1195. magnitude.filter->add(current);
  1196. // Special case for MovingAvergaeFilter
  1197. if (MAGNITUDE_COUNT == magnitude.type ||
  1198. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1199. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1200. current = magnitude.filter->result();
  1201. }
  1202. current = _magnitudeProcess(magnitude.type, magnitude.decimals, current);
  1203. _magnitudes[i].current = current;
  1204. // -------------------------------------------------------------
  1205. // Debug
  1206. // -------------------------------------------------------------
  1207. #if SENSOR_DEBUG
  1208. {
  1209. char buffer[64];
  1210. dtostrf(current, 1-sizeof(buffer), magnitude.decimals, buffer);
  1211. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1212. magnitude.sensor->slot(magnitude.local).c_str(),
  1213. magnitudeTopic(magnitude.type).c_str(),
  1214. buffer,
  1215. magnitudeUnits(magnitude.type).c_str()
  1216. );
  1217. }
  1218. #endif // SENSOR_DEBUG
  1219. // -------------------------------------------------------------
  1220. // Report
  1221. // (we do it every _sensor_report_every readings)
  1222. // -------------------------------------------------------------
  1223. bool report = (0 == report_count);
  1224. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1225. // for MAGNITUDE_ENERGY, filtered value is last value
  1226. double value = _magnitudeProcess(magnitude.type, magnitude.decimals, current);
  1227. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1228. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1229. if (report) {
  1230. filtered = magnitude.filter->result();
  1231. filtered = _magnitudeProcess(magnitude.type, magnitude.decimals, filtered);
  1232. magnitude.filter->reset();
  1233. // Check if there is a minimum change threshold to report
  1234. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1235. _magnitudes[i].reported = filtered;
  1236. _sensorReport(i, filtered);
  1237. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1238. // -------------------------------------------------------------
  1239. // Saving to EEPROM
  1240. // (we do it every _sensor_save_every readings)
  1241. // -------------------------------------------------------------
  1242. if (_sensor_save_every > 0) {
  1243. save_count = (save_count + 1) % _sensor_save_every;
  1244. if (0 == save_count) {
  1245. if (MAGNITUDE_ENERGY == magnitude.type) {
  1246. setSetting("eneTotal", current);
  1247. saveSettings();
  1248. }
  1249. } // if (0 == save_count)
  1250. } // if (_sensor_save_every > 0)
  1251. } // if (report_count == 0)
  1252. } // if (magnitude.sensor->status())
  1253. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1254. // Post-read hook
  1255. _sensorPost();
  1256. #if WEB_SUPPORT
  1257. wsSend(_sensorWebSocketSendData);
  1258. #endif
  1259. #if THINGSPEAK_SUPPORT
  1260. if (report_count == 0) tspkFlush();
  1261. #endif
  1262. }
  1263. }
  1264. #endif // SENSOR_SUPPORT