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.

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