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.

1114 lines
35 KiB

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