cc476770b691d179c39b583fec44fb3d6fcbbb6b
[khatus.git] / khatus_sensor_time.c
1 #include <assert.h>
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <signal.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <time.h>
10 #include <unistd.h>
11
12 #include "khatus_lib_log.h"
13 #include "khatus_lib_sensor.h"
14 #include "khatus_lib_time.h"
15
16 #define usage(...) {print_usage(); fprintf(stderr, "Error:\n " __VA_ARGS__); exit(EXIT_FAILURE);}
17
18 #define MAX_LEN 20
19 #define END_OF_MESSAGE '\n'
20
21 char *argv0 = NULL;
22
23 double opt_interval = 1.0;
24 char *opt_fmt = "%a %b %d %H:%M:%S";
25 char *fifo_name = NULL;
26
27 void
28 print_usage()
29 {
30 printf(
31 "%s: [OPT ...] FIFO\n"
32 "\n"
33 "FIFO = string # path to fifo file\n"
34 "OPT = -i int # interval\n"
35 " | -f string # format string\n"
36 " | -h # help message (i.e. what you're reading now :) )\n",
37 argv0);
38 }
39
40 void
41 opt_parse(int argc, char **argv)
42 {
43 char c;
44
45 while ((c = getopt(argc, argv, "f:i:h")) != -1)
46 switch (c) {
47 case 'f':
48 opt_fmt = calloc(strlen(optarg), sizeof(char));
49 strcpy(opt_fmt, optarg);
50 break;
51 case 'i':
52 opt_interval = atof(optarg);
53 break;
54 case 'h':
55 print_usage();
56 exit(EXIT_SUCCESS);
57 case '?':
58 if (optopt == 'f' || optopt == 'i')
59 fprintf(stderr,
60 "Option -%c requires an argument.\n",
61 optopt);
62 else if (isprint(optopt))
63 fprintf (stderr,
64 "Unknown option `-%c'.\n",
65 optopt);
66 else
67 fprintf(stderr,
68 "Unknown option character `\\x%x'.\n",
69 optopt);
70 exit(EXIT_FAILURE);
71 default:
72 assert(0);
73 }
74 fifo_name = argv[optind];
75 debug("fifo_name: %s\n", fifo_name);
76 if (!fifo_name)
77 usage("No filename was provided\n");
78 }
79
80 int
81 get_time(char *buf, char *fmt)
82 {
83 time_t t;
84
85 t = time(NULL);
86 strftime(buf, MAX_LEN, fmt, localtime(&t));
87 return strlen(buf);
88 }
89
90 int
91 main(int argc, char **argv)
92 {
93 argv0 = argv[0];
94
95 struct timespec ti;
96 char buf[MAX_LEN];
97
98 opt_parse(argc, argv);
99
100 signal(SIGPIPE, SIG_IGN); /* Handled in loop */
101
102 memset(buf, '\0', MAX_LEN);
103 ti = timespec_of_float(opt_interval);
104 loop(
105 &ti,
106 fifo_name,
107 buf,
108 (SENSOR_FUN_T) get_time,
109 (SENSOR_PARAMS_T) opt_fmt
110 );
111 return EXIT_SUCCESS;
112 }
This page took 0.083528 seconds and 3 git commands to generate.