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.

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