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.

1140 lines
36 KiB

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