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.

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