-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathAmsMqttHandler.cpp
More file actions
307 lines (278 loc) · 9.22 KB
/
Copy pathAmsMqttHandler.cpp
File metadata and controls
307 lines (278 loc) · 9.22 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/**
* @copyright Utilitech AS 2023-2026
* License: Fair Source
*
*/
#include "AmsMqttHandler.h"
#include "FirmwareVersion.h"
#include "AmsStorage.h"
#include "LittleFS.h"
#include "Uptime.h"
#include "AmsJsonGenerator.h"
#include <ArduinoJson.h>
void AmsMqttHandler::setCaVerification(bool caVerification) {
this->caVerification = caVerification;
}
void AmsMqttHandler::setConfig(MqttConfig& mqttConfig) {
this->mqttConfig = mqttConfig;
this->mqttConfigChanged = true;
}
bool AmsMqttHandler::connect() {
if(millis() - lastMqttRetry < 10000) {
yield();
return false;
}
lastMqttRetry = millis();
time_t epoch = time(nullptr);
WiFiClient *actualClient = NULL;
if(mqttConfig.ssl) {
if(epoch < FirmwareVersion::BuildEpoch) {
return false;
}
bool applySslConfiguration = mqttConfigChanged;
if(mqttSecureClient == NULL) {
mqttSecureClient = new WiFiClientSecure();
#if defined(ESP8266)
mqttSecureClient->setBufferSizes(512, 512);
return false;
#endif
applySslConfiguration = true;
}
if(applySslConfiguration) {
if(caVerification && LittleFS.begin()) {
File file;
if(LittleFS.exists(FILE_MQTT_CA)) {
file = LittleFS.open(FILE_MQTT_CA, (char*) "r");
#if defined(ESP8266)
BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(file);
mqttSecureClient->setTrustAnchors(serverTrustedCA);
#elif defined(ESP32)
if(!mqttSecureClient->loadCACert(file, file.size())) {
return false;
}
#endif
file.close();
} else {
mqttSecureClient->setInsecure();
}
#if defined(ESP8266)
if(LittleFS.exists(FILE_MQTT_CERT) && LittleFS.exists(FILE_MQTT_KEY)) {
file = LittleFS.open(FILE_MQTT_CERT, (char*) "r");
BearSSL::X509List *serverCertList = new BearSSL::X509List(file);
file.close();
file = LittleFS.open(FILE_MQTT_KEY, (char*) "r");
BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(file);
file.close();
mqttSecureClient->setClientRSACert(serverCertList, serverPrivKey);
}
#endif
#if defined(ESP32)
if(LittleFS.exists(FILE_MQTT_CERT)) {
file = LittleFS.open(FILE_MQTT_CERT, (char*) "r");
mqttSecureClient->loadCertificate(file, file.size());
file.close();
}
if(LittleFS.exists(FILE_MQTT_KEY)) {
file = LittleFS.open(FILE_MQTT_KEY, (char*) "r");
mqttSecureClient->loadPrivateKey(file, file.size());
file.close();
}
#endif
} else {
mqttSecureClient->setInsecure();
}
}
actualClient = mqttSecureClient;
} else {
if(mqttClient == NULL) {
mqttClient = new WiFiClient();
}
actualClient = mqttClient;
}
// This section helps with power saving on ESP32 devices by reducing timeouts
// The timeout is multiplied by 10 because WiFiClient is retrying 10 times internally
// Power drain for this timeout is too great when using the default 3s timeout
// On ESP8266 the timeout is used differently and the following code causes MQTT instability
#if defined(ESP32)
int clientTimeout = mqttConfig.timeout / 1000;
if(clientTimeout > 3) clientTimeout = 3; // 3000ms is default, see WiFiClient.cpp WIFI_CLIENT_DEF_CONN_TIMEOUT_MS
actualClient->setTimeout(clientTimeout);
// Why can't we set number of retries for write here? WiFiClient defaults to 10 (10*3s == 30s)
#endif
mqttConfigChanged = false;
mqtt.setTimeout(mqttConfig.timeout);
mqtt.setKeepAlive(mqttConfig.keepalive);
mqtt.begin(mqttConfig.host, mqttConfig.port, *actualClient);
char statusTopic[72];
snprintf(statusTopic, sizeof(statusTopic), "%s/status", mqttConfig.publishTopic);
mqtt.setWill(statusTopic, "offline", true, 0);
#if defined(ESP8266)
if(mqttSecureClient) {
time_t epoch = time(nullptr);
mqttSecureClient->setX509Time(epoch);
}
#endif
// Connect to a unsecure or secure MQTT server
if ((strlen(mqttConfig.username) == 0 && mqtt.connect(mqttConfig.clientId)) ||
(strlen(mqttConfig.username) > 0 && mqtt.connect(mqttConfig.clientId, mqttConfig.username, mqttConfig.password))) {
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::INFO))
#endif
debugger->printf_P(PSTR("Successfully connected to MQTT\n"));
mqtt.onMessage(std::bind(&AmsMqttHandler::onMessage, this, std::placeholders::_1, std::placeholders::_2));
_connected = mqtt.publish(statusTopic, "online", true, 0);
mqtt.loop();
defaultSubscribe();
postConnect();
return true;
} else {
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::ERROR))
#endif
{
debugger->printf_P(PSTR("Failed to connect to MQTT: %d\n"), mqtt.lastError());
#if defined(ESP8266)
if(mqttSecureClient) {
mqttSecureClient->getLastSSLError((char*) json, BUF_SIZE_COMMON);
debugger->println((char*) json);
}
#endif
}
return false;
}
}
bool AmsMqttHandler::defaultSubscribe() {
bool ret = true;
if(subTopic[0] != '\0') {
if(mqtt.subscribe(subTopic)) {
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::ERROR))
#endif
debugger->printf_P(PSTR(" Subscribed to [%s]\n"), subTopic);
} else {
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::ERROR))
#endif
debugger->printf_P(PSTR(" Unable to subscribe to [%s]\n"), subTopic);
ret = false;
}
}
return ret;
}
void AmsMqttHandler::disconnect() {
mqtt.disconnect();
mqtt.loop();
_connected = false;
delay(10);
yield();
}
lwmqtt_err_t AmsMqttHandler::lastError() {
return mqtt.lastError();
}
bool AmsMqttHandler::connected() {
return _connected && mqtt.connected();
}
bool AmsMqttHandler::loop() {
uint64_t now = millis64();
bool ret = connected() && mqtt.loop();
if(ret) {
lastSuccessfulLoop = now;
} else if(mqttConfig.rebootMinutes > 0) {
if(now - lastSuccessfulLoop > (uint64_t) mqttConfig.rebootMinutes * 60000) {
// Reboot the device if the MQTT connection is lost for too long
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::WARNING))
#endif
debugger->printf_P(PSTR("MQTT connection lost for over %d minutes, rebooting device\n"), mqttConfig.rebootMinutes);
rebootSuggested = true;
}
}
delay(10); // Needed to preserve power. After adding this, the voltage is super smooth on a HAN powered device
yield();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
return ret;
}
bool AmsMqttHandler::isRebootSuggested() {
return rebootSuggested;
}
void AmsMqttHandler::rebootDevice(uint8_t cause) {
if(rdc != NULL) rdc->cause = cause;
#if defined(AMS_REMOTE_DEBUG)
if (debugger->isActive(RemoteDebug::INFO))
#endif
debugger->printf_P(PSTR("Rebooting (MQTT command)\n"));
debugger->flush();
delay(1000);
ESP.restart();
}
// Generic commands available to every payload handler. Accepts either a plain
// payload ("reboot") or a JSON object ({"action":"reboot"}). Destructive actions
// (reboot, factoryreset) require MqttConfig.allowDestructiveCommands; factoryreset
// additionally requires "confirm":true.
bool AmsMqttHandler::handleCommand(String &topic, String &payload) {
if(strcmp(topic.c_str(), subTopic) != 0) return false;
char action[24] = {0};
bool confirm = false;
String version;
if(payload.startsWith("{")) {
DynamicJsonDocument doc(512);
if(deserializeJson(doc, payload)) return false;
JsonObject obj = doc.as<JsonObject>();
if(!obj.containsKey(F("action"))) return false;
strncpy(action, obj[F("action")] | "", sizeof(action) - 1);
confirm = obj[F("confirm")] | false;
if(obj.containsKey(F("version"))) version = (const char*) (obj[F("version")] | "");
} else {
strncpy(action, payload.c_str(), sizeof(action) - 1);
}
if(strcmp_P(action, PSTR("fwupgrade")) == 0) {
const char* target = version.length() > 0 ? version.c_str() : updater->getNextVersion();
if(strlen(target) > 0 && strcmp(target, FirmwareVersion::VersionString) != 0) {
updater->setTargetVersion(target);
}
return true;
} else if(strcmp_P(action, PSTR("dayplot")) == 0) {
if(ds != NULL) {
char plotTopic[80];
snprintf_P(plotTopic, sizeof(plotTopic), PSTR("%s/dayplot"), pubTopic);
AmsJsonGenerator::generateDayPlotJson(ds, json, BUF_SIZE_COMMON);
mqtt.publish(plotTopic, json);
loop();
}
return true;
} else if(strcmp_P(action, PSTR("monthplot")) == 0) {
if(ds != NULL) {
char plotTopic[80];
snprintf_P(plotTopic, sizeof(plotTopic), PSTR("%s/monthplot"), pubTopic);
AmsJsonGenerator::generateMonthPlotJson(ds, json, BUF_SIZE_COMMON);
mqtt.publish(plotTopic, json);
loop();
}
return true;
} else if(strcmp_P(action, PSTR("reboot")) == 0) {
if(!mqttConfig.allowDestructiveCommands) {
debugger->printf_P(PSTR("Ignoring MQTT reboot: destructive commands disabled\n"));
return true;
}
rebootDevice(REBOOT_CAUSE_MQTT_REBOOT);
return true;
} else if(strcmp_P(action, PSTR("factoryreset")) == 0) {
if(!mqttConfig.allowDestructiveCommands) {
debugger->printf_P(PSTR("Ignoring MQTT factoryreset: destructive commands disabled\n"));
return true;
}
if(!confirm) {
debugger->printf_P(PSTR("Ignoring MQTT factoryreset: missing \"confirm\":true\n"));
return true;
}
LittleFS.format();
config->clear();
rebootDevice(REBOOT_CAUSE_MQTT_FACTORY_RESET);
return true;
}
return false;
}