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.

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