-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTT.ino
102 lines (93 loc) · 2.6 KB
/
MQTT.ino
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
boolean callback(char* subTopic, byte* payload, unsigned int length) {
if (!usingMQTT())
return false;
clearBuffer();
if (length > 2990)
length = 2990;
strncpy(buffer, (char*) payload, length);
Serial.print("Received message: ");
Serial.println(buffer);
if (strcmp(buffer, "Mode1") == 0 && deviceMode != 1)
switchMode(1);
else if (strcmp(buffer, "Mode2") == 0)
switchMode(2);
else if (strcmp(buffer, "Mode9") == 0)
switchMode(9);
else if (strcmp(buffer, "SuspendMQTT") == 0) {
suspendMQTT();
}
else if (strcmp(buffer, "Reboot") == 0)
reboot();
else if (strcmp(buffer, "WipeSpiffs") == 0)
wipeSpiffs();
else if (strcmp(buffer, "Timeout900") == 0)
timeout(900);
else if (strcmp(buffer, "Timeout0") == 0)
timeout(0);
else
specialMQTT(buffer);
return true;
} // end callback()
boolean suspendMQTT() {
Serial.println("Disabling MQTT communications.");
useMQTT = false;
} // end suspendMQTT()
void timeout(int timeout) {
mqttTimeout = abs(timeout);
saveMQTTConfig();
} // end timeout()
boolean usingMQTT() {
if (!useMQTT || deviceMode != 1)
return false;
return true;
} // end usingMQTT()
boolean sendMQTT(char* message) {
if (!usingMQTT())
return false;
Serial.print("Sending MQTT message: ");
Serial.println(message);
if (!psClient.connected())
reconnect();
psClient.loop();
return psClient.publish(outTopic, message, strlen(message) + 1);
} // end sendMQTT()
boolean mqttSetup() {
if (!usingMQTT())
return false;
// Connect to MQTT broker and send welcome message.
psClient.setServer(mqttBroker, mqttPort);
psClient.setCallback(callback);
if (!psClient.connected())
reconnect();
psClient.loop();
return true;
} // end mqttSetup()
boolean reconnect() {
if (!usingMQTT())
return true;
static int failures = 0;
long unsigned int startTime = millis();
// Loop until reconnected or mqttTimeout surpassed.
while (!psClient.connected() && usingMQTT()) {
Serial.print("Attempting MQTT connection... ");
if (psClient.connect(deviceName, mqttUser, mqttPass)) {
Serial.print("Connected to MQTT Broker: ");
Serial.println(mqttBroker);
strcpy(buffer, deviceName);
strcat(buffer, " connected.");
psClient.publish(outTopic, buffer);
psClient.subscribe(inTopic);
failures = 0;
return true;
}
else {
failures++;
Serial.print("Attempt failed, rc = ");
Serial.print(psClient.state());
Serial.println(", trying again in five seconds.");
handleDelay(5 * 1000);
commfail(failures);
}
}
return false;
} // end reconnect()