From 5bd0a0cd5e6951723398aadc601f1fcc2a6187b8 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Fri, 25 Oct 2024 17:12:34 +0200 Subject: Teile den Code in einzelne Funktionen auf --- src/main.c | 59 ++++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 42 insertions(+), 17 deletions(-) diff --git a/src/main.c b/src/main.c index 9e806fe..9f76ab2 100644 --- a/src/main.c +++ b/src/main.c @@ -33,41 +33,45 @@ handler(int signal) } } -static void -message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) -{ - UNUSED(obj); - UNUSED(mosq); - printf("message '%.*s' for topic '%s'\n", - message->payloadlen, (const char *) message->payload, - message->topic); -} - static void cleanup(void) { mosquitto_lib_cleanup(); } -int -main(void) +static void +init(void) { (void) signal(SIGINT, handler); mosquitto_lib_init(); (void) atexit(cleanup); +} +static void +message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) +{ + UNUSED(obj); + UNUSED(mosq); + printf("message '%.*s' for topic '%s'\n", + message->payloadlen, (const char *) message->payload, + message->topic); +} + +static struct mosquitto * +setup(void) +{ struct mosquitto *client = mosquitto_new(CLIENT_ID, true, NULL); if ( client == NULL ) { (void) fprintf(stderr, "error on new client...\n"); - return EXIT_FAILURE; + 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 EXIT_FAILURE; + return NULL; } mosquitto_message_callback_set(client, message_callback); @@ -76,25 +80,46 @@ main(void) if ( err != MOSQ_ERR_SUCCESS ) { (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err)); mosquitto_destroy(client); - return EXIT_FAILURE; + return NULL; } + return client; +} + +static void +run(struct mosquitto *client) +{ mosquitto_subscribe(client, NULL, TOPIC, 0); while ( !terminate ) { static const int defaultTimeout = -1; // 1000ms - err = mosquitto_loop(client, defaultTimeout, 1); + 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); } } +} - puts("shutdown..."); +static void +shutdown(struct mosquitto *client) +{ mosquitto_disconnect(client); mosquitto_destroy(client); +} + +int +main(void) +{ + init(); + + struct mosquitto *client = setup(); + if ( client ) { + run(client); + shutdown(client); + } return EXIT_SUCCESS; } -- cgit v1.3