Skip to content

Instantly share code, notes, and snippets.

@f1dz
Created March 29, 2021 15:15
Show Gist options
  • Save f1dz/ccd38a21c72157e12650c39f169b47fc to your computer and use it in GitHub Desktop.
Save f1dz/ccd38a21c72157e12650c39f169b47fc to your computer and use it in GitHub Desktop.
ESP8266 MQTT PubSub Client
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#ifndef STASSID
#define STASSID ""
#define STAPSK ""
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
// Broker
const char* mqtt_server = "";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void setup() {
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(BUILTIN_LED, OUTPUT);
}
void setup_wifi() {
Serial.begin(115200);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String msg;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
msg += (char)message[i];
}
Serial.println();
if (String(topic) == "temptron/output") {
Serial.print("Changing output to ");
if (msg == "on") {
Serial.println("on");
digitalWrite(BUILTIN_LED, LOW);
}
else if (msg == "off") {
Serial.println("off");
digitalWrite(BUILTIN_LED, HIGH);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Subscribe
client.subscribe("temptron/output");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment