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

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