diff options
Diffstat (limited to 'src/mqtt.c')
| -rw-r--r-- | src/mqtt.c | 69 |
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 | |||
| 11 | struct mosquitto * | ||
| 12 | connect(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 | |||
| 45 | void | ||
| 46 | run(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 | |||
| 64 | void | ||
| 65 | shutdown(struct mosquitto *client) | ||
| 66 | { | ||
| 67 | mosquitto_disconnect(client); | ||
| 68 | mosquitto_destroy(client); | ||
| 69 | } | ||
