diff options
Diffstat (limited to 'src/twa_t.c')
-rw-r--r-- | src/twa_t.c | 162 |
1 files changed, 162 insertions, 0 deletions
diff --git a/src/twa_t.c b/src/twa_t.c new file mode 100644 index 0000000..cfebb96 --- /dev/null +++ b/src/twa_t.c @@ -0,0 +1,162 @@ +/* + * twa_t.c: + * + * Copyright (c) 2017 James McKenzie <foss@madingley.org>, + * All rights reserved. + * + */ + +#include "project.h" + +void +tw_dt_to_tm (TW_DateTime * tw_dt, struct tm *tm) +{ + memset (tm, 0, sizeof (*tm)); + + tm->tm_sec = tw_dt->tw_sec; + tm->tm_min = tw_dt->tw_min; + tm->tm_hour = tw_dt->tw_hour; + tm->tm_mday = tw_dt->tw_day; + tm->tm_mon = tw_dt->tw_month - 1; + tm->tm_year = tw_dt->tw_year - 1900; +} + + + +void +tm_to_tw_dt (struct tm *tm, TW_DateTime * tw_dt) +{ + memset (tw_dt, 0, sizeof (*tw_dt)); + + tw_dt->tw_sec = tm->tm_sec; + tw_dt->tw_min = tm->tm_min; + tw_dt->tw_hour = tm->tm_hour; + tw_dt->tw_day = tm->tm_mday; + tw_dt->tw_month = tm->tm_mon + 1; + tw_dt->tw_year = tm->tm_year + 1900; +} + + +static int +show_ctrl_time (int fd) +{ + TW_DateTime dt; + ssize_t ret; + struct tm tm; + + + ret = + twa_get_parameter (fd, TW_TIMEKEEP_TABLE, TW_TIMEKEEP_DATETIME, &dt, + sizeof (dt)); + + if (ret != sizeof (dt)) + { + fprintf (stderr, "Failed to get controller time\n"); + return -1; + } + + tw_dt_to_tm (&dt, &tm); + + printf ("Controller time is: %s", asctime (&tm)); + + return 0; +} + + + +static int +set_ctrl_time (int fd) +{ + TW_DateTime dt; + int ret; + struct tm tm; + time_t t; + + + time (&t); + + localtime_r (&t, &tm); + + tm_to_tw_dt (&tm, &dt); + + ret = + twa_set_parameter (fd, TW_TIMEKEEP_TABLE, TW_TIMEKEEP_DATETIME, &dt, + sizeof (dt)); + + if (ret) + { + fprintf (stderr, "Failed to set controller time\n"); + return -1; + } + return 0; +} + + +static int +check_ctrl_time (int fd) +{ + TW_DateTime dt; + ssize_t ret; + struct tm tm; + time_t ctrl_time, local_time; + double d; + int rc = 0; + + ret = + twa_get_parameter (fd, TW_TIMEKEEP_TABLE, TW_TIMEKEEP_DATETIME, &dt, + sizeof (dt)); + + if (ret != sizeof (dt)) + { + fprintf (stderr, "Failed to get controller time\n"); + rc |= -1; + return rc; + } + + tw_dt_to_tm (&dt, &tm); + + printf ("Controller time is: %s", asctime (&tm)); + + ctrl_time = mktime (&tm); + + time (&local_time); + localtime_r (&local_time, &tm); + local_time = mktime (&tm); + + d = difftime (local_time, ctrl_time); + + printf ("Controller time difference is %.1lf seconds\n", d); + + if ((d > 15.0) || (d < -15.0)) + { + printf ("Setting controller time\n"); + rc |= set_ctrl_time (fd); + rc |= show_ctrl_time (fd); + } + + return rc; +} + + +int +main (int argc, char *argv[]) +{ + char *dev = "/dev/twa0"; + int fd; + int ret = 0; + + if (argc == 2) + dev = argv[1]; + + fd = open (dev, O_RDWR); + + if (fd < 0) + { + fprintf (stderr, "Failed to open %s: %m\n", dev); + ret |= -1; + return ret; + } + + + return check_ctrl_time (fd); +} |