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