-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.cpp
63 lines (52 loc) · 1.42 KB
/
mqtt.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
#include "mqtt.h"
MQTT::MQTT(IPAddress server, int port) : server(server), port(port), func_subscribe_callback(NULL) {
client.setClient(yun);
}
void MQTT::init() {
client.setServer(server, port);
client.setCallback(callback);
Bridge.begin();
Process p;
p.runShellCommand("hostname");
hostname += "arduino-";
hostname += p.readString();
hostname.replace('\n','\0');
hostname = String(hostname.c_str()); //filthy hack lol
debug_topic = "debug/" + hostname;
}
void MQTT::loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
//probably nothing?
//this arduino doesn't really need to listen for messages AFAIK
}
void MQTT::reconnect() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(hostname.c_str()))
{
Serial.println("connected");
if (func_subscribe_callback != NULL)
{
func_subscribe_callback();
}
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 1 seconds");
delay(1000);
}
}
}
void MQTT::set_subscribe_callback(void (*callback)(void)) {
func_subscribe_callback = callback;
}