#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "templates/bio_sockets.h"
void* client_refresher(void* client);
void exit_example(int status, BIO* sockfd, pthread_t *client_daemon);
int main(int argc, const char *argv[])
{
const char* addr;
const char* port;
const char* topic;
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
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";
}
BIO* sockfd = open_nb_socket(addr, port);
if (sockfd == NULL) {
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,
"publishing_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 is ready to begin publishing the time.\n", argv[0]);
printf("Press ENTER to publish the current time.\n");
printf("Press CTRL-D (or any other key) to exit.\n\n");
while(fgetc(stdin) == '\n') {
time_t timer;
time(&timer);
struct tm* tm_info = localtime(&timer);
char timebuf[26];
strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tm_info);
char application_message[256];
snprintf(application_message, sizeof(application_message), "The time is %s", timebuf);
printf("%s published : \"%s\"", argv[0], application_message);
mqtt_publish(&client, topic, application_message, strlen(application_message) + 1, MQTT_PUBLISH_QOS_2);
if (client.error != MQTT_OK) {
exit_example(EXIT_FAILURE, sockfd, &client_daemon);
}
}
printf("\n%s disconnecting from %s\n", argv[0], addr);
sleep(1);
exit_example(EXIT_SUCCESS, sockfd, &client_daemon);
}
void exit_example(int status, BIO* sockfd, pthread_t *client_daemon)
{
if (sockfd != NULL) BIO_free_all(sockfd);
if (client_daemon != NULL) pthread_cancel(*client_daemon);
exit(status);
}
{
}
void* client_refresher(void* client)
{
while(1)
{
usleep(100000U);
}
return NULL;
}