diff options
Diffstat (limited to 'mfi-mqtt/mosquitto.c')
-rw-r--r-- | mfi-mqtt/mosquitto.c | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/mfi-mqtt/mosquitto.c b/mfi-mqtt/mosquitto.c new file mode 100644 index 0000000..1f1a64e --- /dev/null +++ b/mfi-mqtt/mosquitto.c | |||
@@ -0,0 +1,82 @@ | |||
1 | #include <stdio.h> | ||
2 | #include <errno.h> | ||
3 | #include <stdlib.h> | ||
4 | #include <string.h> | ||
5 | #include <unistd.h> | ||
6 | |||
7 | #include "mosquitto.h" | ||
8 | |||
9 | int client_id_generate(char **output) | ||
10 | { | ||
11 | int len; | ||
12 | char hostname[256]; | ||
13 | |||
14 | *output = calloc(sizeof(char), MOSQ_MQTT_ID_MAX_LENGTH); | ||
15 | if (!*output) { | ||
16 | fprintf(stderr, "Error: Out of memory. %s\n", strerror(errno)); | ||
17 | mosquitto_lib_cleanup(); | ||
18 | return 1; | ||
19 | } | ||
20 | |||
21 | memset(hostname, 0, sizeof(hostname)); | ||
22 | gethostname(hostname, 255); | ||
23 | |||
24 | /* Clamp length to MQTT maximum client ID length */ | ||
25 | len = strlen("mfi|-") + 6 + strlen(hostname); | ||
26 | if (len > MOSQ_MQTT_ID_MAX_LENGTH - 1) { | ||
27 | len = MOSQ_MQTT_ID_MAX_LENGTH - 1; | ||
28 | } | ||
29 | |||
30 | snprintf(*output, len, "mfi|%d-%s", getpid(), hostname); | ||
31 | |||
32 | return MOSQ_ERR_SUCCESS; | ||
33 | } | ||
34 | |||
35 | struct mosquitto * connect_to_broker(char *host, int port) { | ||
36 | int rc; | ||
37 | char *id; | ||
38 | struct mosquitto *mosq; | ||
39 | |||
40 | mosquitto_lib_init(); | ||
41 | |||
42 | if (client_id_generate(&id)) { | ||
43 | return NULL; | ||
44 | } | ||
45 | |||
46 | mosq = mosquitto_new(id, true, NULL); | ||
47 | if (!mosq) { | ||
48 | switch (errno) { | ||
49 | case ENOMEM: | ||
50 | fprintf(stderr, "Error: Out of memory.\n"); | ||
51 | break; | ||
52 | case EINVAL: | ||
53 | fprintf(stderr, "Error: Invalid id and/or clean_session.\n"); | ||
54 | break; | ||
55 | } | ||
56 | mosquitto_lib_cleanup(); | ||
57 | return NULL; | ||
58 | } | ||
59 | |||
60 | int protocol_version = MQTT_PROTOCOL_V311; | ||
61 | |||
62 | mosquitto_max_inflight_messages_set(mosq, 20); | ||
63 | mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &protocol_version); | ||
64 | |||
65 | rc = mosquitto_connect(mosq, host, port, 60); | ||
66 | if (rc > 0) { | ||
67 | if (rc == MOSQ_ERR_ERRNO) { | ||
68 | fprintf(stderr, "Error: %s\n", strerror(errno)); | ||
69 | } else { | ||
70 | fprintf(stderr, "Unable to connect (%s).\n", mosquitto_strerror(rc)); | ||
71 | } | ||
72 | mosquitto_lib_cleanup(); | ||
73 | return NULL; | ||
74 | } | ||
75 | |||
76 | return mosq; | ||
77 | } | ||
78 | |||
79 | void shutdown_broker(struct mosquitto *mosq) { | ||
80 | mosquitto_destroy(mosq); | ||
81 | mosquitto_lib_cleanup(); | ||
82 | } | ||