Zachary Kotlarek 14 лет назад
Родитель
Сommit
2758f17051
1 измененных файлов с 51 добавлено и 12 удалено
  1. 51 12
      motion/main.c

+ 51 - 12
motion/main.c

@@ -1,19 +1,59 @@
 #include "USBMicroX.h"
 #include <fcntl.h>
+#include <sys/stat.h>
 
+#define DATA_DIR "plexMonitor/"
 #define OUT_FILE "MOTION"
 #define SERIAL "101128160542"
 #define SLEEP_DELAY 250000
 #define TIMEOUT 2
 
+//#define DEBUG
+
 // Prototypes
 void timeout(int sig);
 
 int main(int argc, const char * argv[])
 {
 	int fd;
+	size_t len;
+	char *outfile, *datadir;
+	struct stat statbuf;
 	unsigned char data;
-	
+
+	// Construct the output file path
+	len = confstr(_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
+	len += sizeof(DATA_DIR);
+	datadir = malloc(len);
+	outfile = malloc(len + sizeof(OUT_FILE));
+	if (datadir == NULL || outfile == NULL) {
+		fprintf(stderr, "Out of memory\n");
+		exit(1);
+	}
+	confstr(_CS_DARWIN_USER_TEMP_DIR, datadir, len);
+	strlcat(datadir, DATA_DIR, len);
+	strlcpy(outfile, datadir, len);
+	strlcat(outfile, OUT_FILE, len + sizeof(OUT_FILE));
+
+	// Create the datadir and outfile as needed
+	stat(datadir, &statbuf);
+	if (!S_ISDIR(statbuf.st_mode)) {
+		fprintf(stderr, "Creating data directory: %s\n", datadir);
+		if (mkdir(datadir, S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
+			fprintf(stderr, "Error creating data directory (%s): %s\n", strerror(errno), outfile);
+			exit(1);
+		}
+	}
+	stat(outfile, &statbuf);
+	if(!S_ISREG(statbuf.st_mode)) {
+		fprintf(stderr, "Creating output file: %s\n", outfile);
+		fd = open(outfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
+		if (fd <= 0 || close(fd) != 0) {
+			fprintf(stderr, "Error creating output file (%s): %s\n", strerror(errno), outfile);
+			exit(1);
+		}
+	}
+
 	// Grab a USBmicroX context
 	USBmX_ContextRef ctx = USBmX_Create();
 	USBmX_Begin(ctx);
@@ -40,21 +80,20 @@ int main(int argc, const char * argv[])
 		
 		// Pin A5 is high when we've got motion
 		if (data & 0x20) {
-			printf("Motion detected");
-			if (utimes(OUT_FILE, NULL) != 0) {
-				fprintf(stderr, "Creating outfile\n");
+			#ifdef DEBUG
+			printf("Motion detected\n");
+			#endif
+			if (utimes(outfile, NULL) != 0) {
 				if (errno == ENOENT) {
-					fd = open(OUT_FILE, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
-					if (fd <= 0 || close(fd) != 0) {
-						fprintf(stderr, "Error creating output file (%d): %s\n", errno, OUT_FILE);
-						exit(1);
-					}
 				} else {
-					fprintf(stderr, "Error touching output file (%d): %s\n", errno, OUT_FILE);
+					fprintf(stderr, "Error touching output file (%s): %s\n", strerror(errno), outfile);
 				}
 			}
+		} else {
+			#ifdef DEBUG
+			printf("\n");
+			#endif
 		}
-		printf("\n");
 		
 		// Sleep and loop
 		usleep(SLEEP_DELAY);
@@ -70,4 +109,4 @@ void timeout(int sig) {
 	signal(sig, SIG_IGN);
 	fprintf(stderr, "Timeout waiting for USB read\n");
 	exit(1);
-}
+}