-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqttArduinoTemplate.ino
More file actions
96 lines (76 loc) · 2.27 KB
/
mqttArduinoTemplate.ino
File metadata and controls
96 lines (76 loc) · 2.27 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
#include "SPI.h"
#include "WiFly.h"
#include "PubSubClient.h"
//broker settings
byte server[] = { 0, 0, 0, 0 }; // replace with the IP address of your broker - swap . for ,
int port = 1883; //default port is 1883. To help get around network restrictions,you may need broker set as port 80
char subscribedChannel[] = "outTopic";
char deviceName[] = "uniqueClientName"; // set a unique name for each device connected to the broker
//used to decode the message payload
String payloadString;
void convertPayload(byte array[], byte len){
payloadString = "";
for (byte i = 0; i < len;){
char c = array[i++];
if (c < 0x20 || c > 0x7e){
Serial.print('.');
payloadString += '.';
}
else {
payloadString += char(c);
}
}
}
//triggered when a message is recieved on a subscribed channel
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("Message Recieved");
// handle message
//check the topic - use this is you want to sunbscribe to more than one channel
if (String(topic) == String(subscribedChannel)){
Serial.println(topic);
//convert the payload to a string, then print it out
convertPayload(payload, length);
Serial.println(payloadString);
}
}
WiFlyClient wifiClient;
PubSubClient client(server, port, callback, wifiClient);
void connectToBroker(){
//connect to the broker
if (client.connect(deviceName)) {
Serial.println("Connecting");
//send a test message
client.publish("outTopic","hello world");
//subscribe to a channel
client.subscribe(subscribedChannel);
Serial.println("Connected");
} else{
Serial.println("Connection Error");
}
}
void setup() {
Serial.begin(115200);
Serial.println("setup");
//connect to network
WiFly.begin();
if (!WiFly.join("ssid", "pass")) { //use if network has passphrase
//if (!WiFly.join("ssid")) { // use id it doesn't
Serial.println("Association failed.");
while (1) {
// Hang on failure.
}
}else{
Serial.println("Joining");
Serial.println(WiFly.ip());
}
}
void loop() {
//check and maintain the connection to the broker
if(!client.connected()){
Serial.println("Disconnected");
connectToBroker();
}else{
client.loop();
}
//Do Stuff!
}