/
mqtt_client.c
373 lines (319 loc) · 9.1 KB
/
mqtt_client.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
// Author: eeff <eeff at eeff dot dev>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
//
// This is just a simple MQTT client demonstration application.
//
// The application has two sub-commands: `pub` and `sub`. The `pub`
// sub-command publishes a given message to the server and then exits.
// The `sub` sub-command subscribes to the given topic filter and blocks
// waiting for incoming messages.
//
// # Example:
//
// Publish 'hello' to `topic` with QoS `0`:
// ```
// $ ./mqtt_client pub mqtt-tcp://127.0.0.1:1883 0 topic hello
// ```
//
// Subscribe to `topic` with QoS `0` and waiting for messages:
// ```
// $ ./mqtt_client sub mqtt-tcp://127.0.0.1:1883 0 topic
// ```
//
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include "nng/mqtt/mqtt_client.h"
#include "nng/nng.h"
#include "nng/supplemental/util/platform.h"
// Subcommands
#define PUBLISH "pub"
#define SUBSCRIBE "sub"
void
fatal(const char *msg, int rv)
{
fprintf(stderr, "%s: %s\n", msg, nng_strerror(rv));
}
int keepRunning = 1;
void
intHandler(int dummy)
{
keepRunning = 0;
fprintf(stderr, "\nclient exit(0).\n");
// nng_closeall();
exit(0);
}
// Print the given string limited to 80 columns.
//
// The `prefix` should be a null terminated string much smaller than 80,
// `str` and `len` designates the string to be printed, `quote` specifies
// whether to print in single quotes.
void
print80(const char *prefix, const char *str, size_t len, bool quote)
{
size_t max_len = 80 - strlen(prefix) - (quote ? 2 : 0);
char * q = quote ? "'" : "";
if (len <= max_len) {
// case the output fit in a line
printf("%s%s%.*s%s\n", prefix, q, (int) len, str, q);
} else {
// case we truncate the payload with ellipses
printf(
"%s%s%.*s%s...\n", prefix, q, (int) (max_len - 3), str, q);
}
}
static void
disconnect_cb(nng_pipe p, nng_pipe_ev ev, void *arg)
{
int reason = 0;
// get connect reason
nng_pipe_get_int(p, NNG_OPT_MQTT_DISCONNECT_REASON, &reason);
// property *prop;
// nng_pipe_get_ptr(p, NNG_OPT_MQTT_DISCONNECT_PROPERTY, &prop);
// nng_socket_get?
printf("%s: disconnected!\n", __FUNCTION__);
}
static void
connect_cb(nng_pipe p, nng_pipe_ev ev, void *arg)
{
int reason;
// get connect reason
nng_pipe_get_int(p, NNG_OPT_MQTT_CONNECT_REASON, &reason);
// get property for MQTT V5
// property *prop;
// nng_pipe_get_ptr(p, NNG_OPT_MQTT_CONNECT_PROPERTY, &prop);
printf("%s: connected!\n", __FUNCTION__);
}
// Connect to the given address.
int
client_connect(
nng_socket *sock, nng_dialer *dialer, const char *url, bool verbose)
{
int rv;
if ((rv = nng_mqtt_client_open(sock)) != 0) {
fatal("nng_socket", rv);
}
if ((rv = nng_dialer_create(dialer, *sock, url)) != 0) {
fatal("nng_dialer_create", rv);
}
// create a CONNECT message
/* CONNECT */
nng_msg *connmsg;
nng_mqtt_msg_alloc(&connmsg, 0);
nng_mqtt_msg_set_packet_type(connmsg, NNG_MQTT_CONNECT);
nng_mqtt_msg_set_connect_proto_version(connmsg, 4);
nng_mqtt_msg_set_connect_keep_alive(connmsg, 60);
nng_mqtt_msg_set_connect_user_name(connmsg, "nng_mqtt_client");
nng_mqtt_msg_set_connect_password(connmsg, "secrets");
nng_mqtt_msg_set_connect_will_msg(
connmsg, (uint8_t *) "bye-bye", strlen("bye-bye"));
nng_mqtt_msg_set_connect_will_topic(connmsg, "will_topic");
nng_mqtt_msg_set_connect_clean_session(connmsg, true);
nng_mqtt_set_connect_cb(*sock, connect_cb, sock);
nng_mqtt_set_disconnect_cb(*sock, disconnect_cb, connmsg);
uint8_t buff[1024] = { 0 };
if (verbose) {
nng_mqtt_msg_dump(connmsg, buff, sizeof(buff), true);
printf("%s\n", buff);
}
printf("Connecting to server ...\n");
nng_dialer_set_ptr(*dialer, NNG_OPT_MQTT_CONNMSG, connmsg);
nng_dialer_start(*dialer, NNG_FLAG_NONBLOCK);
return (0);
}
// Publish a message to the given topic and with the given QoS.
int
client_publish(nng_socket sock, const char *topic, uint8_t *payload,
uint32_t payload_len, uint8_t qos, bool verbose)
{
int rv;
// create a PUBLISH message
nng_msg *pubmsg;
nng_mqtt_msg_alloc(&pubmsg, 0);
nng_mqtt_msg_set_packet_type(pubmsg, NNG_MQTT_PUBLISH);
nng_mqtt_msg_set_publish_dup(pubmsg, 0);
nng_mqtt_msg_set_publish_qos(pubmsg, qos);
nng_mqtt_msg_set_publish_retain(pubmsg, 0);
nng_mqtt_msg_set_publish_payload(
pubmsg, (uint8_t *) payload, payload_len);
nng_mqtt_msg_set_publish_topic(pubmsg, topic);
if (verbose) {
uint8_t print[1024] = { 0 };
nng_mqtt_msg_dump(pubmsg, print, 1024, true);
printf("%s\n", print);
}
printf("Publishing to '%s' ...\n", topic);
if ((rv = nng_sendmsg(sock, pubmsg, NNG_FLAG_NONBLOCK)) != 0) {
fatal("nng_sendmsg", rv);
}
return rv;
}
struct pub_params {
nng_socket *sock;
const char *topic;
uint8_t * data;
uint32_t data_len;
uint8_t qos;
bool verbose;
uint32_t interval;
};
void
publish_cb(void *args)
{
int rv;
struct pub_params *params = args;
do {
client_publish(*params->sock, params->topic, params->data,
params->data_len, params->qos, params->verbose);
nng_msleep(params->interval);
} while (params->interval > 0);
printf("thread_exit\n");
}
struct pub_params params;
static void
send_callback (nng_mqtt_client *client, nng_msg *msg, void *arg) {
nng_aio * aio = client->send_aio;
uint32_t count;
uint8_t * code;
uint8_t type;
if (msg == NULL)
return;
switch (nng_mqtt_msg_get_packet_type(msg)) {
case NNG_MQTT_SUBACK:
code = (reason_code *) nng_mqtt_msg_get_suback_return_codes(
msg, &count);
printf("SUBACK reason codes are");
for (int i = 0; i < count; ++i)
printf("%d ", code[i]);
printf("\n");
break;
case NNG_MQTT_UNSUBACK:
code = (reason_code *) nng_mqtt_msg_get_unsuback_return_codes(
msg, &count);
printf("UNSUBACK reason codes are");
for (int i = 0; i < count; ++i)
printf("%d ", code[i]);
printf("\n");
break;
case NNG_MQTT_PUBACK:
printf("PUBACK");
break;
default:
printf("Sending in async way is done.\n");
break;
}
printf("aio mqtt result %d \n", nng_aio_result(aio));
// printf("suback %d \n", *code);
nng_msg_free(msg);
}
int
main(const int argc, const char **argv)
{
nng_socket sock;
nng_dialer dailer;
const char *exe = argv[0];
const char *cmd;
if (5 == argc && 0 == strcmp(argv[1], SUBSCRIBE)) {
cmd = SUBSCRIBE;
} else if (6 <= argc && 0 == strcmp(argv[1], PUBLISH)) {
cmd = PUBLISH;
} else {
goto error;
}
const char *url = argv[2];
uint8_t qos = atoi(argv[3]);
const char *topic = argv[4];
int rv = 0;
char * verbose_env = getenv("VERBOSE");
bool verbose = verbose_env && strlen(verbose_env) > 0;
client_connect(&sock, &dailer, url, verbose);
signal(SIGINT, intHandler);
if (strcmp(PUBLISH, cmd) == 0) {
const char *data = argv[5];
uint32_t interval = 0;
uint32_t nthread = 1;
if (argc >= 7) {
interval = atoi(argv[6]);
}
if (argc >= 8) {
nthread = atoi(argv[7]);
}
nng_thread *threads[nthread];
params.sock = &sock, params.topic = topic;
params.data = (uint8_t *) data;
params.data_len = strlen(data);
params.qos = qos;
params.interval = interval;
params.verbose = verbose;
char thread_name[20];
size_t i = 0;
for (i = 0; i < nthread; i++) {
nng_thread_create(&threads[i], publish_cb, ¶ms);
}
for (i = 0; i < nthread; i++) {
nng_thread_destroy(threads[i]);
}
} else if (strcmp(SUBSCRIBE, cmd) == 0) {
nng_mqtt_topic_qos subscriptions[] = {
{
.qos = qos,
.topic = {
.buf = (uint8_t *) topic,
.length = strlen(topic),
},
},
};
nng_mqtt_topic unsubscriptions[] = {
{
.buf = (uint8_t *) topic,
.length = strlen(topic),
},
};
// Sync subscription
// rv = nng_mqtt_subscribe(&sock, subscriptions, 1, NULL);
// Asynchronous subscription
nng_mqtt_client *client = nng_mqtt_client_alloc(sock, &send_callback, true);
nng_mqtt_subscribe_async(client, subscriptions, 1, NULL);
uint8_t buff[1024] = { 0 };
printf("Start receiving loop:\n");
while (true) {
nng_msg *msg;
uint8_t *payload;
uint32_t payload_len;
if ((rv = nng_recvmsg(sock, &msg, 0)) != 0) {
fatal("nng_recvmsg", rv);
continue;
}
// we should only receive publish messages
assert(nng_mqtt_msg_get_packet_type(msg) == NNG_MQTT_PUBLISH);
payload = nng_mqtt_msg_get_publish_payload(msg, &payload_len);
print80("Received: ", (char *) payload, payload_len, true);
if (verbose) {
memset(buff, 0, sizeof(buff));
nng_mqtt_msg_dump(msg, buff, sizeof(buff), true);
printf("%s\n", buff);
}
nng_msg_free(msg);
// break;
}
nng_mqtt_unsubscribe_async(client, unsubscriptions, 1, NULL);
}
nng_msleep(1000);
// nng_mqtt_disconnect(&sock, 5, NULL);
return 0;
error:
fprintf(stderr,
"Usage: %s %s <URL> <QOS> <TOPIC> <data> <interval> <parallel>\n"
" %s %s <URL> <QOS> <TOPIC>\n",
exe, PUBLISH, exe, SUBSCRIBE);
return 1;
}