-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ksMqttConnector.cpp
264 lines (226 loc) · 7.45 KB
/
ksMqttConnector.cpp
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
/*
* Copyright (c) 2021-2023, Krzysztof Strehlau
*
* This file is a part of the ksIotFramework library.
* All licensing information can be found inside LICENSE.md file.
*
* https://github.com/cziter15/ksIotFrameworkLib/blob/master/LICENSE
*/
#if defined(ESP32)
#include <esp_wifi.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#elif defined(ESP8266)
#include <user_interface.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#else
#error Platform not implemented.
#endif
#include <PubSubClient.h>
#include "../ksApplication.h"
#include "../ksConstants.h"
#include "../ksConfig.h"
#include "../misc/ksCertUtils.h"
#include "ksWifiConnector.h"
#include "ksMqttConnector.h"
#include "ksMqttConfigProvider.h"
using namespace std::placeholders;
namespace ksf::comps
{
ksMqttConnector::~ksMqttConnector() = default;
ksMqttConnector::ksMqttConnector(bool sendConnectionStatus, bool usePersistentSession)
{
bitflags.sendConnectionStatus = sendConnectionStatus;
bitflags.usePersistentSession = usePersistentSession;
}
bool ksMqttConnector::init(ksApplication* app)
{
ksMqttConfigProvider cfgProvider;
#if APP_LOG_ENABLED
this->app = app;
#endif
cfgProvider.init(app);
cfgProvider.setupMqttConnector(*this);
/*
Object mqttClientUq is created by setupConnection method.
That means init will return false when no MQTT config file found.
*/
return mqttClientUq != nullptr;
}
bool ksMqttConnector::postInit(ksApplication* app)
{
wifiConnWp = app->findComponent<ksWifiConnector>();
return true;
}
void ksMqttConnector::setupConnection(const std::string broker, const std::string& port, std::string login, std::string password, std::string prefix, const std::string& fingerprint)
{
if (!fingerprint.empty())
{
auto secureClient{std::make_unique<ksMqttConnectorNetClientSecure_t>()};
certFingerprint = std::make_unique<ksCertFingerprintHolder>();
if (certFingerprint->setup(secureClient.get(), fingerprint))
netClientUq = std::move(secureClient);
}
else netClientUq = std::make_unique<ksMqttConnectorNetClient_t>();
/* Whoops, it looks like fingerprint validation failed. */
if (!netClientUq)
return;
/* Set socket timeouts. */
netClientUq->setTimeout(KSF_MQTT_TIMEOUT_MS);
/* Load MQTT parameters. */
this->login = std::move(login);
this->password = std::move(password);
this->prefix = std::move(prefix);
this->broker = std::move(broker);
ksf::from_chars(port, portNumber);
/* Create MQTT client. */
mqttClientUq = std::make_unique<PubSubClient>(*netClientUq.get());
}
void ksMqttConnector::mqttConnectedInternal()
{
lastSuccessConnectionTime = millis64();
mqttClientUq->setCallback(std::bind(&ksMqttConnector::mqttMessageInternal, this, _1, _2, _3));
onConnected->broadcast();
}
void ksMqttConnector::mqttMessageInternal(const char* topic, const uint8_t* payload, uint32_t length)
{
bool handlesDeviceMessage{onDeviceMessage->isBound()};
bool handlesAnyMessage{onAnyMessage->isBound()};
if (!handlesDeviceMessage && !handlesAnyMessage)
return;
std::string_view payloadStr{reinterpret_cast<const char*>(payload), length};
std::string_view topicStr{topic};
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Reveived from: ");
out += topicStr;
out += PSTR(", value: ");
out += payloadStr;
});
#endif
if (handlesDeviceMessage && ksf::starts_with(topicStr, prefix))
{
topicStr = topicStr.substr(prefix.length());
onDeviceMessage->broadcast(topicStr, payloadStr);
}
if (handlesAnyMessage)
onAnyMessage->broadcast(topicStr, payloadStr);
}
void ksMqttConnector::subscribe(const std::string& topic, bool skipDevicePrefix, ksMqttConnector::QosLevel qos)
{
uint8_t qosLevel{static_cast<uint8_t>(qos)};
mqttClientUq->subscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), qosLevel);
}
void ksMqttConnector::unsubscribe(const std::string& topic, bool skipDevicePrefix)
{
mqttClientUq->unsubscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str());
}
void ksMqttConnector::publish(const std::string& topic, const std::string& payload, bool retain, bool skipDevicePrefix)
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] ");
if (retain)
out += PSTR("(Retained) ");
out += PSTR("Publish to: ");
out += prefix;
out += topic;
out += PSTR(", value: ");
out += payload;
});
#endif
mqttClientUq->publish(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), reinterpret_cast<const uint8_t*>(payload.c_str()), payload.length(), retain);
}
bool ksMqttConnector::connectToBroker()
{
if (bitflags.sendConnectionStatus)
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Connecting to MQTT broker...");
});
#endif
#if defined(ESP32)
/* If host is an IP Address, use it. Otherwise use domain name. */
if (IPAddress serverIP; serverIP.fromString(this->broker.c_str()))
netClientUq->connect(serverIP, portNumber, KSF_MQTT_TIMEOUT_MS);
else
netClientUq->connect(this->broker.c_str(), portNumber, KSF_MQTT_TIMEOUT_MS);
#elif defined(ESP8266)
/* If host is an IP Address, use it. Otherwise use domain name. */
if (IPAddress serverIP; serverIP.fromString(this->broker.c_str()))
netClientUq->connect(serverIP, portNumber);
else
netClientUq->connect(this->broker.c_str(), portNumber);
#else
#error "Unsupported platform"
#endif
/* If not connected, return. */
if (!netClientUq->connected())
return false;
/* Verify certificate fingerprint. */
if (certFingerprint && !certFingerprint->verify(reinterpret_cast<ksMqttConnectorNetClientSecure_t*>(netClientUq.get())))
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Invalid certificate fingerprint! Disconnecting.");
});
#endif
netClientUq->stop();
return false;
}
std::string willTopic{prefix + PSTR("connected")};
if (mqttClientUq->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), willTopic.c_str(), 0, true, "0", !bitflags.usePersistentSession))
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Connected successfully to ");
out += broker;
out += PSTR(" on port ");
out += std::to_string(portNumber);
});
#endif
mqttClientUq->publish(willTopic.c_str(), reinterpret_cast<const uint8_t*>("1"), 1, true);
return true;
}
return false;
}
return mqttClientUq->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), 0, 0, false, 0, !bitflags.usePersistentSession);
}
bool ksMqttConnector::loop(ksApplication* app)
{
if (!mqttClientUq->loop())
{
if (bitflags.wasConnected)
{
bitflags.wasConnected = false;
reconnectTimer.restart();
onDisconnected->broadcast();
}
else if (reconnectTimer.hasTimePassed())
{
if (auto wifiConnSp{wifiConnWp.lock()})
{
if (wifiConnSp->isConnected() && connectToBroker())
{
++reconnectCounter;
bitflags.wasConnected = true;
mqttConnectedInternal();
}
/* This must be done after connectToBroker, because connect can block for few seconds. */
reconnectTimer.restart();
}
}
}
return true;
}
bool ksMqttConnector::isConnected() const
{
return mqttClientUq ? mqttClientUq->connected() : false;
}
uint32_t ksMqttConnector::getConnectionTimeSeconds() const
{
return isConnected() ? ((millis64() - lastSuccessConnectionTime) / KSF_ONE_SEC_MS) : 0;
}
}