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.

1485 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
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. #endif
  633. #if VEML6075_SUPPORT
  634. {
  635. VEML6075Sensor * sensor = new VEML6075Sensor();
  636. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  637. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  638. _sensors.push_back(sensor);
  639. }
  640. #endif
  641. #if VL53L1X_SUPPORT
  642. {
  643. VL53L1XSensor * sensor = new VL53L1XSensor();
  644. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  645. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  646. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  647. _sensors.push_back(sensor);
  648. }
  649. #endif
  650. }
  651. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  652. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  653. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  654. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  655. _sensorReport(k, value);
  656. return;
  657. }
  658. }
  659. }
  660. void _sensorInit() {
  661. _sensors_ready = true;
  662. _sensor_save_every = getSetting("snsSave", 0).toInt();
  663. for (unsigned char i=0; i<_sensors.size(); i++) {
  664. // Do not process an already initialized sensor
  665. if (_sensors[i]->ready()) continue;
  666. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  667. // Force sensor to reload config
  668. _sensors[i]->begin();
  669. if (!_sensors[i]->ready()) {
  670. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  671. _sensors_ready = false;
  672. continue;
  673. }
  674. // Initialize magnitudes
  675. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  676. unsigned char type = _sensors[i]->type(k);
  677. sensor_magnitude_t new_magnitude;
  678. new_magnitude.sensor = _sensors[i];
  679. new_magnitude.local = k;
  680. new_magnitude.type = type;
  681. new_magnitude.global = _counts[type];
  682. new_magnitude.current = 0;
  683. new_magnitude.reported = 0;
  684. new_magnitude.min_change = 0;
  685. new_magnitude.max_change = 0;
  686. // TODO: find a proper way to extend this to min/max of any magnitude
  687. if (MAGNITUDE_ENERGY == type) {
  688. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  689. } else if (MAGNITUDE_TEMPERATURE == type) {
  690. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  691. } else if (MAGNITUDE_HUMIDITY == type) {
  692. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  693. }
  694. if (MAGNITUDE_ENERGY == type) {
  695. new_magnitude.filter = new LastFilter();
  696. } else if (MAGNITUDE_DIGITAL == type) {
  697. new_magnitude.filter = new MaxFilter();
  698. } 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.
  699. new_magnitude.filter = new MovingAverageFilter();
  700. } else {
  701. new_magnitude.filter = new MedianFilter();
  702. }
  703. new_magnitude.filter->resize(_sensor_report_every);
  704. _magnitudes.push_back(new_magnitude);
  705. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  706. _counts[type] = _counts[type] + 1;
  707. }
  708. // Hook callback
  709. _sensors[i]->onEvent([i](unsigned char type, double value) {
  710. _sensorCallback(i, type, value);
  711. });
  712. // Custom initializations
  713. #if MICS2710_SUPPORT
  714. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  715. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  716. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  717. }
  718. #endif // MICS2710_SUPPORT
  719. #if MICS5525_SUPPORT
  720. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  721. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  722. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  723. }
  724. #endif // MICS5525_SUPPORT
  725. #if EMON_ANALOG_SUPPORT
  726. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  727. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  728. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  729. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  730. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  731. if (value > 0) sensor->resetEnergy(0, value);
  732. }
  733. #endif // EMON_ANALOG_SUPPORT
  734. #if HLW8012_SUPPORT
  735. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  736. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  737. double value;
  738. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  739. if (value > 0) sensor->setCurrentRatio(value);
  740. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  741. if (value > 0) sensor->setVoltageRatio(value);
  742. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  743. if (value > 0) sensor->setPowerRatio(value);
  744. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  745. if (value > 0) sensor->resetEnergy(value);
  746. }
  747. #endif // HLW8012_SUPPORT
  748. #if CSE7766_SUPPORT
  749. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  750. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  751. double value;
  752. value = getSetting("pwrRatioC", 0).toFloat();
  753. if (value > 0) sensor->setCurrentRatio(value);
  754. value = getSetting("pwrRatioV", 0).toFloat();
  755. if (value > 0) sensor->setVoltageRatio(value);
  756. value = getSetting("pwrRatioP", 0).toFloat();
  757. if (value > 0) sensor->setPowerRatio(value);
  758. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  759. if (value > 0) sensor->resetEnergy(value);
  760. }
  761. #endif // CSE7766_SUPPORT
  762. #if PULSEMETER_SUPPORT
  763. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  764. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  765. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  766. }
  767. #endif // PULSEMETER_SUPPORT
  768. }
  769. }
  770. void _sensorConfigure() {
  771. // General sensor settings
  772. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  773. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  774. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  775. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  776. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  777. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  778. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  779. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  780. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  781. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  782. // Specific sensor settings
  783. for (unsigned char i=0; i<_sensors.size(); i++) {
  784. #if MICS2710_SUPPORT
  785. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  786. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  787. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  788. sensor->calibrate();
  789. setSetting("snsR0", sensor->getR0());
  790. }
  791. }
  792. #endif // MICS2710_SUPPORT
  793. #if MICS5525_SUPPORT
  794. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  795. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  796. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  797. sensor->calibrate();
  798. setSetting("snsR0", sensor->getR0());
  799. }
  800. }
  801. #endif // MICS5525_SUPPORT
  802. #if EMON_ANALOG_SUPPORT
  803. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  804. double value;
  805. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  806. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  807. sensor->expectedPower(0, value);
  808. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  809. }
  810. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  811. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  812. delSetting("pwrRatioC");
  813. }
  814. if (getSetting("pwrResetE", 0).toInt() == 1) {
  815. sensor->resetEnergy();
  816. delSetting("eneTotal");
  817. _sensorResetTS();
  818. }
  819. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  820. }
  821. #endif // EMON_ANALOG_SUPPORT
  822. #if EMON_ADC121_SUPPORT
  823. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  824. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  825. if (getSetting("pwrResetE", 0).toInt() == 1) {
  826. sensor->resetEnergy();
  827. delSetting("eneTotal");
  828. _sensorResetTS();
  829. }
  830. }
  831. #endif
  832. #if EMON_ADS1X15_SUPPORT
  833. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  834. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  835. if (getSetting("pwrResetE", 0).toInt() == 1) {
  836. sensor->resetEnergy();
  837. delSetting("eneTotal");
  838. _sensorResetTS();
  839. }
  840. }
  841. #endif
  842. #if HLW8012_SUPPORT
  843. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  844. double value;
  845. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  846. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  847. sensor->expectedCurrent(value);
  848. setSetting("pwrRatioC", sensor->getCurrentRatio());
  849. }
  850. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  851. sensor->expectedVoltage(value);
  852. setSetting("pwrRatioV", sensor->getVoltageRatio());
  853. }
  854. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  855. sensor->expectedPower(value);
  856. setSetting("pwrRatioP", sensor->getPowerRatio());
  857. }
  858. if (getSetting("pwrResetE", 0).toInt() == 1) {
  859. sensor->resetEnergy();
  860. delSetting("eneTotal");
  861. _sensorResetTS();
  862. }
  863. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  864. sensor->resetRatios();
  865. delSetting("pwrRatioC");
  866. delSetting("pwrRatioV");
  867. delSetting("pwrRatioP");
  868. }
  869. }
  870. #endif // HLW8012_SUPPORT
  871. #if CSE7766_SUPPORT
  872. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  873. double value;
  874. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  875. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  876. sensor->expectedCurrent(value);
  877. setSetting("pwrRatioC", sensor->getCurrentRatio());
  878. }
  879. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  880. sensor->expectedVoltage(value);
  881. setSetting("pwrRatioV", sensor->getVoltageRatio());
  882. }
  883. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  884. sensor->expectedPower(value);
  885. setSetting("pwrRatioP", sensor->getPowerRatio());
  886. }
  887. if (getSetting("pwrResetE", 0).toInt() == 1) {
  888. sensor->resetEnergy();
  889. delSetting("eneTotal");
  890. _sensorResetTS();
  891. }
  892. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  893. sensor->resetRatios();
  894. delSetting("pwrRatioC");
  895. delSetting("pwrRatioV");
  896. delSetting("pwrRatioP");
  897. }
  898. }
  899. #endif // CSE7766_SUPPORT
  900. #if PULSEMETER_SUPPORT
  901. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  902. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  903. if (getSetting("pwrResetE", 0).toInt() == 1) {
  904. sensor->resetEnergy();
  905. delSetting("eneTotal");
  906. _sensorResetTS();
  907. }
  908. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  909. }
  910. #endif // PULSEMETER_SUPPORT
  911. #if PZEM004T_SUPPORT
  912. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  913. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  914. if (getSetting("pwrResetE", 0).toInt() == 1) {
  915. unsigned char dev_count = sensor->getAddressesCount();
  916. for(unsigned char dev = 0; dev < dev_count; dev++) {
  917. sensor->resetEnergy(dev, 0);
  918. delSetting("pzEneTotal", dev);
  919. }
  920. _sensorResetTS();
  921. }
  922. }
  923. #endif // PZEM004T_SUPPORT
  924. }
  925. // Update filter sizes
  926. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  927. _magnitudes[i].filter->resize(_sensor_report_every);
  928. }
  929. // General processing
  930. if (0 == _sensor_save_every) {
  931. delSetting("eneTotal");
  932. }
  933. // Save settings
  934. delSetting("snsResetCalibration");
  935. delSetting("pwrExpectedP");
  936. delSetting("pwrExpectedC");
  937. delSetting("pwrExpectedV");
  938. delSetting("pwrResetCalibration");
  939. delSetting("pwrResetE");
  940. saveSettings();
  941. }
  942. void _sensorReport(unsigned char index, double value) {
  943. sensor_magnitude_t magnitude = _magnitudes[index];
  944. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  945. char buffer[10];
  946. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  947. #if BROKER_SUPPORT
  948. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  949. #endif
  950. #if MQTT_SUPPORT
  951. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  952. #if SENSOR_PUBLISH_ADDRESSES
  953. char topic[32];
  954. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  955. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  956. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  957. } else {
  958. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  959. }
  960. #endif // SENSOR_PUBLISH_ADDRESSES
  961. #endif // MQTT_SUPPORT
  962. #if INFLUXDB_SUPPORT
  963. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  964. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  965. } else {
  966. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  967. }
  968. #endif // INFLUXDB_SUPPORT
  969. #if THINGSPEAK_SUPPORT
  970. tspkEnqueueMeasurement(index, buffer);
  971. #endif
  972. #if DOMOTICZ_SUPPORT
  973. {
  974. char key[15];
  975. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  976. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  977. int status;
  978. if (value > 70) {
  979. status = HUMIDITY_WET;
  980. } else if (value > 45) {
  981. status = HUMIDITY_COMFORTABLE;
  982. } else if (value > 30) {
  983. status = HUMIDITY_NORMAL;
  984. } else {
  985. status = HUMIDITY_DRY;
  986. }
  987. char status_buf[5];
  988. itoa(status, status_buf, 10);
  989. domoticzSend(key, buffer, status_buf);
  990. } else {
  991. domoticzSend(key, 0, buffer);
  992. }
  993. }
  994. #endif // DOMOTICZ_SUPPORT
  995. }
  996. // -----------------------------------------------------------------------------
  997. // Public
  998. // -----------------------------------------------------------------------------
  999. unsigned char sensorCount() {
  1000. return _sensors.size();
  1001. }
  1002. unsigned char magnitudeCount() {
  1003. return _magnitudes.size();
  1004. }
  1005. String magnitudeName(unsigned char index) {
  1006. if (index < _magnitudes.size()) {
  1007. sensor_magnitude_t magnitude = _magnitudes[index];
  1008. return magnitude.sensor->slot(magnitude.local);
  1009. }
  1010. return String();
  1011. }
  1012. unsigned char magnitudeType(unsigned char index) {
  1013. if (index < _magnitudes.size()) {
  1014. return int(_magnitudes[index].type);
  1015. }
  1016. return MAGNITUDE_NONE;
  1017. }
  1018. unsigned char magnitudeIndex(unsigned char index) {
  1019. if (index < _magnitudes.size()) {
  1020. return int(_magnitudes[index].global);
  1021. }
  1022. return 0;
  1023. }
  1024. String magnitudeTopic(unsigned char type) {
  1025. char buffer[16] = {0};
  1026. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1027. return String(buffer);
  1028. }
  1029. String magnitudeTopicIndex(unsigned char index) {
  1030. char topic[32] = {0};
  1031. if (index < _magnitudes.size()) {
  1032. sensor_magnitude_t magnitude = _magnitudes[index];
  1033. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1034. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1035. } else {
  1036. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1037. }
  1038. }
  1039. return String(topic);
  1040. }
  1041. String magnitudeUnits(unsigned char type) {
  1042. char buffer[8] = {0};
  1043. if (type < MAGNITUDE_MAX) {
  1044. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1045. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1046. } else if (
  1047. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1048. (_sensor_energy_units == ENERGY_KWH)) {
  1049. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1050. } else if (
  1051. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1052. (_sensor_power_units == POWER_KILOWATTS)) {
  1053. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1054. } else {
  1055. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1056. }
  1057. }
  1058. return String(buffer);
  1059. }
  1060. // -----------------------------------------------------------------------------
  1061. void sensorSetup() {
  1062. // Backwards compatibility
  1063. moveSetting("powerUnits", "pwrUnits");
  1064. moveSetting("energyUnits", "eneUnits");
  1065. // Load sensors
  1066. _sensorLoad();
  1067. _sensorInit();
  1068. // Configure stored values
  1069. _sensorConfigure();
  1070. // Websockets
  1071. #if WEB_SUPPORT
  1072. wsOnSendRegister(_sensorWebSocketStart);
  1073. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1074. wsOnSendRegister(_sensorWebSocketSendData);
  1075. #endif
  1076. // API
  1077. #if API_SUPPORT
  1078. _sensorAPISetup();
  1079. #endif
  1080. // Terminal
  1081. #if TERMINAL_SUPPORT
  1082. _sensorInitCommands();
  1083. #endif
  1084. // Main callbacks
  1085. espurnaRegisterLoop(sensorLoop);
  1086. espurnaRegisterReload(_sensorConfigure);
  1087. }
  1088. void sensorLoop() {
  1089. // Check if we still have uninitialized sensors
  1090. static unsigned long last_init = 0;
  1091. if (!_sensors_ready) {
  1092. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1093. last_init = millis();
  1094. _sensorInit();
  1095. }
  1096. }
  1097. if (_magnitudes.size() == 0) return;
  1098. // Tick hook
  1099. _sensorTick();
  1100. // Check if we should read new data
  1101. static unsigned long last_update = 0;
  1102. static unsigned long report_count = 0;
  1103. static unsigned long save_count = 0;
  1104. if (millis() - last_update > _sensor_read_interval) {
  1105. last_update = millis();
  1106. report_count = (report_count + 1) % _sensor_report_every;
  1107. double current;
  1108. double filtered;
  1109. // Pre-read hook
  1110. _sensorPre();
  1111. // Get the first relay state
  1112. #if SENSOR_POWER_CHECK_STATUS
  1113. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  1114. #endif
  1115. // Get readings
  1116. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1117. sensor_magnitude_t magnitude = _magnitudes[i];
  1118. if (magnitude.sensor->status()) {
  1119. // -------------------------------------------------------------
  1120. // Instant value
  1121. // -------------------------------------------------------------
  1122. current = magnitude.sensor->value(magnitude.local);
  1123. // Completely remove spurious values if relay is OFF
  1124. #if SENSOR_POWER_CHECK_STATUS
  1125. if (relay_off) {
  1126. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1127. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1128. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1129. magnitude.type == MAGNITUDE_CURRENT ||
  1130. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1131. ) {
  1132. current = 0;
  1133. }
  1134. }
  1135. #endif
  1136. // -------------------------------------------------------------
  1137. // Processing (filters)
  1138. // -------------------------------------------------------------
  1139. magnitude.filter->add(current);
  1140. // Special case for MovingAvergaeFilter
  1141. if (MAGNITUDE_COUNT == magnitude.type ||
  1142. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1143. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1144. current = magnitude.filter->result();
  1145. }
  1146. current = _magnitudeProcess(magnitude.type, current);
  1147. _magnitudes[i].current = current;
  1148. // -------------------------------------------------------------
  1149. // Debug
  1150. // -------------------------------------------------------------
  1151. #if SENSOR_DEBUG
  1152. {
  1153. char buffer[64];
  1154. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1155. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1156. magnitude.sensor->slot(magnitude.local).c_str(),
  1157. magnitudeTopic(magnitude.type).c_str(),
  1158. buffer,
  1159. magnitudeUnits(magnitude.type).c_str()
  1160. );
  1161. }
  1162. #endif // SENSOR_DEBUG
  1163. // -------------------------------------------------------------
  1164. // Report
  1165. // (we do it every _sensor_report_every readings)
  1166. // -------------------------------------------------------------
  1167. bool report = (0 == report_count);
  1168. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1169. // for MAGNITUDE_ENERGY, filtered value is last value
  1170. double value = _magnitudeProcess(magnitude.type, current);
  1171. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1172. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1173. if (report) {
  1174. filtered = magnitude.filter->result();
  1175. filtered = _magnitudeProcess(magnitude.type, filtered);
  1176. magnitude.filter->reset();
  1177. // Check if there is a minimum change threshold to report
  1178. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1179. _magnitudes[i].reported = filtered;
  1180. _sensorReport(i, filtered);
  1181. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1182. // -------------------------------------------------------------
  1183. // Saving to EEPROM
  1184. // (we do it every _sensor_save_every readings)
  1185. // -------------------------------------------------------------
  1186. if (_sensor_save_every > 0) {
  1187. save_count = (save_count + 1) % _sensor_save_every;
  1188. if (0 == save_count) {
  1189. if (MAGNITUDE_ENERGY == magnitude.type) {
  1190. setSetting("eneTotal", current);
  1191. saveSettings();
  1192. }
  1193. } // if (0 == save_count)
  1194. } // if (_sensor_save_every > 0)
  1195. } // if (report_count == 0)
  1196. } // if (magnitude.sensor->status())
  1197. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1198. // Post-read hook
  1199. _sensorPost();
  1200. #if WEB_SUPPORT
  1201. wsSend(_sensorWebSocketSendData);
  1202. #endif
  1203. #if THINGSPEAK_SUPPORT
  1204. if (report_count == 0) tspkFlush();
  1205. #endif
  1206. }
  1207. }
  1208. #endif // SENSOR_SUPPORT