-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.ino
192 lines (161 loc) · 6.02 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
const String mqtt_rc_states[10] = { "Connection timeout", "Connection lost", "Connect failed", "Disconnected", "Connected", "Connect: bad protocol", "Connect: bad client ID", "Connect: unavailable", "Connect: bad credentials", "Connect: unauthorised" };
void mqttSend(const String &topic, const String &data, bool retain) {
#ifdef DEBUG
dmesg();
Serial.print(topic);
Serial.print(" ");
Serial.println(data);
#endif
if (mqttClient.connected()) {
tmpString = String(baseTopic + topic);
tmpString.toCharArray(pubTopic, OUT_STR_MAX);
tmpString = String(data);
tmpString.toCharArray(output, OUT_STR_MAX);
if (mqttClient.publish(pubTopic, output, retain))
watchdog = millis(); // feed the watchdog
}
}
void mqttLog(const String &app_name, const String &message) {
mqttSend(String(FPSTR(mqttstr_log)), message, false);
logMessage(app_name, message, true);
}
void mqttConnect() {
if ( mqtt_tls && (! ca_cert_okay) ) {
return; // We can't do much if we are meant to use TLS and haven't been able to load the CA certificate
}
// Loop until we're reconnected
if (!mqttClient.connected() && configured) {
// Attempt to connect
tmpString = String(baseTopic) + String(FPSTR(mqttstr_online));
tmpString.toCharArray(pubTopic, OUT_STR_MAX);
tmpString = str_false;
tmpString.toCharArray(output, OUT_STR_MAX);
mqttClient.disconnect();
bool mqttResult;
// Connect with a will of $online set to false (from output set above)
if (mqtt_auth) {
mqttResult = mqttClient.connect(mqtt_name, mqtt_user, mqtt_passwd, pubTopic, 0, true, output);
} else {
mqttResult = mqttClient.connect(mqtt_name, pubTopic, 0, true, output);
}
if (mqttResult) {
logString = str_connected;
logMessage(app_name_mqtt, logString, true);
if (mqtt_tls) {
// Verify validity of server's certificate before doing anything else
logString = F("server certificate ");
if (espSecureClient.verifyCertChain(mqtt_server)) {
logString = logString + F("verified");
tlsOkay = true;
} else {
logString = String(F("ERROR: ")) + logString + F("verification failed! ") + str_rebooting;
tlsOkay = false;
}
logMessage(app_name_mqtt, logString, false);
if (! tlsOkay) {
delay(1000);
// reconnecting will cause certificate verification to fail so reboot to start clean
ESP.restart();
delay(5000);
while (1); // Do NOT send any other message!!! The certificate is invalid and it could be a security risk
}
}
// Publush $online as true with pubTopic still correct from will above
mqttSend(String(FPSTR(mqttstr_online)), str_true, true);
logString = String(F("Subscribing to ")) + String(subTopic);
logMessage(app_name_mqtt, logString, false);
mqttClient.subscribe(subTopic);
sensorMqttSubs(); // Any extra subscriptions that a sensor may want
mqtt_send_systeminfo();
} else {
logString = F("Failed to connect to MQTT, ");
logString += mqtt_rc_states[mqttClient.state() + 4]; // The return codes start from -4 so we have to add four to get the correct array position
logString += " (rc=" + String(mqttClient.state()) + ")";
logMessage(app_name_mqtt, logString, false);
}
}
}
/// The MQTT callback function for received messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String mqttSubString = "";
String mqttSubCmd = "";
String mqttSubKey = "";
String mqttSubValue = "";
watchdog = millis(); // feed the watchdog
#ifdef DEBUG
dmesg();
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.println("");
#endif
if ( strcmp(subTopic, topic) == 0 ) { // The topic matches the main subTopic
for (int i = 0; i < length; i++) {
if ( ( (char)payload[i] == ':' ) && (mqttSubKey == "") ) {
if (mqttSubCmd == "") mqttSubCmd = mqttSubString;
else if (mqttSubKey == "") mqttSubKey = mqttSubString;
mqttSubString = "";
} else if ( (char)payload[i] == ',' ) {
mqttSubValue = mqttSubString;
mqttCommand(mqttSubCmd, mqttSubKey, mqttSubValue);
mqttSubString = "";
mqttSubCmd = "";
mqttSubKey = "";
mqttSubValue = "";
} else {
mqttSubString = String(mqttSubString + String((char)payload[i]));
}
}
if (mqttSubCmd == "") mqttSubCmd = mqttSubString;
else if (mqttSubKey == "") mqttSubKey = mqttSubString;
else mqttSubValue = mqttSubString;
mqttCommand(mqttSubCmd, mqttSubKey, mqttSubValue);
} else { // The topic belongs to a sensor subscription
sensorMqttCallback(topic, payload, length);
}
}
void mqttCommand(const String &cmd, const String &key, const String &value) {
#ifdef DEBUG
dmesg();
Serial.print(" cmd: ");
Serial.println(cmd);
dmesg();
Serial.print(" key: ");
Serial.println(key);
dmesg();
Serial.print(" value:");
Serial.println(value);
dmesg();
Serial.println("----------");
#endif
if ( cmd == "set" ) {
if ( key == "interval" ) {
mqtt_interval = value.toInt();
}
} else if ( cmd == "get" ) {
if ( key == "system" ) {
mqtt_send_systeminfo();
}
} else if ( cmd == "action" ) {
runAction(key, value);
} else if ( cmd == "update" ) {
if ( key == "firmware" ) {
updateFirmware(value);
}
} else if ( cmd == "config" ) {
updateConfig(key, value);
} else if ( cmd == "saveconfig" ) {
saveConfig();
} else if ( cmd == "savewifi" ) {
WiFi.begin(ssid.c_str(), psk.c_str(), 0, NULL, false);
} else if ( cmd == "reboot" ) {
logString = "Received reboot command.";
logMessage(app_name_mqtt, logString, true);
mqttSend(String(FPSTR(mqttstr_online)), str_false, true);
ESP.restart();
} else {
logString = String("UNKNOWN command: " + key);
mqttLog(app_name_mqtt, logString);
return;
}
}