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.

1476 lines
48 KiB

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