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.

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