Guest User

Untitled

a guest
Feb 7th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3. #include <OneWire.h>
  4. #include <DallasTemperature.h>
  5.  
  6. #define DEBUG false
  7. #define PUBLISH_RATE 3600
  8. #define DEEP_SLEEP true
  9. #define MQTT_TOPIC "home/outdoor/temperature"
  10. #define ONE_WIRE_BUS 2
  11.  
  12. #ifdef DEBUG
  13. #define DEBUG_PRINT(x) Serial.println (x)
  14. #else
  15. #define DEBUG_PRINT(x)
  16. #endif
  17.  
  18. const char* ssid = "XXXX";
  19. const char* password = "XXXXX";
  20.  
  21. const char *mqtt_server = "XXXXXX";
  22. const int mqtt_port = 18967;
  23. const char *mqtt_user = "XXXX";
  24. const char *mqtt_pass = "XXXXX";
  25. const char *mqtt_client_name = "esp8266-outdoor-temperature";
  26.  
  27. OneWire oneWire(ONE_WIRE_BUS);
  28. DallasTemperature sensors(&oneWire);
  29. WiFiClient espClient;
  30. PubSubClient client(espClient);
  31.  
  32. void setup() {
  33. if (DEBUG) Serial.begin(115200);
  34. setup_wifi();
  35. client.setServer(mqtt_server, mqtt_port);
  36.  
  37. sensors.begin();
  38. }
  39.  
  40. void setup_wifi() {
  41.  
  42. delay(10);
  43.  
  44. DEBUG_PRINT(ssid);
  45. WiFi.begin(ssid, password);
  46. WiFi.mode(WIFI_STA);
  47. while (WiFi.status() != WL_CONNECTED) {
  48. delay(500);
  49. Serial.print(".");
  50. }
  51. DEBUG_PRINT(WiFi.localIP());
  52. }
  53.  
  54. void reconnect() {
  55. // Loop until we're reconnected
  56. while (!client.connected()) {
  57. DEBUG_PRINT("Attempting MQTT connection...");
  58. if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass)) {
  59. DEBUG_PRINT("connected");
  60. } else {
  61. Serial.println(" try again in 5 seconds");
  62. delay(5000);
  63. }
  64. }
  65. }
  66.  
  67. void loop() {
  68. if (!client.connected()) {
  69. reconnect();
  70. }
  71. client.loop();
  72.  
  73. sensors.requestTemperatures();
  74.  
  75. float number = sensors.getTempCByIndex(0);
  76. String payload = "{";
  77. payload += "\"temperature\":";
  78. payload += number;
  79. payload += "}";
  80.  
  81. DEBUG_PRINT(payload);
  82.  
  83. client.publish(MQTT_TOPIC, (char*) payload.c_str());
  84. delay(5000);
  85.  
  86. if (DEEP_SLEEP) {
  87. DEBUG_PRINT("Deep Sleep");
  88. ESP.deepSleep(PUBLISH_RATE * 1e6);
  89. } else {
  90. delay(PUBLISH_RATE * 1e3);
  91. }
  92. }
Add Comment
Please, Sign In to add comment