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.

1484 lines
49 KiB

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