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.

1145 lines
37 KiB

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