-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.c
89 lines (73 loc) · 1.74 KB
/
main.c
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
/*
* fhz2mqtt, a FHZ to MQTT bridge
*
* Copyright (c) Ralf Ramsauer, 2018
*
* Authors:
* Ralf Ramsauer <ralf@ramses-pyramidenbau.de>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*/
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "fhz.h"
#include "mqtt.h"
#define MQTT_DEFAULT_PORT 1883
#define MQTT_DEFAULT_HOSTNAME "localhost"
static void __attribute__((noreturn)) usage(int code)
{
printf("Usage: fht2mqtt usb_port"
"[mqtt_server] [mqtt_port] [username] [password]\n");
exit(code);
}
int main(int argc, const char **argv)
{
const char *username = NULL, *password = NULL;
const char *hostname = MQTT_DEFAULT_HOSTNAME;
unsigned int port = MQTT_DEFAULT_PORT;
struct mosquitto *mosquitto;
struct fhz_message message;
int err, fd;
if (argc < 4 && argc != 2)
usage(-EINVAL);
if (argc >= 3)
hostname = argv[2];
if (argc >= 4)
port = strtoul(argv[3], NULL, 10);
if (argc == 6) {
username = argv[4];
password = argv[5];
}
fd = fhz_open_serial(argv[1]);
if (fd < 0)
return fd;
err = mqtt_init(&mosquitto, fd, hostname, port, username, password);
if (err) {
fprintf(stderr, "MQTT connection failure\n");
goto close_out;
}
do {
err = fhz_handle(fd, &message);
if (err && err != -EAGAIN)
error("Error decoding packet: %s\n", strerror(-err));
else if (!err) {
err = mqtt_publish(mosquitto, &message);
if (err)
fprintf(stderr, "mqtt: unable to publish FHZ "
"message\n");
}
err = mqtt_handle(mosquitto);
if (err)
error("MQTT error: %s\n", strerror(-err));
sleep(1);
} while(true);
err = 0;
mqtt_close(mosquitto);
close_out:
close(fd);
return err;
}