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.

1471 lines
48 KiB

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