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.

1562 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("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. // 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. PZEM004TSensor * sensor = pzem004t_sensor = new PZEM004TSensor();
  610. #if PZEM004T_USE_SOFT
  611. sensor->setRX(PZEM004T_RX_PIN);
  612. sensor->setTX(PZEM004T_TX_PIN);
  613. #else
  614. sensor->setSerial(& PZEM004T_HW_PORT);
  615. #endif
  616. sensor->setAddresses(PZEM004T_ADDRESSES);
  617. // Read saved energy offset
  618. unsigned char dev_count = sensor->getAddressesCount();
  619. for(unsigned char dev = 0; dev < dev_count; dev++) {
  620. float value = getSetting("pzEneTotal", dev, 0).toFloat();
  621. if (value > 0) sensor->resetEnergy(dev, value);
  622. }
  623. _sensors.push_back(sensor);
  624. }
  625. #endif
  626. #if SENSEAIR_SUPPORT
  627. {
  628. SenseAirSensor * sensor = new SenseAirSensor();
  629. sensor->setRX(SENSEAIR_RX_PIN);
  630. sensor->setTX(SENSEAIR_TX_PIN);
  631. _sensors.push_back(sensor);
  632. }
  633. #endif
  634. #if SDS011_SUPPORT
  635. {
  636. SDS011Sensor * sensor = new SDS011Sensor();
  637. sensor->setRX(SDS011_RX_PIN);
  638. sensor->setTX(SDS011_TX_PIN);
  639. _sensors.push_back(sensor);
  640. }
  641. #endif
  642. #if SHT3X_I2C_SUPPORT
  643. {
  644. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  645. sensor->setAddress(SHT3X_I2C_ADDRESS);
  646. _sensors.push_back(sensor);
  647. }
  648. #endif
  649. #if SI7021_SUPPORT
  650. {
  651. SI7021Sensor * sensor = new SI7021Sensor();
  652. sensor->setAddress(SI7021_ADDRESS);
  653. _sensors.push_back(sensor);
  654. }
  655. #endif
  656. #if TMP3X_SUPPORT
  657. {
  658. TMP3XSensor * sensor = new TMP3XSensor();
  659. sensor->setType(TMP3X_TYPE);
  660. _sensors.push_back(sensor);
  661. }
  662. #endif
  663. #if V9261F_SUPPORT
  664. {
  665. V9261FSensor * sensor = new V9261FSensor();
  666. sensor->setRX(V9261F_PIN);
  667. sensor->setInverted(V9261F_PIN_INVERSE);
  668. _sensors.push_back(sensor);
  669. }
  670. #endif
  671. #if MAX6675_SUPPORT
  672. {
  673. MAX6675Sensor * sensor = new MAX6675Sensor();
  674. sensor->setCS(MAX6675_CS_PIN);
  675. sensor->setSO(MAX6675_SO_PIN);
  676. sensor->setSCK(MAX6675_SCK_PIN);
  677. _sensors.push_back(sensor);
  678. }
  679. #endif
  680. #if VEML6075_SUPPORT
  681. {
  682. VEML6075Sensor * sensor = new VEML6075Sensor();
  683. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  684. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  685. _sensors.push_back(sensor);
  686. }
  687. #endif
  688. #if VL53L1X_SUPPORT
  689. {
  690. VL53L1XSensor * sensor = new VL53L1XSensor();
  691. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  692. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  693. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  694. _sensors.push_back(sensor);
  695. }
  696. #endif
  697. #if EZOPH_SUPPORT
  698. {
  699. EZOPHSensor * sensor = new EZOPHSensor();
  700. sensor->setRX(EZOPH_RX_PIN);
  701. sensor->setTX(EZOPH_TX_PIN);
  702. _sensors.push_back(sensor);
  703. }
  704. #endif
  705. }
  706. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  707. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  708. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  709. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  710. _sensorReport(k, value);
  711. return;
  712. }
  713. }
  714. }
  715. void _sensorInit() {
  716. _sensors_ready = true;
  717. _sensor_save_every = getSetting("snsSave", 0).toInt();
  718. for (unsigned char i=0; i<_sensors.size(); i++) {
  719. // Do not process an already initialized sensor
  720. if (_sensors[i]->ready()) continue;
  721. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  722. // Force sensor to reload config
  723. _sensors[i]->begin();
  724. if (!_sensors[i]->ready()) {
  725. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  726. _sensors_ready = false;
  727. continue;
  728. }
  729. // Initialize magnitudes
  730. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  731. unsigned char type = _sensors[i]->type(k);
  732. signed char decimals = _sensors[i]->decimals(type);
  733. if (decimals < 0) decimals = _magnitudeDecimals(type);
  734. sensor_magnitude_t new_magnitude;
  735. new_magnitude.sensor = _sensors[i];
  736. new_magnitude.local = k;
  737. new_magnitude.type = type;
  738. new_magnitude.decimals = (unsigned char) decimals;
  739. new_magnitude.global = _counts[type];
  740. new_magnitude.last = 0;
  741. new_magnitude.reported = 0;
  742. new_magnitude.min_change = 0;
  743. new_magnitude.max_change = 0;
  744. // TODO: find a proper way to extend this to min/max of any magnitude
  745. if (MAGNITUDE_ENERGY == type) {
  746. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  747. } else if (MAGNITUDE_TEMPERATURE == type) {
  748. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  749. } else if (MAGNITUDE_HUMIDITY == type) {
  750. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  751. }
  752. if (MAGNITUDE_ENERGY == type) {
  753. new_magnitude.filter = new LastFilter();
  754. } else if (MAGNITUDE_DIGITAL == type) {
  755. new_magnitude.filter = new MaxFilter();
  756. } 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.
  757. new_magnitude.filter = new MovingAverageFilter();
  758. } else {
  759. new_magnitude.filter = new MedianFilter();
  760. }
  761. new_magnitude.filter->resize(_sensor_report_every);
  762. _magnitudes.push_back(new_magnitude);
  763. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  764. _counts[type] = _counts[type] + 1;
  765. }
  766. // Hook callback
  767. _sensors[i]->onEvent([i](unsigned char type, double value) {
  768. _sensorCallback(i, type, value);
  769. });
  770. // Custom initializations
  771. #if MICS2710_SUPPORT
  772. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  773. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  774. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  775. }
  776. #endif // MICS2710_SUPPORT
  777. #if MICS5525_SUPPORT
  778. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  779. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  780. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  781. }
  782. #endif // MICS5525_SUPPORT
  783. #if EMON_ANALOG_SUPPORT
  784. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  785. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  786. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  787. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  788. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  789. if (value > 0) sensor->resetEnergy(0, value);
  790. }
  791. #endif // EMON_ANALOG_SUPPORT
  792. #if HLW8012_SUPPORT
  793. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  794. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  795. double value;
  796. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  797. if (value > 0) sensor->setCurrentRatio(value);
  798. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  799. if (value > 0) sensor->setVoltageRatio(value);
  800. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  801. if (value > 0) sensor->setPowerRatio(value);
  802. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  803. if (value > 0) sensor->resetEnergy(value);
  804. }
  805. #endif // HLW8012_SUPPORT
  806. #if CSE7766_SUPPORT
  807. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  808. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  809. double value;
  810. value = getSetting("pwrRatioC", 0).toFloat();
  811. if (value > 0) sensor->setCurrentRatio(value);
  812. value = getSetting("pwrRatioV", 0).toFloat();
  813. if (value > 0) sensor->setVoltageRatio(value);
  814. value = getSetting("pwrRatioP", 0).toFloat();
  815. if (value > 0) sensor->setPowerRatio(value);
  816. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  817. if (value > 0) sensor->resetEnergy(value);
  818. }
  819. #endif // CSE7766_SUPPORT
  820. #if PULSEMETER_SUPPORT
  821. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  822. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  823. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  824. }
  825. #endif // PULSEMETER_SUPPORT
  826. }
  827. }
  828. void _sensorConfigure() {
  829. // General sensor settings
  830. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  831. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  832. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  833. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  834. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  835. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  836. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  837. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  838. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  839. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  840. // Specific sensor settings
  841. for (unsigned char i=0; i<_sensors.size(); i++) {
  842. #if MICS2710_SUPPORT
  843. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  844. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  845. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  846. sensor->calibrate();
  847. setSetting("snsR0", sensor->getR0());
  848. }
  849. }
  850. #endif // MICS2710_SUPPORT
  851. #if MICS5525_SUPPORT
  852. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  853. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  854. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  855. sensor->calibrate();
  856. setSetting("snsR0", sensor->getR0());
  857. }
  858. }
  859. #endif // MICS5525_SUPPORT
  860. #if EMON_ANALOG_SUPPORT
  861. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  862. double value;
  863. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  864. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  865. sensor->expectedPower(0, value);
  866. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  867. }
  868. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  869. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  870. delSetting("pwrRatioC");
  871. }
  872. if (getSetting("pwrResetE", 0).toInt() == 1) {
  873. sensor->resetEnergy();
  874. delSetting("eneTotal");
  875. _sensorResetTS();
  876. }
  877. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  878. }
  879. #endif // EMON_ANALOG_SUPPORT
  880. #if EMON_ADC121_SUPPORT
  881. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  882. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  883. if (getSetting("pwrResetE", 0).toInt() == 1) {
  884. sensor->resetEnergy();
  885. delSetting("eneTotal");
  886. _sensorResetTS();
  887. }
  888. }
  889. #endif
  890. #if EMON_ADS1X15_SUPPORT
  891. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  892. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  893. if (getSetting("pwrResetE", 0).toInt() == 1) {
  894. sensor->resetEnergy();
  895. delSetting("eneTotal");
  896. _sensorResetTS();
  897. }
  898. }
  899. #endif
  900. #if HLW8012_SUPPORT
  901. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  902. double value;
  903. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  904. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  905. sensor->expectedCurrent(value);
  906. setSetting("pwrRatioC", sensor->getCurrentRatio());
  907. }
  908. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  909. sensor->expectedVoltage(value);
  910. setSetting("pwrRatioV", sensor->getVoltageRatio());
  911. }
  912. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  913. sensor->expectedPower(value);
  914. setSetting("pwrRatioP", sensor->getPowerRatio());
  915. }
  916. if (getSetting("pwrResetE", 0).toInt() == 1) {
  917. sensor->resetEnergy();
  918. delSetting("eneTotal");
  919. _sensorResetTS();
  920. }
  921. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  922. sensor->resetRatios();
  923. delSetting("pwrRatioC");
  924. delSetting("pwrRatioV");
  925. delSetting("pwrRatioP");
  926. }
  927. }
  928. #endif // HLW8012_SUPPORT
  929. #if CSE7766_SUPPORT
  930. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  931. double value;
  932. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  933. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  934. sensor->expectedCurrent(value);
  935. setSetting("pwrRatioC", sensor->getCurrentRatio());
  936. }
  937. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  938. sensor->expectedVoltage(value);
  939. setSetting("pwrRatioV", sensor->getVoltageRatio());
  940. }
  941. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  942. sensor->expectedPower(value);
  943. setSetting("pwrRatioP", sensor->getPowerRatio());
  944. }
  945. if (getSetting("pwrResetE", 0).toInt() == 1) {
  946. sensor->resetEnergy();
  947. delSetting("eneTotal");
  948. _sensorResetTS();
  949. }
  950. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  951. sensor->resetRatios();
  952. delSetting("pwrRatioC");
  953. delSetting("pwrRatioV");
  954. delSetting("pwrRatioP");
  955. }
  956. }
  957. #endif // CSE7766_SUPPORT
  958. #if PULSEMETER_SUPPORT
  959. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  960. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  961. if (getSetting("pwrResetE", 0).toInt() == 1) {
  962. sensor->resetEnergy();
  963. delSetting("eneTotal");
  964. _sensorResetTS();
  965. }
  966. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  967. }
  968. #endif // PULSEMETER_SUPPORT
  969. #if PZEM004T_SUPPORT
  970. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  971. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  972. if (getSetting("pwrResetE", 0).toInt() == 1) {
  973. unsigned char dev_count = sensor->getAddressesCount();
  974. for(unsigned char dev = 0; dev < dev_count; dev++) {
  975. sensor->resetEnergy(dev, 0);
  976. delSetting("pzEneTotal", dev);
  977. }
  978. _sensorResetTS();
  979. }
  980. }
  981. #endif // PZEM004T_SUPPORT
  982. }
  983. // Update filter sizes
  984. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  985. _magnitudes[i].filter->resize(_sensor_report_every);
  986. }
  987. // General processing
  988. if (0 == _sensor_save_every) {
  989. delSetting("eneTotal");
  990. }
  991. // Save settings
  992. delSetting("snsResetCalibration");
  993. delSetting("pwrExpectedP");
  994. delSetting("pwrExpectedC");
  995. delSetting("pwrExpectedV");
  996. delSetting("pwrResetCalibration");
  997. delSetting("pwrResetE");
  998. saveSettings();
  999. }
  1000. void _sensorReport(unsigned char index, double value) {
  1001. sensor_magnitude_t magnitude = _magnitudes[index];
  1002. unsigned char decimals = magnitude.decimals;
  1003. char buffer[10];
  1004. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  1005. #if BROKER_SUPPORT
  1006. brokerPublish(BROKER_MSG_TYPE_SENSOR ,magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  1007. #endif
  1008. #if MQTT_SUPPORT
  1009. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1010. #if SENSOR_PUBLISH_ADDRESSES
  1011. char topic[32];
  1012. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1013. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1014. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1015. } else {
  1016. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1017. }
  1018. #endif // SENSOR_PUBLISH_ADDRESSES
  1019. #endif // MQTT_SUPPORT
  1020. #if THINGSPEAK_SUPPORT
  1021. tspkEnqueueMeasurement(index, buffer);
  1022. #endif
  1023. #if DOMOTICZ_SUPPORT
  1024. {
  1025. char key[15];
  1026. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  1027. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  1028. int status;
  1029. if (value > 70) {
  1030. status = HUMIDITY_WET;
  1031. } else if (value > 45) {
  1032. status = HUMIDITY_COMFORTABLE;
  1033. } else if (value > 30) {
  1034. status = HUMIDITY_NORMAL;
  1035. } else {
  1036. status = HUMIDITY_DRY;
  1037. }
  1038. char status_buf[5];
  1039. itoa(status, status_buf, 10);
  1040. domoticzSend(key, buffer, status_buf);
  1041. } else {
  1042. domoticzSend(key, 0, buffer);
  1043. }
  1044. }
  1045. #endif // DOMOTICZ_SUPPORT
  1046. }
  1047. // -----------------------------------------------------------------------------
  1048. // Public
  1049. // -----------------------------------------------------------------------------
  1050. unsigned char sensorCount() {
  1051. return _sensors.size();
  1052. }
  1053. unsigned char magnitudeCount() {
  1054. return _magnitudes.size();
  1055. }
  1056. String magnitudeName(unsigned char index) {
  1057. if (index < _magnitudes.size()) {
  1058. sensor_magnitude_t magnitude = _magnitudes[index];
  1059. return magnitude.sensor->slot(magnitude.local);
  1060. }
  1061. return String();
  1062. }
  1063. unsigned char magnitudeType(unsigned char index) {
  1064. if (index < _magnitudes.size()) {
  1065. return int(_magnitudes[index].type);
  1066. }
  1067. return MAGNITUDE_NONE;
  1068. }
  1069. double magnitudeValue(unsigned char index) {
  1070. if (index < _magnitudes.size()) {
  1071. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  1072. }
  1073. return DBL_MIN;
  1074. }
  1075. unsigned char magnitudeIndex(unsigned char index) {
  1076. if (index < _magnitudes.size()) {
  1077. return int(_magnitudes[index].global);
  1078. }
  1079. return 0;
  1080. }
  1081. String magnitudeTopic(unsigned char type) {
  1082. char buffer[16] = {0};
  1083. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1084. return String(buffer);
  1085. }
  1086. String magnitudeTopicIndex(unsigned char index) {
  1087. char topic[32] = {0};
  1088. if (index < _magnitudes.size()) {
  1089. sensor_magnitude_t magnitude = _magnitudes[index];
  1090. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1091. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1092. } else {
  1093. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1094. }
  1095. }
  1096. return String(topic);
  1097. }
  1098. String magnitudeUnits(unsigned char type) {
  1099. char buffer[8] = {0};
  1100. if (type < MAGNITUDE_MAX) {
  1101. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1102. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1103. } else if (
  1104. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1105. (_sensor_energy_units == ENERGY_KWH)) {
  1106. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1107. } else if (
  1108. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1109. (_sensor_power_units == POWER_KILOWATTS)) {
  1110. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1111. } else {
  1112. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1113. }
  1114. }
  1115. return String(buffer);
  1116. }
  1117. // -----------------------------------------------------------------------------
  1118. void sensorSetup() {
  1119. // Backwards compatibility
  1120. moveSetting("powerUnits", "pwrUnits");
  1121. moveSetting("energyUnits", "eneUnits");
  1122. // Load sensors
  1123. _sensorLoad();
  1124. _sensorInit();
  1125. // Configure stored values
  1126. _sensorConfigure();
  1127. // Websockets
  1128. #if WEB_SUPPORT
  1129. wsOnSendRegister(_sensorWebSocketStart);
  1130. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1131. wsOnSendRegister(_sensorWebSocketSendData);
  1132. #endif
  1133. // API
  1134. #if API_SUPPORT
  1135. _sensorAPISetup();
  1136. #endif
  1137. // Terminal
  1138. #if TERMINAL_SUPPORT
  1139. _sensorInitCommands();
  1140. #endif
  1141. // Main callbacks
  1142. espurnaRegisterLoop(sensorLoop);
  1143. espurnaRegisterReload(_sensorConfigure);
  1144. }
  1145. void sensorLoop() {
  1146. // Check if we still have uninitialized sensors
  1147. static unsigned long last_init = 0;
  1148. if (!_sensors_ready) {
  1149. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1150. last_init = millis();
  1151. _sensorInit();
  1152. }
  1153. }
  1154. if (_magnitudes.size() == 0) return;
  1155. // Tick hook
  1156. _sensorTick();
  1157. // Check if we should read new data
  1158. static unsigned long last_update = 0;
  1159. static unsigned long report_count = 0;
  1160. static unsigned long save_count = 0;
  1161. if (millis() - last_update > _sensor_read_interval) {
  1162. last_update = millis();
  1163. report_count = (report_count + 1) % _sensor_report_every;
  1164. double value_raw; // holds the raw value as the sensor returns it
  1165. double value_show; // holds the processed value applying units and decimals
  1166. double value_filtered; // holds the processed value applying filters, and the units and decimals
  1167. // Pre-read hook
  1168. _sensorPre();
  1169. // Get the first relay state
  1170. #if SENSOR_POWER_CHECK_STATUS
  1171. bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1172. #endif
  1173. // Get readings
  1174. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1175. sensor_magnitude_t magnitude = _magnitudes[i];
  1176. if (magnitude.sensor->status()) {
  1177. // -------------------------------------------------------------
  1178. // Instant value
  1179. // -------------------------------------------------------------
  1180. value_raw = magnitude.sensor->value(magnitude.local);
  1181. // Completely remove spurious values if relay is OFF
  1182. #if SENSOR_POWER_CHECK_STATUS
  1183. if (relay_off) {
  1184. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1185. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1186. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1187. magnitude.type == MAGNITUDE_CURRENT ||
  1188. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1189. ) {
  1190. value_raw = 0;
  1191. }
  1192. }
  1193. #endif
  1194. _magnitudes[i].last = value_raw;
  1195. // -------------------------------------------------------------
  1196. // Processing (filters)
  1197. // -------------------------------------------------------------
  1198. magnitude.filter->add(value_raw);
  1199. // Special case for MovingAverageFilter
  1200. if (MAGNITUDE_COUNT == magnitude.type ||
  1201. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1202. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1203. value_raw = magnitude.filter->result();
  1204. }
  1205. // -------------------------------------------------------------
  1206. // Procesing (units and decimals)
  1207. // -------------------------------------------------------------
  1208. value_show = _magnitudeProcess(magnitude.type, magnitude.decimals, value_raw);
  1209. // -------------------------------------------------------------
  1210. // Debug
  1211. // -------------------------------------------------------------
  1212. #if SENSOR_DEBUG
  1213. {
  1214. char buffer[64];
  1215. dtostrf(value_show, 1-sizeof(buffer), magnitude.decimals, buffer);
  1216. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1217. magnitude.sensor->slot(magnitude.local).c_str(),
  1218. magnitudeTopic(magnitude.type).c_str(),
  1219. buffer,
  1220. magnitudeUnits(magnitude.type).c_str()
  1221. );
  1222. }
  1223. #endif // SENSOR_DEBUG
  1224. // -------------------------------------------------------------
  1225. // Report
  1226. // (we do it every _sensor_report_every readings)
  1227. // -------------------------------------------------------------
  1228. bool report = (0 == report_count);
  1229. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1230. // for MAGNITUDE_ENERGY, filtered value is last value
  1231. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  1232. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1233. if (report) {
  1234. value_filtered = magnitude.filter->result();
  1235. value_filtered = _magnitudeProcess(magnitude.type, magnitude.decimals, value_filtered);
  1236. magnitude.filter->reset();
  1237. // Check if there is a minimum change threshold to report
  1238. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  1239. _magnitudes[i].reported = value_filtered;
  1240. _sensorReport(i, value_filtered);
  1241. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  1242. // -------------------------------------------------------------
  1243. // Saving to EEPROM
  1244. // (we do it every _sensor_save_every readings)
  1245. // -------------------------------------------------------------
  1246. if (_sensor_save_every > 0) {
  1247. save_count = (save_count + 1) % _sensor_save_every;
  1248. if (0 == save_count) {
  1249. if (MAGNITUDE_ENERGY == magnitude.type) {
  1250. setSetting("eneTotal", value_raw);
  1251. saveSettings();
  1252. }
  1253. } // if (0 == save_count)
  1254. } // if (_sensor_save_every > 0)
  1255. } // if (report_count == 0)
  1256. } // if (magnitude.sensor->status())
  1257. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1258. // Post-read hook
  1259. _sensorPost();
  1260. #if WEB_SUPPORT
  1261. wsSend(_sensorWebSocketSendData);
  1262. #endif
  1263. #if THINGSPEAK_SUPPORT
  1264. if (report_count == 0) tspkFlush();
  1265. #endif
  1266. }
  1267. }
  1268. #endif // SENSOR_SUPPORT