Last active
June 9, 2022 14:03
-
-
Save quantumsheep/ac36f98b571d32d3e3104844915ee352 to your computer and use it in GitHub Desktop.
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 <Dns.h> | |
#include <PubSubClient.h> | |
#include <WiFi.h> | |
#define CLIENT_ID "clientid" | |
#define TOPIC_IN "topicin" | |
#define TOPIC_OUT "topicout" | |
WiFiClient wifiClient; | |
PubSubClient mqttClient(wifiClient); | |
void connectToWiFi() | |
{ | |
WiFi.begin("", ""); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
Serial.printf("Attempting to connect to WiFi: %d\n\r", WiFi.status()); | |
delay(1000); | |
} | |
Serial.println("Connected to WiFi"); | |
WiFi.config(WiFi.localIP(), WiFi.gatewayIP(), WiFi.subnetMask(), IPAddress(8, 8, 8, 8)); | |
Serial.println("DNS configured"); | |
} | |
void reconnectToMQTT() | |
{ | |
while (!mqttClient.connected()) | |
{ | |
Serial.println("Attempting MQTT connection..."); | |
if (mqttClient.connect(CLIENT_ID)) | |
{ | |
Serial.println("Connected to MQTT broker"); | |
// client.publish(TOPIC_OUT, "hello world"); | |
mqttClient.subscribe(TOPIC_IN); | |
} | |
else | |
{ | |
Serial.printf("Failed, rc=%d. Trying again in 5 seconds...\n\r", mqttClient.state()); | |
delay(5000); | |
} | |
} | |
} | |
void mqttCallback(char *topic, byte *payload, unsigned int length) | |
{ | |
char data[length + 1]; | |
memset(data, 0, sizeof(byte) * (length + 1)); | |
memcpy(data, payload, length); | |
Serial.printf("Message arrived [%s] %s\n\r", topic, data); | |
digitalWrite(23, HIGH); | |
delay(200); | |
digitalWrite(23, LOW); | |
} | |
void setup() | |
{ | |
pinMode(23, OUTPUT); | |
Serial.begin(9600); | |
connectToWiFi(); | |
mqttClient.setServer(IPAddress(5, 196, 95, 208), 1883); | |
mqttClient.setCallback(mqttCallback); | |
delay(1500); | |
} | |
void loop() | |
{ | |
if (!mqttClient.connected()) | |
{ | |
reconnectToMQTT(); | |
} | |
mqttClient.loop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment