Update usage message
[khatus.git] / x5 / khatus.c
CommitLineData
77c76070 1#include <sys/select.h>
bec93767 2#include <sys/stat.h>
4d66492f 3
9b5ebc12
SK
4#include <assert.h>
5#include <ctype.h>
77c76070 6#include <errno.h>
c5d1af8c 7#include <fcntl.h>
9b5ebc12
SK
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
b7487ec5 11#include <time.h>
c5d1af8c
SK
12#include <unistd.h>
13
14#include <X11/Xlib.h>
9b5ebc12 15
b7487ec5
SK
16#include "bsdtimespec.h"
17
6626f8ba
SK
18#define debug(args...) {fprintf(stderr, "[debug] " args); fflush(stderr);}
19#define info( args...) {fprintf(stderr, "[info] " args); fflush(stderr);}
20#define error(args...) {fprintf(stderr, "[error] " args); fflush(stderr);}
4d66492f
SK
21#define fatal(args...) {fprintf(stderr, "[fatal] " args); exit(EXIT_FAILURE);}
22#define usage(args...) {print_usage(); fatal("[usage] " args);}
9b5ebc12 23
e6c523cd
SK
24#define ERRMSG "ERROR"
25
26static const char errmsg[] = ERRMSG;
27static const int errlen = sizeof(ERRMSG) - 1;
28
4d66492f 29char *argv0;
9b5ebc12 30
1872c5c1
SK
31/* TODO: Convert fifo list to fifo array. */
32typedef struct Fifo Fifo;
33struct Fifo {
4d66492f
SK
34 char *name;
35 int fd;
9b5ebc12 36 int width;
4d66492f 37 int last_read;
9b5ebc12 38 int ttl;
4d66492f 39 int pos; /* Position on the output buffer. */
1872c5c1 40 Fifo *next;
9b5ebc12
SK
41};
42
4d66492f
SK
43typedef struct Config Config;
44struct Config {
9b5ebc12 45 int interval;
4d66492f 46 char * separator;
1872c5c1
SK
47 Fifo * fifos;
48 int fifo_count;
4d66492f 49 int total_width;
fabb8771 50 int output_to_x_root_window;
4d66492f
SK
51} defaults = {
52 .interval = 1,
53 .separator = "|",
1872c5c1
SK
54 .fifos = NULL,
55 .fifo_count = 0,
4d66492f 56 .total_width = 0,
fabb8771 57 .output_to_x_root_window = 0,
9b5ebc12
SK
58};
59
77c76070 60void
1872c5c1 61fifo_print_one(Fifo *f)
77c76070
SK
62{
63 debug(
1872c5c1 64 "Fifo "
77c76070
SK
65 "{"
66 " name = %s,"
67 " fd = %d,"
68 " width = %d,"
69 " last_read = %d,"
70 " ttl = %d,"
71 " pos = %d,"
72 " next = %p,"
73 " }\n",
74 f->name,
75 f->fd,
76 f->width,
77 f->last_read,
78 f->ttl,
79 f->pos,
80 f->next
81 );
82}
83
84void
1872c5c1 85fifo_print_all(Fifo *head)
77c76070 86{
1872c5c1
SK
87 for (Fifo *f = head; f; f = f->next) {
88 fifo_print_one(f);
77c76070
SK
89 }
90}
91
92void
93config_print(Config *c)
94{
95 debug(
96 "Config "
97 "{"
98 " interval = %d,"
99 " separator = %s,"
1872c5c1 100 " fifo_count = %d,"
77c76070 101 " total_width = %d,"
1872c5c1 102 " fifos = ..."
77c76070
SK
103 " }\n",
104 c->interval,
105 c->separator,
1872c5c1 106 c->fifo_count,
77c76070
SK
107 c->total_width
108 );
1872c5c1 109 fifo_print_all(c->fifos);
77c76070 110}
9b5ebc12
SK
111
112int
113is_pos_num(char *s)
114{
115 while (*s != '\0')
116 if (!isdigit(*(s++)))
117 return 0;
118 return 1;
119}
120
121void
122print_usage()
123{
4d66492f 124 assert(argv0);
9b5ebc12
SK
125 fprintf(
126 stderr,
127 "\n"
4d66492f 128 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
9b5ebc12 129 "\n"
4d66492f
SK
130 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
131 " FILE_PATH = string\n"
132 " DATA_WIDTH = int (* (positive) number of characters *)\n"
133 " DATA_TTL = int (* (positive) number of seconds *)\n"
134 " OPTION = -i INTERVAL\n"
135 " | -s SEPARATOR\n"
01936218 136 " | -x (* Output to X root window *)\n"
4d66492f
SK
137 " SEPARATOR = string\n"
138 " INTERVAL = int (* (positive) number of seconds *)\n"
9b5ebc12 139 "\n",
4d66492f 140 argv0
9b5ebc12
SK
141 );
142 fprintf(
143 stderr,
144 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
145 "\n",
4d66492f 146 argv0
9b5ebc12
SK
147 );
148}
149
4d66492f 150void opts_parse_any(Config *, int, char *[], int); /* For mutually-recursive calls. */
9b5ebc12
SK
151
152void
4d66492f 153parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
154{
155 if (i < argc) {
156 char *param = argv[i++];
157
158 if (is_pos_num(param)) {
4d66492f
SK
159 cfg->interval = atoi(param);
160 opts_parse_any(cfg, argc, argv, i);
9b5ebc12
SK
161 } else {
162 usage("Option -i parameter is invalid: \"%s\"\n", param);
163 }
164 } else {
165 usage("Option -i parameter is missing.\n");
166 }
167}
168
169void
4d66492f
SK
170parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
171{
172 if (i < argc) {
3c836bfd 173 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
4d66492f
SK
174 strcpy(cfg->separator, argv[i]);
175 opts_parse_any(cfg, argc, argv, ++i);
176 } else {
177 usage("Option -s parameter is missing.\n");
178 }
179}
180
4d66492f
SK
181void
182parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
183{
184 switch (argv[i][1]) {
fb8745ba
SK
185 case 'i':
186 /* TODO: Generic set_int */
187 parse_opts_opt_i(cfg, argc, argv, ++i);
188 break;
189 case 's':
190 /* TODO: Generic set_str */
191 parse_opts_opt_s(cfg, argc, argv, ++i);
192 break;
193 case 'x':
fabb8771
SK
194 cfg->output_to_x_root_window = 1;
195 opts_parse_any(cfg, argc, argv, ++i);
196 break;
fb8745ba
SK
197 default :
198 usage("Option \"%s\" is invalid\n", argv[i]);
9b5ebc12
SK
199 }
200}
201
202void
4d66492f 203parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
204{
205 if ((i + 3) > argc)
1872c5c1 206 usage("[spec] Parameter(s) missing for fifo \"%s\".\n", argv[i]);
9b5ebc12
SK
207
208 char *n = argv[i++];
209 char *w = argv[i++];
210 char *t = argv[i++];
211
212 if (!is_pos_num(w))
1872c5c1 213 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
9b5ebc12 214 if (!is_pos_num(t))
1872c5c1
SK
215 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
216 Fifo *f = calloc(1, sizeof(struct Fifo));
9b5ebc12 217 if (f) {
4d66492f
SK
218 f->name = n;
219 f->fd = -1;
220 f->width = atoi(w);
221 f->ttl = atoi(t);
222 f->last_read = 0;
223 f->pos = cfg->total_width;
1872c5c1 224 f->next = cfg->fifos;
4d66492f 225
1872c5c1 226 cfg->fifos = f;
4d66492f 227 cfg->total_width += f->width;
1872c5c1 228 cfg->fifo_count++;
9b5ebc12 229 } else {
4d66492f 230 fatal("[memory] Allocation failure.");
9b5ebc12 231 }
4d66492f 232 opts_parse_any(cfg, argc, argv, i);
9b5ebc12
SK
233}
234
235void
4d66492f 236opts_parse_any(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
237{
238 if (i < argc) {
239 switch (argv[i][0]) {
fb8745ba
SK
240 case '-':
241 parse_opts_opt(cfg, argc, argv, i);
242 break;
243 default :
244 parse_opts_spec(cfg, argc, argv, i);
4d66492f
SK
245 }
246 }
247}
248
249void
5400b86f 250opts_parse(Config *cfg, int argc, char *argv[])
4d66492f
SK
251{
252 opts_parse_any(cfg, argc, argv, 1);
253
1872c5c1
SK
254 Fifo *last = cfg->fifos;
255 cfg->fifos = NULL;
256 for (Fifo *f = last; f; ) {
257 Fifo *next = f->next;
258 f->next = cfg->fifos;
259 cfg->fifos = f;
4d66492f
SK
260 f = next;
261 }
262}
263
e6c523cd 264void
69b75a40 265fifo_read_error(Fifo *f, char *buf)
e6c523cd
SK
266{
267 char *b;
268 int i;
269
270 b = buf + f->pos;
271 /* Copy as much of the error message as possible.
272 * EXCLUDING the reminating \0. */
273 for (i = 0; i < errlen && i < f->width; i++)
274 b[i] = errmsg[i];
275 /* Any remaining slots: */
276 for (; i < f->width; i++)
277 b[i] = '_';
278}
279
77c76070 280void
69b75a40 281fifo_read_one(Fifo *f, char *buf)
77c76070 282{
3efcce25
SK
283 ssize_t current;
284 ssize_t total;
77c76070 285 char *b;
3efcce25 286 char c;
77c76070 287
3efcce25
SK
288 current = 0;
289 total = 0;
290 c = '\0';
77c76070 291 b = buf + f->pos;
3efcce25
SK
292 while ((current = read(f->fd, &c, 1)) && c != '\n' && c != '\0' && total++ < f->width)
293 *b++ = c;
e6c523cd 294 if (current == -1) {
3efcce25 295 error("Failed to read: \"%s\". Error: %s\n", f->name, strerror(errno));
69b75a40 296 fifo_read_error(f, buf);
7fb02106
SK
297 } else
298 while (total++ < f->width)
299 *b++ = ' ';
6c29392d 300 /* TODO Record timestamp read */
77c76070
SK
301 close(f->fd);
302 f->fd = -1;
303}
304
4d66492f 305void
69b75a40 306fifo_read_all(Config *cfg, char *buf)
4d66492f 307{
77c76070 308 fd_set fds;
bfab34f8 309 int maxfd = -1;
77c76070 310 int ready;
bec93767 311 struct stat st;
77c76070
SK
312
313 FD_ZERO(&fds);
1872c5c1 314 for (Fifo *f = cfg->fifos; f; f = f->next) {
bec93767 315 /* TODO: Create the FIFO if it doesn't already exist. */
e6c523cd
SK
316 if (lstat(f->name, &st) < 0) {
317 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
69b75a40 318 fifo_read_error(f, buf);
e6c523cd
SK
319 continue;
320 }
321 if (!(st.st_mode & S_IFIFO)) {
322 error("\"%s\" is not a FIFO\n", f->name);
69b75a40 323 fifo_read_error(f, buf);
e6c523cd
SK
324 continue;
325 }
77c76070 326 debug("opening: %s\n", f->name);
4d66492f 327 if (f->fd < 0)
77c76070 328 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
e6c523cd 329 if (f->fd == -1) {
1872c5c1 330 /* TODO: Consider backing off retries for failed fifos. */
e6c523cd 331 error("Failed to open \"%s\"\n", f->name);
69b75a40 332 fifo_read_error(f, buf);
e6c523cd
SK
333 continue;
334 }
77c76070
SK
335 if (f->fd > maxfd)
336 maxfd = f->fd;
337 FD_SET(f->fd, &fds);
338 }
339 debug("selecting...\n");
340 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
341 debug("ready: %d\n", ready);
342 assert(ready != 0);
343 if (ready < 0)
344 fatal("%s", strerror(errno));
1872c5c1 345 for (Fifo *f = cfg->fifos; f; f = f->next) {
77c76070
SK
346 if (FD_ISSET(f->fd, &fds)) {
347 debug("reading: %s\n", f->name);
69b75a40 348 fifo_read_one(f, buf);
9b5ebc12
SK
349 }
350 }
351}
352
b7487ec5
SK
353void
354snooze(struct timespec *t)
355{
356 struct timespec remainder;
357 int result;
358
359 result = nanosleep(t, &remainder);
360
361 if (result < 0) {
362 if (errno == EINTR) {
363 info(
364 "nanosleep interrupted. Remainder: "
365 "{ tv_sec = %ld, tv_nsec = %ld }",
366 remainder.tv_sec, remainder.tv_nsec);
367 /* No big deal if we occasionally sleep less,
368 * so not attempting to correct after an interruption.
369 */
370 } else {
371 fatal("nanosleep: %s\n", strerror(errno));
372 }
373 }
374}
375
9b5ebc12 376int
4d66492f 377main(int argc, char *argv[])
9b5ebc12 378{
f277f405 379 int width = 0;
1872c5c1 380 int nfifos = 0;
f277f405 381 int seplen = 0;
4d66492f 382 int prefix = 0;
e6c523cd 383 int errors = 0;
4d66492f 384 char *buf;
a6d4c9c3
SK
385 Config cfg0 = defaults;
386 Config *cfg = &cfg0;
bfab34f8 387 Display *display = NULL;
e6c523cd 388 struct stat st;
b7487ec5
SK
389 struct timespec
390 t0, /* time stamp. before reading fifos */
391 t1, /* time stamp. after reading fifos */
392 ti, /* time interval desired (t1 - t0) */
393 td, /* time interval measured (t1 - t0) */
394 tc; /* time interval correction (ti - td) when td < ti */
4d66492f
SK
395
396 argv0 = argv[0];
397
5400b86f 398 opts_parse(cfg, argc, argv);
4d66492f 399 debug("argv0 = %s\n", argv0);
77c76070 400 config_print(cfg);
b7487ec5
SK
401
402 /* TODO: Support interval < 1. i.e. implement timespec_of_float */
403 ti.tv_sec = cfg->interval;
404 ti.tv_nsec = 0;
405
1872c5c1
SK
406 if (cfg->fifos == NULL)
407 usage("No fifo specs were given!\n");
4d66492f 408
e6c523cd
SK
409 /* 1st pass to check file existence and type */
410 for (Fifo *f = cfg->fifos; f; f = f->next) {
411 if (lstat(f->name, &st) < 0) {
412 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
413 errors++;
414 continue;
415 }
416 if (!(st.st_mode & S_IFIFO)) {
417 error("\"%s\" is not a FIFO\n", f->name);
418 errors++;
419 continue;
420 }
421 }
422 if (errors)
423 fatal("Encountered errors with the given file paths. See log.\n");
424
4d66492f
SK
425 width = cfg->total_width;
426 seplen = strlen(cfg->separator);
427
e6c523cd 428 /* 2nd pass to make space for separators */
1872c5c1 429 for (Fifo *f = cfg->fifos; f; f = f->next) {
4d66492f
SK
430 f->pos += prefix;
431 prefix += seplen;
1872c5c1 432 nfifos++;
4d66492f 433 }
1872c5c1 434 width += (seplen * (nfifos - 1));
3c836bfd 435 buf = calloc(1, width + 1);
4d66492f
SK
436 if (buf == NULL)
437 fatal("[memory] Failed to allocate buffer of %d bytes", width);
438 memset(buf, ' ', width);
439 buf[width] = '\0';
e6c523cd 440 /* 3rd pass to set the separators */
1872c5c1 441 for (Fifo *f = cfg->fifos; f; f = f->next) {
4d66492f 442 if (f->pos) { /* Skip the first, left-most */
77c76070
SK
443 /* Copying only seplen ensures we omit the '\0' byte. */
444 strncpy(buf + (f->pos - seplen), cfg->separator, seplen);
4d66492f
SK
445 }
446 }
447
fabb8771
SK
448 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
449 fatal("XOpenDisplay failed with: %p\n", display);
805f0d22 450 /* TODO: Handle signals */
4d66492f 451 for (;;) {
b7487ec5
SK
452 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
453 /* TODO: Cache expiration. i.e. use the TTL */
6c29392d 454 /* TODO: How to trigger TTL check? On select? Alarm signal? */
69b75a40
SK
455 /* TODO: Set timeout on fifo_read_all based on diff of last time of
456 * fifo_read_all and desired time of next TTL check.
b7487ec5
SK
457 */
458 /* TODO: How long to wait on IO? Max TTL? */
69b75a40 459 fifo_read_all(cfg, buf);
fabb8771
SK
460 if (cfg->output_to_x_root_window) {
461 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
462 fatal("XStoreName failed.\n");
463 XFlush(display);
464 } else {
465 puts(buf);
466 fflush(stdout);
467 }
b7487ec5
SK
468 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
469 timespecsub(&t1, &t0, &td);
470 debug("td {tv_sec = %ld, tv_nsec = %ld}\n", td.tv_sec, td.tv_nsec);
471 if (timespeccmp(&td, &ti, <)) {
472 /* Pushback on data producers by refusing to read the
473 * pipe more frequently than the interval.
474 */
475 timespecsub(&ti, &td, &tc);
476 debug("snooze YES\n");
477 snooze(&tc);
478 } else
479 debug("snooze NO\n");
4d66492f 480 }
3d7e82a8
SK
481
482 return EXIT_SUCCESS;
9b5ebc12 483}
This page took 0.079419 seconds and 4 git commands to generate.