Simplify sensor IO model and fix opts and timeouts
[khatus.git] / x5 / khatus_sensor_time.c
CommitLineData
707b2f79
SK
1#include <assert.h>
2#include <ctype.h>
8345f2b3 3#include <errno.h>
707b2f79 4#include <signal.h>
8345f2b3
SK
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <time.h>
9#include <unistd.h>
10
11#include "khatus_lib_log.h"
12#include "khatus_lib_time.h"
13
707b2f79
SK
14#define usage(...) {print_usage(); fprintf(stderr, "Error:\n " __VA_ARGS__); exit(EXIT_FAILURE);}
15
16#define MAX_LEN 20
17#define END_OF_MESSAGE '\n'
18
f1eff928
SK
19char *argv0 = NULL;
20
21double opt_interval = 1.0;
22char *opt_fmt = "%a %b %d %H:%M:%S";
8345f2b3
SK
23
24void
707b2f79 25print_usage()
8345f2b3
SK
26{
27 printf(
521d3106 28 "%s: [OPT ...]\n"
8345f2b3
SK
29 "\n"
30 "OPT = -i int # interval\n"
31 " | -f string # format string\n"
32 " | -h # help message (i.e. what you're reading now :) )\n",
33 argv0);
8345f2b3
SK
34}
35
f1eff928
SK
36void
37opt_parse(int argc, char **argv)
8345f2b3 38{
8345f2b3
SK
39 char c;
40
8345f2b3
SK
41 while ((c = getopt(argc, argv, "f:i:h")) != -1)
42 switch (c) {
43 case 'f':
44 opt_fmt = calloc(strlen(optarg), sizeof(char));
45 strcpy(opt_fmt, optarg);
46 break;
47 case 'i':
48 opt_interval = atof(optarg);
49 break;
50 case 'h':
707b2f79 51 print_usage();
f1eff928 52 exit(EXIT_SUCCESS);
707b2f79
SK
53 case '?':
54 if (optopt == 'f' || optopt == 'i')
55 fprintf(stderr,
56 "Option -%c requires an argument.\n",
57 optopt);
58 else if (isprint(optopt))
59 fprintf (stderr,
60 "Unknown option `-%c'.\n",
61 optopt);
62 else
63 fprintf(stderr,
64 "Unknown option character `\\x%x'.\n",
65 optopt);
f1eff928 66 exit(EXIT_FAILURE);
8345f2b3 67 default:
707b2f79 68 assert(0);
8345f2b3 69 }
55883d9a
SK
70}
71
f1eff928
SK
72int
73main(int argc, char **argv)
74{
75 argv0 = argv[0];
76
521d3106 77 time_t t;
f1eff928
SK
78 struct timespec ti;
79 char buf[MAX_LEN];
80
f1eff928 81 opt_parse(argc, argv);
8345f2b3 82 ti = timespec_of_float(opt_interval);
521d3106
SK
83 debug("opt_fmt: \"%s\"\n", opt_fmt);
84 debug("opt_interval: %f\n", opt_interval);
85 debug("ti: {tv_sec = %ld, tv_nsec = %ld}\n", ti.tv_sec, ti.tv_nsec);
86 memset(buf, '\0', MAX_LEN);
87 signal(SIGPIPE, SIG_IGN);
88
89 for (;;) {
90 t = time(NULL);
91 strftime(buf, MAX_LEN, opt_fmt, localtime(&t));
92 puts(buf);
93 fflush(stdout);
94 snooze(&ti);
95 }
8345f2b3
SK
96 return EXIT_SUCCESS;
97}
This page took 0.028671 seconds and 4 git commands to generate.