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