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.

1494 lines
49 KiB

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