// Standard C #include #include #include #include // System #include // Project #include #include "config.h" #ifndef UNUSED # define UNUSED(x) (void) (x) #endif static volatile bool terminate = false; // NOLINT static void handler(int signal) { if ( signal == SIGINT ) { terminate = true; } } static void cleanup(void) { mosquitto_lib_cleanup(); } static void init(void) { (void) signal(SIGINT, handler); mosquitto_lib_init(); (void) atexit(cleanup); } static struct mosquitto * connect(const char *clientid, // NOLINT const char *username, // NOLINT const char *password, // NOLINT const char *hostname, // NOLINT int port, void callback(struct mosquitto *, void *, const struct mosquitto_message *), void *userdata) { struct mosquitto *client = mosquitto_new(clientid, true, userdata); if ( client == NULL ) { (void) fprintf(stderr, "error on new client...\n"); return NULL; } int err = mosquitto_username_pw_set(client, username, password); if ( err != MOSQ_ERR_SUCCESS ) { (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err)); mosquitto_destroy(client); return NULL; } mosquitto_message_callback_set(client, callback); err = mosquitto_connect(client, hostname, port, KEEPALIVE); if ( err != MOSQ_ERR_SUCCESS ) { (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err)); mosquitto_destroy(client); return NULL; } return client; } static void run(struct mosquitto *client, const char *topic) { mosquitto_subscribe(client, NULL, topic, 0); while ( !terminate ) { static const int defaultTimeout = -1; // 1000ms int err = mosquitto_loop(client, defaultTimeout, 1); if ( !terminate && err ) { (void) fprintf(stderr, "connection error: %s\n", mosquitto_strerror(err)); sleep(WAIT_UNTIL_RECONNECT); // NOLINT mosquitto_reconnect(client); } } } static void shutdown(struct mosquitto *client) { mosquitto_disconnect(client); mosquitto_destroy(client); } static void callback(struct mosquitto *client, void *userdata, const struct mosquitto_message *message) { UNUSED(client); UNUSED(userdata); printf("message '%.*s' for topic '%s'\n", message->payloadlen, (const char *) message->payload, message->topic); } int main(void) { init(); struct mosquitto *client = connect( CLIENT_ID, USERNAME, PASSWORD, HOST, PORT, callback, NULL); if ( !client ) { return EXIT_FAILURE; } run(client, TOPIC); shutdown(client); return EXIT_SUCCESS; }