From af2339434d35ee2a40eb99af84e8571dc59dfc62 Mon Sep 17 00:00:00 2001 From: Jake Mannens Date: Wed, 23 Oct 2019 21:25:26 +1100 Subject: Initial commit --- server/Makefile | 23 +++++++++++++ server/main.c | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 server/Makefile create mode 100644 server/main.c (limited to 'server') diff --git a/server/Makefile b/server/Makefile new file mode 100644 index 0000000..f2b6ca3 --- /dev/null +++ b/server/Makefile @@ -0,0 +1,23 @@ +TARGET = $(shell basename $(CURDIR)) + +SRCS = $(wildcard *.c) +OBJS = $(SRCS:.c=.o) + +CC = gcc + +all: build + +build: $(TARGET) + +clean: + rm -f $(OBJS) + rm -f $(TARGET) + +run: $(TARGET) + $(realpath $(TARGET)) + +$(TARGET): $(OBJS) + $(CC) -o $(TARGET) $(OBJS) + +.c.o: + $(CC) -c -o $*.o $^ diff --git a/server/main.c b/server/main.c new file mode 100644 index 0000000..e37c33e --- /dev/null +++ b/server/main.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define PORT 2319 + +static int ifd; + +static void log_data(char *name, char *value) { + char buf[512]; + struct sockaddr_in addr; + struct timeval tv; + + addr.sin_family = AF_INET; + addr.sin_port = htons(8089); + inet_aton("10.51.0.15", &addr.sin_addr); + + gettimeofday(&tv, NULL); + + snprintf(buf, sizeof(buf), "%s %s %ld\n", name, value, (tv.tv_sec * 1000000000) + (tv.tv_usec * 1000)); + printf(buf); + + sendto(ifd, buf, strlen(buf), 0, (struct sockaddr*) &addr, sizeof(addr)); +} + +int main(int argc, char **argv) { + int ret; + char c = 'L', last = 'L'; + ssize_t in; + + int fd; + int sfd; + + int be = 1; + char buf[256]; + + struct sockaddr_in addr; + + if(argc < 2) { + printf("Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + fd = open(argv[1], O_RDONLY); + if(fd < 0) { + perror("Failed to open serial port"); + exit(EXIT_FAILURE); + } + + sfd = socket(AF_INET, SOCK_DGRAM, 0); + if(sfd < 0) { + perror("Failed to open socket"); + exit(EXIT_FAILURE); + } + + setsockopt(sfd, SOL_SOCKET, SO_BROADCAST, &be, sizeof(be)); + if(ret < 0) { + perror("Failed to enable broadcasts on socket"); + exit(EXIT_FAILURE); + } + + ifd = socket(AF_INET, SOCK_DGRAM, 0); + if(sfd < 0) { + perror("Failed to open InfluxDB socket"); + exit(EXIT_FAILURE); + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(PORT); + addr.sin_addr.s_addr = htonl(INADDR_BROADCAST); + + for(;;) { + in = read(fd, &c, 1); + if(in < 0) { + perror("Failed to read from serial port"); + exit(EXIT_FAILURE); + } + + if(c != 'H' && c != 'L') + continue; + + snprintf(buf, sizeof(buf), "%c->%c", last, c); + puts(buf); + sendto(sfd, buf, strlen(buf), 0, (struct sockaddr*) &addr, sizeof(addr)); + + if(c != last) { + if(last == 'L' && c == 'H') + log_data("bedroom_door", "open=true"); + + if(last == 'H' && c == 'L') + log_data("bedroom_door", "open=false"); + } + + last = c; + } + + return 0; +} -- cgit v1.3