Created
October 21, 2017 04:20
-
-
Save dustinrue/50f8435d3ee4b6c7e3db64b1182aa2ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#include <DHT.h> | |
#include <SimpleTimer.h> | |
#define DHTPIN 2 | |
#define DHTTYPE DHT22 | |
const char* ssid = "ssid"; | |
const char* password = "password"; | |
const char* mqtt = "ip of your hass.io server"; | |
DHT dht(DHTPIN, DHTTYPE); | |
SimpleTimer timer; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (client.connect("ESP8266 Client")) { | |
Serial.println("connected"); | |
} | |
else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
dht.begin(); | |
delay(500); | |
// We start by connecting to a WiFi network | |
Serial.println(); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.print("IP address: "); | |
Serial.println(WiFi.localIP()); | |
Serial.print("Netmask: "); | |
Serial.println(WiFi.subnetMask()); | |
Serial.print("Gateway: "); | |
Serial.println(WiFi.gatewayIP()); | |
client.setServer(mqtt, 1883); | |
reconnect(); | |
timer.setInterval(120000, getTemperature); | |
getTemperature(); | |
} | |
void getTemperature() { | |
float f = dht.readTemperature(true); | |
float h = dht.readHumidity(); | |
Serial.print("Temperature: "); | |
Serial.print(f); | |
Serial.print(", Humidity: "); | |
Serial.println(h); | |
String tempString = String(f, 0); | |
String humidityString = String(h, 0); | |
client.publish("home/office/temperature", tempString.c_str(), 2); | |
client.publish("home/office/humidity", humidityString.c_str(), 2); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
timer.run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment