summaryrefslogtreecommitdiff
path: root/src/mqtt.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-10-29 22:34:23 +0100
committerThomas Schmucker <ts@its1.de>2024-10-29 22:34:23 +0100
commit868d0a1ecbfbcd1f04b5c03403d6cffb439ce8fe (patch)
treee992bb530f623e53df9fe15ef1cdbdfc3128092a /src/mqtt.c
parent0714998ef54e8c1a46af7ec48698faa3abdf457a (diff)
downloaduse-mosquitto-868d0a1ecbfbcd1f04b5c03403d6cffb439ce8fe.tar.gz
use-mosquitto-868d0a1ecbfbcd1f04b5c03403d6cffb439ce8fe.tar.bz2
use-mosquitto-868d0a1ecbfbcd1f04b5c03403d6cffb439ce8fe.zip
Verschiebe MQTT Code in ein eigenes Modul
Diffstat (limited to 'src/mqtt.c')
-rw-r--r--src/mqtt.c69
1 files changed, 69 insertions, 0 deletions
diff --git a/src/mqtt.c b/src/mqtt.c
new file mode 100644
index 0000000..50cfa6a
--- /dev/null
+++ b/src/mqtt.c
@@ -0,0 +1,69 @@
1// Standard C
2#include <stdio.h>
3
4// System
5#include <unistd.h>
6
7// Project
8#include "config.h"
9#include "mqtt.h"
10
11struct mosquitto *
12connect(const char *clientid, // NOLINT
13 const char *username, // NOLINT
14 const char *password, // NOLINT
15 const char *hostname, // NOLINT
16 int port,
17 void callback(struct mosquitto *, void *, const struct mosquitto_message *),
18 void *userdata)
19{
20 struct mosquitto *client = mosquitto_new(clientid, true, userdata);
21 if ( client == NULL ) {
22 (void) fprintf(stderr, "error on new client...\n");
23 return NULL;
24 }
25
26 int err = mosquitto_username_pw_set(client, username, password);
27 if ( err != MOSQ_ERR_SUCCESS ) {
28 (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err));
29 mosquitto_destroy(client);
30 return NULL;
31 }
32
33 mosquitto_message_callback_set(client, callback);
34
35 err = mosquitto_connect(client, hostname, port, KEEPALIVE);
36 if ( err != MOSQ_ERR_SUCCESS ) {
37 (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err));
38 mosquitto_destroy(client);
39 return NULL;
40 }
41
42 return client;
43}
44
45void
46run(struct mosquitto *client, const char *topics[], const volatile bool *quit)
47{
48 for ( size_t idx = 0; topics[idx] != NULL; ++idx ) {
49 mosquitto_subscribe(client, NULL, topics[idx], 0);
50 }
51
52 while ( !*quit ) {
53 static const int defaultTimeout = -1; // 1000ms
54
55 int err = mosquitto_loop(client, defaultTimeout, 1);
56 if ( !*quit && err ) {
57 (void) fprintf(stderr, "connection error: %s\n", mosquitto_strerror(err));
58 sleep(WAIT_UNTIL_RECONNECT); // NOLINT
59 mosquitto_reconnect(client);
60 }
61 }
62}
63
64void
65shutdown(struct mosquitto *client)
66{
67 mosquitto_disconnect(client);
68 mosquitto_destroy(client);
69}