profil-dwmstatus-1.0.c - sites - public wiki contents of suckless.org
(HTM) git clone git://git.suckless.org/sites
(DIR) Log
(DIR) Files
(DIR) Refs
---
profil-dwmstatus-1.0.c (2489B)
---
1 /* made by profil 2011-12-29.
2 **
3 ** Compile with:
4 ** gcc -Wall -pedantic -std=c99 -lX11 status.c
5 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <time.h>
10 #include <X11/Xlib.h>
11
12 static Display *dpy;
13
14 void setstatus(char *str) {
15 XStoreName(dpy, DefaultRootWindow(dpy), str);
16 XSync(dpy, False);
17 }
18
19 float getfreq(char *file) {
20 FILE *fd;
21 char *freq;
22 float ret;
23
24 freq = malloc(10);
25 fd = fopen(file, "r");
26 if(fd == NULL) {
27 fprintf(stderr, "Cannot open '%s' for reading.\n", file);
28 exit(1);
29 }
30
31 fgets(freq, 10, fd);
32 fclose(fd);
33
34 ret = atof(freq)/1000000;
35 free(freq);
36 return ret;
37 }
38
39 char *getdatetime() {
40 char *buf;
41 time_t result;
42 struct tm *resulttm;
43
44 if((buf = malloc(sizeof(char)*65)) == NULL) {
45 fprintf(stderr, "Cannot allocate memory for buf.\n");
46 exit(1);
47 }
48 result = time(NULL);
49 resulttm = localtime(&result);
50 if(resulttm == NULL) {
51 fprintf(stderr, "Error getting localtime.\n");
52 exit(1);
53 }
54 if(!strftime(buf, sizeof(char)*65-1, "%a %b %d %H:%M:%S", resulttm)) {
55 fprintf(stderr, "strftime is 0.\n");
56 exit(1);
57 }
58
59 return buf;
60 }
61
62 float getbattery() {
63 FILE *fd;
64 int energy_now, energy_full, voltage_now;
65
66 fd = fopen("/sys/class/power_supply/BAT0/energy_now", "r");
67 if(fd == NULL) {
68 fprintf(stderr, "Error opening energy_now.\n");
69 return -1;
70 }
71 fscanf(fd, "%d", &energy_now);
72 fclose(fd);
73
74
75 fd = fopen("/sys/class/power_supply/BAT0/energy_full", "r");
76 if(fd == NULL) {
77 fprintf(stderr, "Error opening energy_full.\n");
78 return -1;
79 }
80 fscanf(fd, "%d", &energy_full);
81 fclose(fd);
82
83
84 fd = fopen("/sys/class/power_supply/BAT0/voltage_now", "r");
85 if(fd == NULL) {
86 fprintf(stderr, "Error opening voltage_now.\n");
87 return -1;
88 }
89 fscanf(fd, "%d", &voltage_now);
90 fclose(fd);
91
92
93 return ((float)energy_now * 1000 / (float)voltage_now) * 100 / ((float)energy_full * 1000 / (float)voltage_now);
94 }
95
96 int main(void) {
97 char *status;
98 float cpu0, cpu1;
99 char *datetime;
100 int bat0;
101
102
103 if (!(dpy = XOpenDisplay(NULL))) {
104 fprintf(stderr, "Cannot open display.\n");
105 return 1;
106 }
107
108 if((status = malloc(200)) == NULL)
109 exit(1);
110
111
112 for (;;sleep(1)) {
113 cpu0 = getfreq("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
114 cpu1 = getfreq("/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq");
115 datetime = getdatetime();
116 bat0 = getbattery();
117 snprintf(status, 200, "%0.2f, %0.2f | %.2lf%% | %s", cpu0, cpu1, bat0, datetime);
118
119 free(datetime);
120 setstatus(status);
121 }
122
123 free(status);
124 XCloseDisplay(dpy);
125
126 return 0;
127 }
128