Created
March 29, 2021 15:21
-
-
Save f1dz/ef7b0f01f8f599bfd2b18d9edc753d2f to your computer and use it in GitHub Desktop.
ESP32 MQTT PubSub Client
This file contains hidden or 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 <Wifi.h> | |
#include <PubSubClient.h> | |
#ifndef STASSID | |
#define STASSID "" | |
#define STAPSK "" | |
#endif | |
const char* ssid = STASSID; | |
const char* password = STAPSK; | |
const int LED = 2; | |
// Broker | |
const char* mqtt_server = ""; | |
WiFiClient wifiClient; | |
PubSubClient client(wifiClient); | |
void setup() { | |
setup_wifi(); | |
client.setServer(mqtt_server, 1883); | |
client.setCallback(callback); | |
pinMode(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); | |
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(LED, HIGH); | |
} | |
else if (msg == "off") { | |
Serial.println("off"); | |
digitalWrite(LED, LOW); | |
} | |
} | |
} | |
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