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.

91 lines
2.3 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. DHT MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if ENABLE_DHT
  6. #include <DHT.h>
  7. #include <Adafruit_Sensor.h>
  8. DHT dht(DHT_PIN, DHT_TYPE, DHT_TIMING);
  9. double _dhtTemperature = 0;
  10. unsigned int _dhtHumidity = 0;
  11. // -----------------------------------------------------------------------------
  12. // Values
  13. // -----------------------------------------------------------------------------
  14. double getDHTTemperature() {
  15. return _dhtTemperature;
  16. }
  17. unsigned int getDHTHumidity() {
  18. return _dhtHumidity;
  19. }
  20. void dhtSetup() {
  21. dht.begin();
  22. apiRegister("/api/temperature", "temperature", [](char * buffer, size_t len) {
  23. dtostrf(_dhtTemperature, len-1, 1, buffer);
  24. });
  25. apiRegister("/api/humidity", "humidity", [](char * buffer, size_t len) {
  26. snprintf(buffer, len, "%d", _dhtHumidity);
  27. });
  28. }
  29. void dhtLoop() {
  30. // Check if we should read new data
  31. static unsigned long last_update = 0;
  32. if ((millis() - last_update > DHT_UPDATE_INTERVAL) || (last_update == 0)) {
  33. last_update = millis();
  34. // Read sensor data
  35. double h = dht.readHumidity();
  36. double t = dht.readTemperature();
  37. // Check if readings are valid
  38. if (isnan(h) || isnan(t)) {
  39. DEBUG_MSG("[DHT] Error reading sensor\n");
  40. } else {
  41. _dhtTemperature = t;
  42. _dhtHumidity = h;
  43. char temperature[6];
  44. char humidity[6];
  45. dtostrf(t, 4, 1, temperature);
  46. itoa((unsigned int) h, humidity, 10);
  47. DEBUG_MSG("[DHT] Temperature: %s\n", temperature);
  48. DEBUG_MSG("[DHT] Humidity: %s\n", humidity);
  49. // Send MQTT messages
  50. mqttSend(getSetting("dhtTmpTopic", DHT_TEMPERATURE_TOPIC).c_str(), temperature);
  51. mqttSend(getSetting("dhtHumTopic", DHT_HUMIDITY_TOPIC).c_str(), humidity);
  52. // Send to Domoticz
  53. #if ENABLE_DOMOTICZ
  54. domoticzSend("dczTmpIdx", temperature);
  55. domoticzSend("dczHumIdx", humidity);
  56. #endif
  57. // Update websocket clients
  58. char buffer[100];
  59. sprintf_P(buffer, PSTR("{\"dhtVisible\": 1, \"dhtTmp\": %s, \"dhtHum\": %s}"), temperature, humidity);
  60. wsSend(buffer);
  61. }
  62. }
  63. }
  64. #endif