-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTTClient.cpp
79 lines (63 loc) · 1.82 KB
/
MQTTClient.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
#include "Particle.h";
#include "MQTT.h";
#include "MQTTClient.h";
#include "ArduinoJson.h";
MQTTClient::MQTTClient(MQTT *conn, String devID) {
connection = conn;
deviceID = devID;
}
void MQTTClient::tick() {
if(connection->isConnected()) {
connection->loop();
} else {
Log.info("No MQTT connection. (Re)connecting.");
reconnect();
}
}
void MQTTClient::connect() {
Log.info("Connecting to MQTT broker");
connection->connect("darter-" + System.deviceID());
delay(50);
if(connection->isConnected()) {
Log.info("MQTT connection established. Subscribing to topics.");
subscribeToTopics();
publishIntroduction();
} else {
Log.warn("Failed to connect to MQTT broker.");
}
}
void MQTTClient::reconnect() {
// Wait 15 seconds for dead sockets to timeout and so forth
delay(5000);
connect();
}
void MQTTClient::subscribeToTopics() {
connection->subscribe(darterTopic("playShow"));
connection->subscribe("darter/all/#");
}
void MQTTClient::publishIntroduction() {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
char deviceId[32];
System.deviceID().toCharArray(deviceId, 32);
root["deviceId"] = deviceId;
char jsonString[255];
root.printTo(jsonString, 255);
connection->publish(darterTopic("introduction"), jsonString);
}
void MQTTClient::publishHit() {
if(connection->isConnected()) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
char deviceId[32];
System.deviceID().toCharArray(deviceId, 32);
root["deviceId"] = deviceId;
root["timestamp"] = Time.now();
char jsonString[255];
root.printTo(jsonString, 255);
connection->publish(darterTopic("hits"), jsonString);
}
}
String MQTTClient::darterTopic(const char* lastElement) {
return "darter/" + deviceID + "/" + lastElement;
}