summaryrefslogtreecommitdiff
path: root/src/publish.c
blob: cc19502d65089aabe49b43d8c0beab7d22be9e61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Standard C
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// System
#include <unistd.h>

// Mosquitto
#include <mosquitto.h>

// Project
#include "config.h"
#include "mqtt.h"

static bool
streq(const char *lhs, const char *rhs)
{
	return strcmp(lhs, rhs) == 0;
}

static void
cleanup_app(void)
{
	mosquitto_lib_cleanup();
}

static void
init_app(void)
{
	mosquitto_lib_init();
	(void) atexit(cleanup_app);
}

int
main(void)
{
	init_app();

	struct mosquitto *client = mqtt_connect(
	    NULL,
	    USERNAME,
	    PASSWORD,
	    HOSTNAME,
	    PORT,
	    NULL);

	if ( !client ) {
		return EXIT_FAILURE;
	}

	// logic
	for ( bool quit = false; !quit; ) {
		printf("> ");

		char command[100] = { 0 }; // NOLINT
		if ( fgets(command, sizeof command, stdin) == NULL ) {
			quit = true;
			continue;
		}

		// remove 'newline' symbol at the end
		command[strcspn(command, "\n")] = '\0';

		if ( streq(command, "") ) {
			; // do nothing
		}
		else if ( streq(command, "quit") ) {
			quit = true;
		}
		else if ( streq(command, "send") ) {
			static const char payload[] = "ich bin ein payload";
			static const char topic[] = "testtopic";

			int err = mosquitto_publish(
			    client,
			    NULL,
			    topic,
			    sizeof payload,
			    payload,
			    0,
			    false);

			if ( err ) {
				(void) fprintf(stderr, "error on send: %s\n", mosquitto_strerror(err));
			}
		}
		else {
			(void) fprintf(stderr, "unknown command: '%s'\n", command);
		}
	}

	mqtt_shutdown(client);

	return EXIT_SUCCESS;
}