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.

1475 lines
48 KiB

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