Factor-out common loop
[khatus.git] / x5 / khatus_sensor_battery.c
CommitLineData
d03cabfe
SK
1#include <assert.h>
2#include <ctype.h>
3#include <errno.h>
4#include <fcntl.h>
5#include <limits.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"
55883d9a 13#include "khatus_lib_sensor.h"
d03cabfe
SK
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
d03cabfe
SK
19
20char *argv0;
21
22char path[PATH_MAX];
23
24double opt_interval = 1.0;
25char *opt_battery = "BAT0";
26char *opt_fifo = NULL;
27
28void
29print_usage()
30{
31 printf(
32 "%s: [OPT ...] FIFO\n"
33 "\n"
34 "FIFO = string # path to fifo file\n"
35 "OPT = -i int # interval\n"
36 " | -b string # battery file name from /sys/class/power_supply/\n"
37 " | -h # help message (i.e. what you're reading now :) )\n",
38 argv0);
39}
40
41void
42opt_parse(int argc, char **argv)
43{
44 char c;
45
46 while ((c = getopt(argc, argv, "f:i:h")) != -1)
47 switch (c) {
48 case 'f':
49 opt_battery = calloc(strlen(optarg), sizeof(char));
50 strcpy(opt_battery, optarg);
51 break;
52 case 'i':
53 opt_interval = atof(optarg);
54 break;
55 case 'h':
56 print_usage();
57 exit(EXIT_SUCCESS);
58 case '?':
59 if (optopt == 'f' || optopt == 'i')
60 fprintf(stderr,
61 "Option -%c requires an argument.\n",
62 optopt);
63 else if (isprint(optopt))
64 fprintf (stderr,
65 "Unknown option `-%c'.\n",
66 optopt);
67 else
68 fprintf(stderr,
69 "Unknown option character `\\x%x'.\n",
70 optopt);
71 exit(EXIT_FAILURE);
72 default:
73 assert(0);
74 }
75 opt_fifo = argv[optind];
76 debug("opt_fifo: %s\n", opt_fifo);
77 if (!opt_fifo)
78 usage("No filename was provided\n");
79}
80
d03cabfe 81int
55883d9a 82get_capacity(char *buf)
d03cabfe
SK
83{
84 FILE *fp;
85 int cap;
86
87 if (!(fp = fopen(path, "r")))
88 fatal("Failed to open %s. errno: %d, msg: %s\n",
89 path, errno, strerror(errno));
90
91 switch (fscanf(fp, "%d", &cap)) {
92 case -1: fatal("EOF\n");
93 case 0: fatal("Read 0\n");
94 case 1: break;
95 default: assert(0);
96 }
97 fclose(fp);
98 return snprintf(buf, 6, "%3d%%\n", cap);
99}
100
101int
102main(int argc, char **argv)
103{
104 argv0 = argv[0];
105
106 char buf[10];
107 char *path_fmt = "/sys/class/power_supply/%s/capacity";
108 struct timespec ti = timespec_of_float(opt_interval);
109
110 opt_parse(argc, argv);
111
112 memset(path, '\0', PATH_MAX);
113 snprintf(path, PATH_MAX, path_fmt, opt_battery);
55883d9a 114 loop(&ti, opt_fifo, buf, &get_capacity);
d03cabfe 115}
This page took 0.027643 seconds and 4 git commands to generate.