-
Notifications
You must be signed in to change notification settings - Fork 0
/
batstat.c
108 lines (97 loc) · 2.66 KB
/
batstat.c
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
104
105
106
107
108
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <libnotify/notification.h>
#include <libnotify/notify.h>
#define POWER_SUPPLY_CAPACITY "/sys/class/power_supply/BAT0/capacity"
#define POWER_SUPPLY_STATUS "/sys/class/power_supply/BAT0/status"
int battery_perc(char **buffer, size_t n)
{
static char *path = POWER_SUPPLY_CAPACITY;
FILE *fp;
if ((fp = fopen(path, "r")) != NULL) {
getline(buffer, &n, fp);
}
return fclose(fp);
}
int battery_state(char **buffer, size_t n)
{
static char *path = POWER_SUPPLY_STATUS;
FILE *fp;
if ((fp = fopen(path, "r")) != NULL) {
getline(buffer, &n, fp);
}
return fclose(fp);
}
void send_notification(const char *msg, int is_critical)
{
notify_init("batstat");
NotifyNotification *Notification =
notify_notification_new("batstat", msg, NULL);
if (is_critical) {
notify_notification_set_timeout(Notification,
NOTIFY_EXPIRES_NEVER);
notify_notification_set_urgency(Notification,
NOTIFY_URGENCY_CRITICAL);
}
notify_notification_show(Notification, NULL);
g_object_unref(G_OBJECT(Notification));
notify_uninit();
}
int main()
{
int LESS_20_SWITCH = 0;
int LESS_10_SWITCH = 0;
int LESS_05_SWITCH = 0;
char *percent_buffer;
char *state_buffer;
size_t percent_bufsize = 4;
size_t state_bufsize = 20;
percent_buffer = (char *)malloc(percent_bufsize * sizeof(char));
state_buffer = (char *)malloc(state_bufsize * sizeof(char));
if (percent_buffer == NULL || state_buffer == NULL) {
perror("Unable to allocate buffers");
exit(EXIT_FAILURE);
}
do {
battery_perc(&percent_buffer, percent_bufsize);
battery_state(&state_buffer, state_bufsize);
int current_percent = atoi(percent_buffer);
if (strncmp(state_buffer, "Discharging", 11) == 0) {
if (current_percent < 5 && LESS_05_SWITCH == 0) {
send_notification("Battery below 5%", 1);
LESS_05_SWITCH = 1;
LESS_10_SWITCH = 1;
LESS_20_SWITCH = 1;
} else if (current_percent < 10 &&
LESS_10_SWITCH == 0) {
send_notification("Battery below 10%", 1);
LESS_10_SWITCH = 1;
LESS_20_SWITCH = 1;
} else if (current_percent < 20 &&
LESS_20_SWITCH == 0) {
send_notification("Battery below 20%", 0);
LESS_20_SWITCH = 1;
};
} else {
if (current_percent >= 20 && LESS_20_SWITCH == 1) {
LESS_20_SWITCH = 0;
LESS_10_SWITCH = 0;
LESS_05_SWITCH = 0;
} else if (current_percent >= 10 &&
LESS_10_SWITCH == 1) {
LESS_10_SWITCH = 0;
LESS_05_SWITCH = 0;
} else if (current_percent >= 5 &&
LESS_05_SWITCH == 1) {
LESS_05_SWITCH = 0;
};
}
} while (!sleep(30));
free(percent_buffer);
free(state_buffer);
return 0;
}