From 8345f2b388e0986829ceeae50ecf186d5d540a9c Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Mon, 16 Mar 2020 18:48:38 -0400 Subject: [PATCH] Implement time sensor --- x5/.gitignore | 1 + x5/Makefile | 7 ++++- x5/khatus_lib_time.c | 14 +++++++++ x5/khatus_lib_time.h | 2 ++ x5/khatus_sensor_time.c | 65 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 x5/khatus_sensor_time.c diff --git a/x5/.gitignore b/x5/.gitignore index fa71cac..09901ba 100644 --- a/x5/.gitignore +++ b/x5/.gitignore @@ -1,2 +1,3 @@ *.o khatus +khatus_sensor_time diff --git a/x5/Makefile b/x5/Makefile index 1a356f5..c6a0576 100644 --- a/x5/Makefile +++ b/x5/Makefile @@ -5,12 +5,17 @@ LDLIBS := -lX11 .PHONY: build clean rebuild build: \ - khatus + khatus \ + khatus_sensor_time khatus: \ khatus_lib_log.o \ khatus_lib_time.o +khatus_sensor_time: \ + khatus_lib_log.o \ + khatus_lib_time.o + khatus_lib_time.o: khatus_lib_log.o clean: diff --git a/x5/khatus_lib_time.c b/x5/khatus_lib_time.c index ba74226..a169471 100644 --- a/x5/khatus_lib_time.c +++ b/x5/khatus_lib_time.c @@ -7,6 +7,20 @@ #include "khatus_lib_log.h" #include "khatus_lib_time.h" +struct timespec +timespec_of_float(double n) +{ + double integral; + double fractional; + struct timespec t; + + fractional = modf(n, &integral); + t.tv_sec = (int) integral; + t.tv_nsec = (int) (1E9 * fractional); + + return t; +} + void snooze(struct timespec *t) { diff --git a/x5/khatus_lib_time.h b/x5/khatus_lib_time.h index 2d16d65..1d4bb44 100644 --- a/x5/khatus_lib_time.h +++ b/x5/khatus_lib_time.h @@ -1 +1,3 @@ +struct timespec timespec_of_float(double); + void snooze(struct timespec *); diff --git a/x5/khatus_sensor_time.c b/x5/khatus_sensor_time.c new file mode 100644 index 0000000..f156f45 --- /dev/null +++ b/x5/khatus_sensor_time.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "khatus_lib_log.h" +#include "khatus_lib_time.h" + +char *argv0; + +void +usage() +{ + printf( + "%s: [OPT ...]\n" + "\n" + "OPT = -i int # interval\n" + " | -f string # format string\n" + " | -h # help message (i.e. what you're reading now :) )\n", + argv0); + fatal("usage\n"); +} + +int +main(int argc, char **argv) +{ + argv0 = argv[0]; + + double opt_interval = 1.0; + char *opt_fmt = "%a %b %d %H:%M:%S"; + + time_t t; + struct timespec ti; + char buf[128]; + char c; + + memset(buf, '\0', 128); + while ((c = getopt(argc, argv, "f:i:h")) != -1) + switch (c) { + case 'f': + opt_fmt = calloc(strlen(optarg), sizeof(char)); + strcpy(opt_fmt, optarg); + break; + case 'i': + opt_interval = atof(optarg); + break; + case 'h': + usage(); + break; + default: + usage(); + } + ti = timespec_of_float(opt_interval); + for (;;) { + t = time(NULL); + strftime(buf, sizeof(buf), opt_fmt, localtime(&t)); + puts(buf); + fflush(stdout); + snooze(&ti); + } + return EXIT_SUCCESS; +} -- 2.20.1