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.

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