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.

1545 lines
50 KiB

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