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.

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