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.

1177 lines
38 KiB

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