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.

1416 lines
46 KiB

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