summaryrefslogtreecommitdiff
path: root/src/publish.c
blob: 28a9c3a812a47d0082c5cbc4361d8092a2a86154 (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
99
100
101
102
103
104
105
106
107
// Standard C
#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"

#ifndef MAX_COMMAND_LENGTH
#	define MAX_COMMAND_LENGTH 100
#endif

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

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

static void
application_init(void)
{
	mosquitto_lib_init();
	(void) atexit(application_cleanup);
}

static void
application_run(struct mosquitto *client)
{
	char command[MAX_COMMAND_LENGTH];

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

		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);
		}
	}
}

int
main(void)
{
	application_init();

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

	if ( !client ) {
		return EXIT_FAILURE;
	}

	application_run(client);

	mqtt_shutdown(client);

	return EXIT_SUCCESS;
}