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.

1611 lines
53 KiB

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