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.

1126 lines
36 KiB

7 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/MaxFilter.h"
  8. #include "filters/MedianFilter.h"
  9. #include "filters/MovingAverageFilter.h"
  10. #include "sensors/BaseSensor.h"
  11. typedef struct {
  12. BaseSensor * sensor; // Sensor object
  13. BaseFilter * filter; // Filter object
  14. unsigned char local; // Local index in its provider
  15. unsigned char type; // Type of measurement
  16. unsigned char global; // Global index in its type
  17. double current; // Current (last) value, unfiltered
  18. double filtered; // Filtered (averaged) value
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. } sensor_magnitude_t;
  22. std::vector<BaseSensor *> _sensors;
  23. std::vector<sensor_magnitude_t> _magnitudes;
  24. bool _sensors_ready = false;
  25. unsigned char _counts[MAGNITUDE_MAX];
  26. bool _sensor_realtime = API_REAL_TIME_VALUES;
  27. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  28. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  29. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  30. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  31. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  32. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  33. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  34. String _sensor_energy_reset_ts = String();
  35. // -----------------------------------------------------------------------------
  36. // Private
  37. // -----------------------------------------------------------------------------
  38. unsigned char _magnitudeDecimals(unsigned char type) {
  39. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  40. if (type == MAGNITUDE_ENERGY ||
  41. type == MAGNITUDE_ENERGY_DELTA) {
  42. if (_sensor_energy_units == ENERGY_KWH) return 3;
  43. }
  44. if (type == MAGNITUDE_POWER_ACTIVE ||
  45. type == MAGNITUDE_POWER_APPARENT ||
  46. type == MAGNITUDE_POWER_REACTIVE) {
  47. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  48. }
  49. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  50. return 0;
  51. }
  52. double _magnitudeProcess(unsigned char type, double value) {
  53. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  54. if (type == MAGNITUDE_TEMPERATURE) {
  55. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  56. value = value + _sensor_temperature_correction;
  57. }
  58. if (type == MAGNITUDE_HUMIDITY) {
  59. value = constrain(value + _sensor_humidity_correction, 0, 100);
  60. }
  61. if (type == MAGNITUDE_ENERGY ||
  62. type == MAGNITUDE_ENERGY_DELTA) {
  63. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  64. }
  65. if (type == MAGNITUDE_POWER_ACTIVE ||
  66. type == MAGNITUDE_POWER_APPARENT ||
  67. type == MAGNITUDE_POWER_REACTIVE) {
  68. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  69. }
  70. return roundTo(value, _magnitudeDecimals(type));
  71. }
  72. // -----------------------------------------------------------------------------
  73. #if WEB_SUPPORT
  74. bool _sensorWebSocketOnReceive(const char * key, JsonVariant& value) {
  75. if (strncmp(key, "pwr", 3) == 0) return true;
  76. if (strncmp(key, "sns", 3) == 0) return true;
  77. if (strncmp(key, "tmp", 3) == 0) return true;
  78. if (strncmp(key, "hum", 3) == 0) return true;
  79. if (strncmp(key, "energy", 6) == 0) return true;
  80. return false;
  81. }
  82. void _sensorWebSocketSendData(JsonObject& root) {
  83. char buffer[10];
  84. bool hasTemperature = false;
  85. bool hasHumidity = false;
  86. JsonArray& list = root.createNestedArray("magnitudes");
  87. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  88. sensor_magnitude_t magnitude = _magnitudes[i];
  89. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  90. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  91. JsonObject& element = list.createNestedObject();
  92. element["index"] = int(magnitude.global);
  93. element["type"] = int(magnitude.type);
  94. element["value"] = String(buffer);
  95. element["units"] = magnitudeUnits(magnitude.type);
  96. element["error"] = magnitude.sensor->error();
  97. if (magnitude.type == MAGNITUDE_ENERGY) {
  98. if (_sensor_energy_reset_ts.length() == 0) _sensorReset();
  99. element["description"] = magnitude.sensor->slot(magnitude.local) + _sensor_energy_reset_ts;
  100. } else {
  101. element["description"] = magnitude.sensor->slot(magnitude.local);
  102. }
  103. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  104. if (magnitude.type == MAGNITUDE_HUMIDITY) hasHumidity = true;
  105. }
  106. if (hasTemperature) root["temperatureVisible"] = 1;
  107. if (hasHumidity) root["humidityVisible"] = 1;
  108. }
  109. void _sensorWebSocketStart(JsonObject& root) {
  110. for (unsigned char i=0; i<_sensors.size(); i++) {
  111. BaseSensor * sensor = _sensors[i];
  112. #if EMON_ANALOG_SUPPORT
  113. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  114. root["emonVisible"] = 1;
  115. root["pwrVisible"] = 1;
  116. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  117. }
  118. #endif
  119. #if HLW8012_SUPPORT
  120. if (sensor->getID() == SENSOR_HLW8012_ID) {
  121. root["hlwVisible"] = 1;
  122. root["pwrVisible"] = 1;
  123. }
  124. #endif
  125. #if CSE7766_SUPPORT
  126. if (sensor->getID() == SENSOR_CSE7766_ID) {
  127. root["cseVisible"] = 1;
  128. root["pwrVisible"] = 1;
  129. }
  130. #endif
  131. #if V9261F_SUPPORT
  132. if (sensor->getID() == SENSOR_V9261F_ID) {
  133. root["pwrVisible"] = 1;
  134. }
  135. #endif
  136. #if ECH1560_SUPPORT
  137. if (sensor->getID() == SENSOR_ECH1560_ID) {
  138. root["pwrVisible"] = 1;
  139. }
  140. #endif
  141. #if PZEM004T_SUPPORT
  142. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  143. root["pzemVisible"] = 1;
  144. root["pwrVisible"] = 1;
  145. }
  146. #endif
  147. }
  148. if (_magnitudes.size() > 0) {
  149. root["sensorsVisible"] = 1;
  150. //root["apiRealTime"] = _sensor_realtime;
  151. root["pwrUnits"] = _sensor_power_units;
  152. root["energyUnits"] = _sensor_energy_units;
  153. root["tmpUnits"] = _sensor_temperature_units;
  154. root["tmpCorrection"] = _sensor_temperature_correction;
  155. root["humCorrection"] = _sensor_humidity_correction;
  156. root["snsRead"] = _sensor_read_interval / 1000;
  157. root["snsReport"] = _sensor_report_every;
  158. }
  159. /*
  160. // Sensors manifest
  161. JsonArray& manifest = root.createNestedArray("manifest");
  162. #if BMX280_SUPPORT
  163. BMX280Sensor::manifest(manifest);
  164. #endif
  165. // Sensors configuration
  166. JsonArray& sensors = root.createNestedArray("sensors");
  167. for (unsigned char i; i<_sensors.size(); i++) {
  168. JsonObject& sensor = sensors.createNestedObject();
  169. sensor["index"] = i;
  170. sensor["id"] = _sensors[i]->getID();
  171. _sensors[i]->getConfig(sensor);
  172. }
  173. */
  174. }
  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
  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 _sensorReset() {
  228. #if NTP_SUPPORT
  229. if (ntpSynced()) {
  230. _sensor_energy_reset_ts = String(" (since ") + ntpDateTime() + String(")");
  231. }
  232. #endif
  233. }
  234. // -----------------------------------------------------------------------------
  235. // Sensor initialization
  236. // -----------------------------------------------------------------------------
  237. void _sensorLoad() {
  238. /*
  239. This is temporal, in the future sensors will be initialized based on
  240. soft configuration (data stored in EEPROM config) so you will be able
  241. to define and configure new sensors on the fly
  242. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  243. loaded and initialized here. If you want to add new sensors of the same type
  244. just duplicate the block and change the arguments for the set* methods.
  245. Check the DHT block below for an example
  246. */
  247. #if AM2320_SUPPORT
  248. {
  249. AM2320Sensor * sensor = new AM2320Sensor();
  250. sensor->setAddress(AM2320_ADDRESS);
  251. _sensors.push_back(sensor);
  252. }
  253. #endif
  254. #if ANALOG_SUPPORT
  255. {
  256. AnalogSensor * sensor = new AnalogSensor();
  257. _sensors.push_back(sensor);
  258. }
  259. #endif
  260. #if BH1750_SUPPORT
  261. {
  262. BH1750Sensor * sensor = new BH1750Sensor();
  263. sensor->setAddress(BH1750_ADDRESS);
  264. sensor->setMode(BH1750_MODE);
  265. _sensors.push_back(sensor);
  266. }
  267. #endif
  268. #if BMX280_SUPPORT
  269. {
  270. BMX280Sensor * sensor = new BMX280Sensor();
  271. sensor->setAddress(BMX280_ADDRESS);
  272. _sensors.push_back(sensor);
  273. }
  274. #endif
  275. #if CSE7766_SUPPORT
  276. {
  277. CSE7766Sensor * sensor = new CSE7766Sensor();
  278. sensor->setRX(CSE7766_PIN);
  279. _sensors.push_back(sensor);
  280. }
  281. #endif
  282. #if DALLAS_SUPPORT
  283. {
  284. DallasSensor * sensor = new DallasSensor();
  285. sensor->setGPIO(DALLAS_PIN);
  286. _sensors.push_back(sensor);
  287. }
  288. #endif
  289. #if DHT_SUPPORT
  290. {
  291. DHTSensor * sensor = new DHTSensor();
  292. sensor->setGPIO(DHT_PIN);
  293. sensor->setType(DHT_TYPE);
  294. _sensors.push_back(sensor);
  295. }
  296. #endif
  297. /*
  298. // Example on how to add a second DHT sensor
  299. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  300. #if DHT_SUPPORT
  301. {
  302. DHTSensor * sensor = new DHTSensor();
  303. sensor->setGPIO(DHT2_PIN);
  304. sensor->setType(DHT2_TYPE);
  305. _sensors.push_back(sensor);
  306. }
  307. #endif
  308. */
  309. #if DIGITAL_SUPPORT
  310. {
  311. DigitalSensor * sensor = new DigitalSensor();
  312. sensor->setGPIO(DIGITAL_PIN);
  313. sensor->setMode(DIGITAL_PIN_MODE);
  314. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  315. _sensors.push_back(sensor);
  316. }
  317. #endif
  318. #if ECH1560_SUPPORT
  319. {
  320. ECH1560Sensor * sensor = new ECH1560Sensor();
  321. sensor->setCLK(ECH1560_CLK_PIN);
  322. sensor->setMISO(ECH1560_MISO_PIN);
  323. sensor->setInverted(ECH1560_INVERTED);
  324. _sensors.push_back(sensor);
  325. }
  326. #endif
  327. #if EMON_ADC121_SUPPORT
  328. {
  329. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  330. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  331. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  332. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  333. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  334. _sensors.push_back(sensor);
  335. }
  336. #endif
  337. #if EMON_ADS1X15_SUPPORT
  338. {
  339. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  340. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  341. sensor->setType(EMON_ADS1X15_TYPE);
  342. sensor->setMask(EMON_ADS1X15_MASK);
  343. sensor->setGain(EMON_ADS1X15_GAIN);
  344. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  345. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  346. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  347. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  348. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  349. _sensors.push_back(sensor);
  350. }
  351. #endif
  352. #if EMON_ANALOG_SUPPORT
  353. {
  354. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  355. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  356. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  357. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  358. _sensors.push_back(sensor);
  359. }
  360. #endif
  361. #if EVENTS_SUPPORT
  362. {
  363. EventSensor * sensor = new EventSensor();
  364. sensor->setGPIO(EVENTS_PIN);
  365. sensor->setMode(EVENTS_PIN_MODE);
  366. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  367. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  368. _sensors.push_back(sensor);
  369. }
  370. #endif
  371. #if GEIGER_SUPPORT
  372. {
  373. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  374. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  375. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  376. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  377. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  378. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  379. _sensors.push_back(sensor);
  380. }
  381. #endif
  382. #if GUVAS12SD_SUPPORT
  383. {
  384. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  385. sensor->setGPIO(GUVAS12SD_PIN);
  386. _sensors.push_back(sensor);
  387. }
  388. #endif
  389. #if HCSR04_SUPPORT
  390. {
  391. HCSR04Sensor * sensor = new HCSR04Sensor();
  392. sensor->setTrigger(HCSR04_TRIGGER);
  393. sensor->setEcho(HCSR04_ECHO);
  394. _sensors.push_back(sensor);
  395. }
  396. #endif
  397. #if HLW8012_SUPPORT
  398. {
  399. HLW8012Sensor * sensor = new HLW8012Sensor();
  400. sensor->setSEL(HLW8012_SEL_PIN);
  401. sensor->setCF(HLW8012_CF_PIN);
  402. sensor->setCF1(HLW8012_CF1_PIN);
  403. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  404. _sensors.push_back(sensor);
  405. }
  406. #endif
  407. #if MHZ19_SUPPORT
  408. {
  409. MHZ19Sensor * sensor = new MHZ19Sensor();
  410. sensor->setRX(MHZ19_RX_PIN);
  411. sensor->setTX(MHZ19_TX_PIN);
  412. _sensors.push_back(sensor);
  413. }
  414. #endif
  415. #if SENSEAIR_SUPPORT
  416. {
  417. SenseAirSensor * sensor = new SenseAirSensor();
  418. sensor->setRX(SENSEAIR_RX_PIN);
  419. sensor->setTX(SENSEAIR_TX_PIN);
  420. _sensors.push_back(sensor);
  421. }
  422. #endif
  423. #if PMSX003_SUPPORT
  424. {
  425. PMSX003Sensor * sensor = new PMSX003Sensor();
  426. sensor->setRX(PMS_RX_PIN);
  427. sensor->setTX(PMS_TX_PIN);
  428. sensor->setType(PMS_TYPE);
  429. _sensors.push_back(sensor);
  430. }
  431. #endif
  432. #if PZEM004T_SUPPORT
  433. {
  434. PZEM004TSensor * sensor = new PZEM004TSensor();
  435. #if PZEM004T_USE_SOFT
  436. sensor->setRX(PZEM004T_RX_PIN);
  437. sensor->setTX(PZEM004T_TX_PIN);
  438. #else
  439. sensor->setSerial(& PZEM004T_HW_PORT);
  440. #endif
  441. _sensors.push_back(sensor);
  442. }
  443. #endif
  444. #if SHT3X_I2C_SUPPORT
  445. {
  446. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  447. sensor->setAddress(SHT3X_I2C_ADDRESS);
  448. _sensors.push_back(sensor);
  449. }
  450. #endif
  451. #if SI7021_SUPPORT
  452. {
  453. SI7021Sensor * sensor = new SI7021Sensor();
  454. sensor->setAddress(SI7021_ADDRESS);
  455. _sensors.push_back(sensor);
  456. }
  457. #endif
  458. #if TMP3X_SUPPORT
  459. {
  460. TMP3XSensor * sensor = new TMP3XSensor();
  461. sensor->setType(TMP3X_TYPE);
  462. _sensors.push_back(sensor);
  463. }
  464. #endif
  465. #if V9261F_SUPPORT
  466. {
  467. V9261FSensor * sensor = new V9261FSensor();
  468. sensor->setRX(V9261F_PIN);
  469. sensor->setInverted(V9261F_PIN_INVERSE);
  470. _sensors.push_back(sensor);
  471. }
  472. #endif
  473. }
  474. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  475. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  476. }
  477. void _sensorInit() {
  478. _sensors_ready = true;
  479. for (unsigned char i=0; i<_sensors.size(); i++) {
  480. // Do not process an already initialized sensor
  481. if (_sensors[i]->ready()) continue;
  482. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  483. // Force sensor to reload config
  484. _sensors[i]->begin();
  485. if (!_sensors[i]->ready()) {
  486. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  487. _sensors_ready = false;
  488. continue;
  489. }
  490. // Initialize magnitudes
  491. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  492. unsigned char type = _sensors[i]->type(k);
  493. sensor_magnitude_t new_magnitude;
  494. new_magnitude.sensor = _sensors[i];
  495. new_magnitude.local = k;
  496. new_magnitude.type = type;
  497. new_magnitude.global = _counts[type];
  498. new_magnitude.current = 0;
  499. new_magnitude.filtered = 0;
  500. new_magnitude.reported = 0;
  501. new_magnitude.min_change = 0;
  502. if (type == MAGNITUDE_DIGITAL) {
  503. new_magnitude.filter = new MaxFilter();
  504. } else if (type == MAGNITUDE_EVENTS || type == MAGNITUDE_GEIGER_CPM|| type == MAGNITUDE_GEIGER_SIEVERT) { // For geiger counting moving average filter is the most appropriate if needed at all.
  505. new_magnitude.filter = new MovingAverageFilter();
  506. } else {
  507. new_magnitude.filter = new MedianFilter();
  508. }
  509. new_magnitude.filter->resize(_sensor_report_every);
  510. _magnitudes.push_back(new_magnitude);
  511. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  512. _counts[type] = _counts[type] + 1;
  513. }
  514. // Hook callback
  515. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  516. _sensorCallback(i, type, payload);
  517. });
  518. // Custom initializations
  519. #if EMON_ANALOG_SUPPORT
  520. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  521. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  522. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  523. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  524. }
  525. #endif // EMON_ANALOG_SUPPORT
  526. #if HLW8012_SUPPORT
  527. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  528. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  529. double value;
  530. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  531. if (value > 0) sensor->setCurrentRatio(value);
  532. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  533. if (value > 0) sensor->setVoltageRatio(value);
  534. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  535. if (value > 0) sensor->setPowerRatio(value);
  536. }
  537. #endif // HLW8012_SUPPORT
  538. #if CSE7766_SUPPORT
  539. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  540. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  541. double value;
  542. value = getSetting("pwrRatioC", 0).toFloat();
  543. if (value > 0) sensor->setCurrentRatio(value);
  544. value = getSetting("pwrRatioV", 0).toFloat();
  545. if (value > 0) sensor->setVoltageRatio(value);
  546. value = getSetting("pwrRatioP", 0).toFloat();
  547. if (value > 0) sensor->setPowerRatio(value);
  548. }
  549. #endif // CSE7766_SUPPORT
  550. }
  551. }
  552. void _sensorConfigure() {
  553. // General sensor settings
  554. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  555. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  556. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  557. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  558. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  559. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  560. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  561. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  562. // Specific sensor settings
  563. for (unsigned char i=0; i<_sensors.size(); i++) {
  564. #if EMON_ANALOG_SUPPORT
  565. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  566. double value;
  567. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  568. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  569. sensor->expectedPower(0, value);
  570. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  571. }
  572. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  573. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  574. delSetting("pwrRatioC");
  575. }
  576. if (getSetting("pwrResetE", 0).toInt() == 1) {
  577. sensor->resetEnergy();
  578. _sensorReset();
  579. }
  580. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  581. }
  582. #endif // EMON_ANALOG_SUPPORT
  583. #if EMON_ADC121_SUPPORT
  584. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  585. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  586. if (getSetting("pwrResetE", 0).toInt() == 1) {
  587. sensor->resetEnergy();
  588. _sensorReset();
  589. }
  590. }
  591. #endif
  592. #if EMON_ADS1X15_SUPPORT
  593. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  594. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  595. if (getSetting("pwrResetE", 0).toInt() == 1) {
  596. sensor->resetEnergy();
  597. _sensorReset();
  598. }
  599. }
  600. #endif
  601. #if HLW8012_SUPPORT
  602. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  603. double value;
  604. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  605. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  606. sensor->expectedCurrent(value);
  607. setSetting("pwrRatioC", sensor->getCurrentRatio());
  608. }
  609. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  610. sensor->expectedVoltage(value);
  611. setSetting("pwrRatioV", sensor->getVoltageRatio());
  612. }
  613. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  614. sensor->expectedPower(value);
  615. setSetting("pwrRatioP", sensor->getPowerRatio());
  616. }
  617. if (getSetting("pwrResetE", 0).toInt() == 1) {
  618. sensor->resetEnergy();
  619. _sensorReset();
  620. }
  621. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  622. sensor->resetRatios();
  623. delSetting("pwrRatioC");
  624. delSetting("pwrRatioV");
  625. delSetting("pwrRatioP");
  626. }
  627. }
  628. #endif // HLW8012_SUPPORT
  629. #if CSE7766_SUPPORT
  630. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  631. double value;
  632. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  633. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  634. sensor->expectedCurrent(value);
  635. setSetting("pwrRatioC", sensor->getCurrentRatio());
  636. }
  637. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  638. sensor->expectedVoltage(value);
  639. setSetting("pwrRatioV", sensor->getVoltageRatio());
  640. }
  641. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  642. sensor->expectedPower(value);
  643. setSetting("pwrRatioP", sensor->getPowerRatio());
  644. }
  645. if (getSetting("pwrResetE", 0).toInt() == 1) {
  646. sensor->resetEnergy();
  647. _sensorReset();
  648. }
  649. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  650. sensor->resetRatios();
  651. delSetting("pwrRatioC");
  652. delSetting("pwrRatioV");
  653. delSetting("pwrRatioP");
  654. }
  655. }
  656. #endif // CSE7766_SUPPORT
  657. }
  658. // Update filter sizes
  659. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  660. _magnitudes[i].filter->resize(_sensor_report_every);
  661. }
  662. // Save settings
  663. delSetting("pwrExpectedP");
  664. delSetting("pwrExpectedC");
  665. delSetting("pwrExpectedV");
  666. delSetting("pwrResetCalibration");
  667. delSetting("pwrResetE");
  668. saveSettings();
  669. }
  670. // -----------------------------------------------------------------------------
  671. // Public
  672. // -----------------------------------------------------------------------------
  673. unsigned char sensorCount() {
  674. return _sensors.size();
  675. }
  676. unsigned char magnitudeCount() {
  677. return _magnitudes.size();
  678. }
  679. String magnitudeName(unsigned char index) {
  680. if (index < _magnitudes.size()) {
  681. sensor_magnitude_t magnitude = _magnitudes[index];
  682. return magnitude.sensor->slot(magnitude.local);
  683. }
  684. return String();
  685. }
  686. unsigned char magnitudeType(unsigned char index) {
  687. if (index < _magnitudes.size()) {
  688. return int(_magnitudes[index].type);
  689. }
  690. return MAGNITUDE_NONE;
  691. }
  692. unsigned char magnitudeIndex(unsigned char index) {
  693. if (index < _magnitudes.size()) {
  694. return int(_magnitudes[index].global);
  695. }
  696. return 0;
  697. }
  698. String magnitudeTopic(unsigned char type) {
  699. char buffer[16] = {0};
  700. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  701. return String(buffer);
  702. }
  703. String magnitudeTopicIndex(unsigned char index) {
  704. char topic[32] = {0};
  705. if (index < _magnitudes.size()) {
  706. sensor_magnitude_t magnitude = _magnitudes[index];
  707. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  708. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  709. } else {
  710. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  711. }
  712. }
  713. return String(topic);
  714. }
  715. String magnitudeUnits(unsigned char type) {
  716. char buffer[8] = {0};
  717. if (type < MAGNITUDE_MAX) {
  718. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  719. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  720. } else if (
  721. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  722. (_sensor_energy_units == ENERGY_KWH)) {
  723. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  724. } else if (
  725. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  726. (_sensor_power_units == POWER_KILOWATTS)) {
  727. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  728. } else {
  729. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  730. }
  731. }
  732. return String(buffer);
  733. }
  734. // -----------------------------------------------------------------------------
  735. void sensorSetup() {
  736. // Backwards compatibility
  737. moveSetting("powerUnits", "pwrUnits");
  738. // Load sensors
  739. _sensorLoad();
  740. _sensorInit();
  741. // Configure stored values
  742. _sensorConfigure();
  743. #if WEB_SUPPORT
  744. // Websockets
  745. wsOnSendRegister(_sensorWebSocketStart);
  746. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  747. wsOnSendRegister(_sensorWebSocketSendData);
  748. wsOnAfterParseRegister(_sensorConfigure);
  749. // API
  750. _sensorAPISetup();
  751. #endif
  752. #if TERMINAL_SUPPORT
  753. _sensorInitCommands();
  754. #endif
  755. // Register loop
  756. espurnaRegisterLoop(sensorLoop);
  757. }
  758. void sensorLoop() {
  759. // Check if we still have uninitialized sensors
  760. static unsigned long last_init = 0;
  761. if (!_sensors_ready) {
  762. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  763. last_init = millis();
  764. _sensorInit();
  765. }
  766. }
  767. if (_magnitudes.size() == 0) return;
  768. // Tick hook
  769. _sensorTick();
  770. // Check if we should read new data
  771. static unsigned long last_update = 0;
  772. static unsigned long report_count = 0;
  773. if (millis() - last_update > _sensor_read_interval) {
  774. last_update = millis();
  775. report_count = (report_count + 1) % _sensor_report_every;
  776. double current;
  777. double filtered;
  778. char buffer[64];
  779. // Pre-read hook
  780. _sensorPre();
  781. // Get the first relay state
  782. #if SENSOR_POWER_CHECK_STATUS
  783. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  784. #endif
  785. // Get readings
  786. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  787. sensor_magnitude_t magnitude = _magnitudes[i];
  788. if (magnitude.sensor->status()) {
  789. current = magnitude.sensor->value(magnitude.local);
  790. // Completely remove spurious values if relay is OFF
  791. #if SENSOR_POWER_CHECK_STATUS
  792. if (relay_off) {
  793. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  794. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  795. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  796. magnitude.type == MAGNITUDE_CURRENT ||
  797. magnitude.type == MAGNITUDE_ENERGY_DELTA
  798. ) {
  799. current = 0;
  800. }
  801. }
  802. #endif
  803. magnitude.filter->add(current);
  804. // Special case
  805. if (magnitude.type == MAGNITUDE_EVENTS) {
  806. current = magnitude.filter->result();
  807. }
  808. current = _magnitudeProcess(magnitude.type, current);
  809. _magnitudes[i].current = current;
  810. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  811. // Debug
  812. #if SENSOR_DEBUG
  813. {
  814. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  815. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  816. magnitude.sensor->slot(magnitude.local).c_str(),
  817. magnitudeTopic(magnitude.type).c_str(),
  818. buffer,
  819. magnitudeUnits(magnitude.type).c_str()
  820. );
  821. }
  822. #endif // SENSOR_DEBUG
  823. // Time to report (we do it every _sensor_report_every readings)
  824. if (report_count == 0) {
  825. filtered = magnitude.filter->result();
  826. magnitude.filter->reset();
  827. filtered = _magnitudeProcess(magnitude.type, filtered);
  828. _magnitudes[i].filtered = filtered;
  829. // Check if there is a minimum change threshold to report
  830. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  831. _magnitudes[i].reported = filtered;
  832. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  833. #if BROKER_SUPPORT
  834. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  835. #endif
  836. #if MQTT_SUPPORT
  837. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  838. #if SENSOR_PUBLISH_ADDRESSES
  839. char topic[32];
  840. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  841. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  842. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  843. } else {
  844. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  845. }
  846. #endif // SENSOR_PUBLISH_ADDRESSES
  847. #endif // MQTT_SUPPORT
  848. #if INFLUXDB_SUPPORT
  849. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  850. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  851. } else {
  852. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  853. }
  854. #endif // INFLUXDB_SUPPORT
  855. #if THINGSPEAK_SUPPORT
  856. tspkEnqueueMeasurement(i, buffer);
  857. #endif
  858. #if DOMOTICZ_SUPPORT
  859. {
  860. char key[15];
  861. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  862. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  863. int status;
  864. if (filtered > 70) {
  865. status = HUMIDITY_WET;
  866. } else if (filtered > 45) {
  867. status = HUMIDITY_COMFORTABLE;
  868. } else if (filtered > 30) {
  869. status = HUMIDITY_NORMAL;
  870. } else {
  871. status = HUMIDITY_DRY;
  872. }
  873. char status_buf[5];
  874. itoa(status, status_buf, 10);
  875. domoticzSend(key, buffer, status_buf);
  876. } else {
  877. domoticzSend(key, 0, buffer);
  878. }
  879. }
  880. #endif // DOMOTICZ_SUPPORT
  881. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  882. } // if (report_count == 0)
  883. } // if (magnitude.sensor->status())
  884. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  885. // Post-read hook
  886. _sensorPost();
  887. #if WEB_SUPPORT
  888. wsSend(_sensorWebSocketSendData);
  889. #endif
  890. #if THINGSPEAK_SUPPORT
  891. if (report_count == 0) tspkFlush();
  892. #endif
  893. }
  894. }
  895. #endif // SENSOR_SUPPORT