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.

1101 lines
34 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["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 (ntpSynced()) {
  228. _sensor_energy_reset_ts = String(" (since ") + ntpDateTime() + String(")");
  229. }
  230. }
  231. // -----------------------------------------------------------------------------
  232. // Sensor initialization
  233. // -----------------------------------------------------------------------------
  234. void _sensorLoad() {
  235. /*
  236. This is temporal, in the future sensors will be initialized based on
  237. soft configuration (data stored in EEPROM config) so you will be able
  238. to define and configure new sensors on the fly
  239. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  240. loaded and initialized here. If you want to add new sensors of the same type
  241. just duplicate the block and change the arguments for the set* methods.
  242. Check the DHT block below for an example
  243. */
  244. #if AM2320_SUPPORT
  245. {
  246. AM2320Sensor * sensor = new AM2320Sensor();
  247. sensor->setAddress(AM2320_ADDRESS);
  248. _sensors.push_back(sensor);
  249. }
  250. #endif
  251. #if ANALOG_SUPPORT
  252. {
  253. AnalogSensor * sensor = new AnalogSensor();
  254. _sensors.push_back(sensor);
  255. }
  256. #endif
  257. #if BH1750_SUPPORT
  258. {
  259. BH1750Sensor * sensor = new BH1750Sensor();
  260. sensor->setAddress(BH1750_ADDRESS);
  261. sensor->setMode(BH1750_MODE);
  262. _sensors.push_back(sensor);
  263. }
  264. #endif
  265. #if BMX280_SUPPORT
  266. {
  267. BMX280Sensor * sensor = new BMX280Sensor();
  268. sensor->setAddress(BMX280_ADDRESS);
  269. _sensors.push_back(sensor);
  270. }
  271. #endif
  272. #if CSE7766_SUPPORT
  273. {
  274. CSE7766Sensor * sensor = new CSE7766Sensor();
  275. sensor->setRX(CSE7766_PIN);
  276. _sensors.push_back(sensor);
  277. }
  278. #endif
  279. #if DALLAS_SUPPORT
  280. {
  281. DallasSensor * sensor = new DallasSensor();
  282. sensor->setGPIO(DALLAS_PIN);
  283. _sensors.push_back(sensor);
  284. }
  285. #endif
  286. #if DHT_SUPPORT
  287. {
  288. DHTSensor * sensor = new DHTSensor();
  289. sensor->setGPIO(DHT_PIN);
  290. sensor->setType(DHT_TYPE);
  291. _sensors.push_back(sensor);
  292. }
  293. #endif
  294. /*
  295. // Example on how to add a second DHT sensor
  296. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  297. #if DHT_SUPPORT
  298. {
  299. DHTSensor * sensor = new DHTSensor();
  300. sensor->setGPIO(DHT2_PIN);
  301. sensor->setType(DHT2_TYPE);
  302. _sensors.push_back(sensor);
  303. }
  304. #endif
  305. */
  306. #if DIGITAL_SUPPORT
  307. {
  308. DigitalSensor * sensor = new DigitalSensor();
  309. sensor->setGPIO(DIGITAL_PIN);
  310. sensor->setMode(DIGITAL_PIN_MODE);
  311. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  312. _sensors.push_back(sensor);
  313. }
  314. #endif
  315. #if ECH1560_SUPPORT
  316. {
  317. ECH1560Sensor * sensor = new ECH1560Sensor();
  318. sensor->setCLK(ECH1560_CLK_PIN);
  319. sensor->setMISO(ECH1560_MISO_PIN);
  320. sensor->setInverted(ECH1560_INVERTED);
  321. _sensors.push_back(sensor);
  322. }
  323. #endif
  324. #if EMON_ADC121_SUPPORT
  325. {
  326. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  327. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  328. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  329. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  330. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  331. _sensors.push_back(sensor);
  332. }
  333. #endif
  334. #if EMON_ADS1X15_SUPPORT
  335. {
  336. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  337. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  338. sensor->setType(EMON_ADS1X15_TYPE);
  339. sensor->setMask(EMON_ADS1X15_MASK);
  340. sensor->setGain(EMON_ADS1X15_GAIN);
  341. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  342. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  343. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  344. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  345. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  346. _sensors.push_back(sensor);
  347. }
  348. #endif
  349. #if EMON_ANALOG_SUPPORT
  350. {
  351. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  352. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  353. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  354. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  355. _sensors.push_back(sensor);
  356. }
  357. #endif
  358. #if EVENTS_SUPPORT
  359. {
  360. EventSensor * sensor = new EventSensor();
  361. sensor->setGPIO(EVENTS_PIN);
  362. sensor->setMode(EVENTS_PIN_MODE);
  363. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  364. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  365. _sensors.push_back(sensor);
  366. }
  367. #endif
  368. #if GUVAS12SD_SUPPORT
  369. {
  370. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  371. sensor->setGPIO(GUVAS12SD_PIN);
  372. _sensors.push_back(sensor);
  373. }
  374. #endif
  375. #if HCSR04_SUPPORT
  376. {
  377. HCSR04Sensor * sensor = new HCSR04Sensor();
  378. sensor->setTrigger(HCSR04_TRIGGER);
  379. sensor->setEcho(HCSR04_ECHO);
  380. _sensors.push_back(sensor);
  381. }
  382. #endif
  383. #if HLW8012_SUPPORT
  384. {
  385. HLW8012Sensor * sensor = new HLW8012Sensor();
  386. sensor->setSEL(HLW8012_SEL_PIN);
  387. sensor->setCF(HLW8012_CF_PIN);
  388. sensor->setCF1(HLW8012_CF1_PIN);
  389. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  390. _sensors.push_back(sensor);
  391. }
  392. #endif
  393. #if MHZ19_SUPPORT
  394. {
  395. MHZ19Sensor * sensor = new MHZ19Sensor();
  396. sensor->setRX(MHZ19_RX_PIN);
  397. sensor->setTX(MHZ19_TX_PIN);
  398. _sensors.push_back(sensor);
  399. }
  400. #endif
  401. #if PMSX003_SUPPORT
  402. {
  403. PMSX003Sensor * sensor = new PMSX003Sensor();
  404. sensor->setRX(PMS_RX_PIN);
  405. sensor->setTX(PMS_TX_PIN);
  406. _sensors.push_back(sensor);
  407. }
  408. #endif
  409. #if PZEM004T_SUPPORT
  410. {
  411. PZEM004TSensor * sensor = new PZEM004TSensor();
  412. #if PZEM004T_USE_SOFT
  413. sensor->setRX(PZEM004T_RX_PIN);
  414. sensor->setTX(PZEM004T_TX_PIN);
  415. #else
  416. sensor->setSerial(& PZEM004T_HW_PORT);
  417. #endif
  418. _sensors.push_back(sensor);
  419. }
  420. #endif
  421. #if SHT3X_I2C_SUPPORT
  422. {
  423. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  424. sensor->setAddress(SHT3X_I2C_ADDRESS);
  425. _sensors.push_back(sensor);
  426. }
  427. #endif
  428. #if SI7021_SUPPORT
  429. {
  430. SI7021Sensor * sensor = new SI7021Sensor();
  431. sensor->setAddress(SI7021_ADDRESS);
  432. _sensors.push_back(sensor);
  433. }
  434. #endif
  435. #if TMP3X_SUPPORT
  436. {
  437. TMP3XSensor * sensor = new TMP3XSensor();
  438. sensor->setType(TMP3X_TYPE);
  439. _sensors.push_back(sensor);
  440. }
  441. #endif
  442. #if V9261F_SUPPORT
  443. {
  444. V9261FSensor * sensor = new V9261FSensor();
  445. sensor->setRX(V9261F_PIN);
  446. sensor->setInverted(V9261F_PIN_INVERSE);
  447. _sensors.push_back(sensor);
  448. }
  449. #endif
  450. }
  451. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  452. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  453. }
  454. void _sensorInit() {
  455. _sensors_ready = true;
  456. for (unsigned char i=0; i<_sensors.size(); i++) {
  457. // Do not process an already initialized sensor
  458. if (_sensors[i]->ready()) continue;
  459. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  460. // Force sensor to reload config
  461. _sensors[i]->begin();
  462. if (!_sensors[i]->ready()) {
  463. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  464. _sensors_ready = false;
  465. continue;
  466. }
  467. // Initialize magnitudes
  468. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  469. unsigned char type = _sensors[i]->type(k);
  470. sensor_magnitude_t new_magnitude;
  471. new_magnitude.sensor = _sensors[i];
  472. new_magnitude.local = k;
  473. new_magnitude.type = type;
  474. new_magnitude.global = _counts[type];
  475. new_magnitude.current = 0;
  476. new_magnitude.filtered = 0;
  477. new_magnitude.reported = 0;
  478. new_magnitude.min_change = 0;
  479. if (type == MAGNITUDE_DIGITAL) {
  480. new_magnitude.filter = new MaxFilter();
  481. } else if (type == MAGNITUDE_EVENTS) {
  482. new_magnitude.filter = new MovingAverageFilter();
  483. } else {
  484. new_magnitude.filter = new MedianFilter();
  485. }
  486. new_magnitude.filter->resize(_sensor_report_every);
  487. _magnitudes.push_back(new_magnitude);
  488. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  489. _counts[type] = _counts[type] + 1;
  490. }
  491. // Hook callback
  492. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  493. _sensorCallback(i, type, payload);
  494. });
  495. // Custom initializations
  496. #if EMON_ANALOG_SUPPORT
  497. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  498. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  499. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  500. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  501. }
  502. #endif // EMON_ANALOG_SUPPORT
  503. #if HLW8012_SUPPORT
  504. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  505. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  506. double value;
  507. value = getSetting("pwrRatioC", 0).toFloat();
  508. if (value > 0) sensor->setCurrentRatio(value);
  509. value = getSetting("pwrRatioV", 0).toFloat();
  510. if (value > 0) sensor->setVoltageRatio(value);
  511. value = getSetting("pwrRatioP", 0).toFloat();
  512. if (value > 0) sensor->setPowerRatio(value);
  513. }
  514. #endif // HLW8012_SUPPORT
  515. #if CSE7766_SUPPORT
  516. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  517. CSE7766Sensor * sensor = (CSE7766Sensor *) _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 // CSE7766_SUPPORT
  527. }
  528. }
  529. void _sensorConfigure() {
  530. // General sensor settings
  531. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  532. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  533. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  534. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  535. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  536. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  537. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  538. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  539. // Specific sensor settings
  540. for (unsigned char i=0; i<_sensors.size(); i++) {
  541. #if EMON_ANALOG_SUPPORT
  542. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  543. double value;
  544. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  545. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  546. sensor->expectedPower(0, value);
  547. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  548. }
  549. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  550. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  551. delSetting("pwrRatioC");
  552. }
  553. if (getSetting("pwrResetE", 0).toInt() == 1) {
  554. sensor->resetEnergy();
  555. _sensorReset();
  556. }
  557. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  558. }
  559. #endif // EMON_ANALOG_SUPPORT
  560. #if EMON_ADC121_SUPPORT
  561. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  562. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  563. if (getSetting("pwrResetE", 0).toInt() == 1) {
  564. sensor->resetEnergy();
  565. _sensorReset();
  566. }
  567. }
  568. #endif
  569. #if EMON_ADS1X15_SUPPORT
  570. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  571. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  572. if (getSetting("pwrResetE", 0).toInt() == 1) {
  573. sensor->resetEnergy();
  574. _sensorReset();
  575. }
  576. }
  577. #endif
  578. #if HLW8012_SUPPORT
  579. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  580. double value;
  581. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  582. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  583. sensor->expectedCurrent(value);
  584. setSetting("pwrRatioC", sensor->getCurrentRatio());
  585. }
  586. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  587. sensor->expectedVoltage(value);
  588. setSetting("pwrRatioV", sensor->getVoltageRatio());
  589. }
  590. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  591. sensor->expectedPower(value);
  592. setSetting("pwrRatioP", sensor->getPowerRatio());
  593. }
  594. if (getSetting("pwrResetE", 0).toInt() == 1) {
  595. sensor->resetEnergy();
  596. _sensorReset();
  597. }
  598. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  599. sensor->resetRatios();
  600. delSetting("pwrRatioC");
  601. delSetting("pwrRatioV");
  602. delSetting("pwrRatioP");
  603. }
  604. }
  605. #endif // HLW8012_SUPPORT
  606. #if CSE7766_SUPPORT
  607. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  608. double value;
  609. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  610. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  611. sensor->expectedCurrent(value);
  612. setSetting("pwrRatioC", sensor->getCurrentRatio());
  613. }
  614. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  615. sensor->expectedVoltage(value);
  616. setSetting("pwrRatioV", sensor->getVoltageRatio());
  617. }
  618. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  619. sensor->expectedPower(value);
  620. setSetting("pwrRatioP", sensor->getPowerRatio());
  621. }
  622. if (getSetting("pwrResetE", 0).toInt() == 1) {
  623. sensor->resetEnergy();
  624. _sensorReset();
  625. }
  626. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  627. sensor->resetRatios();
  628. delSetting("pwrRatioC");
  629. delSetting("pwrRatioV");
  630. delSetting("pwrRatioP");
  631. }
  632. }
  633. #endif // CSE7766_SUPPORT
  634. }
  635. // Update filter sizes
  636. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  637. _magnitudes[i].filter->resize(_sensor_report_every);
  638. }
  639. // Save settings
  640. delSetting("pwrExpectedP");
  641. delSetting("pwrExpectedC");
  642. delSetting("pwrExpectedV");
  643. delSetting("pwrResetCalibration");
  644. delSetting("pwrResetE");
  645. saveSettings();
  646. }
  647. // -----------------------------------------------------------------------------
  648. // Public
  649. // -----------------------------------------------------------------------------
  650. unsigned char sensorCount() {
  651. return _sensors.size();
  652. }
  653. unsigned char magnitudeCount() {
  654. return _magnitudes.size();
  655. }
  656. String magnitudeName(unsigned char index) {
  657. if (index < _magnitudes.size()) {
  658. sensor_magnitude_t magnitude = _magnitudes[index];
  659. return magnitude.sensor->slot(magnitude.local);
  660. }
  661. return String();
  662. }
  663. unsigned char magnitudeType(unsigned char index) {
  664. if (index < _magnitudes.size()) {
  665. return int(_magnitudes[index].type);
  666. }
  667. return MAGNITUDE_NONE;
  668. }
  669. unsigned char magnitudeIndex(unsigned char index) {
  670. if (index < _magnitudes.size()) {
  671. return int(_magnitudes[index].global);
  672. }
  673. return 0;
  674. }
  675. String magnitudeTopic(unsigned char type) {
  676. char buffer[16] = {0};
  677. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  678. return String(buffer);
  679. }
  680. String magnitudeTopicIndex(unsigned char index) {
  681. char topic[32] = {0};
  682. if (index < _magnitudes.size()) {
  683. sensor_magnitude_t magnitude = _magnitudes[index];
  684. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  685. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  686. } else {
  687. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  688. }
  689. }
  690. return String(topic);
  691. }
  692. String magnitudeUnits(unsigned char type) {
  693. char buffer[8] = {0};
  694. if (type < MAGNITUDE_MAX) {
  695. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  696. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  697. } else if (
  698. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  699. (_sensor_energy_units == ENERGY_KWH)) {
  700. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  701. } else if (
  702. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  703. (_sensor_power_units == POWER_KILOWATTS)) {
  704. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  705. } else {
  706. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  707. }
  708. }
  709. return String(buffer);
  710. }
  711. // -----------------------------------------------------------------------------
  712. void sensorSetup() {
  713. // Backwards compatibility
  714. moveSetting("powerUnits", "pwrUnits");
  715. // Load sensors
  716. _sensorLoad();
  717. _sensorInit();
  718. // Configure stored values
  719. _sensorConfigure();
  720. #if WEB_SUPPORT
  721. // Websockets
  722. wsOnSendRegister(_sensorWebSocketStart);
  723. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  724. wsOnSendRegister(_sensorWebSocketSendData);
  725. wsOnAfterParseRegister(_sensorConfigure);
  726. // API
  727. _sensorAPISetup();
  728. #endif
  729. #if TERMINAL_SUPPORT
  730. _sensorInitCommands();
  731. #endif
  732. // Register loop
  733. espurnaRegisterLoop(sensorLoop);
  734. }
  735. void sensorLoop() {
  736. // Check if we still have uninitialized sensors
  737. static unsigned long last_init = 0;
  738. if (!_sensors_ready) {
  739. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  740. last_init = millis();
  741. _sensorInit();
  742. }
  743. }
  744. if (_magnitudes.size() == 0) return;
  745. // Tick hook
  746. _sensorTick();
  747. // Check if we should read new data
  748. static unsigned long last_update = 0;
  749. static unsigned long report_count = 0;
  750. if (millis() - last_update > _sensor_read_interval) {
  751. last_update = millis();
  752. report_count = (report_count + 1) % _sensor_report_every;
  753. double current;
  754. double filtered;
  755. char buffer[64];
  756. // Pre-read hook
  757. _sensorPre();
  758. // Get the first relay state
  759. #if SENSOR_POWER_CHECK_STATUS
  760. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  761. #endif
  762. // Get readings
  763. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  764. sensor_magnitude_t magnitude = _magnitudes[i];
  765. if (magnitude.sensor->status()) {
  766. current = magnitude.sensor->value(magnitude.local);
  767. // Completely remove spurious values if relay is OFF
  768. #if SENSOR_POWER_CHECK_STATUS
  769. if (relay_off) {
  770. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  771. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  772. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  773. magnitude.type == MAGNITUDE_CURRENT ||
  774. magnitude.type == MAGNITUDE_ENERGY_DELTA
  775. ) {
  776. current = 0;
  777. }
  778. }
  779. #endif
  780. magnitude.filter->add(current);
  781. // Special case
  782. if (magnitude.type == MAGNITUDE_EVENTS) {
  783. current = magnitude.filter->result();
  784. }
  785. current = _magnitudeProcess(magnitude.type, current);
  786. _magnitudes[i].current = current;
  787. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  788. // Debug
  789. #if SENSOR_DEBUG
  790. {
  791. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  792. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  793. magnitude.sensor->slot(magnitude.local).c_str(),
  794. magnitudeTopic(magnitude.type).c_str(),
  795. buffer,
  796. magnitudeUnits(magnitude.type).c_str()
  797. );
  798. }
  799. #endif // SENSOR_DEBUG
  800. // Time to report (we do it every _sensor_report_every readings)
  801. if (report_count == 0) {
  802. filtered = magnitude.filter->result();
  803. magnitude.filter->reset();
  804. filtered = _magnitudeProcess(magnitude.type, filtered);
  805. _magnitudes[i].filtered = filtered;
  806. // Check if there is a minimum change threshold to report
  807. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  808. _magnitudes[i].reported = filtered;
  809. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  810. #if BROKER_SUPPORT
  811. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  812. #endif
  813. #if MQTT_SUPPORT
  814. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  815. #if SENSOR_PUBLISH_ADDRESSES
  816. char topic[32];
  817. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  818. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  819. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  820. } else {
  821. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  822. }
  823. #endif // SENSOR_PUBLISH_ADDRESSES
  824. #endif // MQTT_SUPPORT
  825. #if INFLUXDB_SUPPORT
  826. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  827. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  828. } else {
  829. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  830. }
  831. #endif // INFLUXDB_SUPPORT
  832. #if THINGSPEAK_SUPPORT
  833. tspkEnqueueMeasurement(i, buffer);
  834. #endif
  835. #if DOMOTICZ_SUPPORT
  836. {
  837. char key[15];
  838. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  839. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  840. int status;
  841. if (filtered > 70) {
  842. status = HUMIDITY_WET;
  843. } else if (filtered > 45) {
  844. status = HUMIDITY_COMFORTABLE;
  845. } else if (filtered > 30) {
  846. status = HUMIDITY_NORMAL;
  847. } else {
  848. status = HUMIDITY_DRY;
  849. }
  850. char status_buf[5];
  851. itoa(status, status_buf, 10);
  852. domoticzSend(key, buffer, status_buf);
  853. } else {
  854. domoticzSend(key, 0, buffer);
  855. }
  856. }
  857. #endif // DOMOTICZ_SUPPORT
  858. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  859. } // if (report_count == 0)
  860. } // if (magnitude.sensor->status())
  861. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  862. // Post-read hook
  863. _sensorPost();
  864. #if WEB_SUPPORT
  865. wsSend(_sensorWebSocketSendData);
  866. #endif
  867. #if THINGSPEAK_SUPPORT
  868. if (report_count == 0) tspkFlush();
  869. #endif
  870. }
  871. }
  872. #endif // SENSOR_SUPPORT