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.

1082 lines
34 KiB

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