Support arbitrary parameter passing to sensor function
[khatus.git] / x5 / khatus_sensor_time.c
CommitLineData
707b2f79
SK
1#include <assert.h>
2#include <ctype.h>
8345f2b3 3#include <errno.h>
707b2f79
SK
4#include <fcntl.h>
5#include <signal.h>
8345f2b3
SK
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"
55883d9a 13#include "khatus_lib_sensor.h"
8345f2b3
SK
14#include "khatus_lib_time.h"
15
707b2f79
SK
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
f1eff928
SK
21char *argv0 = NULL;
22
23double opt_interval = 1.0;
24char *opt_fmt = "%a %b %d %H:%M:%S";
25char *fifo_name = NULL;
8345f2b3
SK
26
27void
707b2f79 28print_usage()
8345f2b3
SK
29{
30 printf(
707b2f79 31 "%s: [OPT ...] FIFO\n"
8345f2b3 32 "\n"
707b2f79 33 "FIFO = string # path to fifo file\n"
8345f2b3
SK
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);
8345f2b3
SK
38}
39
f1eff928
SK
40void
41opt_parse(int argc, char **argv)
8345f2b3 42{
8345f2b3
SK
43 char c;
44
8345f2b3
SK
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':
707b2f79 55 print_usage();
f1eff928 56 exit(EXIT_SUCCESS);
707b2f79
SK
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);
f1eff928 70 exit(EXIT_FAILURE);
8345f2b3 71 default:
707b2f79 72 assert(0);
8345f2b3 73 }
707b2f79
SK
74 fifo_name = argv[optind];
75 debug("fifo_name: %s\n", fifo_name);
76 if (!fifo_name)
77 usage("No filename was provided\n");
f1eff928
SK
78}
79
55883d9a 80int
fa2a9b44 81get_time(char *buf, char *fmt)
55883d9a
SK
82{
83 time_t t;
84
85 t = time(NULL);
fa2a9b44 86 strftime(buf, MAX_LEN, fmt, localtime(&t));
55883d9a
SK
87 return strlen(buf);
88}
89
f1eff928
SK
90int
91main(int argc, char **argv)
92{
93 argv0 = argv[0];
94
f1eff928
SK
95 struct timespec ti;
96 char buf[MAX_LEN];
97
f1eff928
SK
98 opt_parse(argc, argv);
99
55883d9a 100 signal(SIGPIPE, SIG_IGN); /* Handled in loop */
f1eff928
SK
101
102 memset(buf, '\0', MAX_LEN);
8345f2b3 103 ti = timespec_of_float(opt_interval);
fa2a9b44
SK
104 loop(
105 &ti,
106 fifo_name,
107 buf,
108 (SENSOR_FUN_T) get_time,
109 (SENSOR_PARAMS_T) opt_fmt
110 );
8345f2b3
SK
111 return EXIT_SUCCESS;
112}
This page took 0.030553 seconds and 4 git commands to generate.