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.

1320 lines
47 KiB

6 years ago
6 years ago
6 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. Module key prefix: sns
  5. Magnitude-based key prefix: pwr ene cur vol tmp hum
  6. Sensor-based key previs: air am ana bh bmx cse dht dig ds ech emon evt gei guv hlw mhz ntc pms pzem sht son tmp3x v92
  7. */
  8. #if SENSOR_SUPPORT
  9. #include <vector>
  10. #include "filters/LastFilter.h"
  11. #include "filters/MaxFilter.h"
  12. #include "filters/MedianFilter.h"
  13. #include "filters/MovingAverageFilter.h"
  14. #include "sensors/BaseSensor.h"
  15. typedef struct {
  16. BaseSensor * sensor; // Sensor object
  17. BaseFilter * filter; // Filter object
  18. unsigned char local; // Local index in its provider
  19. unsigned char type; // Type of measurement
  20. unsigned char global; // Global index in its type
  21. double current; // Current (last) value, unfiltered
  22. double reported; // Last reported value
  23. double min_change; // Minimum value change to report
  24. double max_change; // Maximum value change to report
  25. } sensor_magnitude_t;
  26. std::vector<BaseSensor *> _sensors;
  27. std::vector<sensor_magnitude_t> _magnitudes;
  28. bool _sensors_ready = false;
  29. unsigned char _counts[MAGNITUDE_MAX];
  30. bool _sensor_realtime = API_REAL_TIME_VALUES;
  31. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  32. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  33. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  34. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  35. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  36. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  37. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  38. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  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. void _sensorWebSocketSendData(JsonObject& root) {
  80. char buffer[10];
  81. bool hasTemperature = false;
  82. bool hasHumidity = false;
  83. JsonArray& list = root.createNestedArray("magnitudes");
  84. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  85. sensor_magnitude_t magnitude = _magnitudes[i];
  86. if (magnitude.type == MAGNITUDE_EVENT) continue;
  87. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  88. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  89. JsonObject& element = list.createNestedObject();
  90. element["index"] = int(magnitude.global);
  91. element["type"] = int(magnitude.type);
  92. element["value"] = String(buffer);
  93. element["units"] = magnitudeUnits(magnitude.type);
  94. element["error"] = magnitude.sensor->error();
  95. if (magnitude.type == MAGNITUDE_ENERGY) {
  96. if (_sensor_energy_reset_ts.length() == 0) _sensorResetTS();
  97. element["description"] = magnitude.sensor->slot(magnitude.local) + String(" (since ") + _sensor_energy_reset_ts + String(")");
  98. } else {
  99. element["description"] = magnitude.sensor->slot(magnitude.local);
  100. }
  101. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  102. if (magnitude.type == MAGNITUDE_HUMIDITY) hasHumidity = true;
  103. }
  104. if (hasTemperature) root["tmpVisible"] = 1;
  105. if (hasHumidity) root["humVisible"] = 1;
  106. }
  107. void _sensorWebSocketStart(JsonObject& root) {
  108. for (unsigned char i=0; i<_sensors.size(); i++) {
  109. BaseSensor * sensor = _sensors[i];
  110. #if EMON_ANALOG_SUPPORT
  111. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  112. root["emonVisible"] = 1;
  113. root["pwrVisible"] = 1;
  114. root["volNominal"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  115. }
  116. #endif
  117. #if HLW8012_SUPPORT
  118. if (sensor->getID() == SENSOR_HLW8012_ID) {
  119. root["hlwVisible"] = 1;
  120. root["pwrVisible"] = 1;
  121. }
  122. #endif
  123. #if CSE7766_SUPPORT
  124. if (sensor->getID() == SENSOR_CSE7766_ID) {
  125. root["cseVisible"] = 1;
  126. root["pwrVisible"] = 1;
  127. }
  128. #endif
  129. #if V9261F_SUPPORT
  130. if (sensor->getID() == SENSOR_V9261F_ID) {
  131. root["pwrVisible"] = 1;
  132. }
  133. #endif
  134. #if ECH1560_SUPPORT
  135. if (sensor->getID() == SENSOR_ECH1560_ID) {
  136. root["pwrVisible"] = 1;
  137. }
  138. #endif
  139. #if PZEM004T_SUPPORT
  140. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  141. root["pzemVisible"] = 1;
  142. root["pwrVisible"] = 1;
  143. }
  144. #endif
  145. }
  146. if (_magnitudes.size() > 0) {
  147. root["snsVisible"] = 1;
  148. root["pwrUnits"] = _sensor_power_units;
  149. root["eneUnits"] = _sensor_energy_units;
  150. root["tmpUnits"] = _sensor_temperature_units;
  151. root["tmpOffset"] = _sensor_temperature_correction;
  152. root["humOffset"] = _sensor_humidity_correction;
  153. root["snsRead"] = _sensor_read_interval / 1000;
  154. root["snsReport"] = _sensor_report_every;
  155. root["snsSave"] = _sensor_save_every;
  156. }
  157. /*
  158. // Sensors manifest
  159. JsonArray& manifest = root.createNestedArray("manifest");
  160. #if BMX280_SUPPORT
  161. BMX280Sensor::manifest(manifest);
  162. #endif
  163. // Sensors configuration
  164. JsonArray& sensors = root.createNestedArray("sensors");
  165. for (unsigned char i; i<_sensors.size(); i++) {
  166. JsonObject& sensor = sensors.createNestedObject();
  167. sensor["index"] = i;
  168. sensor["id"] = _sensors[i]->getID();
  169. _sensors[i]->getConfig(sensor);
  170. }
  171. */
  172. }
  173. #endif // WEB_SUPPORT
  174. #if API_SUPPORT
  175. void _sensorAPISetup() {
  176. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  177. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  178. String topic = magnitudeTopic(magnitude.type);
  179. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  180. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  181. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  182. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  183. double value = _sensor_realtime ? magnitude.current : magnitude.reported;
  184. dtostrf(value, 1-len, decimals, buffer);
  185. });
  186. }
  187. }
  188. #endif // API_SUPPORT
  189. #if TERMINAL_SUPPORT
  190. void _sensorInitCommands() {
  191. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  192. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  193. sensor_magnitude_t magnitude = _magnitudes[i];
  194. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  195. i,
  196. magnitudeTopic(magnitude.type).c_str(),
  197. magnitude.sensor->slot(magnitude.local).c_str(),
  198. magnitudeTopic(magnitude.type).c_str(),
  199. magnitude.global
  200. );
  201. }
  202. DEBUG_MSG_P(PSTR("+OK\n"));
  203. });
  204. }
  205. #endif
  206. void _sensorTick() {
  207. for (unsigned char i=0; i<_sensors.size(); i++) {
  208. _sensors[i]->tick();
  209. }
  210. }
  211. void _sensorPre() {
  212. for (unsigned char i=0; i<_sensors.size(); i++) {
  213. _sensors[i]->pre();
  214. if (!_sensors[i]->status()) {
  215. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  216. _sensors[i]->description().c_str(),
  217. _sensors[i]->error()
  218. );
  219. }
  220. }
  221. }
  222. void _sensorPost() {
  223. for (unsigned char i=0; i<_sensors.size(); i++) {
  224. _sensors[i]->post();
  225. }
  226. }
  227. void _sensorResetTS() {
  228. #if NTP_SUPPORT
  229. if (ntpSynced()) {
  230. if (_sensor_energy_reset_ts.length() == 0) {
  231. _sensor_energy_reset_ts = ntpDateTime(now() - millis() / 1000);
  232. } else {
  233. _sensor_energy_reset_ts = ntpDateTime(now());
  234. }
  235. } else {
  236. _sensor_energy_reset_ts = String();
  237. }
  238. setSetting("snsResetTS", _sensor_energy_reset_ts);
  239. #endif
  240. }
  241. // -----------------------------------------------------------------------------
  242. // Sensor initialization
  243. // -----------------------------------------------------------------------------
  244. void _sensorLoad() {
  245. /*
  246. Only loaded (those with *_SUPPORT to 1) and enabled (*Enabled setting to 1)
  247. sensors are being initialized here.
  248. */
  249. unsigned char index = 0;
  250. unsigned char gpio = GPIO_NONE;
  251. _sensor_save_every = getSetting("snsSave", 0).toInt();
  252. #if AM2320_SUPPORT
  253. if (getSetting("amEnabled", 0).toInt() == 1) {
  254. AM2320Sensor * sensor = new AM2320Sensor();
  255. sensor->setAddress(getSetting("amAddress", AM2320_ADDRESS).toInt());
  256. _sensors.push_back(sensor);
  257. }
  258. #endif
  259. #if ANALOG_SUPPORT
  260. if (getSetting("anaEnabled", 0).toInt() == 1) {
  261. AnalogSensor * sensor = new AnalogSensor();
  262. sensor->setSamples(getSetting("anaSamples", ANALOG_SAMPLES).toInt());
  263. sensor->setDelay(getSetting("anaDelay", ANALOG_DELAY).toInt());
  264. _sensors.push_back(sensor);
  265. }
  266. #endif
  267. #if BH1750_SUPPORT
  268. if (getSetting("bhEnabled", 0).toInt() == 1) {
  269. BH1750Sensor * sensor = new BH1750Sensor();
  270. sensor->setAddress(getSetting("bhAddress", BH1750_ADDRESS).toInt());
  271. sensor->setMode(getSetting("bhMode", BH1750_MODE).toInt());
  272. _sensors.push_back(sensor);
  273. }
  274. #endif
  275. #if BMX280_SUPPORT
  276. if (getSetting("bmx280Enabled", 0).toInt() == 1) {
  277. BMX280Sensor * sensor = new BMX280Sensor();
  278. sensor->setAddress(getSetting("bmx280Address", BMX280_ADDRESS).toInt());
  279. _sensors.push_back(sensor);
  280. }
  281. #endif
  282. #if CSE7766_SUPPORT
  283. if (getSetting("cseEnabled", 0).toInt() == 1) {
  284. if ((gpio = getSetting("cseGPIO", GPIO_NONE).toInt()) != GPIO_NONE) {
  285. CSE7766Sensor * sensor = new CSE7766Sensor();
  286. sensor->setRX(gpio);
  287. double value;
  288. value = getSetting("curRatio", 0).toFloat();
  289. if (value > 0) sensor->setCurrentRatio(value);
  290. value = getSetting("volRatio", 0).toFloat();
  291. if (value > 0) sensor->setVoltageRatio(value);
  292. value = getSetting("pwrRatio", 0).toFloat();
  293. if (value > 0) sensor->setPowerRatio(value);
  294. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  295. if (value > 0) sensor->resetEnergy(value);
  296. _sensors.push_back(sensor);
  297. }
  298. }
  299. #endif
  300. #if DALLAS_SUPPORT
  301. if (getSetting("dsEnabled", 0).toInt() == 1) {
  302. index = 0;
  303. while ((gpio = getSetting("dsGPIO", index, GPIO_NONE).toInt()) != GPIO_NONE) {
  304. DallasSensor * sensor = new DallasSensor();
  305. sensor->setGPIO(gpio);
  306. _sensors.push_back(sensor);
  307. index++;
  308. }
  309. }
  310. #endif
  311. #if DHT_SUPPORT
  312. if (getSetting("dhtEnabled", 0).toInt() == 1) {
  313. index = 0;
  314. while ((gpio = getSetting("dhtGPIO", index, GPIO_NONE).toInt()) != GPIO_NONE) {
  315. DHTSensor * sensor = new DHTSensor();
  316. sensor->setGPIO(gpio);
  317. sensor->setType(getSetting("dhtType", index, DHT_CHIP_DHT22).toInt());
  318. _sensors.push_back(sensor);
  319. index++;
  320. }
  321. }
  322. #endif
  323. #if DIGITAL_SUPPORT
  324. if (getSetting("digEnabled", 0).toInt() == 1) {
  325. index = 0;
  326. while ((gpio = getSetting("digGPIO", index, GPIO_NONE).toInt()) != GPIO_NONE) {
  327. DigitalSensor * sensor = new DigitalSensor();
  328. sensor->setGPIO(gpio);
  329. sensor->setMode(getSetting("digMode", index, DIGITAL_PIN_MODE).toInt());
  330. sensor->setDefault(getSetting("digDefault", index, DIGITAL_DEFAULT_STATE).toInt());
  331. _sensors.push_back(sensor);
  332. index++;
  333. }
  334. }
  335. #endif
  336. #if ECH1560_SUPPORT
  337. if (getSetting("echEnabled", 0).toInt() == 1) {
  338. ECH1560Sensor * sensor = new ECH1560Sensor();
  339. sensor->setCLK(getSetting("echCLKGPIO", ECH1560_CLK_PIN).toInt());
  340. sensor->setMISO(getSetting("echMISOGPIO", ECH1560_MISO_PIN).toInt());
  341. sensor->setInverted(getSetting("echLogic", ECH1560_INVERTED).toInt());
  342. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  343. if (value > 0) sensor->resetEnergy(value);
  344. _sensors.push_back(sensor);
  345. }
  346. #endif
  347. #if EMON_ADC121_SUPPORT || EMON_ADS1X15_SUPPORT || EMON_ANALOG_SUPPORT
  348. if (getSetting("emonEnabled", 0).toInt() == 1) {
  349. #if EMON_ADC121_SUPPORT
  350. if (getSetting("emonProvider", 0).toInt() == EMON_PROVIDER_ADC121) {
  351. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  352. sensor->setAddress(getSetting("emonAddress", EMON_ADC121_I2C_ADDRESS).toInt());
  353. sensor->setReference(getSetting("emonReference", EMON_REFERENCE_VOLTAGE).toInt());
  354. sensor->setCurrentRatio(0, getSetting("curRatio", EMON_CURRENT_RATIO).toFloat());
  355. sensor->setVoltage(getSetting("volNominal", EMON_MAINS_VOLTAGE).toInt());
  356. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  357. if (value > 0) sensor->resetEnergy(0, value);
  358. _sensors.push_back(sensor);
  359. }
  360. #endif
  361. #if EMON_ADS1X15_SUPPORT
  362. if (getSetting("emonProvider", 0).toInt() == EMON_PROVIDER_ADS1X15) {
  363. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  364. sensor->setAddress(getSetting("emonAddress", EMON_ADS1X15_I2C_ADDRESS).toInt());
  365. sensor->setType(getSetting("emonType", EMON_ADS1X15_TYPE).toInt());
  366. sensor->setMask(getSetting("emonMask", EMON_ADS1X15_MASK).toInt());
  367. sensor->setGain(getSetting("emonGain", EMON_ADS1X15_GAIN).toInt());
  368. sensor->setReference(getSetting("emonReference", EMON_REFERENCE_VOLTAGE).toInt());
  369. double value = getSetting("curRatio", EMON_CURRENT_RATIO).toFloat();
  370. sensor->setCurrentRatio(0, getSetting("curRatio", 0, value).toFloat());
  371. sensor->setCurrentRatio(1, getSetting("curRatio", 1, value).toFloat());
  372. sensor->setCurrentRatio(2, getSetting("curRatio", 2, value).toFloat());
  373. sensor->setCurrentRatio(3, getSetting("curRatio", 3, value).toFloat());
  374. sensor->setVoltage(getSetting("volNominal", EMON_MAINS_VOLTAGE).toInt());
  375. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  376. if (value > 0) sensor->resetEnergy(0, value);
  377. _sensors.push_back(sensor);
  378. }
  379. #endif
  380. #if EMON_ANALOG_SUPPORT
  381. if (getSetting("emonProvider", 0).toInt() == EMON_PROVIDER_ANALOG) {
  382. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  383. sensor->setReference(getSetting("emonReference", EMON_REFERENCE_VOLTAGE).toInt());
  384. sensor->setCurrentRatio(0, getSetting("curRatio", EMON_CURRENT_RATIO).toFloat());
  385. sensor->setVoltage(getSetting("volNominal", EMON_MAINS_VOLTAGE).toInt());
  386. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  387. if (value > 0) sensor->resetEnergy(0, value);
  388. _sensors.push_back(sensor);
  389. }
  390. #endif
  391. }
  392. #endif
  393. #if EVENTS_SUPPORT
  394. if (getSetting("evtEnabled", 0).toInt() == 1) {
  395. index = 0;
  396. while ((gpio = getSetting("evtGPIO", index, GPIO_NONE).toInt()) != GPIO_NONE) {
  397. EventSensor * sensor = new EventSensor();
  398. sensor->setGPIO(gpio);
  399. sensor->setTrigger(getSetting("evtTrigger", index, EVENTS_TRIGGER).toInt());
  400. sensor->setPinMode(getSetting("evtMode", index, EVENTS_PIN_MODE).toInt());
  401. sensor->setDebounceTime(getSetting("evtDebounce", index, EVENTS_DEBOUNCE).toInt());
  402. sensor->setInterruptMode(getSetting("evtIntMode", index, EVENTS_INTERRUPT_MODE).toInt());
  403. _sensors.push_back(sensor);
  404. index++;
  405. }
  406. }
  407. #endif
  408. #if GEIGER_SUPPORT
  409. if (getSetting("geiEnabled", 0).toInt() == 1) {
  410. if ((gpio = getSetting("geiGPIO", GPIO_NONE).toInt()) != GPIO_NONE) {
  411. GeigerSensor * sensor = new GeigerSensor(); // Create instance of the Geiger module.
  412. sensor->setGPIO(gpio); // Interrupt pin of the attached geiger counter board.
  413. sensor->setMode(getSetting("geiMode", GEIGER_PIN_MODE).toInt()); // This pin is an input.
  414. sensor->setDebounceTime(getSetting("geiDebounce", GEIGER_DEBOUNCE).toInt()); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  415. sensor->setInterruptMode(getSetting("geiIntMode", GEIGER_INTERRUPT_MODE).toInt()); // Interrupt triggering: edge detection rising.
  416. sensor->setCPM2SievertFactor(getSetting("geiRatio", GEIGER_CPM2SIEVERT).toInt()); // Conversion factor from counts per minute to µSv/h
  417. _sensors.push_back(sensor);
  418. }
  419. }
  420. #endif
  421. #if GUVAS12SD_SUPPORT
  422. if (getSetting("guvEnabled", 0).toInt() == 1) {
  423. if ((gpio = getSetting("guvGPIO", GPIO_NONE).toInt()) != GPIO_NONE) {
  424. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  425. sensor->setGPIO(gpio);
  426. _sensors.push_back(sensor);
  427. }
  428. }
  429. #endif
  430. #if SONAR_SUPPORT
  431. if (getSetting("sonEnabled", 0).toInt() == 1) {
  432. SonarSensor * sensor = new SonarSensor();
  433. sensor->setEcho(getSetting("sonEcho", SONAR_ECHO).toInt());
  434. sensor->setTrigger(getSetting("sonTrigger", SONAR_TRIGGER).toInt());
  435. sensor->setIterations(getSetting("sonIterations", SONAR_ITERATIONS).toInt());
  436. sensor->setMaxDistance(getSetting("sonMaxDist", SONAR_MAX_DISTANCE).toInt());
  437. _sensors.push_back(sensor);
  438. }
  439. #endif
  440. #if HLW8012_SUPPORT
  441. if (getSetting("hlwEnabled", 0).toInt() == 1) {
  442. HLW8012Sensor * sensor = new HLW8012Sensor();
  443. sensor->setSEL(getSetting("hlwSELGPIO", HLW8012_SEL_PIN).toInt());
  444. sensor->setCF(getSetting("hlwCFGPIO", HLW8012_CF_PIN).toInt());
  445. sensor->setCF1(getSetting("hlwCF1GPIO", HLW8012_CF1_PIN).toInt());
  446. sensor->setCurrentSEL(getSetting("hlwCurSel", HLW8012_SEL_CURRENT).toInt());
  447. sensor->setInterruptMode(getSetting("hlwIntMode", HLW8012_INTERRUPT_ON).toInt());
  448. sensor->setCurrentResistor(getSetting("hlwCurRes", HLW8012_CURRENT_R ).toFloat());
  449. sensor->setUpstreamResistor(getSetting("hlwVolResUp", HLW8012_VOLTAGE_R_UP).toFloat());
  450. sensor->setDownstreamResistor(getSetting("hlwVolResDw", HLW8012_VOLTAGE_R_DOWN).toFloat());
  451. double value;
  452. value = getSetting("curRatio", HLW8012_CURRENT_RATIO).toFloat();
  453. if (value > 0) sensor->setCurrentRatio(value);
  454. value = getSetting("volRatio", HLW8012_VOLTAGE_RATIO).toFloat();
  455. if (value > 0) sensor->setVoltageRatio(value);
  456. value = getSetting("pwrRatio", HLW8012_POWER_RATIO).toFloat();
  457. if (value > 0) sensor->setPowerRatio(value);
  458. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  459. if (value > 0) sensor->resetEnergy(value);
  460. _sensors.push_back(sensor);
  461. }
  462. #endif
  463. #if MHZ19_SUPPORT
  464. if (getSetting("mhzEnabled", 0).toInt() == 1) {
  465. MHZ19Sensor * sensor = new MHZ19Sensor();
  466. sensor->setRX(getSetting("mhzRX", MHZ19_RX_PIN).toInt());
  467. sensor->setTX(getSetting("mhzTX", MHZ19_TX_PIN).toInt());
  468. _sensors.push_back(sensor);
  469. }
  470. #endif
  471. #if SDS011_SUPPORT
  472. {
  473. SDS011Sensor * sensor = new SDS011Sensor();
  474. sensor->setRX(SDS011_RX_PIN);
  475. sensor->setTX(SDS011_TX_PIN);
  476. _sensors.push_back(sensor);
  477. }
  478. #endif
  479. #if NTC_SUPPORT
  480. if (getSetting("ntcEnabled", 0).toInt() == 1) {
  481. NTCSensor * sensor = new NTCSensor();
  482. sensor->setSamples(getSetting("ntcSamples", NTC_SAMPLES).toInt());
  483. sensor->setDelay(getSetting("ntcDelay", NTC_DELAY).toInt());
  484. sensor->setUpstreamResistor(getSetting("ntcResUp", NTC_R_UP).toInt());
  485. sensor->setDownstreamResistor(getSetting("ntcResDown", NTC_R_DOWN).toInt());
  486. sensor->setBeta(getSetting("ntcBeta", NTC_BETA).toInt());
  487. sensor->setR0(getSetting("ntcR0", NTC_R0).toInt());
  488. sensor->setT0(getSetting("ntcT0", NTC_T0).toFloat());
  489. _sensors.push_back(sensor);
  490. }
  491. #endif
  492. #if SENSEAIR_SUPPORT
  493. if (getSetting("airEnabled", 0).toInt() == 1) {
  494. SenseAirSensor * sensor = new SenseAirSensor();
  495. sensor->setRX(getSetting("airRX", SENSEAIR_RX_PIN).toInt());
  496. sensor->setTX(getSetting("airTX", SENSEAIR_TX_PIN).toInt());
  497. _sensors.push_back(sensor);
  498. }
  499. #endif
  500. #if PMSX003_SUPPORT
  501. if (getSetting("pmsEnabled", 0).toInt() == 1) {
  502. PMSX003Sensor * sensor = new PMSX003Sensor();
  503. if (getSetting("pmsSoft", PMS_USE_SOFT).toInt() == 1) {
  504. sensor->setRX(getSetting("pmsRX", PMS_RX_PIN).toInt());
  505. sensor->setTX(getSetting("pmsTX", PMS_TX_PIN).toInt());
  506. } else {
  507. sensor->setSerial(& PMS_HW_PORT);
  508. }
  509. sensor->setType(getSetting("pmsType", PMS_TYPE).toInt());
  510. _sensors.push_back(sensor);
  511. }
  512. #endif
  513. #if PZEM004T_SUPPORT
  514. if (getSetting("pzemEnabled", 0).toInt() == 1) {
  515. PZEM004TSensor * sensor = new PZEM004TSensor();
  516. if (getSetting("pzemSoft", PZEM004T_USE_SOFT).toInt() == 1) {
  517. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN).toInt());
  518. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN).toInt());
  519. } else {
  520. sensor->setSerial(& PZEM004T_HW_PORT);
  521. }
  522. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  523. if (value > 0) sensor->resetEnergy(value);
  524. _sensors.push_back(sensor);
  525. }
  526. #endif
  527. #if SHT3X_I2C_SUPPORT
  528. if (getSetting("shtEnabled", 0).toInt() == 1) {
  529. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  530. sensor->setAddress(getSetting("shtAddress", SHT3X_I2C_ADDRESS).toInt());
  531. _sensors.push_back(sensor);
  532. }
  533. #endif
  534. #if SI7021_SUPPORT
  535. if (getSetting("si7021Enabled", 0).toInt() == 1) {
  536. SI7021Sensor * sensor = new SI7021Sensor();
  537. sensor->setAddress(getSetting("si7021Address", SI7021_ADDRESS).toInt());
  538. _sensors.push_back(sensor);
  539. }
  540. #endif
  541. #if TMP3X_SUPPORT
  542. if (getSetting("tmp3xEnabled", 0).toInt() == 1) {
  543. TMP3XSensor * sensor = new TMP3XSensor();
  544. sensor->setType(getSetting("tmp3xType", TMP3X_TYPE).toInt());
  545. _sensors.push_back(sensor);
  546. }
  547. #endif
  548. #if V9261F_SUPPORT
  549. if (getSetting("v92Enabled", 0).toInt() == 1) {
  550. if ((gpio = getSetting("v92GPIO", GPIO_NONE).toInt()) != GPIO_NONE) {
  551. V9261FSensor * sensor = new V9261FSensor();
  552. sensor->setRX(gpio);
  553. sensor->setInverted(getSetting("v92Inverse", V9261F_PIN_INVERSE).toInt());
  554. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  555. if (value > 0) sensor->resetEnergy(value);
  556. _sensors.push_back(sensor);
  557. }
  558. }
  559. #endif
  560. }
  561. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  562. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  563. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  564. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  565. _sensorReport(k, value);
  566. return;
  567. }
  568. }
  569. }
  570. void _sensorInit() {
  571. _sensors_ready = true;
  572. for (unsigned char i=0; i<_sensors.size(); i++) {
  573. // Do not process an already initialized sensor
  574. if (_sensors[i]->ready()) continue;
  575. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  576. // Force sensor to reload config
  577. _sensors[i]->begin();
  578. if (!_sensors[i]->ready()) {
  579. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  580. _sensors_ready = false;
  581. continue;
  582. }
  583. // Initialize magnitudes
  584. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  585. unsigned char type = _sensors[i]->type(k);
  586. sensor_magnitude_t new_magnitude;
  587. new_magnitude.sensor = _sensors[i];
  588. new_magnitude.local = k;
  589. new_magnitude.type = type;
  590. new_magnitude.global = _counts[type];
  591. new_magnitude.current = 0;
  592. new_magnitude.reported = 0;
  593. new_magnitude.min_change = 0;
  594. new_magnitude.max_change = 0;
  595. // TODO: find a proper way to extend this to min/max of any magnitude
  596. if (MAGNITUDE_ENERGY == type) {
  597. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  598. } else if (MAGNITUDE_TEMPERATURE == type) {
  599. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  600. } else if (MAGNITUDE_HUMIDITY == type) {
  601. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  602. }
  603. if (MAGNITUDE_ENERGY == type) {
  604. new_magnitude.filter = new LastFilter();
  605. } else if (MAGNITUDE_DIGITAL == type) {
  606. new_magnitude.filter = new MaxFilter();
  607. } 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.
  608. new_magnitude.filter = new MovingAverageFilter();
  609. } else {
  610. new_magnitude.filter = new MedianFilter();
  611. }
  612. new_magnitude.filter->resize(_sensor_report_every);
  613. _magnitudes.push_back(new_magnitude);
  614. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  615. _counts[type] = _counts[type] + 1;
  616. }
  617. // Hook callback
  618. _sensors[i]->onEvent([i](unsigned char type, double value) {
  619. _sensorCallback(i, type, value);
  620. });
  621. }
  622. }
  623. void _sensorConfigure() {
  624. // General sensor settings
  625. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  626. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  627. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  628. _sensor_realtime = apiRealTime();
  629. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  630. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  631. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  632. _sensor_temperature_correction = getSetting("tmpOffset", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  633. _sensor_humidity_correction = getSetting("humOffset", SENSOR_HUMIDITY_CORRECTION).toFloat();
  634. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  635. // Specific sensor settings
  636. for (unsigned char i=0; i<_sensors.size(); i++) {
  637. #if EMON_ANALOG_SUPPORT
  638. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  639. double value;
  640. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  641. if ((value = getSetting("pwrExpected", 0).toInt())) {
  642. sensor->expectedPower(0, value);
  643. setSetting("curRatio", sensor->getCurrentRatio(0));
  644. }
  645. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  646. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  647. delSetting("curRatio");
  648. }
  649. if (getSetting("eneReset", 0).toInt() == 1) {
  650. sensor->resetEnergy();
  651. delSetting("eneTotal");
  652. _sensorResetTS();
  653. }
  654. sensor->setVoltage(getSetting("volNominal", EMON_MAINS_VOLTAGE).toInt());
  655. }
  656. #endif // EMON_ANALOG_SUPPORT
  657. #if EMON_ADC121_SUPPORT
  658. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  659. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  660. if (getSetting("eneReset", 0).toInt() == 1) {
  661. sensor->resetEnergy();
  662. delSetting("eneTotal");
  663. _sensorResetTS();
  664. }
  665. }
  666. #endif
  667. #if EMON_ADS1X15_SUPPORT
  668. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  669. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  670. if (getSetting("eneReset", 0).toInt() == 1) {
  671. sensor->resetEnergy();
  672. delSetting("eneTotal");
  673. _sensorResetTS();
  674. }
  675. }
  676. #endif
  677. #if HLW8012_SUPPORT
  678. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  679. double value;
  680. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  681. if (value = getSetting("curExpected", 0).toFloat()) {
  682. sensor->expectedCurrent(value);
  683. setSetting("curRatio", sensor->getCurrentRatio());
  684. }
  685. if (value = getSetting("volExpected", 0).toInt()) {
  686. sensor->expectedVoltage(value);
  687. setSetting("volRatio", sensor->getVoltageRatio());
  688. }
  689. if (value = getSetting("pwrExpected", 0).toInt()) {
  690. sensor->expectedPower(value);
  691. setSetting("pwrRatio", sensor->getPowerRatio());
  692. }
  693. if (getSetting("eneReset", 0).toInt() == 1) {
  694. sensor->resetEnergy();
  695. delSetting("eneTotal");
  696. _sensorResetTS();
  697. }
  698. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  699. sensor->resetRatios();
  700. delSetting("curRatio");
  701. delSetting("volRatio");
  702. delSetting("pwrRatio");
  703. }
  704. }
  705. #endif // HLW8012_SUPPORT
  706. #if CSE7766_SUPPORT
  707. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  708. double value;
  709. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  710. if ((value = getSetting("curExpected", 0).toFloat())) {
  711. sensor->expectedCurrent(value);
  712. setSetting("curRatio", sensor->getCurrentRatio());
  713. }
  714. if ((value = getSetting("volExpected", 0).toInt())) {
  715. sensor->expectedVoltage(value);
  716. setSetting("volRatio", sensor->getVoltageRatio());
  717. }
  718. if ((value = getSetting("pwrExpected", 0).toInt())) {
  719. sensor->expectedPower(value);
  720. setSetting("pwrRatio", sensor->getPowerRatio());
  721. }
  722. if (getSetting("eneReset", 0).toInt() == 1) {
  723. sensor->resetEnergy();
  724. delSetting("eneTotal");
  725. _sensorResetTS();
  726. }
  727. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  728. sensor->resetRatios();
  729. delSetting("curRatio");
  730. delSetting("volRatio");
  731. delSetting("pwrRatio");
  732. }
  733. }
  734. #endif // CSE7766_SUPPORT
  735. }
  736. // Update filter sizes
  737. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  738. sensor_magnitude_t magnitude = _magnitudes[i];
  739. magnitude.filter->resize(_sensor_report_every);
  740. magnitude.min_change = getSetting("tmpDelta", magnitude.type, 0).toFloat();
  741. }
  742. // General processing
  743. if (0 == _sensor_save_every) {
  744. delSetting("eneTotal");
  745. }
  746. // Save settings
  747. delSetting("pwrExpected");
  748. delSetting("curExpected");
  749. delSetting("volExpected");
  750. delSetting("snsResetCalibrarion");
  751. delSetting("eneReset");
  752. saveSettings();
  753. }
  754. bool _sensorKeyCheck(const char * key) {
  755. if (strncmp(key, "sns", 3) == 0) return true;
  756. if (strncmp(key, "pwr", 3) == 0) return true;
  757. if (strncmp(key, "ene", 3) == 0) return true;
  758. if (strncmp(key, "cur", 3) == 0) return true;
  759. if (strncmp(key, "vol", 3) == 0) return true;
  760. if (strncmp(key, "tmp", 3) == 0) return true;
  761. if (strncmp(key, "hum", 3) == 0) return true;
  762. if (strncmp(key, "air", 3) == 0) return true;
  763. if (strncmp(key, "am", 2) == 0) return true;
  764. if (strncmp(key, "ana", 3) == 0) return true;
  765. if (strncmp(key, "bh", 2) == 0) return true;
  766. if (strncmp(key, "bmx", 3) == 0) return true;
  767. if (strncmp(key, "cse", 3) == 0) return true;
  768. if (strncmp(key, "dht", 3) == 0) return true;
  769. if (strncmp(key, "dig", 3) == 0) return true;
  770. if (strncmp(key, "ds" , 2) == 0) return true;
  771. if (strncmp(key, "ech", 3) == 0) return true;
  772. if (strncmp(key, "emon", 4) == 0) return true;
  773. if (strncmp(key, "evt", 3) == 0) return true;
  774. if (strncmp(key, "gei", 3) == 0) return true;
  775. if (strncmp(key, "guv", 3) == 0) return true;
  776. if (strncmp(key, "hlw", 3) == 0) return true;
  777. if (strncmp(key, "mhz", 3) == 0) return true;
  778. if (strncmp(key, "ntc", 3) == 0) return true;
  779. if (strncmp(key, "pms", 3) == 0) return true;
  780. if (strncmp(key, "pzem", 4) == 0) return true;
  781. if (strncmp(key, "sht", 3) == 0) return true;
  782. if (strncmp(key, "son", 3) == 0) return true;
  783. if (strncmp(key, "tmp3x", 4) == 0) return true;
  784. if (strncmp(key, "v92", 3) == 0) return true;
  785. return false;
  786. }
  787. void _sensorBackwards() {
  788. moveSetting("powerUnits", "pwrUnits"); // 1.12.5 - 2018-04-03
  789. moveSetting("tmpCorrection", "tmpOffset"); // 1.14.0 - 2018-06-26
  790. moveSetting("humCorrection", "humOffset"); // 1.14.0 - 2018-06-26
  791. moveSetting("energyUnits", "eneUnits"); // 1.14.0 - 2018-06-26
  792. moveSetting("pwrRatioC", "curRatio"); // 1.14.0 - 2018-06-26
  793. moveSetting("pwrRatioP", "pwrRatio"); // 1.14.0 - 2018-06-26
  794. moveSetting("pwrRatioV", "volRatio"); // 1.14.0 - 2018-06-26
  795. moveSetting("pwrVoltage", "volNominal"); // 1.14.0 - 2018-06-26
  796. moveSetting("pwrExpectedP", "pwrExpected"); // 1.14.0 - 2018-06-26
  797. moveSetting("pwrExpectedC", "curExpected"); // 1.14.0 - 2018-06-26
  798. moveSetting("pwrExpectedV", "volExpected"); // 1.14.0 - 2018-06-26
  799. moveSetting("pwrResetCalibration", "snsResetCalibration"); // 1.14.0 - 2018-06-26
  800. moveSetting("pwrResetE", "eneReset"); // 1.14.0 - 2018-06-26
  801. }
  802. void _sensorReport(unsigned char index, double value) {
  803. sensor_magnitude_t magnitude = _magnitudes[index];
  804. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  805. char buffer[10];
  806. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  807. #if BROKER_SUPPORT
  808. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  809. #endif
  810. #if MQTT_SUPPORT
  811. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  812. #if SENSOR_PUBLISH_ADDRESSES
  813. char topic[32];
  814. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  815. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  816. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  817. } else {
  818. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  819. }
  820. #endif // SENSOR_PUBLISH_ADDRESSES
  821. #endif // MQTT_SUPPORT
  822. #if INFLUXDB_SUPPORT
  823. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  824. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  825. } else {
  826. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  827. }
  828. #endif // INFLUXDB_SUPPORT
  829. #if THINGSPEAK_SUPPORT
  830. tspkEnqueueMeasurement(index, buffer);
  831. #endif
  832. #if DOMOTICZ_SUPPORT
  833. {
  834. char key[15];
  835. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  836. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  837. int status;
  838. if (value > 70) {
  839. status = HUMIDITY_WET;
  840. } else if (value > 45) {
  841. status = HUMIDITY_COMFORTABLE;
  842. } else if (value > 30) {
  843. status = HUMIDITY_NORMAL;
  844. } else {
  845. status = HUMIDITY_DRY;
  846. }
  847. char status_buf[5];
  848. itoa(status, status_buf, 10);
  849. domoticzSend(key, buffer, status_buf);
  850. } else {
  851. domoticzSend(key, 0, buffer);
  852. }
  853. }
  854. #endif // DOMOTICZ_SUPPORT
  855. }
  856. // -----------------------------------------------------------------------------
  857. // Public
  858. // -----------------------------------------------------------------------------
  859. unsigned char sensorCount() {
  860. return _sensors.size();
  861. }
  862. unsigned char magnitudeCount() {
  863. return _magnitudes.size();
  864. }
  865. String magnitudeName(unsigned char index) {
  866. if (index < _magnitudes.size()) {
  867. sensor_magnitude_t magnitude = _magnitudes[index];
  868. return magnitude.sensor->slot(magnitude.local);
  869. }
  870. return String();
  871. }
  872. unsigned char magnitudeType(unsigned char index) {
  873. if (index < _magnitudes.size()) {
  874. return int(_magnitudes[index].type);
  875. }
  876. return MAGNITUDE_NONE;
  877. }
  878. unsigned char magnitudeIndex(unsigned char index) {
  879. if (index < _magnitudes.size()) {
  880. return int(_magnitudes[index].global);
  881. }
  882. return 0;
  883. }
  884. String magnitudeTopic(unsigned char type) {
  885. char buffer[16] = {0};
  886. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  887. return String(buffer);
  888. }
  889. String magnitudeTopicIndex(unsigned char index) {
  890. char topic[32] = {0};
  891. if (index < _magnitudes.size()) {
  892. sensor_magnitude_t magnitude = _magnitudes[index];
  893. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  894. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  895. } else {
  896. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  897. }
  898. }
  899. return String(topic);
  900. }
  901. String magnitudeUnits(unsigned char type) {
  902. char buffer[8] = {0};
  903. if (type < MAGNITUDE_MAX) {
  904. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  905. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  906. } else if (
  907. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  908. (_sensor_energy_units == ENERGY_KWH)) {
  909. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  910. } else if (
  911. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  912. (_sensor_power_units == POWER_KILOWATTS)) {
  913. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  914. } else {
  915. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  916. }
  917. }
  918. return String(buffer);
  919. }
  920. // -----------------------------------------------------------------------------
  921. void sensorSetup() {
  922. // Backwards compatibility
  923. _sensorBackwards();
  924. // Load sensors
  925. _sensorLoad();
  926. _sensorInit();
  927. // Configure stored values
  928. _sensorConfigure();
  929. // Websockets
  930. #if WEB_SUPPORT
  931. wsOnSendRegister(_sensorWebSocketStart);
  932. wsOnSendRegister(_sensorWebSocketSendData);
  933. #endif
  934. // API
  935. #if API_SUPPORT
  936. _sensorAPISetup();
  937. #endif
  938. // Terminal
  939. #if TERMINAL_SUPPORT
  940. _sensorInitCommands();
  941. #endif
  942. settingsRegisterKeyCheck(_sensorKeyCheck);
  943. // Main callbacks
  944. espurnaRegisterLoop(sensorLoop);
  945. espurnaRegisterReload(_sensorConfigure);
  946. }
  947. void sensorLoop() {
  948. // Check if we still have uninitialized sensors
  949. static unsigned long last_init = 0;
  950. if (!_sensors_ready) {
  951. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  952. last_init = millis();
  953. _sensorInit();
  954. }
  955. }
  956. if (_magnitudes.size() == 0) return;
  957. // Tick hook
  958. _sensorTick();
  959. // Check if we should read new data
  960. static unsigned long last_update = 0;
  961. static unsigned long report_count = 0;
  962. static unsigned long save_count = 0;
  963. if (millis() - last_update > _sensor_read_interval) {
  964. last_update = millis();
  965. report_count = (report_count + 1) % _sensor_report_every;
  966. double current;
  967. double filtered;
  968. // Pre-read hook
  969. _sensorPre();
  970. // Get the first relay state
  971. #if SENSOR_POWER_CHECK_STATUS
  972. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  973. #endif
  974. // Get readings
  975. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  976. sensor_magnitude_t magnitude = _magnitudes[i];
  977. if (magnitude.sensor->status()) {
  978. // -------------------------------------------------------------
  979. // Instant value
  980. // -------------------------------------------------------------
  981. current = magnitude.sensor->value(magnitude.local);
  982. // Completely remove spurious values if relay is OFF
  983. #if SENSOR_POWER_CHECK_STATUS
  984. if (relay_off) {
  985. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  986. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  987. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  988. magnitude.type == MAGNITUDE_CURRENT ||
  989. magnitude.type == MAGNITUDE_ENERGY_DELTA
  990. ) {
  991. current = 0;
  992. }
  993. }
  994. #endif
  995. // -------------------------------------------------------------
  996. // Processing (filters)
  997. // -------------------------------------------------------------
  998. magnitude.filter->add(current);
  999. // Special case for MovingAvergaeFilter
  1000. if (MAGNITUDE_COUNT == magnitude.type ||
  1001. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1002. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1003. current = magnitude.filter->result();
  1004. }
  1005. current = _magnitudeProcess(magnitude.type, current);
  1006. _magnitudes[i].current = current;
  1007. // -------------------------------------------------------------
  1008. // Debug
  1009. // -------------------------------------------------------------
  1010. #if SENSOR_DEBUG
  1011. {
  1012. char buffer[64];
  1013. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1014. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1015. magnitude.sensor->slot(magnitude.local).c_str(),
  1016. magnitudeTopic(magnitude.type).c_str(),
  1017. buffer,
  1018. magnitudeUnits(magnitude.type).c_str()
  1019. );
  1020. }
  1021. #endif // SENSOR_DEBUG
  1022. // -------------------------------------------------------------
  1023. // Report
  1024. // (we do it every _sensor_report_every readings)
  1025. // -------------------------------------------------------------
  1026. bool report = (0 == report_count);
  1027. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1028. // for MAGNITUDE_ENERGY, filtered value is last value
  1029. double value = _magnitudeProcess(magnitude.type, current);
  1030. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1031. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1032. if (report) {
  1033. filtered = magnitude.filter->result();
  1034. filtered = _magnitudeProcess(magnitude.type, filtered);
  1035. magnitude.filter->reset();
  1036. // Check if there is a minimum change threshold to report
  1037. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1038. _magnitudes[i].reported = filtered;
  1039. _sensorReport(i, filtered);
  1040. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1041. // -------------------------------------------------------------
  1042. // Saving to EEPROM
  1043. // (we do it every _sensor_save_every readings)
  1044. // -------------------------------------------------------------
  1045. if (_sensor_save_every > 0) {
  1046. save_count = (save_count + 1) % _sensor_save_every;
  1047. if (0 == save_count) {
  1048. if (MAGNITUDE_ENERGY == magnitude.type) {
  1049. setSetting("eneTotal", current);
  1050. saveSettings();
  1051. }
  1052. } // if (0 == save_count)
  1053. } // if (_sensor_save_every > 0)
  1054. } // if (report_count == 0)
  1055. } // if (magnitude.sensor->status())
  1056. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1057. // Post-read hook
  1058. _sensorPost();
  1059. #if WEB_SUPPORT
  1060. wsSend(_sensorWebSocketSendData);
  1061. #endif
  1062. #if THINGSPEAK_SUPPORT
  1063. if (report_count == 0) tspkFlush();
  1064. #endif
  1065. }
  1066. }
  1067. #endif // SENSOR_SUPPORT