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.

1112 lines
35 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 GUVAS12SD_SUPPORT
  371. {
  372. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  373. sensor->setGPIO(GUVAS12SD_PIN);
  374. _sensors.push_back(sensor);
  375. }
  376. #endif
  377. #if HCSR04_SUPPORT
  378. {
  379. HCSR04Sensor * sensor = new HCSR04Sensor();
  380. sensor->setTrigger(HCSR04_TRIGGER);
  381. sensor->setEcho(HCSR04_ECHO);
  382. _sensors.push_back(sensor);
  383. }
  384. #endif
  385. #if HLW8012_SUPPORT
  386. {
  387. HLW8012Sensor * sensor = new HLW8012Sensor();
  388. sensor->setSEL(HLW8012_SEL_PIN);
  389. sensor->setCF(HLW8012_CF_PIN);
  390. sensor->setCF1(HLW8012_CF1_PIN);
  391. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  392. _sensors.push_back(sensor);
  393. }
  394. #endif
  395. #if MHZ19_SUPPORT
  396. {
  397. MHZ19Sensor * sensor = new MHZ19Sensor();
  398. sensor->setRX(MHZ19_RX_PIN);
  399. sensor->setTX(MHZ19_TX_PIN);
  400. _sensors.push_back(sensor);
  401. }
  402. #endif
  403. #if SENSEAIR_SUPPORT
  404. {
  405. SenseAirSensor * sensor = new SenseAirSensor();
  406. sensor->setRX(SENSEAIR_RX_PIN);
  407. sensor->setTX(SENSEAIR_TX_PIN);
  408. _sensors.push_back(sensor);
  409. }
  410. #endif
  411. #if PMSX003_SUPPORT
  412. {
  413. PMSX003Sensor * sensor = new PMSX003Sensor();
  414. sensor->setRX(PMS_RX_PIN);
  415. sensor->setTX(PMS_TX_PIN);
  416. _sensors.push_back(sensor);
  417. }
  418. #endif
  419. #if PZEM004T_SUPPORT
  420. {
  421. PZEM004TSensor * sensor = new PZEM004TSensor();
  422. #if PZEM004T_USE_SOFT
  423. sensor->setRX(PZEM004T_RX_PIN);
  424. sensor->setTX(PZEM004T_TX_PIN);
  425. #else
  426. sensor->setSerial(& PZEM004T_HW_PORT);
  427. #endif
  428. _sensors.push_back(sensor);
  429. }
  430. #endif
  431. #if SHT3X_I2C_SUPPORT
  432. {
  433. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  434. sensor->setAddress(SHT3X_I2C_ADDRESS);
  435. _sensors.push_back(sensor);
  436. }
  437. #endif
  438. #if SI7021_SUPPORT
  439. {
  440. SI7021Sensor * sensor = new SI7021Sensor();
  441. sensor->setAddress(SI7021_ADDRESS);
  442. _sensors.push_back(sensor);
  443. }
  444. #endif
  445. #if TMP3X_SUPPORT
  446. {
  447. TMP3XSensor * sensor = new TMP3XSensor();
  448. sensor->setType(TMP3X_TYPE);
  449. _sensors.push_back(sensor);
  450. }
  451. #endif
  452. #if V9261F_SUPPORT
  453. {
  454. V9261FSensor * sensor = new V9261FSensor();
  455. sensor->setRX(V9261F_PIN);
  456. sensor->setInverted(V9261F_PIN_INVERSE);
  457. _sensors.push_back(sensor);
  458. }
  459. #endif
  460. }
  461. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  462. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  463. }
  464. void _sensorInit() {
  465. _sensors_ready = true;
  466. for (unsigned char i=0; i<_sensors.size(); i++) {
  467. // Do not process an already initialized sensor
  468. if (_sensors[i]->ready()) continue;
  469. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  470. // Force sensor to reload config
  471. _sensors[i]->begin();
  472. if (!_sensors[i]->ready()) {
  473. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  474. _sensors_ready = false;
  475. continue;
  476. }
  477. // Initialize magnitudes
  478. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  479. unsigned char type = _sensors[i]->type(k);
  480. sensor_magnitude_t new_magnitude;
  481. new_magnitude.sensor = _sensors[i];
  482. new_magnitude.local = k;
  483. new_magnitude.type = type;
  484. new_magnitude.global = _counts[type];
  485. new_magnitude.current = 0;
  486. new_magnitude.filtered = 0;
  487. new_magnitude.reported = 0;
  488. new_magnitude.min_change = 0;
  489. if (type == MAGNITUDE_DIGITAL) {
  490. new_magnitude.filter = new MaxFilter();
  491. } else if (type == MAGNITUDE_EVENTS) {
  492. new_magnitude.filter = new MovingAverageFilter();
  493. } else {
  494. new_magnitude.filter = new MedianFilter();
  495. }
  496. new_magnitude.filter->resize(_sensor_report_every);
  497. _magnitudes.push_back(new_magnitude);
  498. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  499. _counts[type] = _counts[type] + 1;
  500. }
  501. // Hook callback
  502. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  503. _sensorCallback(i, type, payload);
  504. });
  505. // Custom initializations
  506. #if EMON_ANALOG_SUPPORT
  507. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  508. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  509. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  510. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  511. }
  512. #endif // EMON_ANALOG_SUPPORT
  513. #if HLW8012_SUPPORT
  514. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  515. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  516. double value;
  517. value = getSetting("pwrRatioC", 0).toFloat();
  518. if (value > 0) sensor->setCurrentRatio(value);
  519. value = getSetting("pwrRatioV", 0).toFloat();
  520. if (value > 0) sensor->setVoltageRatio(value);
  521. value = getSetting("pwrRatioP", 0).toFloat();
  522. if (value > 0) sensor->setPowerRatio(value);
  523. }
  524. #endif // HLW8012_SUPPORT
  525. #if CSE7766_SUPPORT
  526. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  527. CSE7766Sensor * sensor = (CSE7766Sensor *) _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 // CSE7766_SUPPORT
  537. }
  538. }
  539. void _sensorConfigure() {
  540. // General sensor settings
  541. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  542. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  543. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  544. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  545. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  546. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  547. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  548. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  549. // Specific sensor settings
  550. for (unsigned char i=0; i<_sensors.size(); i++) {
  551. #if EMON_ANALOG_SUPPORT
  552. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  553. double value;
  554. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  555. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  556. sensor->expectedPower(0, value);
  557. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  558. }
  559. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  560. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  561. delSetting("pwrRatioC");
  562. }
  563. if (getSetting("pwrResetE", 0).toInt() == 1) {
  564. sensor->resetEnergy();
  565. _sensorReset();
  566. }
  567. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  568. }
  569. #endif // EMON_ANALOG_SUPPORT
  570. #if EMON_ADC121_SUPPORT
  571. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  572. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  573. if (getSetting("pwrResetE", 0).toInt() == 1) {
  574. sensor->resetEnergy();
  575. _sensorReset();
  576. }
  577. }
  578. #endif
  579. #if EMON_ADS1X15_SUPPORT
  580. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  581. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  582. if (getSetting("pwrResetE", 0).toInt() == 1) {
  583. sensor->resetEnergy();
  584. _sensorReset();
  585. }
  586. }
  587. #endif
  588. #if HLW8012_SUPPORT
  589. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  590. double value;
  591. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  592. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  593. sensor->expectedCurrent(value);
  594. setSetting("pwrRatioC", sensor->getCurrentRatio());
  595. }
  596. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  597. sensor->expectedVoltage(value);
  598. setSetting("pwrRatioV", sensor->getVoltageRatio());
  599. }
  600. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  601. sensor->expectedPower(value);
  602. setSetting("pwrRatioP", sensor->getPowerRatio());
  603. }
  604. if (getSetting("pwrResetE", 0).toInt() == 1) {
  605. sensor->resetEnergy();
  606. _sensorReset();
  607. }
  608. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  609. sensor->resetRatios();
  610. delSetting("pwrRatioC");
  611. delSetting("pwrRatioV");
  612. delSetting("pwrRatioP");
  613. }
  614. }
  615. #endif // HLW8012_SUPPORT
  616. #if CSE7766_SUPPORT
  617. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  618. double value;
  619. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  620. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  621. sensor->expectedCurrent(value);
  622. setSetting("pwrRatioC", sensor->getCurrentRatio());
  623. }
  624. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  625. sensor->expectedVoltage(value);
  626. setSetting("pwrRatioV", sensor->getVoltageRatio());
  627. }
  628. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  629. sensor->expectedPower(value);
  630. setSetting("pwrRatioP", sensor->getPowerRatio());
  631. }
  632. if (getSetting("pwrResetE", 0).toInt() == 1) {
  633. sensor->resetEnergy();
  634. _sensorReset();
  635. }
  636. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  637. sensor->resetRatios();
  638. delSetting("pwrRatioC");
  639. delSetting("pwrRatioV");
  640. delSetting("pwrRatioP");
  641. }
  642. }
  643. #endif // CSE7766_SUPPORT
  644. }
  645. // Update filter sizes
  646. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  647. _magnitudes[i].filter->resize(_sensor_report_every);
  648. }
  649. // Save settings
  650. delSetting("pwrExpectedP");
  651. delSetting("pwrExpectedC");
  652. delSetting("pwrExpectedV");
  653. delSetting("pwrResetCalibration");
  654. delSetting("pwrResetE");
  655. saveSettings();
  656. }
  657. // -----------------------------------------------------------------------------
  658. // Public
  659. // -----------------------------------------------------------------------------
  660. unsigned char sensorCount() {
  661. return _sensors.size();
  662. }
  663. unsigned char magnitudeCount() {
  664. return _magnitudes.size();
  665. }
  666. String magnitudeName(unsigned char index) {
  667. if (index < _magnitudes.size()) {
  668. sensor_magnitude_t magnitude = _magnitudes[index];
  669. return magnitude.sensor->slot(magnitude.local);
  670. }
  671. return String();
  672. }
  673. unsigned char magnitudeType(unsigned char index) {
  674. if (index < _magnitudes.size()) {
  675. return int(_magnitudes[index].type);
  676. }
  677. return MAGNITUDE_NONE;
  678. }
  679. unsigned char magnitudeIndex(unsigned char index) {
  680. if (index < _magnitudes.size()) {
  681. return int(_magnitudes[index].global);
  682. }
  683. return 0;
  684. }
  685. String magnitudeTopic(unsigned char type) {
  686. char buffer[16] = {0};
  687. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  688. return String(buffer);
  689. }
  690. String magnitudeTopicIndex(unsigned char index) {
  691. char topic[32] = {0};
  692. if (index < _magnitudes.size()) {
  693. sensor_magnitude_t magnitude = _magnitudes[index];
  694. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  695. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  696. } else {
  697. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  698. }
  699. }
  700. return String(topic);
  701. }
  702. String magnitudeUnits(unsigned char type) {
  703. char buffer[8] = {0};
  704. if (type < MAGNITUDE_MAX) {
  705. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  706. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  707. } else if (
  708. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  709. (_sensor_energy_units == ENERGY_KWH)) {
  710. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  711. } else if (
  712. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  713. (_sensor_power_units == POWER_KILOWATTS)) {
  714. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  715. } else {
  716. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  717. }
  718. }
  719. return String(buffer);
  720. }
  721. // -----------------------------------------------------------------------------
  722. void sensorSetup() {
  723. // Backwards compatibility
  724. moveSetting("powerUnits", "pwrUnits");
  725. // Load sensors
  726. _sensorLoad();
  727. _sensorInit();
  728. // Configure stored values
  729. _sensorConfigure();
  730. #if WEB_SUPPORT
  731. // Websockets
  732. wsOnSendRegister(_sensorWebSocketStart);
  733. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  734. wsOnSendRegister(_sensorWebSocketSendData);
  735. wsOnAfterParseRegister(_sensorConfigure);
  736. // API
  737. _sensorAPISetup();
  738. #endif
  739. #if TERMINAL_SUPPORT
  740. _sensorInitCommands();
  741. #endif
  742. // Register loop
  743. espurnaRegisterLoop(sensorLoop);
  744. }
  745. void sensorLoop() {
  746. // Check if we still have uninitialized sensors
  747. static unsigned long last_init = 0;
  748. if (!_sensors_ready) {
  749. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  750. last_init = millis();
  751. _sensorInit();
  752. }
  753. }
  754. if (_magnitudes.size() == 0) return;
  755. // Tick hook
  756. _sensorTick();
  757. // Check if we should read new data
  758. static unsigned long last_update = 0;
  759. static unsigned long report_count = 0;
  760. if (millis() - last_update > _sensor_read_interval) {
  761. last_update = millis();
  762. report_count = (report_count + 1) % _sensor_report_every;
  763. double current;
  764. double filtered;
  765. char buffer[64];
  766. // Pre-read hook
  767. _sensorPre();
  768. // Get the first relay state
  769. #if SENSOR_POWER_CHECK_STATUS
  770. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  771. #endif
  772. // Get readings
  773. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  774. sensor_magnitude_t magnitude = _magnitudes[i];
  775. if (magnitude.sensor->status()) {
  776. current = magnitude.sensor->value(magnitude.local);
  777. // Completely remove spurious values if relay is OFF
  778. #if SENSOR_POWER_CHECK_STATUS
  779. if (relay_off) {
  780. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  781. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  782. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  783. magnitude.type == MAGNITUDE_CURRENT ||
  784. magnitude.type == MAGNITUDE_ENERGY_DELTA
  785. ) {
  786. current = 0;
  787. }
  788. }
  789. #endif
  790. magnitude.filter->add(current);
  791. // Special case
  792. if (magnitude.type == MAGNITUDE_EVENTS) {
  793. current = magnitude.filter->result();
  794. }
  795. current = _magnitudeProcess(magnitude.type, current);
  796. _magnitudes[i].current = current;
  797. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  798. // Debug
  799. #if SENSOR_DEBUG
  800. {
  801. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  802. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  803. magnitude.sensor->slot(magnitude.local).c_str(),
  804. magnitudeTopic(magnitude.type).c_str(),
  805. buffer,
  806. magnitudeUnits(magnitude.type).c_str()
  807. );
  808. }
  809. #endif // SENSOR_DEBUG
  810. // Time to report (we do it every _sensor_report_every readings)
  811. if (report_count == 0) {
  812. filtered = magnitude.filter->result();
  813. magnitude.filter->reset();
  814. filtered = _magnitudeProcess(magnitude.type, filtered);
  815. _magnitudes[i].filtered = filtered;
  816. // Check if there is a minimum change threshold to report
  817. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  818. _magnitudes[i].reported = filtered;
  819. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  820. #if BROKER_SUPPORT
  821. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  822. #endif
  823. #if MQTT_SUPPORT
  824. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  825. #if SENSOR_PUBLISH_ADDRESSES
  826. char topic[32];
  827. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  828. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  829. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  830. } else {
  831. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  832. }
  833. #endif // SENSOR_PUBLISH_ADDRESSES
  834. #endif // MQTT_SUPPORT
  835. #if INFLUXDB_SUPPORT
  836. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  837. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  838. } else {
  839. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  840. }
  841. #endif // INFLUXDB_SUPPORT
  842. #if THINGSPEAK_SUPPORT
  843. tspkEnqueueMeasurement(i, buffer);
  844. #endif
  845. #if DOMOTICZ_SUPPORT
  846. {
  847. char key[15];
  848. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  849. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  850. int status;
  851. if (filtered > 70) {
  852. status = HUMIDITY_WET;
  853. } else if (filtered > 45) {
  854. status = HUMIDITY_COMFORTABLE;
  855. } else if (filtered > 30) {
  856. status = HUMIDITY_NORMAL;
  857. } else {
  858. status = HUMIDITY_DRY;
  859. }
  860. char status_buf[5];
  861. itoa(status, status_buf, 10);
  862. domoticzSend(key, buffer, status_buf);
  863. } else {
  864. domoticzSend(key, 0, buffer);
  865. }
  866. }
  867. #endif // DOMOTICZ_SUPPORT
  868. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  869. } // if (report_count == 0)
  870. } // if (magnitude.sensor->status())
  871. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  872. // Post-read hook
  873. _sensorPost();
  874. #if WEB_SUPPORT
  875. wsSend(_sensorWebSocketSendData);
  876. #endif
  877. #if THINGSPEAK_SUPPORT
  878. if (report_count == 0) tspkFlush();
  879. #endif
  880. }
  881. }
  882. #endif // SENSOR_SUPPORT