-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.cpp
277 lines (235 loc) · 8.95 KB
/
main.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// ----------------------------------------------------------------------------
// Copyright 2016-2019 ARM Ltd.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------
#define MQTTCLIENT_QOS1 0
#define MQTTCLIENT_QOS2 0
#include "mbed.h"
#include "TLSSocket.h"
#include "MQTTClientMbedOs.h"
#include "MQTT_server_setting.h"
#include "mbed-trace/mbed_trace.h"
#include "mbed_events.h"
#include "NTPClient.h"
#include "mbedtls/error.h"
#define MQTT_MAX_CONNECTIONS 5
#define MQTT_MAX_PACKET_SIZE 1024
#define TIME_JWT_EXP (60*60*24) // 24 hours (MAX)
// LED on/off - This could be different among boards
#define LED_ON 0
#define LED_OFF 1
/* Flag to be set when a message needs to be published, i.e. BUTTON is pushed. */
static volatile bool isPublish = false;
/* Flag to be set when received a message from the server. */
static volatile bool isMessageArrived = false;
/* Buffer size for a receiving message. */
const int MESSAGE_BUFFER_SIZE = 1024;
/* Buffer for a receiving message. */
char messageBuffer[MESSAGE_BUFFER_SIZE];
// Function prototypes
void handleMqttMessage(MQTT::MessageData& md);
void handleButtonRise();
int main(int argc, char* argv[])
{
mbed_trace_init();
const float version = 1.0;
NetworkInterface* network = NULL;
DigitalOut led_red(LED1, LED_OFF);
DigitalOut led_green(LED2, LED_OFF);
DigitalOut led_blue(LED3, LED_OFF);
printf("Mbed to Azure IoT Hub: version is %.2f\r\n", version);
printf("\r\n");
#ifdef MBED_MAJOR_VERSION
printf("Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
#endif
// Turns on green LED to indicate processing initialization process
led_green = LED_ON;
printf("Opening network interface...\r\n");
network = NetworkInterface::get_default_instance();
if (!network) {
printf("Unable to open network interface.\r\n");
return -1;
}
nsapi_error_t net_status = NSAPI_ERROR_NO_CONNECTION;
while ((net_status = network->connect()) != NSAPI_ERROR_OK) {
printf("Unable to connect to network (%d). Retrying...\r\n", net_status);
}
printf("Connected to the network successfully. IP address: %s\r\n", network->get_ip_address());
printf("\r\n");
// sync the real time clock (RTC)
{
NTPClient ntp(network);
ntp.set_server("time.google.com", 123);
time_t now = ntp.get_timestamp();
if (now <= 0) {
printf("Failed to retrieve the time from time.google.com:123\r\n");
return 1;
}
set_time(now);
printf("Time is now %s", ctime(&now));
}
/* Establish a network connection. */
TLSSocket *socket = new TLSSocket; // Allocate on heap to avoid stack overflow.
printf("Connecting to host %s:%d ...\r\n", MQTT_SERVER_HOST_NAME, MQTT_SERVER_PORT);
{
nsapi_error_t ret = socket->open(network);
if (ret != NSAPI_ERROR_OK) {
printf("Could not open socket! Returned %d\n", ret);
return -1;
}
ret = socket->set_root_ca_cert(SSL_CA_PEM);
if (ret != NSAPI_ERROR_OK) {
printf("Could not set ca cert! Returned %d\n", ret);
return -1;
}
#if IOTHUB_AUTH_METHOD == IOTHUB_AUTH_CLIENT_SIDE_CERT
ret = socket->set_client_cert_key(SSL_CLIENT_CERT_PEM, SSL_CLIENT_PRIVATE_KEY_PEM);
if (ret != NSAPI_ERROR_OK) {
printf("Could not set keys! Returned %d\n", ret);
return -1;
}
#endif
ret = socket->connect(MQTT_SERVER_HOST_NAME, MQTT_SERVER_PORT);
if (ret != NSAPI_ERROR_OK) {
printf("Could not connect! Returned %d\n", ret);
return -1;
}
}
printf("Connection established.\r\n");
printf("\r\n");
// Generate username from host name and client id.
const char *username = MQTT_SERVER_HOST_NAME "/" DEVICE_ID "/api-version=2016-11-14";
/* Establish a MQTT connection. */
MQTTClient* mqttClient = new MQTTClient(socket);
printf("MQTT client is connecting to the service ...\r\n");
{
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 4; // 3 = 3.1 4 = 3.1.1
data.clientID.cstring = (char*)DEVICE_ID;
data.username.cstring = (char*)username;
data.password.cstring = (char*)MQTT_SERVER_PASSWORD;
int rc = mqttClient->connect(data);
if (rc != MQTT::SUCCESS) {
printf("ERROR: rc from MQTT connect is %d\r\n", rc);
return -1;
}
}
printf("Client connected.\r\n");
printf("\r\n");
// Network initialization done. Turn off the green LED
led_green = LED_OFF;
// Generates topic names from user's setting in MQTT_server_setting.h
//devices/{device_id}/messages/events/
const char *mqtt_topic_pub = "devices/" DEVICE_ID "/messages/events/";
const char *mqtt_topic_sub = "devices/" DEVICE_ID "/messages/devicebound/#";
/* Subscribe a topic. */
bool isSubscribed = false;
printf("Client is trying to subscribe a topic \"%s\".\r\n", mqtt_topic_sub);
{
int rc = mqttClient->subscribe(mqtt_topic_sub, MQTT::QOS0, handleMqttMessage);
if (rc != MQTT::SUCCESS) {
printf("ERROR: rc from MQTT subscribe is %d\r\n", rc);
return -1;
}
isSubscribed = true;
}
printf("Client has subscribed a topic \"%s\".\r\n", mqtt_topic_sub);
printf("\r\n");
// Enable button 1 for publishing a message.
InterruptIn btn1(BUTTON1);
btn1.rise(handleButtonRise);
printf("To send a packet, push the button 1 on your board.\r\n");
/* Main loop */
while(1) {
/* Client is disconnected. */
if(!mqttClient->isConnected()){
break;
}
/* Waits a message and handles keepalive. */
if(mqttClient->yield(100) != MQTT::SUCCESS) {
break;
}
/* Received a message. */
if(isMessageArrived) {
isMessageArrived = false;
printf("\r\nMessage arrived:\r\n%s\r\n", messageBuffer);
}
/* Button is pushed - publish a message. */
if(isPublish) {
isPublish = false;
static unsigned int id = 0;
static unsigned int count = 0;
// When sending a message, blue LED lights.
led_blue = LED_ON;
MQTT::Message message;
message.retained = false;
message.dup = false;
const size_t len = 128;
char buf[len];
snprintf(buf, len, "Message #%d from %s.", count, DEVICE_ID);
message.payload = (void*)buf;
message.qos = MQTT::QOS0;
message.id = id++;
message.payloadlen = strlen(buf);
// Publish a message.
printf("\r\nPublishing message to the topic %s:\r\n%s\r\n", mqtt_topic_pub, buf);
int rc = mqttClient->publish(mqtt_topic_pub, message);
if(rc != MQTT::SUCCESS) {
printf("ERROR: rc from MQTT publish is %d\r\n", rc);
}
printf("Message published.\r\n");
count++;
led_blue = LED_OFF;
}
}
printf("The client has disconnected.\r\n");
if(mqttClient) {
if(isSubscribed) {
mqttClient->unsubscribe(mqtt_topic_sub);
mqttClient->setMessageHandler(mqtt_topic_sub, 0);
}
if(mqttClient->isConnected())
mqttClient->disconnect();
delete mqttClient;
}
if(socket) {
socket->close();
delete socket;
}
if(network) {
network->disconnect();
// network is not created by new.
}
// Turn on the red LED when the program is done.
led_red = LED_ON;
}
/*
* Callback function called when a message arrived from server.
*/
void handleMqttMessage(MQTT::MessageData& md)
{
// Copy payload to the buffer.
MQTT::Message &message = md.message;
memcpy(messageBuffer, message.payload, message.payloadlen);
messageBuffer[message.payloadlen] = '\0';
isMessageArrived = true;
}
/*
* Callback function called when button is pushed.
*/
void handleButtonRise() {
isPublish = true;
}