Skip to content

Instantly share code, notes, and snippets.

@danrl
Created April 27, 2017 12:52
Show Gist options
  • Save danrl/0080caba129c0e83bda6f1f8b787b022 to your computer and use it in GitHub Desktop.
Save danrl/0080caba129c0e83bda6f1f8b787b022 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <MQTTClient.h>
#include "DHT.h"
const char *wifi_ssid = "wifi";
const char *wifi_password = "secret";
const char *mqtt_server = "broker.shiftr.io";
const char *mqtt_id = "my_first_node";
const char *mqtt_user = "login";
const char *mqtt_password = "secret";
const int dht_pin = D6;
WiFiClient net;
MQTTClient client;
DHT dht(dht_pin, DHT22);
void setup() {
Serial.begin(115200);
// wifi
Serial.print("wifi: ssid=");
Serial.println(wifi_ssid);
Serial.print("wifi: password=");
Serial.println(wifi_password);
Serial.print("wifi: connecting");
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("wifi: ip_addr=");
Serial.println(WiFi.localIP());
Serial.println("wifi: done!");
// message broker connection
client.begin(mqtt_server, net);
connect();
}
void connect() {
Serial.print("mqtt: server=");
Serial.println(mqtt_server);
Serial.print("mqtt: id=");
Serial.println(mqtt_id);
Serial.print("mqtt: user=");
Serial.println(mqtt_user);
Serial.print("mqtt: password=");
Serial.println(mqtt_password);
Serial.print("mqtt: connecting");
while (!client.connect(mqtt_id, mqtt_user, mqtt_password)) {
Serial.print(".");
delay(1000);
}
Serial.println();
Serial.println("mqtt: done!");
client.subscribe("commands");
}
void loop() {
// vars
float temperature = 0.0;
float humidity = 0.0;
String message;
client.loop();
delay(10); // stability fix
if(!client.connected()) {
connect();
}
temperature = dht.readTemperature();
humidity = dht.readHumidity();
message = "temperature=";
message += String(temperature, 1);
message += " ";
message += "humidity=";
message += String(humidity, 1); Serial.print("message_out: ");
Serial.println(message);
client.publish("sensors", message);
delay(3000);
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("message_in: topic=");
Serial.print(topic);
Serial.print(" payload='");
Serial.print(payload);
Serial.println("'");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment