forked from UEk/mqttPublishExample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqttPublishExample.ino
258 lines (216 loc) · 7.55 KB
/
mqttPublishExample.ino
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
/**
* \file mqttPublishExample.ino
* \author Ulrik Eklund
* \date 2016
* \brief File containing example sketch for connecting arduino as a client to IBM Bluemix MQTT broker.
* \copyright MIT license, see LICENSE.txt
*
* Part of this sketch is based on MQTT example code from Nick O'Leary - @knolleary
* other parts are from arduino.cc tutorials
*/
#include <SPI.h> /* Installed in default arduino IDE */
#include <Ethernet.h> /* Installed in default arduino IDE */
#include <WiFi.h> /* Installed in default arduino IDE */
/* Install from https://github.com/knolleary/pubsubclient/releases/latest */
#include <PubSubClient.h>
/* Install from https://github.com/bblanchon/ArduinoJson */
#include <ArduinoJson.h>
/* Set this to 'true' to use terminal output, the the sketch will halt until a terminal is connected
* Set to 'false' to just run the sketch with no serial terminal connected */
#define TERMINAL false
/* Generic definitions for all devices connected to Bluemix */
#define MQTT_PORT 1883
#define MQTT_TOPIC "iot-2/evt/status/fmt/json"
#define MQTT_SUBSCRIBE_TOPIC "iot-2/cmd/+/fmt/json"
#define MQTT_USERNAME "use-token-auth"
/* These defintions must be changed for each device
* See https://software.intel.com/en-us/articles/connecting-to-ibm-bluemix-internet-of-things-using-mqtt
* for instructions on how they need to be defined */
#define MQTT_CLIENTID "<USE PROVIDED ID>"
#define MQTT_SERVER "<USE PROVIDED SERVER NAME>"
#define MQTT_PASSWORD "<USE PROVIDED TOKEN>"
#define DEVICE_ID "<USE DEVICE PROVIDED ID>" /* not really used seprately in the MQTT comm */
/* Functions to help the structure of the code in setup() and loop() */
void callback(char* topic, byte* payload, unsigned int length);
void reconnectToBroker(void);
double getSensorValue(void);
int connectToNetwork(void); /* Function dealing with the connection to Wifi or ethernet */
/* Update these global variables with values suitable for your network. */
byte mac[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; /* The MAC address of the NIC */
char ssid[] = "<INSERT SSID HERE>"; /* The name of the wifi network */
byte ip[] = {192, 168, 0, 1}; /* Static address retrieved from IPAM. */
//char passwd[] = "Please!"
/* Global variables and instances used in multiple functions */
int status = WL_IDLE_STATUS; /* the wifi radio's status */
/* Use this for wifi */
//WiFiClient wclient; /* construct a wifi client based on WiFi.h */
//PubSubClient client(wclient); /* construct the object for the MQTT client based on PubSubClient.h */
/* Use this for ethernet */
EthernetClient ethClient; /* construct a ethernet client */
PubSubClient client(ethClient);
void setup()
{
if (TERMINAL)
{
Serial.begin(9600); /* Initialize the serial port */
while (!Serial)
{
; /* wait for the port to connect. Needed only for Leonardo according to Arduino */
}
Serial.println("Booting up");
}
//connectToNetwork(); /* connect to the wifi SSID network */
connectToEthernet();
if (TERMINAL)
{
Serial.println("Ready to set MQTT server settings");
}
client.setServer(MQTT_SERVER, MQTT_PORT); /* Setting MQTT server details */
client.setCallback(callback); /* Set callback function for subscription from MQTT broker*/
}
void loop()
{
/* create the payload string (should haved made a function to do this...) */
char buffer[256]; /* character string containing the JSON payload */
StaticJsonBuffer<200> jsonBuffer; /* Reserve memory space for the Json buffer */
JsonObject& payload = jsonBuffer.createObject(); /*create the payload object */
JsonObject& data = payload.createNestedObject("d"); /* Bluemix has all data as a singe tuple {d:data} */
data["myName"] = "<INSERT NAME HERE>"; /* 1st data item */
data["temperature"] = double_with_n_digits(getSensorValue(), 2); /* 2nd data item */
payload.printTo(buffer, sizeof(buffer)); /* convert to buffer, which is the string to be used as the message */
if (!client.connected()) /* client disconnected from the MQTT broker? */
{
reconnectToBroker(); /* if disconnected, reconnect to the broker */
}
if (client.publish(MQTT_TOPIC, buffer) && TERMINAL) /* publish the payload in buffer[], print if ok */
{
Serial.print("Message published: ");
Serial.println(buffer);
}
else if(TERMINAL)
{
Serial.println("Failed to publish MQTT message");
}
client.loop(); /* called regularly to handle incomming */
delay(5000); /* this delay defines the frequency of published messages */
}
void callback(char* topic, byte* payload, unsigned int length)
/* This MQTT callback function is based on code from Nick O'Leary - @knolleary
* Rewrite according to you own needs */
{
if (TERMINAL)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
}
}
double getSensorValue(void)
/* Fake random temperature sensor values 20-25 C
* Rewrite according to your own needs */
{
double t;
t = 20.0 + (random(50)/10.0);
return (t);
}
is
int connectToEthernet()
/*
* This method tries to connect to an Ethernet network using DHCP.
*/
{
int success = false;
if (TERMINAL)
{
Serial.println("Connecting to network");
}
if (Ethernet.begin(mac) == 0) // Try to use DHCP
{
// If that failed, use static address
Ethernet.begin(mac, ip);
}
if (TERMINAL)
{
Serial.print("Connected as ");
for (byte thisByte = 0; thisByte < 4; thisByte++)
{
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
return success;
}
int connectToNetwork(void)
/* Quick and dirty to connect to a wifi network, based on
* https://www.arduino.cc/en/Tutorial/ConnectNoEncryption
* needs to be modified if using ethernet, see e.g.
* https://www.arduino.cc/en/Tutorial/WebClient */
{
int success = false;
if (WiFi.status() == WL_NO_SHIELD) /* check if wifi shield is present */
{
if (TERMINAL)
{
Serial.println("WiFi shield is not connected!");
}
while (true); /* wait here for eternity */
}
String fv = WiFi.firmwareVersion();
if (fv != "1.1.0")
{
Serial.println("Please upgrade the firmware");
}
while (status != WL_CONNECTED) /* attempt to connect to Wifi network */
{
if (TERMINAL)
{
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
}
status = WiFi.begin(ssid); /* Connect to the wifi network, no password */
delay(3000); /* wait 3 seconds for wifi connection */
}
if (TERMINAL)
{
Serial.print("You're connected to SSID: ");
Serial.println(ssid);
}
success = true;
return success;
}
void reconnectToBroker(void)
/* This function is based on code from Nick O'Leary - @knolleary
* Probably not needed to change in your own application! */
{
while (!client.connected()) /* Loop until reconnected */
{
if (TERMINAL)
{
Serial.println("Attempting MQTT connection to broker...");
}
if (client.connect(MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD)) /* Attempt to connect */
{
if (TERMINAL)
{
Serial.print("Connected to ");
Serial.println(MQTT_SERVER);
}
//client.publish(MQTT_TOPIC, "hello world"); /* Once connected, publish an announcement */
client.subscribe(MQTT_SUBSCRIBE_TOPIC); /* resubscribe */
}
else if (TERMINAL)
{
Serial.print("failed, rc = ");
Serial.print(client.state());
Serial.println(", try again in 5 seconds");
}
delay(5000);
}
}