From d2a6897f05a07a058b2185c953b30d26fded081b Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Sun, 6 Oct 2024 12:58:03 +0200 Subject: erster Import --- src/main.c | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/main.c (limited to 'src') diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..9579568 --- /dev/null +++ b/src/main.c @@ -0,0 +1,89 @@ +// Standard C +#include +#include +#include +#include + +// System +#include + +// Project +#include + +#define CLIENT_ID "my-client-id" +#define HOST "192.168.77.2" +#define PORT 1883 +#define USERNAME "zigbee2mqtt" +#define PASSWORD "xoorei2uk2booSudies4Numoek1uot" +#define TOPIC "zigbee2mqtt/Kontaktsensor" +#define KEEPALIVE 10 +#define WAIT_UNTIL_RECONNECT 10 + +static volatile bool terminate = false; // NOLINT + +void +handler(int signal) +{ + if ( signal == SIGINT ) { + terminate = true; + } +} + +static void +message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) +{ + (void) obj; + (void) mosq; + printf("message '%.*s' for topic '%s'\n", + message->payloadlen, (const char *) message->payload, + message->topic); +} + +int +main(void) +{ + (void) signal(SIGINT, handler); + + mosquitto_lib_init(); + + struct mosquitto *client = mosquitto_new(CLIENT_ID, true, NULL); + if ( client == NULL ) { + (void) fprintf(stderr, "error on new client...\n"); + return EXIT_FAILURE; + } + + 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; + } + + mosquitto_message_callback_set(client, message_callback); + + err = mosquitto_connect(client, HOST, PORT, KEEPALIVE); + if ( err != MOSQ_ERR_SUCCESS ) { + (void) fprintf(stderr, "error: %s\n", mosquitto_strerror(err)); + mosquitto_destroy(client); + return EXIT_FAILURE; + } + + mosquitto_subscribe(client, NULL, TOPIC, 0); + + while ( !terminate ) { + err = mosquitto_loop(client, -1, 1); + if ( !terminate && err ) { + (void) fprintf(stderr, "connection error: %s\n", mosquitto_strerror(err)); + sleep(WAIT_UNTIL_RECONNECT); // NOLINT + mosquitto_reconnect(client); + } + } + + printf("cleanup...\n"); + mosquitto_disconnect(client); + mosquitto_destroy(client); + + mosquitto_lib_cleanup(); + + return EXIT_SUCCESS; +} -- cgit v1.3