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.

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