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.

1261 lines
40 KiB

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