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.

1573 lines
52 KiB

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