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.

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