summaryrefslogtreecommitdiff
path: root/main.c
blob: 39927f1837d17b78574dfa7a1627199efe3a100a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#define _GNU_SOURCE
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include <err.h>

static char SYSPATH[] = "/sys/class/power_supply/BAT0/";
static char charging[] = "↯";

static char *readline(char *dir, char *file)
{
	static char 	*line = NULL;
	static size_t 	nbytes = 0;

	char path[512];
	ssize_t n;
	FILE *fp;

	if (! dir && ! file) {
		free(line);
		return line = NULL;
	}

	snprintf(path, sizeof(path), "%s%s", dir, file);

	if (! (fp = fopen(path, "r"))) {
		warn("fopen %s", path);
		_exit(1);
	}

	if ((n = getline(&line, &nbytes, fp)) < 0) {
		warn("getline");
		_exit(1);
	}

	fclose(fp);

	assert(line);

	if (n && line[n - 1] == '\n')
		line[n - 1] = '\0';

	return line;
}

static int isdir(const char *path)
{
	struct stat st;

	return ! stat(path, &st) && S_ISDIR(st.st_mode);
}

static void print_battery_status(void)
{
#define PRINT(...) str += snprintf(str, sizeof(status) - (str - status), __VA_ARGS__)

	static char status[512];

	char *str = status;

	if (! isdir(SYSPATH))
		return;

	if (! strcasecmp("charging", readline(SYSPATH, "status")))
		PRINT("%s ", charging);

	int capacity = atoi(readline(SYSPATH, "capacity"));

	if (capacity == 100)
		PRINT("full");
	else
		PRINT("%d%%", capacity);

	printf(", bat: %s", status);

	readline(NULL, NULL);
}

int main(int argc, char *argv[])
{
	struct sysinfo si;

	if (sysinfo(&si) < 0)
		return 1;

	printf("used: %ld", (si.totalram - si.freeram) * si.mem_unit >> 20);
	printf(", free: %ld", si.freeram * si.mem_unit >> 20);
#if 0
	printf(", swap: %d", (si.totalswap - si.freeswap) * si.mem_unit >> 10);
#endif
	printf(", procs: %d", si.procs);

	print_battery_status();

	printf("\n");

	return 0;
}