-
Notifications
You must be signed in to change notification settings - Fork 3
/
MqttController.cpp
108 lines (85 loc) · 2.58 KB
/
MqttController.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
#ifdef ESP8266
#include "MqttController.h"
/* ugly */
extern MqttController *mqttController;
static void mqtt_message_handler(char* topic, byte* payload, unsigned int length) {
mqttController->handle(topic, payload, length);
}
MqttController::MqttController(IColorControllable *colorControllable, Client& client)
: colorControllable(colorControllable) {
mqttClient.setCallback(mqtt_message_handler);
mqttClient.setClient(client);
}
void MqttController::maintain() {
if (!mqttClient.connected())
reconnect();
mqttClient.loop();
}
void MqttController::reconnect() {
Serial.println("Attempting MQTT connection...");
if (!mqttClient.connect(id, user, password)) {
Serial.println("MQTT connect failed.");
return; /* failed to connect */
}
publish("status", "hello world");
subscribe("color/red");
subscribe("color/green");
subscribe("color/blue");
}
void MqttController::publish(const char *topic, const char *payload) {
uint8_t i = strlen(id);
char buffer[i + strlen(topic) + 2];
strcpy(buffer, id);
buffer[i++] = '/';
strcpy(&buffer[i], topic);
Serial.print("publishing to topic: ");
Serial.println(buffer);
mqttClient.publish(buffer, payload);
}
void MqttController::subscribe(const char *topic) {
uint8_t i = strlen(id);
char buffer[i + strlen(topic) + 2];
strcpy(buffer, id);
buffer[i++] = '/';
strcpy(&buffer[i], topic);
Serial.print("subscribing to: ");
Serial.println(buffer);
mqttClient.subscribe(buffer);
}
void MqttController::handle(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (unsigned int i = 0; i < length; i ++)
Serial.print((char) payload[i]);
if (length > 10) {
Serial.println("ignoring loooong message");
return;
}
Serial.println();
Serial.println(topic);
Serial.println(id);
Serial.println(String(strlen(id)));
char *ptr = topic + strlen(id) + 1;
Serial.print("subcommand: ");
Serial.println(ptr);
char buf[length + 1];
memmove (buf, payload, length);
buf[length] = 0;
int value = atoi(buf);
Serial.print("converted value: ");
Serial.println(String(value));
if (strncmp(ptr, "color/red", 9) == 0) {
Serial.println("color change for RED");
colorControllable->setRed(value);
}
else if (strncmp(ptr, "color/green", 11) == 0) {
Serial.println("color change for GREEN");
colorControllable->setGreen(value);
}
else if (strncmp(ptr, "color/blue", 10) == 0) {
Serial.println("color change for BLUE");
colorControllable->setBlue(value);
}
}
#endif /* ESP8266 */