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