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.

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