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.

1467 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. _sensors.push_back(sensor);
  552. }
  553. #endif
  554. #if PZEM004T_SUPPORT
  555. {
  556. PZEM004TSensor * sensor = pzem004t_sensor = new PZEM004TSensor();
  557. #if PZEM004T_USE_SOFT
  558. sensor->setRX(PZEM004T_RX_PIN);
  559. sensor->setTX(PZEM004T_TX_PIN);
  560. #else
  561. sensor->setSerial(& PZEM004T_HW_PORT);
  562. #endif
  563. sensor->setAddresses(PZEM004T_ADDRESSES);
  564. // Read saved energy offset
  565. unsigned char dev_count = sensor->getAddressesCount();
  566. for(unsigned char dev = 0; dev < dev_count; dev++) {
  567. float value = getSetting("pzEneTotal", dev, 0).toFloat();
  568. if (value > 0) sensor->resetEnergy(dev, value);
  569. }
  570. _sensors.push_back(sensor);
  571. }
  572. #endif
  573. #if SENSEAIR_SUPPORT
  574. {
  575. SenseAirSensor * sensor = new SenseAirSensor();
  576. sensor->setRX(SENSEAIR_RX_PIN);
  577. sensor->setTX(SENSEAIR_TX_PIN);
  578. _sensors.push_back(sensor);
  579. }
  580. #endif
  581. #if SDS011_SUPPORT
  582. {
  583. SDS011Sensor * sensor = new SDS011Sensor();
  584. sensor->setRX(SDS011_RX_PIN);
  585. sensor->setTX(SDS011_TX_PIN);
  586. _sensors.push_back(sensor);
  587. }
  588. #endif
  589. #if SHT3X_I2C_SUPPORT
  590. {
  591. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  592. sensor->setAddress(SHT3X_I2C_ADDRESS);
  593. _sensors.push_back(sensor);
  594. }
  595. #endif
  596. #if SI7021_SUPPORT
  597. {
  598. SI7021Sensor * sensor = new SI7021Sensor();
  599. sensor->setAddress(SI7021_ADDRESS);
  600. _sensors.push_back(sensor);
  601. }
  602. #endif
  603. #if TMP3X_SUPPORT
  604. {
  605. TMP3XSensor * sensor = new TMP3XSensor();
  606. sensor->setType(TMP3X_TYPE);
  607. _sensors.push_back(sensor);
  608. }
  609. #endif
  610. #if V9261F_SUPPORT
  611. {
  612. V9261FSensor * sensor = new V9261FSensor();
  613. sensor->setRX(V9261F_PIN);
  614. sensor->setInverted(V9261F_PIN_INVERSE);
  615. _sensors.push_back(sensor);
  616. }
  617. #endif
  618. #if VEML6075_SUPPORT
  619. {
  620. VEML6075Sensor * sensor = new VEML6075Sensor();
  621. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  622. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  623. _sensors.push_back(sensor);
  624. }
  625. #endif
  626. #if VL53L1X_SUPPORT
  627. {
  628. VL53L1XSensor * sensor = new VL53L1XSensor();
  629. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  630. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  631. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  632. _sensors.push_back(sensor);
  633. }
  634. #endif
  635. }
  636. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  637. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  638. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  639. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  640. _sensorReport(k, value);
  641. return;
  642. }
  643. }
  644. }
  645. void _sensorInit() {
  646. _sensors_ready = true;
  647. _sensor_save_every = getSetting("snsSave", 0).toInt();
  648. for (unsigned char i=0; i<_sensors.size(); i++) {
  649. // Do not process an already initialized sensor
  650. if (_sensors[i]->ready()) continue;
  651. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  652. // Force sensor to reload config
  653. _sensors[i]->begin();
  654. if (!_sensors[i]->ready()) {
  655. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  656. _sensors_ready = false;
  657. continue;
  658. }
  659. // Initialize magnitudes
  660. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  661. unsigned char type = _sensors[i]->type(k);
  662. sensor_magnitude_t new_magnitude;
  663. new_magnitude.sensor = _sensors[i];
  664. new_magnitude.local = k;
  665. new_magnitude.type = type;
  666. new_magnitude.global = _counts[type];
  667. new_magnitude.current = 0;
  668. new_magnitude.reported = 0;
  669. new_magnitude.min_change = 0;
  670. new_magnitude.max_change = 0;
  671. // TODO: find a proper way to extend this to min/max of any magnitude
  672. if (MAGNITUDE_ENERGY == type) {
  673. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  674. } else if (MAGNITUDE_TEMPERATURE == type) {
  675. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  676. } else if (MAGNITUDE_HUMIDITY == type) {
  677. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  678. }
  679. if (MAGNITUDE_ENERGY == type) {
  680. new_magnitude.filter = new LastFilter();
  681. } else if (MAGNITUDE_DIGITAL == type) {
  682. new_magnitude.filter = new MaxFilter();
  683. } 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.
  684. new_magnitude.filter = new MovingAverageFilter();
  685. } else {
  686. new_magnitude.filter = new MedianFilter();
  687. }
  688. new_magnitude.filter->resize(_sensor_report_every);
  689. _magnitudes.push_back(new_magnitude);
  690. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  691. _counts[type] = _counts[type] + 1;
  692. }
  693. // Hook callback
  694. _sensors[i]->onEvent([i](unsigned char type, double value) {
  695. _sensorCallback(i, type, value);
  696. });
  697. // Custom initializations
  698. #if MICS2710_SUPPORT
  699. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  700. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  701. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  702. }
  703. #endif // MICS2710_SUPPORT
  704. #if MICS5525_SUPPORT
  705. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  706. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  707. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  708. }
  709. #endif // MICS5525_SUPPORT
  710. #if EMON_ANALOG_SUPPORT
  711. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  712. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  713. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  714. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  715. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  716. if (value > 0) sensor->resetEnergy(0, value);
  717. }
  718. #endif // EMON_ANALOG_SUPPORT
  719. #if HLW8012_SUPPORT
  720. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  721. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  722. double value;
  723. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  724. if (value > 0) sensor->setCurrentRatio(value);
  725. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  726. if (value > 0) sensor->setVoltageRatio(value);
  727. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  728. if (value > 0) sensor->setPowerRatio(value);
  729. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  730. if (value > 0) sensor->resetEnergy(value);
  731. }
  732. #endif // HLW8012_SUPPORT
  733. #if CSE7766_SUPPORT
  734. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  735. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  736. double value;
  737. value = getSetting("pwrRatioC", 0).toFloat();
  738. if (value > 0) sensor->setCurrentRatio(value);
  739. value = getSetting("pwrRatioV", 0).toFloat();
  740. if (value > 0) sensor->setVoltageRatio(value);
  741. value = getSetting("pwrRatioP", 0).toFloat();
  742. if (value > 0) sensor->setPowerRatio(value);
  743. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  744. if (value > 0) sensor->resetEnergy(value);
  745. }
  746. #endif // CSE7766_SUPPORT
  747. #if PULSEMETER_SUPPORT
  748. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  749. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  750. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  751. }
  752. #endif // PULSEMETER_SUPPORT
  753. }
  754. }
  755. void _sensorConfigure() {
  756. // General sensor settings
  757. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  758. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  759. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  760. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  761. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  762. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  763. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  764. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  765. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  766. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  767. // Specific sensor settings
  768. for (unsigned char i=0; i<_sensors.size(); i++) {
  769. #if MICS2710_SUPPORT
  770. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  771. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  772. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  773. sensor->calibrate();
  774. setSetting("snsR0", sensor->getR0());
  775. }
  776. }
  777. #endif // MICS2710_SUPPORT
  778. #if MICS5525_SUPPORT
  779. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  780. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  781. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  782. sensor->calibrate();
  783. setSetting("snsR0", sensor->getR0());
  784. }
  785. }
  786. #endif // MICS5525_SUPPORT
  787. #if EMON_ANALOG_SUPPORT
  788. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  789. double value;
  790. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  791. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  792. sensor->expectedPower(0, value);
  793. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  794. }
  795. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  796. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  797. delSetting("pwrRatioC");
  798. }
  799. if (getSetting("pwrResetE", 0).toInt() == 1) {
  800. sensor->resetEnergy();
  801. delSetting("eneTotal");
  802. _sensorResetTS();
  803. }
  804. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  805. }
  806. #endif // EMON_ANALOG_SUPPORT
  807. #if EMON_ADC121_SUPPORT
  808. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  809. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  810. if (getSetting("pwrResetE", 0).toInt() == 1) {
  811. sensor->resetEnergy();
  812. delSetting("eneTotal");
  813. _sensorResetTS();
  814. }
  815. }
  816. #endif
  817. #if EMON_ADS1X15_SUPPORT
  818. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  819. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  820. if (getSetting("pwrResetE", 0).toInt() == 1) {
  821. sensor->resetEnergy();
  822. delSetting("eneTotal");
  823. _sensorResetTS();
  824. }
  825. }
  826. #endif
  827. #if HLW8012_SUPPORT
  828. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  829. double value;
  830. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  831. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  832. sensor->expectedCurrent(value);
  833. setSetting("pwrRatioC", sensor->getCurrentRatio());
  834. }
  835. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  836. sensor->expectedVoltage(value);
  837. setSetting("pwrRatioV", sensor->getVoltageRatio());
  838. }
  839. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  840. sensor->expectedPower(value);
  841. setSetting("pwrRatioP", sensor->getPowerRatio());
  842. }
  843. if (getSetting("pwrResetE", 0).toInt() == 1) {
  844. sensor->resetEnergy();
  845. delSetting("eneTotal");
  846. _sensorResetTS();
  847. }
  848. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  849. sensor->resetRatios();
  850. delSetting("pwrRatioC");
  851. delSetting("pwrRatioV");
  852. delSetting("pwrRatioP");
  853. }
  854. }
  855. #endif // HLW8012_SUPPORT
  856. #if CSE7766_SUPPORT
  857. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  858. double value;
  859. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  860. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  861. sensor->expectedCurrent(value);
  862. setSetting("pwrRatioC", sensor->getCurrentRatio());
  863. }
  864. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  865. sensor->expectedVoltage(value);
  866. setSetting("pwrRatioV", sensor->getVoltageRatio());
  867. }
  868. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  869. sensor->expectedPower(value);
  870. setSetting("pwrRatioP", sensor->getPowerRatio());
  871. }
  872. if (getSetting("pwrResetE", 0).toInt() == 1) {
  873. sensor->resetEnergy();
  874. delSetting("eneTotal");
  875. _sensorResetTS();
  876. }
  877. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  878. sensor->resetRatios();
  879. delSetting("pwrRatioC");
  880. delSetting("pwrRatioV");
  881. delSetting("pwrRatioP");
  882. }
  883. }
  884. #endif // CSE7766_SUPPORT
  885. #if PULSEMETER_SUPPORT
  886. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  887. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  888. if (getSetting("pwrResetE", 0).toInt() == 1) {
  889. sensor->resetEnergy();
  890. delSetting("eneTotal");
  891. _sensorResetTS();
  892. }
  893. }
  894. #endif // PULSEMETER_SUPPORT
  895. #if PZEM004T_SUPPORT
  896. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  897. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  898. if (getSetting("pwrResetE", 0).toInt() == 1) {
  899. unsigned char dev_count = sensor->getAddressesCount();
  900. for(unsigned char dev = 0; dev < dev_count; dev++) {
  901. sensor->resetEnergy(dev, 0);
  902. delSetting("pzEneTotal", dev);
  903. }
  904. _sensorResetTS();
  905. }
  906. }
  907. #endif // PZEM004T_SUPPORT
  908. }
  909. // Update filter sizes
  910. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  911. _magnitudes[i].filter->resize(_sensor_report_every);
  912. }
  913. // General processing
  914. if (0 == _sensor_save_every) {
  915. delSetting("eneTotal");
  916. }
  917. // Save settings
  918. delSetting("snsResetCalibration");
  919. delSetting("pwrExpectedP");
  920. delSetting("pwrExpectedC");
  921. delSetting("pwrExpectedV");
  922. delSetting("pwrResetCalibration");
  923. delSetting("pwrResetE");
  924. saveSettings();
  925. }
  926. void _sensorReport(unsigned char index, double value) {
  927. sensor_magnitude_t magnitude = _magnitudes[index];
  928. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  929. char buffer[10];
  930. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  931. #if BROKER_SUPPORT
  932. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  933. #endif
  934. #if MQTT_SUPPORT
  935. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  936. #if SENSOR_PUBLISH_ADDRESSES
  937. char topic[32];
  938. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  939. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  940. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  941. } else {
  942. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  943. }
  944. #endif // SENSOR_PUBLISH_ADDRESSES
  945. #endif // MQTT_SUPPORT
  946. #if INFLUXDB_SUPPORT
  947. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  948. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  949. } else {
  950. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  951. }
  952. #endif // INFLUXDB_SUPPORT
  953. #if THINGSPEAK_SUPPORT
  954. tspkEnqueueMeasurement(index, buffer);
  955. #endif
  956. #if DOMOTICZ_SUPPORT
  957. {
  958. char key[15];
  959. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  960. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  961. int status;
  962. if (value > 70) {
  963. status = HUMIDITY_WET;
  964. } else if (value > 45) {
  965. status = HUMIDITY_COMFORTABLE;
  966. } else if (value > 30) {
  967. status = HUMIDITY_NORMAL;
  968. } else {
  969. status = HUMIDITY_DRY;
  970. }
  971. char status_buf[5];
  972. itoa(status, status_buf, 10);
  973. domoticzSend(key, buffer, status_buf);
  974. } else {
  975. domoticzSend(key, 0, buffer);
  976. }
  977. }
  978. #endif // DOMOTICZ_SUPPORT
  979. }
  980. // -----------------------------------------------------------------------------
  981. // Public
  982. // -----------------------------------------------------------------------------
  983. unsigned char sensorCount() {
  984. return _sensors.size();
  985. }
  986. unsigned char magnitudeCount() {
  987. return _magnitudes.size();
  988. }
  989. String magnitudeName(unsigned char index) {
  990. if (index < _magnitudes.size()) {
  991. sensor_magnitude_t magnitude = _magnitudes[index];
  992. return magnitude.sensor->slot(magnitude.local);
  993. }
  994. return String();
  995. }
  996. unsigned char magnitudeType(unsigned char index) {
  997. if (index < _magnitudes.size()) {
  998. return int(_magnitudes[index].type);
  999. }
  1000. return MAGNITUDE_NONE;
  1001. }
  1002. unsigned char magnitudeIndex(unsigned char index) {
  1003. if (index < _magnitudes.size()) {
  1004. return int(_magnitudes[index].global);
  1005. }
  1006. return 0;
  1007. }
  1008. String magnitudeTopic(unsigned char type) {
  1009. char buffer[16] = {0};
  1010. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1011. return String(buffer);
  1012. }
  1013. String magnitudeTopicIndex(unsigned char index) {
  1014. char topic[32] = {0};
  1015. if (index < _magnitudes.size()) {
  1016. sensor_magnitude_t magnitude = _magnitudes[index];
  1017. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1018. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1019. } else {
  1020. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1021. }
  1022. }
  1023. return String(topic);
  1024. }
  1025. String magnitudeUnits(unsigned char type) {
  1026. char buffer[8] = {0};
  1027. if (type < MAGNITUDE_MAX) {
  1028. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1029. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1030. } else if (
  1031. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1032. (_sensor_energy_units == ENERGY_KWH)) {
  1033. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1034. } else if (
  1035. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1036. (_sensor_power_units == POWER_KILOWATTS)) {
  1037. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1038. } else {
  1039. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1040. }
  1041. }
  1042. return String(buffer);
  1043. }
  1044. // -----------------------------------------------------------------------------
  1045. void sensorSetup() {
  1046. // Backwards compatibility
  1047. moveSetting("powerUnits", "pwrUnits");
  1048. moveSetting("energyUnits", "eneUnits");
  1049. // Load sensors
  1050. _sensorLoad();
  1051. _sensorInit();
  1052. // Configure stored values
  1053. _sensorConfigure();
  1054. // Websockets
  1055. #if WEB_SUPPORT
  1056. wsOnSendRegister(_sensorWebSocketStart);
  1057. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1058. wsOnSendRegister(_sensorWebSocketSendData);
  1059. #endif
  1060. // API
  1061. #if API_SUPPORT
  1062. _sensorAPISetup();
  1063. #endif
  1064. // Terminal
  1065. #if TERMINAL_SUPPORT
  1066. _sensorInitCommands();
  1067. #endif
  1068. // Main callbacks
  1069. espurnaRegisterLoop(sensorLoop);
  1070. espurnaRegisterReload(_sensorConfigure);
  1071. }
  1072. void sensorLoop() {
  1073. // Check if we still have uninitialized sensors
  1074. static unsigned long last_init = 0;
  1075. if (!_sensors_ready) {
  1076. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1077. last_init = millis();
  1078. _sensorInit();
  1079. }
  1080. }
  1081. if (_magnitudes.size() == 0) return;
  1082. // Tick hook
  1083. _sensorTick();
  1084. // Check if we should read new data
  1085. static unsigned long last_update = 0;
  1086. static unsigned long report_count = 0;
  1087. static unsigned long save_count = 0;
  1088. if (millis() - last_update > _sensor_read_interval) {
  1089. last_update = millis();
  1090. report_count = (report_count + 1) % _sensor_report_every;
  1091. double current;
  1092. double filtered;
  1093. // Pre-read hook
  1094. _sensorPre();
  1095. // Get the first relay state
  1096. #if SENSOR_POWER_CHECK_STATUS
  1097. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  1098. #endif
  1099. // Get readings
  1100. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1101. sensor_magnitude_t magnitude = _magnitudes[i];
  1102. if (magnitude.sensor->status()) {
  1103. // -------------------------------------------------------------
  1104. // Instant value
  1105. // -------------------------------------------------------------
  1106. current = magnitude.sensor->value(magnitude.local);
  1107. // Completely remove spurious values if relay is OFF
  1108. #if SENSOR_POWER_CHECK_STATUS
  1109. if (relay_off) {
  1110. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1111. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1112. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1113. magnitude.type == MAGNITUDE_CURRENT ||
  1114. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1115. ) {
  1116. current = 0;
  1117. }
  1118. }
  1119. #endif
  1120. // -------------------------------------------------------------
  1121. // Processing (filters)
  1122. // -------------------------------------------------------------
  1123. magnitude.filter->add(current);
  1124. // Special case for MovingAvergaeFilter
  1125. if (MAGNITUDE_COUNT == magnitude.type ||
  1126. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1127. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1128. current = magnitude.filter->result();
  1129. }
  1130. current = _magnitudeProcess(magnitude.type, current);
  1131. _magnitudes[i].current = current;
  1132. // -------------------------------------------------------------
  1133. // Debug
  1134. // -------------------------------------------------------------
  1135. #if SENSOR_DEBUG
  1136. {
  1137. char buffer[64];
  1138. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1139. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1140. magnitude.sensor->slot(magnitude.local).c_str(),
  1141. magnitudeTopic(magnitude.type).c_str(),
  1142. buffer,
  1143. magnitudeUnits(magnitude.type).c_str()
  1144. );
  1145. }
  1146. #endif // SENSOR_DEBUG
  1147. // -------------------------------------------------------------
  1148. // Report
  1149. // (we do it every _sensor_report_every readings)
  1150. // -------------------------------------------------------------
  1151. bool report = (0 == report_count);
  1152. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1153. // for MAGNITUDE_ENERGY, filtered value is last value
  1154. double value = _magnitudeProcess(magnitude.type, current);
  1155. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1156. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1157. if (report) {
  1158. filtered = magnitude.filter->result();
  1159. filtered = _magnitudeProcess(magnitude.type, filtered);
  1160. magnitude.filter->reset();
  1161. // Check if there is a minimum change threshold to report
  1162. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1163. _magnitudes[i].reported = filtered;
  1164. _sensorReport(i, filtered);
  1165. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1166. // -------------------------------------------------------------
  1167. // Saving to EEPROM
  1168. // (we do it every _sensor_save_every readings)
  1169. // -------------------------------------------------------------
  1170. if (_sensor_save_every > 0) {
  1171. save_count = (save_count + 1) % _sensor_save_every;
  1172. if (0 == save_count) {
  1173. if (MAGNITUDE_ENERGY == magnitude.type) {
  1174. setSetting("eneTotal", current);
  1175. saveSettings();
  1176. }
  1177. } // if (0 == save_count)
  1178. } // if (_sensor_save_every > 0)
  1179. } // if (report_count == 0)
  1180. } // if (magnitude.sensor->status())
  1181. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1182. // Post-read hook
  1183. _sensorPost();
  1184. #if WEB_SUPPORT
  1185. wsSend(_sensorWebSocketSendData);
  1186. #endif
  1187. #if THINGSPEAK_SUPPORT
  1188. if (report_count == 0) tspkFlush();
  1189. #endif
  1190. }
  1191. }
  1192. #endif // SENSOR_SUPPORT