chiark / gitweb /
Record the current time displayed on the dial to a file.
authorBen Harris <bjh21@bjh21.me.uk>
Sun, 11 Nov 2018 15:54:18 +0000 (15:54 +0000)
committerBen Harris <bjh21@bjh21.me.uk>
Sun, 11 Nov 2018 15:54:18 +0000 (15:54 +0000)
This would allow for recovering from a power failure automatically, if
clunk bothered reading the file.

clunk.c

diff --git a/clunk.c b/clunk.c
index c9ad397127453c73b8c117cc34e6013ddc757583..0ca065aab8306aaf2e0fbcea63376d3f75ef6369 100644 (file)
--- a/clunk.c
+++ b/clunk.c
@@ -1,4 +1,5 @@
 #include <err.h>
+#include <fcntl.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <time.h>
@@ -26,6 +27,8 @@ static int const maxadvance = (10 * 3600) + (50 * 60);
 
 static struct tm displayed;
 
+static int statefd = -1;
+
 static void
 dummy_out(bool state)
 {
@@ -39,15 +42,12 @@ dummy_out(bool state)
                fflush(stdout);
        }
 }
-
 static void
-pulse()
+record_tick()
 {
-       struct timespec const ts = { 0, pulsewidth };
+       ssize_t ret;
+       char buf[10];
 
-       dummy_out(true);
-       clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
-       dummy_out(false);
        displayed.tm_sec += 30;
        while (displayed.tm_sec >= 60) {
                displayed.tm_min++;
@@ -58,9 +58,26 @@ pulse()
                displayed.tm_min -= 60;
        }
        displayed.tm_hour %= 12;
-       printf(" (%d:%02d:%02d)\n",
-              displayed.tm_hour, displayed.tm_min, displayed.tm_sec);
-       fflush(stdout);
+       sprintf(buf, "%2d:%02d:%02d\n",
+               displayed.tm_hour, displayed.tm_min, displayed.tm_sec);
+       if (statefd != -1) {
+               ret = pwrite(statefd, buf, 9, 0);
+               if (ret == -1)
+                       err(1, "write to state file");
+               if (ret != 9)
+                       errx(1, "short write to state file");
+       }
+}
+
+static void
+pulse()
+{
+       struct timespec const ts = { 0, pulsewidth };
+
+       dummy_out(true);
+       record_tick();
+       clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
+       dummy_out(false);
 }
 
 static void
@@ -75,8 +92,14 @@ init(int argc, char **argv)
        if (localtime_r(&ts.tv_sec, &displayed) == NULL)
                err(1, "localtime_r");
        displayed.tm_sec = (displayed.tm_sec >= 30) ? 30 : 0;
-       while ((opt = getopt(argc, argv, "s:")) != -1) {
+       while ((opt = getopt(argc, argv, "f:s:")) != -1) {
                switch (opt) {
+               case 'f':
+                       statefd =
+                               open(optarg, O_RDWR | O_CREAT | O_DSYNC, 0666);
+                       if (statefd == -1)
+                               err(1, "%s", optarg);
+                       break;
                case 's':
                        if (sscanf(optarg, "%d:%d:%d", &displayed.tm_hour,
                                   &displayed.tm_min, &displayed.tm_sec) != 3)