A simple program that subscribes to a single topic and prints all updates that are received.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "templates/posix_sockets.h"
void* client_refresher(void* client);
void exit_example(int status, int sockfd, pthread_t *client_daemon);
int main(int argc, const char *argv[])
{
const char* addr;
const char* port;
const char* topic;
if (argc > 1) {
addr = argv[1];
} else {
addr = "test.mosquitto.org";
}
if (argc > 2) {
port = argv[2];
} else {
port = "1883";
}
if (argc > 3) {
topic = argv[3];
} else {
topic = "datetime";
}
int sockfd = open_nb_socket(addr, port);
if (sockfd == -1) {
perror("Failed to open socket: ");
exit_example(EXIT_FAILURE, sockfd, NULL);
}
uint8_t sendbuf[2048];
uint8_t recvbuf[1024];
mqtt_init(&client, sockfd, sendbuf,
sizeof(sendbuf), recvbuf,
sizeof(recvbuf), publish_callback);
mqtt_connect(&client,
"subscribing_client", NULL, NULL, 0, NULL, NULL, 0, 400);
if (client.error != MQTT_OK) {
exit_example(EXIT_FAILURE, sockfd, NULL);
}
pthread_t client_daemon;
if(pthread_create(&client_daemon, NULL, client_refresher, &client)) {
fprintf(stderr, "Failed to start client daemon.\n");
exit_example(EXIT_FAILURE, sockfd, NULL);
}
printf("%s listening for '%s' messages.\n", argv[0], topic);
printf("Press CTRL-D to exit.\n\n");
while(fgetc(stdin) != EOF);
printf("\n%s disconnecting from %s\n", argv[0], addr);
sleep(1);
exit_example(EXIT_SUCCESS, sockfd, &client_daemon);
}
void exit_example(int status, int sockfd, pthread_t *client_daemon)
{
if (sockfd != -1) close(sockfd);
if (client_daemon != NULL) pthread_cancel(*client_daemon);
exit(status);
}
{
printf(
"Received publish('%s'): %s\n", topic_name, (
const char*) published->
application_message);
free(topic_name);
}
void* client_refresher(void* client)
{
while(1)
{
usleep(100000U);
}
return NULL;
}