-
Notifications
You must be signed in to change notification settings - Fork 253
/
mqtt-example.c
450 lines (365 loc) · 13.4 KB
/
mqtt-example.c
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
* Copyright (c) 2014-2016 Alibaba Group. All rights reserved.
* 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.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "iot_import.h"
#include "iot_export.h"
#if defined(MQTT_ID2_AUTH) && defined(TEST_ID2_DAILY)
#define PRODUCT_KEY "OvNmiEYRDSY"
#define DEVICE_NAME "sh_online_sample_mqtt"
#define DEVICE_SECRET "v9mqGzepKEphLhXmAoiaUIR2HZ7XwTky"
#elif defined(TEST_MQTT_DAILY)
#define PRODUCT_KEY "gsYfsxQJgeD"
#define DEVICE_NAME "DailyEnvDN"
#define DEVICE_SECRET "y1vzFkEgcuXnvkAfm627pwarx4HRNikX"
#elif defined(MQTT_ID2_AUTH)
#define PRODUCT_KEY "micKUvuzOps"
#define DEVICE_NAME "00AAAAAABBBBBB4B645F5800"
#define DEVICE_SECRET "v9mqGzepKEphLhXmAoiaUIR2HZ7XwTky"
#else
#define PRODUCT_KEY "yfTuLfBJTiL"
#define DEVICE_NAME "TestDeviceForDemo"
#define DEVICE_SECRET "fSCl9Ns5YPnYN8Ocg0VEel1kXFnRlV6c"
#endif
/* These are pre-defined topics */
#define TOPIC_UPDATE "/"PRODUCT_KEY"/"DEVICE_NAME"/update"
#define TOPIC_ERROR "/"PRODUCT_KEY"/"DEVICE_NAME"/update/error"
#define TOPIC_GET "/"PRODUCT_KEY"/"DEVICE_NAME"/get"
#define TOPIC_DATA "/"PRODUCT_KEY"/"DEVICE_NAME"/data"
#define MQTT_MSGLEN (1024)
#define EXAMPLE_TRACE(fmt, ...) \
do { \
HAL_Printf("%s|%03d :: ", __func__, __LINE__); \
HAL_Printf(fmt, ##__VA_ARGS__); \
HAL_Printf("%s", "\r\n"); \
} while(0)
static int user_argc;
static char **user_argv;
void event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
{
uintptr_t packet_id = (uintptr_t)msg->msg;
iotx_mqtt_topic_info_pt topic_info = (iotx_mqtt_topic_info_pt)msg->msg;
switch (msg->event_type) {
case IOTX_MQTT_EVENT_UNDEF:
EXAMPLE_TRACE("undefined event occur.");
break;
case IOTX_MQTT_EVENT_DISCONNECT:
EXAMPLE_TRACE("MQTT disconnect.");
break;
case IOTX_MQTT_EVENT_RECONNECT:
EXAMPLE_TRACE("MQTT reconnect.");
break;
case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS:
EXAMPLE_TRACE("subscribe success, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT:
EXAMPLE_TRACE("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_SUBCRIBE_NACK:
EXAMPLE_TRACE("subscribe nack, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS:
EXAMPLE_TRACE("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
EXAMPLE_TRACE("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK:
EXAMPLE_TRACE("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_PUBLISH_SUCCESS:
EXAMPLE_TRACE("publish success, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT:
EXAMPLE_TRACE("publish timeout, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_PUBLISH_NACK:
EXAMPLE_TRACE("publish nack, packet-id=%u", (unsigned int)packet_id);
break;
case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED:
EXAMPLE_TRACE("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
topic_info->topic_len,
topic_info->ptopic,
topic_info->payload_len,
topic_info->payload);
break;
case IOTX_MQTT_EVENT_BUFFER_OVERFLOW:
EXAMPLE_TRACE("buffer overflow, %s", msg->msg);
break;
default:
EXAMPLE_TRACE("Should NOT arrive here.");
break;
}
}
static void _demo_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
{
iotx_mqtt_topic_info_pt ptopic_info = (iotx_mqtt_topic_info_pt) msg->msg;
/* print topic name and topic message */
EXAMPLE_TRACE("----");
EXAMPLE_TRACE("Topic: '%.*s' (Length: %d)",
ptopic_info->topic_len,
ptopic_info->ptopic,
ptopic_info->topic_len);
EXAMPLE_TRACE("Payload: '%.*s' (Length: %d)",
ptopic_info->payload_len,
ptopic_info->payload,
ptopic_info->payload_len);
EXAMPLE_TRACE("----");
}
int mqtt_client(void)
{
int rc = 0, msg_len, cnt = 0;
void *pclient;
iotx_conn_info_pt pconn_info;
iotx_mqtt_param_t mqtt_params;
iotx_mqtt_topic_info_t topic_msg;
char msg_pub[128];
char *msg_buf = NULL, *msg_readbuf = NULL;
if (NULL == (msg_buf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
EXAMPLE_TRACE("not enough memory");
rc = -1;
goto do_exit;
}
if (NULL == (msg_readbuf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
EXAMPLE_TRACE("not enough memory");
rc = -1;
goto do_exit;
}
/* Device AUTH */
if (0 != IOT_SetupConnInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, (void **)&pconn_info)) {
EXAMPLE_TRACE("AUTH request failed!");
rc = -1;
goto do_exit;
}
/* Initialize MQTT parameter */
memset(&mqtt_params, 0x0, sizeof(mqtt_params));
mqtt_params.port = pconn_info->port;
mqtt_params.host = pconn_info->host_name;
mqtt_params.client_id = pconn_info->client_id;
mqtt_params.username = pconn_info->username;
mqtt_params.password = pconn_info->password;
mqtt_params.pub_key = pconn_info->pub_key;
mqtt_params.request_timeout_ms = 2000;
mqtt_params.clean_session = 0;
mqtt_params.keepalive_interval_ms = 60000;
mqtt_params.pread_buf = msg_readbuf;
mqtt_params.read_buf_size = MQTT_MSGLEN;
mqtt_params.pwrite_buf = msg_buf;
mqtt_params.write_buf_size = MQTT_MSGLEN;
mqtt_params.handle_event.h_fp = event_handle;
mqtt_params.handle_event.pcontext = NULL;
/* Construct a MQTT client with specify parameter */
pclient = IOT_MQTT_Construct(&mqtt_params);
if (NULL == pclient) {
EXAMPLE_TRACE("MQTT construct failed");
rc = -1;
goto do_exit;
}
/* Subscribe the specific topic */
rc = IOT_MQTT_Subscribe(pclient, TOPIC_DATA, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
if (rc < 0) {
IOT_MQTT_Destroy(&pclient);
EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
rc = -1;
goto do_exit;
}
HAL_SleepMs(1000);
/* Initialize topic information */
memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
strcpy(msg_pub, "message: hello! start!");
topic_msg.qos = IOTX_MQTT_QOS1;
topic_msg.retain = 0;
topic_msg.dup = 0;
topic_msg.payload = (void *)msg_pub;
topic_msg.payload_len = strlen(msg_pub);
rc = IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
EXAMPLE_TRACE("rc = IOT_MQTT_Publish() = %d", rc);
do {
/* Generate topic message */
cnt++;
msg_len = snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"temperature\", \"attr_value\":\"%d\"}", cnt);
if (msg_len < 0) {
EXAMPLE_TRACE("Error occur! Exit program");
rc = -1;
break;
}
topic_msg.payload = (void *)msg_pub;
topic_msg.payload_len = msg_len;
rc = IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
if (rc < 0) {
EXAMPLE_TRACE("error occur when publish");
rc = -1;
break;
}
#ifdef MQTT_ID2_CRYPTO
EXAMPLE_TRACE("packet-id=%u, publish topic msg='0x%02x%02x%02x%02x'...",
(uint32_t)rc,
msg_pub[0], msg_pub[1], msg_pub[2], msg_pub[3]
);
#else
EXAMPLE_TRACE("packet-id=%u, publish topic msg=%s", (uint32_t)rc, msg_pub);
#endif
/* handle the MQTT packet received from TCP or SSL connection */
IOT_MQTT_Yield(pclient, 200);
/* infinite loop if running with 'loop' argument */
if (user_argc >= 2 && !strcmp("loop", user_argv[1])) {
HAL_SleepMs(2000);
cnt = 0;
}
} while (cnt < 1);
IOT_MQTT_Unsubscribe(pclient, TOPIC_DATA);
HAL_SleepMs(200);
IOT_MQTT_Destroy(&pclient);
do_exit:
if (NULL != msg_buf) {
HAL_Free(msg_buf);
}
if (NULL != msg_readbuf) {
HAL_Free(msg_readbuf);
}
return rc;
}
#ifdef MQTT_ID2_AUTH
int mqtt_client_secure()
{
int rc = 0, msg_len, cnt = 0;
void *pclient;
iotx_conn_info_pt pconn_info;
iotx_mqtt_param_t mqtt_params;
iotx_mqtt_topic_info_t topic_msg;
char msg_pub[128];
char *msg_buf = NULL, *msg_readbuf = NULL;
if (NULL == (msg_buf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
EXAMPLE_TRACE("not enough memory");
rc = -1;
goto do_exit;
}
if (NULL == (msg_readbuf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
EXAMPLE_TRACE("not enough memory");
rc = -1;
goto do_exit;
}
/* Device AUTH */
rc = IOT_SetupConnInfoSecure(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, (void **)&pconn_info);
if (rc != 0) {
EXAMPLE_TRACE("AUTH request failed!");
goto do_exit;
}
/* Initialize MQTT parameter */
memset(&mqtt_params, 0x0, sizeof(mqtt_params));
mqtt_params.port = pconn_info->port;
mqtt_params.host = pconn_info->host_name;
mqtt_params.client_id = pconn_info->client_id;
mqtt_params.username = pconn_info->username;
mqtt_params.password = pconn_info->password;
mqtt_params.pub_key = pconn_info->pub_key;
mqtt_params.request_timeout_ms = 2000;
mqtt_params.clean_session = 0;
mqtt_params.keepalive_interval_ms = 60000;
mqtt_params.pread_buf = msg_readbuf;
mqtt_params.read_buf_size = MQTT_MSGLEN;
mqtt_params.pwrite_buf = msg_buf;
mqtt_params.write_buf_size = MQTT_MSGLEN;
mqtt_params.handle_event.h_fp = event_handle;
mqtt_params.handle_event.pcontext = NULL;
/* Construct a MQTT client with specify parameter */
pclient = IOT_MQTT_ConstructSecure(&mqtt_params);
if (NULL == pclient) {
EXAMPLE_TRACE("MQTT construct failed");
rc = -1;
goto do_exit;
}
/* Subscribe the specific topic */
rc = IOT_MQTT_Subscribe(pclient, TOPIC_DATA, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
if (rc < 0) {
IOT_MQTT_Destroy(&pclient);
EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
rc = -1;
goto do_exit;
}
HAL_SleepMs(1000);
/* Initialize topic information */
memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
strcpy(msg_pub, "message: hello! start!");
topic_msg.qos = IOTX_MQTT_QOS1;
topic_msg.retain = 0;
topic_msg.dup = 0;
topic_msg.payload = (void *)msg_pub;
topic_msg.payload_len = strlen(msg_pub);
rc = IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
EXAMPLE_TRACE("rc = IOT_MQTT_Publish() = %d", rc);
do {
/* Generate topic message */
cnt++;
msg_len = snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"temperature\", \"attr_value\":\"%d\"}", cnt);
if (msg_len < 0) {
EXAMPLE_TRACE("Error occur! Exit program");
rc = -1;
break;
}
topic_msg.payload = (void *)msg_pub;
topic_msg.payload_len = msg_len;
rc = IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
if (rc < 0) {
EXAMPLE_TRACE("error occur when publish");
rc = -1;
break;
}
EXAMPLE_TRACE("packet-id=%u, publish topic msg='0x%02x%02x%02x%02x'...",
(uint32_t)rc,
msg_pub[0], msg_pub[1], msg_pub[2], msg_pub[3]
);
/* handle the MQTT packet received from TCP or SSL connection */
IOT_MQTT_Yield(pclient, 200);
/* infinite loop if running with 'loop' argument */
if (user_argc >= 2 && !strcmp("loop", user_argv[1])) {
HAL_SleepMs(2000);
cnt = 0;
}
} while (cnt < 1);
IOT_MQTT_Unsubscribe(pclient, TOPIC_DATA);
HAL_SleepMs(200);
IOT_MQTT_Destroy(&pclient);
do_exit:
if (NULL != msg_buf) {
HAL_Free(msg_buf);
}
if (NULL != msg_readbuf) {
HAL_Free(msg_readbuf);
}
return rc;
}
#endif
int main(int argc, char **argv)
{
IOT_OpenLog("mqtt");
IOT_SetLogLevel(IOT_LOG_DEBUG);
user_argc = argc;
user_argv = argv;
#ifndef MQTT_ID2_AUTH
mqtt_client();
#else
mqtt_client_secure();
#endif
IOT_DumpMemoryStats(IOT_LOG_DEBUG);
IOT_CloseLog();
EXAMPLE_TRACE("out of sample!");
return 0;
}