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.

1294 lines
46 KiB

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; // Lat raw value (unfiltered)
  22. double filtered; // Last filtered value (averaged)
  23. double reported; // Last reported value (averaged)
  24. double min_change; // Minimum 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.filtered;
  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 NTC_SUPPORT
  472. if (getSetting("ntcEnabled", 0).toInt() == 1) {
  473. NTCSensor * sensor = new NTCSensor();
  474. sensor->setSamples(getSetting("ntcSamples", NTC_SAMPLES).toInt());
  475. sensor->setDelay(getSetting("ntcDelay", NTC_DELAY).toInt());
  476. sensor->setUpstreamResistor(getSetting("ntcResUp", NTC_R_UP).toInt());
  477. sensor->setDownstreamResistor(getSetting("ntcResDown", NTC_R_DOWN).toInt());
  478. sensor->setBeta(getSetting("ntcBeta", NTC_BETA).toInt());
  479. sensor->setR0(getSetting("ntcR0", NTC_R0).toInt());
  480. sensor->setT0(getSetting("ntcT0", NTC_T0).toFloat());
  481. _sensors.push_back(sensor);
  482. }
  483. #endif
  484. #if SENSEAIR_SUPPORT
  485. if (getSetting("airEnabled", 0).toInt() == 1) {
  486. SenseAirSensor * sensor = new SenseAirSensor();
  487. sensor->setRX(getSetting("airRX", SENSEAIR_RX_PIN).toInt());
  488. sensor->setTX(getSetting("airTX", SENSEAIR_TX_PIN).toInt());
  489. _sensors.push_back(sensor);
  490. }
  491. #endif
  492. #if PMSX003_SUPPORT
  493. if (getSetting("pmsEnabled", 0).toInt() == 1) {
  494. PMSX003Sensor * sensor = new PMSX003Sensor();
  495. if (getSetting("pmsSoft", PMS_USE_SOFT).toInt() == 1) {
  496. sensor->setRX(getSetting("pmsRX", PMS_RX_PIN).toInt());
  497. sensor->setTX(getSetting("pmsTX", PMS_TX_PIN).toInt());
  498. } else {
  499. sensor->setSerial(& PMS_HW_PORT);
  500. }
  501. sensor->setType(getSetting("pmsType", PMS_TYPE).toInt());
  502. _sensors.push_back(sensor);
  503. }
  504. #endif
  505. #if PZEM004T_SUPPORT
  506. if (getSetting("pzemEnabled", 0).toInt() == 1) {
  507. PZEM004TSensor * sensor = new PZEM004TSensor();
  508. if (getSetting("pzemSoft", PZEM004T_USE_SOFT).toInt() == 1) {
  509. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN).toInt());
  510. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN).toInt());
  511. } else {
  512. sensor->setSerial(& PZEM004T_HW_PORT);
  513. }
  514. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  515. if (value > 0) sensor->resetEnergy(value);
  516. _sensors.push_back(sensor);
  517. }
  518. #endif
  519. #if SHT3X_I2C_SUPPORT
  520. if (getSetting("shtEnabled", 0).toInt() == 1) {
  521. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  522. sensor->setAddress(getSetting("shtAddress", SHT3X_I2C_ADDRESS).toInt());
  523. _sensors.push_back(sensor);
  524. }
  525. #endif
  526. #if SI7021_SUPPORT
  527. if (getSetting("si7021Enabled", 0).toInt() == 1) {
  528. SI7021Sensor * sensor = new SI7021Sensor();
  529. sensor->setAddress(getSetting("si7021Address", SI7021_ADDRESS).toInt());
  530. _sensors.push_back(sensor);
  531. }
  532. #endif
  533. #if TMP3X_SUPPORT
  534. if (getSetting("tmp3xEnabled", 0).toInt() == 1) {
  535. TMP3XSensor * sensor = new TMP3XSensor();
  536. sensor->setType(getSetting("tmp3xType", TMP3X_TYPE).toInt());
  537. _sensors.push_back(sensor);
  538. }
  539. #endif
  540. #if V9261F_SUPPORT
  541. if (getSetting("v92Enabled", 0).toInt() == 1) {
  542. if ((gpio = getSetting("v92GPIO", GPIO_NONE).toInt()) != GPIO_NONE) {
  543. V9261FSensor * sensor = new V9261FSensor();
  544. sensor->setRX(gpio);
  545. sensor->setInverted(getSetting("v92Inverse", V9261F_PIN_INVERSE).toInt());
  546. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toFloat() : 0;
  547. if (value > 0) sensor->resetEnergy(value);
  548. _sensors.push_back(sensor);
  549. }
  550. }
  551. #endif
  552. }
  553. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  554. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  555. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  556. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  557. _sensorReport(k, value);
  558. return;
  559. }
  560. }
  561. }
  562. void _sensorInit() {
  563. _sensors_ready = true;
  564. for (unsigned char i=0; i<_sensors.size(); i++) {
  565. // Do not process an already initialized sensor
  566. if (_sensors[i]->ready()) continue;
  567. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  568. // Force sensor to reload config
  569. _sensors[i]->begin();
  570. if (!_sensors[i]->ready()) {
  571. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  572. _sensors_ready = false;
  573. continue;
  574. }
  575. // Initialize magnitudes
  576. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  577. unsigned char type = _sensors[i]->type(k);
  578. sensor_magnitude_t new_magnitude;
  579. new_magnitude.sensor = _sensors[i];
  580. new_magnitude.local = k;
  581. new_magnitude.type = type;
  582. new_magnitude.global = _counts[type];
  583. new_magnitude.current = 0;
  584. new_magnitude.filtered = 0;
  585. new_magnitude.reported = 0;
  586. new_magnitude.min_change = 0;
  587. if (MAGNITUDE_ENERGY == type) {
  588. new_magnitude.filter = new LastFilter();
  589. } else if (MAGNITUDE_DIGITAL == type) {
  590. new_magnitude.filter = new MaxFilter();
  591. } 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.
  592. new_magnitude.filter = new MovingAverageFilter();
  593. } else {
  594. new_magnitude.filter = new MedianFilter();
  595. }
  596. new_magnitude.filter->resize(_sensor_report_every);
  597. _magnitudes.push_back(new_magnitude);
  598. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  599. _counts[type] = _counts[type] + 1;
  600. }
  601. // Hook callback
  602. _sensors[i]->onEvent([i](unsigned char type, double value) {
  603. _sensorCallback(i, type, value);
  604. });
  605. }
  606. }
  607. void _sensorConfigure() {
  608. // General sensor settings
  609. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  610. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  611. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  612. _sensor_realtime = apiRealTime();
  613. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  614. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  615. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  616. _sensor_temperature_correction = getSetting("tmpOffset", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  617. _sensor_humidity_correction = getSetting("humOffset", SENSOR_HUMIDITY_CORRECTION).toFloat();
  618. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  619. // Specific sensor settings
  620. for (unsigned char i=0; i<_sensors.size(); i++) {
  621. #if EMON_ANALOG_SUPPORT
  622. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  623. double value;
  624. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  625. if ((value = getSetting("pwrExpected", 0).toInt())) {
  626. sensor->expectedPower(0, value);
  627. setSetting("curRatio", sensor->getCurrentRatio(0));
  628. }
  629. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  630. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  631. delSetting("curRatio");
  632. }
  633. if (getSetting("eneReset", 0).toInt() == 1) {
  634. sensor->resetEnergy();
  635. delSetting("eneTotal");
  636. _sensorResetTS();
  637. }
  638. sensor->setVoltage(getSetting("volNominal", EMON_MAINS_VOLTAGE).toInt());
  639. }
  640. #endif // EMON_ANALOG_SUPPORT
  641. #if EMON_ADC121_SUPPORT
  642. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  643. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  644. if (getSetting("eneReset", 0).toInt() == 1) {
  645. sensor->resetEnergy();
  646. delSetting("eneTotal");
  647. _sensorResetTS();
  648. }
  649. }
  650. #endif
  651. #if EMON_ADS1X15_SUPPORT
  652. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  653. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  654. if (getSetting("eneReset", 0).toInt() == 1) {
  655. sensor->resetEnergy();
  656. delSetting("eneTotal");
  657. _sensorResetTS();
  658. }
  659. }
  660. #endif
  661. #if HLW8012_SUPPORT
  662. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  663. double value;
  664. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  665. if (value = getSetting("curExpected", 0).toFloat()) {
  666. sensor->expectedCurrent(value);
  667. setSetting("curRatio", sensor->getCurrentRatio());
  668. }
  669. if (value = getSetting("volExpected", 0).toInt()) {
  670. sensor->expectedVoltage(value);
  671. setSetting("volRatio", sensor->getVoltageRatio());
  672. }
  673. if (value = getSetting("pwrExpected", 0).toInt()) {
  674. sensor->expectedPower(value);
  675. setSetting("pwrRatio", sensor->getPowerRatio());
  676. }
  677. if (getSetting("eneReset", 0).toInt() == 1) {
  678. sensor->resetEnergy();
  679. delSetting("eneTotal");
  680. _sensorResetTS();
  681. }
  682. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  683. sensor->resetRatios();
  684. delSetting("curRatio");
  685. delSetting("volRatio");
  686. delSetting("pwrRatio");
  687. }
  688. }
  689. #endif // HLW8012_SUPPORT
  690. #if CSE7766_SUPPORT
  691. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  692. double value;
  693. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  694. if ((value = getSetting("curExpected", 0).toFloat())) {
  695. sensor->expectedCurrent(value);
  696. setSetting("curRatio", sensor->getCurrentRatio());
  697. }
  698. if ((value = getSetting("volExpected", 0).toInt())) {
  699. sensor->expectedVoltage(value);
  700. setSetting("volRatio", sensor->getVoltageRatio());
  701. }
  702. if ((value = getSetting("pwrExpected", 0).toInt())) {
  703. sensor->expectedPower(value);
  704. setSetting("pwrRatio", sensor->getPowerRatio());
  705. }
  706. if (getSetting("eneReset", 0).toInt() == 1) {
  707. sensor->resetEnergy();
  708. delSetting("eneTotal");
  709. _sensorResetTS();
  710. }
  711. if (getSetting("snsResetCalibrarion", 0).toInt() == 1) {
  712. sensor->resetRatios();
  713. delSetting("curRatio");
  714. delSetting("volRatio");
  715. delSetting("pwrRatio");
  716. }
  717. }
  718. #endif // CSE7766_SUPPORT
  719. }
  720. // Update filter sizes
  721. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  722. sensor_magnitude_t magnitude = _magnitudes[i];
  723. magnitude.filter->resize(_sensor_report_every);
  724. magnitude.min_change = getSetting("tmpDelta", magnitude.type, 0).toFloat();
  725. }
  726. // General processing
  727. if (0 == _sensor_save_every) {
  728. delSetting("eneTotal");
  729. }
  730. // Save settings
  731. delSetting("pwrExpected");
  732. delSetting("curExpected");
  733. delSetting("volExpected");
  734. delSetting("snsResetCalibrarion");
  735. delSetting("eneReset");
  736. saveSettings();
  737. }
  738. bool _sensorKeyCheck(const char * key) {
  739. if (strncmp(key, "sns", 3) == 0) return true;
  740. if (strncmp(key, "pwr", 3) == 0) return true;
  741. if (strncmp(key, "ene", 3) == 0) return true;
  742. if (strncmp(key, "cur", 3) == 0) return true;
  743. if (strncmp(key, "vol", 3) == 0) return true;
  744. if (strncmp(key, "tmp", 3) == 0) return true;
  745. if (strncmp(key, "hum", 3) == 0) return true;
  746. if (strncmp(key, "air", 3) == 0) return true;
  747. if (strncmp(key, "am", 2) == 0) return true;
  748. if (strncmp(key, "ana", 3) == 0) return true;
  749. if (strncmp(key, "bh", 2) == 0) return true;
  750. if (strncmp(key, "bmx", 3) == 0) return true;
  751. if (strncmp(key, "cse", 3) == 0) return true;
  752. if (strncmp(key, "dht", 3) == 0) return true;
  753. if (strncmp(key, "dig", 3) == 0) return true;
  754. if (strncmp(key, "ds" , 2) == 0) return true;
  755. if (strncmp(key, "ech", 3) == 0) return true;
  756. if (strncmp(key, "emon", 4) == 0) return true;
  757. if (strncmp(key, "evt", 3) == 0) return true;
  758. if (strncmp(key, "gei", 3) == 0) return true;
  759. if (strncmp(key, "guv", 3) == 0) return true;
  760. if (strncmp(key, "hlw", 3) == 0) return true;
  761. if (strncmp(key, "mhz", 3) == 0) return true;
  762. if (strncmp(key, "ntc", 3) == 0) return true;
  763. if (strncmp(key, "pms", 3) == 0) return true;
  764. if (strncmp(key, "pzem", 4) == 0) return true;
  765. if (strncmp(key, "sht", 3) == 0) return true;
  766. if (strncmp(key, "son", 3) == 0) return true;
  767. if (strncmp(key, "tmp3x", 4) == 0) return true;
  768. if (strncmp(key, "v92", 3) == 0) return true;
  769. return false;
  770. }
  771. void _sensorBackwards() {
  772. moveSetting("powerUnits", "pwrUnits"); // 1.12.5 - 2018-04-03
  773. moveSetting("tmpCorrection", "tmpOffset"); // 1.14.0 - 2018-06-26
  774. moveSetting("humCorrection", "humOffset"); // 1.14.0 - 2018-06-26
  775. moveSetting("energyUnits", "eneUnits"); // 1.14.0 - 2018-06-26
  776. moveSetting("pwrRatioC", "curRatio"); // 1.14.0 - 2018-06-26
  777. moveSetting("pwrRatioP", "pwrRatio"); // 1.14.0 - 2018-06-26
  778. moveSetting("pwrRatioV", "volRatio"); // 1.14.0 - 2018-06-26
  779. moveSetting("pwrVoltage", "volNominal"); // 1.14.0 - 2018-06-26
  780. moveSetting("pwrExpectedP", "pwrExpected"); // 1.14.0 - 2018-06-26
  781. moveSetting("pwrExpectedC", "curExpected"); // 1.14.0 - 2018-06-26
  782. moveSetting("pwrExpectedV", "volExpected"); // 1.14.0 - 2018-06-26
  783. moveSetting("pwrResetCalibration", "snsResetCalibration"); // 1.14.0 - 2018-06-26
  784. moveSetting("pwrResetE", "eneReset"); // 1.14.0 - 2018-06-26
  785. }
  786. void _sensorReport(unsigned char index, double value) {
  787. sensor_magnitude_t magnitude = _magnitudes[index];
  788. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  789. char buffer[10];
  790. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  791. #if BROKER_SUPPORT
  792. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  793. #endif
  794. #if MQTT_SUPPORT
  795. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  796. #if SENSOR_PUBLISH_ADDRESSES
  797. char topic[32];
  798. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  799. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  800. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  801. } else {
  802. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  803. }
  804. #endif // SENSOR_PUBLISH_ADDRESSES
  805. #endif // MQTT_SUPPORT
  806. #if INFLUXDB_SUPPORT
  807. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  808. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  809. } else {
  810. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  811. }
  812. #endif // INFLUXDB_SUPPORT
  813. #if THINGSPEAK_SUPPORT
  814. tspkEnqueueMeasurement(index, buffer);
  815. #endif
  816. #if DOMOTICZ_SUPPORT
  817. {
  818. char key[15];
  819. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  820. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  821. int status;
  822. if (value > 70) {
  823. status = HUMIDITY_WET;
  824. } else if (value > 45) {
  825. status = HUMIDITY_COMFORTABLE;
  826. } else if (value > 30) {
  827. status = HUMIDITY_NORMAL;
  828. } else {
  829. status = HUMIDITY_DRY;
  830. }
  831. char status_buf[5];
  832. itoa(status, status_buf, 10);
  833. domoticzSend(key, buffer, status_buf);
  834. } else {
  835. domoticzSend(key, 0, buffer);
  836. }
  837. }
  838. #endif // DOMOTICZ_SUPPORT
  839. }
  840. // -----------------------------------------------------------------------------
  841. // Public
  842. // -----------------------------------------------------------------------------
  843. unsigned char sensorCount() {
  844. return _sensors.size();
  845. }
  846. unsigned char magnitudeCount() {
  847. return _magnitudes.size();
  848. }
  849. String magnitudeName(unsigned char index) {
  850. if (index < _magnitudes.size()) {
  851. sensor_magnitude_t magnitude = _magnitudes[index];
  852. return magnitude.sensor->slot(magnitude.local);
  853. }
  854. return String();
  855. }
  856. unsigned char magnitudeType(unsigned char index) {
  857. if (index < _magnitudes.size()) {
  858. return int(_magnitudes[index].type);
  859. }
  860. return MAGNITUDE_NONE;
  861. }
  862. unsigned char magnitudeIndex(unsigned char index) {
  863. if (index < _magnitudes.size()) {
  864. return int(_magnitudes[index].global);
  865. }
  866. return 0;
  867. }
  868. String magnitudeTopic(unsigned char type) {
  869. char buffer[16] = {0};
  870. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  871. return String(buffer);
  872. }
  873. String magnitudeTopicIndex(unsigned char index) {
  874. char topic[32] = {0};
  875. if (index < _magnitudes.size()) {
  876. sensor_magnitude_t magnitude = _magnitudes[index];
  877. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  878. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  879. } else {
  880. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  881. }
  882. }
  883. return String(topic);
  884. }
  885. String magnitudeUnits(unsigned char type) {
  886. char buffer[8] = {0};
  887. if (type < MAGNITUDE_MAX) {
  888. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  889. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  890. } else if (
  891. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  892. (_sensor_energy_units == ENERGY_KWH)) {
  893. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  894. } else if (
  895. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  896. (_sensor_power_units == POWER_KILOWATTS)) {
  897. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  898. } else {
  899. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  900. }
  901. }
  902. return String(buffer);
  903. }
  904. // -----------------------------------------------------------------------------
  905. void sensorSetup() {
  906. // Backwards compatibility
  907. _sensorBackwards();
  908. // Load sensors
  909. _sensorLoad();
  910. _sensorInit();
  911. // Configure stored values
  912. _sensorConfigure();
  913. // Websockets
  914. #if WEB_SUPPORT
  915. wsOnSendRegister(_sensorWebSocketStart);
  916. wsOnSendRegister(_sensorWebSocketSendData);
  917. wsOnAfterParseRegister(_sensorConfigure);
  918. #endif
  919. // API
  920. #if API_SUPPORT
  921. _sensorAPISetup();
  922. #endif
  923. // Terminal
  924. #if TERMINAL_SUPPORT
  925. _sensorInitCommands();
  926. #endif
  927. settingsRegisterKeyCheck(_sensorKeyCheck);
  928. // Register loop
  929. espurnaRegisterLoop(sensorLoop);
  930. }
  931. void sensorLoop() {
  932. // Check if we still have uninitialized sensors
  933. static unsigned long last_init = 0;
  934. if (!_sensors_ready) {
  935. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  936. last_init = millis();
  937. _sensorInit();
  938. }
  939. }
  940. if (_magnitudes.size() == 0) return;
  941. // Tick hook
  942. _sensorTick();
  943. // Check if we should read new data
  944. static unsigned long last_update = 0;
  945. static unsigned long report_count = 0;
  946. static unsigned long save_count = 0;
  947. if (millis() - last_update > _sensor_read_interval) {
  948. last_update = millis();
  949. report_count = (report_count + 1) % _sensor_report_every;
  950. double current;
  951. double filtered;
  952. // Pre-read hook
  953. _sensorPre();
  954. // Get the first relay state
  955. #if SENSOR_POWER_CHECK_STATUS
  956. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  957. #endif
  958. // Get readings
  959. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  960. sensor_magnitude_t magnitude = _magnitudes[i];
  961. if (magnitude.sensor->status()) {
  962. // -------------------------------------------------------------
  963. // Instant value
  964. // -------------------------------------------------------------
  965. current = magnitude.sensor->value(magnitude.local);
  966. // Completely remove spurious values if relay is OFF
  967. #if SENSOR_POWER_CHECK_STATUS
  968. if (relay_off) {
  969. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  970. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  971. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  972. magnitude.type == MAGNITUDE_CURRENT ||
  973. magnitude.type == MAGNITUDE_ENERGY_DELTA
  974. ) {
  975. current = 0;
  976. }
  977. }
  978. #endif
  979. // -------------------------------------------------------------
  980. // Processing (filters)
  981. // -------------------------------------------------------------
  982. magnitude.filter->add(current);
  983. // Special case for MovingAvergaeFilter
  984. if (MAGNITUDE_COUNT == magnitude.type ||
  985. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  986. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  987. current = magnitude.filter->result();
  988. }
  989. current = _magnitudeProcess(magnitude.type, current);
  990. _magnitudes[i].current = current;
  991. // -------------------------------------------------------------
  992. // Debug
  993. // -------------------------------------------------------------
  994. #if SENSOR_DEBUG
  995. {
  996. char buffer[64];
  997. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  998. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  999. magnitude.sensor->slot(magnitude.local).c_str(),
  1000. magnitudeTopic(magnitude.type).c_str(),
  1001. buffer,
  1002. magnitudeUnits(magnitude.type).c_str()
  1003. );
  1004. }
  1005. #endif // SENSOR_DEBUG
  1006. // -------------------------------------------------------------
  1007. // Report
  1008. // (we do it every _sensor_report_every readings)
  1009. // -------------------------------------------------------------
  1010. if (0 == report_count) {
  1011. filtered = magnitude.filter->result();
  1012. magnitude.filter->reset();
  1013. filtered = _magnitudeProcess(magnitude.type, filtered);
  1014. _magnitudes[i].filtered = filtered;
  1015. // Check if there is a minimum change threshold to report
  1016. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1017. _magnitudes[i].reported = filtered;
  1018. _sensorReport(i, filtered);
  1019. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1020. // -------------------------------------------------------------
  1021. // Saving to EEPROM
  1022. // (we do it every _sensor_save_every readings)
  1023. // -------------------------------------------------------------
  1024. if (_sensor_save_every > 0) {
  1025. save_count = (save_count + 1) % _sensor_save_every;
  1026. if (0 == save_count) {
  1027. if (MAGNITUDE_ENERGY == magnitude.type) {
  1028. setSetting("eneTotal", current);
  1029. saveSettings();
  1030. }
  1031. } // if (0 == save_count)
  1032. } // if (_sensor_save_every > 0)
  1033. } // if (report_count == 0)
  1034. } // if (magnitude.sensor->status())
  1035. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1036. // Post-read hook
  1037. _sensorPost();
  1038. #if WEB_SUPPORT
  1039. wsSend(_sensorWebSocketSendData);
  1040. #endif
  1041. #if THINGSPEAK_SUPPORT
  1042. if (report_count == 0) tspkFlush();
  1043. #endif
  1044. }
  1045. }
  1046. #endif // SENSOR_SUPPORT