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.

1433 lines
47 KiB

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