This repository was archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMQTT.cpp
More file actions
68 lines (53 loc) · 1.27 KB
/
MQTT.cpp
File metadata and controls
68 lines (53 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "MQTT.h"
WiFiClient espClient;
PubSubClient client(espClient);
void MQTT_Setup()
{
WiFi_Setup();
client.setServer(SECRET_MQTT_SERVER, SECRET_MQTT_PORT);
client.setCallback(callback);
}
void MQTT_Loop()
{
ArduinoOTA.handle();
if (!client.connected()) {
reconnect();
}
if (WiFi.status() != WL_CONNECTED) {
delay(1);
DebugMessage(DM_ERROR, "WIFI Disconnected. Attempting reconnection.");
WiFi_Setup();
return;
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
DebugMessage(DM_INFO, "Connecting to MQTT");
// Attempt to connect
if (client.connect(SECRET_MQTT_NAME, SECRET_MQTT_ID, SECRET_MQTT_PWD)) {
DebugMessage(DM_INFO, "Connected to MQTT Server");
client.subscribe(SECRET_MQTT_STATE_TOPIC);
}
else {
DebugMessage(DM_ERROR, "Retry in 5s");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
char* message = new char[length + 1];
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
message[length] = '\0';
DebugMessage(DM_RECEIVE, "[" + String(topic) + "]: " + String(message));
delete message;
}
void publish(char* buffer)
{
client.publish(SECRET_MQTT_STATE_TOPIC, buffer, true);
}