summaryrefslogtreecommitdiff
path: root/server/main.c
diff options
context:
space:
mode:
authorJake Mannens <jakem_5@hotmail.com>2019-10-23 21:25:26 +1100
committerJake Mannens <jakem_5@hotmail.com>2019-10-23 21:25:26 +1100
commitaf2339434d35ee2a40eb99af84e8571dc59dfc62 (patch)
tree9faf31f92171145bc70d860360c36fcfd09ffd37 /server/main.c
Initial commitHEADmaster
Diffstat (limited to 'server/main.c')
-rw-r--r--server/main.c103
1 files changed, 103 insertions, 0 deletions
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 <arpa/inet.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#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 <serial port>\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;
+}