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.

67 lines
1.7 KiB

7 years ago
7 years ago
  1. /*
  2. ESPurna
  3. DHT MODULE
  4. Copyright (C) 2016 by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #if ENABLE_DHT
  7. #include <DHT.h>
  8. DHT dht(DHT_PIN, DHT_TYPE, DHT_TIMING);
  9. // -----------------------------------------------------------------------------
  10. // DHT
  11. // -----------------------------------------------------------------------------
  12. void dhtSetup() {
  13. dht.begin();
  14. }
  15. void dhtLoop() {
  16. if (!mqttConnected()) return;
  17. // Check if we should read new data
  18. static unsigned long last_update = 0;
  19. if ((millis() - last_update > DHT_UPDATE_INTERVAL) || (last_update == 0)) {
  20. last_update = millis();
  21. // Read sensor data
  22. double h = dht.readHumidity();
  23. double t = dht.readTemperature();
  24. // Check if readings are valid
  25. if (isnan(h) || isnan(t)) {
  26. DEBUG_MSG("[DHT] Error reading sensor\n");
  27. } else {
  28. char temperature[6];
  29. char humidity[6];
  30. dtostrf(t, 4, 1, temperature);
  31. itoa((int) h, humidity, 10);
  32. DEBUG_MSG("[DHT] Temperature: %s\n", temperature);
  33. DEBUG_MSG("[DHT] Humidity: %s\n", humidity);
  34. // Send MQTT messages
  35. mqttSend((char *) getSetting("dhtTemperatureTopic", DHT_TEMPERATURE_TOPIC).c_str(), temperature);
  36. mqttSend((char *) getSetting("dhtHumidityTopic", DHT_HUMIDITY_TOPIC).c_str(), humidity);
  37. // Update websocket clients
  38. char buffer[20];
  39. sprintf_P(buffer, PSTR("{\"temperature\": %s, \"humidity\": %s}"), temperature, humidity);
  40. webSocketSend(buffer);
  41. }
  42. }
  43. }
  44. #endif