summaryrefslogtreecommitdiff
path: root/status.c
blob: 38ee75ac786ff3490c5374cc169b25cf72666f76 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#include <arpa/inet.h>
#include <errno.h>
#include <ifaddrs.h>
#include <linux/if.h>
#include <linux/wireless.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>

/* Constants */
#define ELEMENT_SEPERATOR "   "

#define STATUS_STRBUF_SZ 512
#define ELEMENT_STRBUF_SZ 128

/* Type definitions */
typedef void (*element_function)(char*);

/* Data structures */
struct element {
  const element_function f;
  const struct timespec fire_interval;
  struct timespec fire_previous;
  char buf[ELEMENT_STRBUF_SZ];
};

enum battery_status_charge {
  bat_unknown,
  bat_not_charging,
  bat_charging,
  bat_discharging
};

struct battery_status {
  enum battery_status_charge status;
  float charge;
};

#define ADDRSTRLEN                                                             \
  (INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN
struct interface_status {
  enum { loopback, ethernet, wifi, wan } type;
  struct {
    char ip4[INET_ADDRSTRLEN];
    char ip6[INET6_ADDRSTRLEN];
  } address;
  char ssid[IW_ESSID_MAX_SIZE + 1];
  char name[IFNAMSIZ + 1];
};

/* Prototypes */
void date(char* buf);
struct battery_status get_battery_status(const char* buf);
void get_battery1_status(char* buf);
void get_battery0_status(char* buf);
void get_all_bat_status(char* buf);
void get_net_link_status(char* buf);

/* Data */
static char* battery_level_icon[] = {
  "󰂎", /* '\Uf008e' */
  "󰁺", /* '\Uf007a' */
  "󰁻", /* '\Uf007b' */
  "󰁼", /* '\Uf007c' */
  "󰁽", /* '\Uf007d' */
  "󰁾", /* '\Uf007e' */
  "󰁿", /* '\Uf007f' */
  "󰂀", /* '\Uf0080' */
  "󰂁", /* '\Uf0081' */
  "󰂂", /* '\Uf0082' */
  "󰁹", /* '\Uf0079' */
};

// Converts milliseconds to nanoseconds
#define MSEC(msec) (msec * 1000 * 1000)
static struct element statusbar[] = {
  /* Add status elements here */
  /*{element_function, {seconds, nanoseconds}, {0}, {0}},*/

  {get_net_link_status,        {15, 0}, {0}, {0}},
  {get_battery0_status,        {60, 0}, {0}, {0}},
  {get_battery1_status,        {60, 0}, {0}, {0}},
  { get_all_bat_status,        {60, 0}, {0}, {0}},
  {               date, {7, MSEC(500)}, {0}, {0}},
};

// surely noone has more than 8 interfaces.
struct interface_status interfaces[8];

/* Functions */
void
date(char* buf) {
  time_t now = time(NULL);
  struct tm *tm = localtime(&now);

  strftime(buf, ELEMENT_STRBUF_SZ, "%Y-%m-%d %H:%M", tm);
}

struct battery_status
get_battery_status(const char* buf) {
  const char path_prefix[] = "/sys/class/power_supply/";

  char charge_path[128];
  char capacity_path[128];

  char charge_str[512];
  char capacity_str[512];

  int charge   = 0;
  int capacity = 0;

  FILE* bat_charge;
  FILE* bat_capacity;

  memset(charge_path, 0, 128);
  memset(capacity_path, 0, 128);

  strcat(charge_path, path_prefix);
  strcat(charge_path, buf);
  strcat(charge_path, "/energy_now");

  strcat(capacity_path, path_prefix);
  strcat(capacity_path, buf);
  strcat(capacity_path, "/energy_full");

  bat_charge   = fopen(charge_path, "r");
  bat_capacity = fopen(capacity_path, "r");

  if (!bat_charge) {
    printf("%d: \"%s\" %s\n", errno, charge_path, strerror(errno));
    return (struct battery_status){bat_unknown, -1};
  }
  if (!bat_capacity) {
    printf("%d: \"%s\" %s\n", errno, capacity_path, strerror(errno));
    return (struct battery_status){bat_unknown, -1};
  }

  fread(charge_str, sizeof(char), 512, bat_charge);
  fread(capacity_str, sizeof(char), 512, bat_capacity);

  fclose(bat_charge);
  fclose(bat_capacity);

  charge   = atoi(charge_str);
  capacity = atoi(capacity_str);

  return (struct battery_status){bat_unknown, (float)charge / capacity};
}

void
get_battery1_status(char* buf) {
  struct battery_status s = get_battery_status("BAT1");

  int batlvl              = (int)(s.charge * 100.f) / 10;
  char* batlvl_icon       = battery_level_icon[batlvl];

  snprintf(buf, ELEMENT_STRBUF_SZ, "%s %.1f%%", batlvl_icon, 100.f * s.charge);
}

void
get_battery0_status(char* buf) {
  struct battery_status s = get_battery_status("BAT0");

  int batlvl              = (int)(s.charge * 100.f) / 10;
  char* batlvl_icon       = battery_level_icon[batlvl];

  snprintf(buf, ELEMENT_STRBUF_SZ, "%s %.1f%%", batlvl_icon, 100.f * s.charge);
}

/* todo, remake this to enumerate all possible batteries */
void
get_all_bat_status(char* buf) {
  struct battery_status s = get_battery_status("BAT0");
  struct battery_status t = get_battery_status("BAT1");

  s.charge                = (s.charge + t.charge) / 2.f;

  int batlvl              = (int)(s.charge * 100.f) / 10;
  char* batlvl_icon       = battery_level_icon[batlvl];

  /*snprintf(buf, ELEMENT_STRBUF_SZ, "%.1f%%", 100.f * s.charge);*/
  snprintf(buf, ELEMENT_STRBUF_SZ, "%s %.1f%%", batlvl_icon, 100.f * s.charge);
}

void
get_essid(char* if_name, char* dst) {
  /* Get the SSID */
  struct iwreq wreq;
  const size_t if_namelen = strlen(if_name) - 1;
  const size_t l          = if_namelen > IFNAMSIZ ? IFNAMSIZ : if_namelen;
  int sock                = socket(AF_INET, SOCK_DGRAM, 0);

  if (sock == -1) {
    return;
  }

  memset(&wreq, 0, sizeof(struct iwreq));

  if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, if_name, l) == -1) {
    close(sock);
    return;
  }

  strncpy(wreq.ifr_name, if_name, l);

  wreq.u.essid.pointer = dst;
  wreq.u.essid.length  = IW_ESSID_MAX_SIZE;

  // Test if we have wireless on this interface
  if (ioctl(sock, SIOCGIWNAME, &wreq) != -1) {
    // protocol stored in  wreq.u.name
    close(sock);
    return;
  }

  if (ioctl(sock, SIOCGIWESSID, &wreq) < 0) {
    dst[0] = '\0';
  }

  close(sock);
}

void
get_net_link_status(char* buf) {
  struct ifaddrs* if_addr;
  size_t n = 0;
  size_t c = 0;

  getifaddrs(&if_addr);

  while (c < 8 && strlen(interfaces[c].name) > 0) {
    c++;
  }

  for (struct ifaddrs* ifa = if_addr; ifa != NULL; ifa = ifa->ifa_next) {
    size_t i         = 0;
    const char* name = ifa->ifa_name;

    while (i < c && strcmp(name, interfaces[i].name))
      i++;

    /* We're not interested in interfaces that are not "up" */
    if (!(ifa->ifa_flags & IFF_LOWER_UP)) {
      const size_t status_sz = sizeof(struct interface_status);

      /* Remove it from the list */
      if (i < c) {
        /* Don't memmove if last element */
        if (c - i > 1) {
          memmove(&interfaces[i], &interfaces[i + 1], status_sz * (c - i));
        }

        /* "wipe" last element */
        memset(&interfaces[c - 1], 0, status_sz);

        c--;
      }
      continue;
    }

    /* Ignore loopback interface flag */
    if (ifa->ifa_flags & IFF_LOOPBACK)
      continue;

    ///* Ignore interfaces without an address */
    // if (ifa->ifa_addr == NULL)
    //   continue;

    ///* Ignore everythings not an IPv4 link */
    ///* (AF_PACKET might be usefull if you want to display tx) */
    // if (ifa->ifa_addr->sa_family != AF_INET)
    //   continue;

    /* Find the interface in status, if it exists */
    struct interface_status s; // = &status[c];
    memset(&s, 0, sizeof(struct interface_status));

    s = interfaces[i];

    if (ifa->ifa_addr != NULL) {
      const int family = ifa->ifa_addr->sa_family;

      size_t strsize   = 0;
      char* dst        = NULL;

      if (family == AF_INET) {
        strsize = INET_ADDRSTRLEN;
        dst     = s.address.ip4;
      } else if (family == AF_INET6) {
        strsize = INET6_ADDRSTRLEN;
        dst     = s.address.ip6;
      } else if (family == AF_PACKET) {
        continue;
      } else
        /* In this case, there's probably something horribly wrong */
        continue;

      /* Get the IP address */
      inet_ntop(family, (void*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr,
                dst, strsize);
    }

    // Get the ESSID
    get_essid(s.name, s.ssid);

    /* if we got nothing out of it, don't increment */
    if (ifa->ifa_addr == NULL && strlen(s.ssid) == 0)
      continue;

    /* If the interface didn't exist in interfaces before, we should add
     * the name:) */
    if (i == c) {
      strncpy(s.name, name, IFNAMSIZ);
      c++;
    }

    memcpy(&interfaces[i], &s, sizeof(struct interface_status));
  }
  freeifaddrs(if_addr);

  memset(buf, 0, ELEMENT_STRBUF_SZ);
  for (size_t i = 0; i < c; i++) {
    struct interface_status* s = &interfaces[i];
    // Write the status string to the output buffer
    size_t namelen = strlen(s->name);

    /* test the size */
    if (namelen + n >= ELEMENT_STRBUF_SZ)
      return;

    memcpy(buf + n, s->name, namelen);
    n += namelen;

    if (n >= ELEMENT_STRBUF_SZ)
      return;
    size_t ssid_len = strlen(s->ssid);
    if (ssid_len > 0) {
      buf[n++] = ' ';
      buf[n++] = '(';
      strncpy(buf + n, s->ssid, ssid_len);
      n += ssid_len;

      buf[n++] = ')';
    }

    //{ // Add the addresses
    //  const size_t addr4_len = strlen(s->address.ip4);
    //  if (addr4_len > 0) {
    //    buf[n++] = ' ';
    //    strncat(buf + n, s->address.ip4, addr4_len);
    //    n += addr4_len;
    //  }

    //  const size_t addr6_len = strlen(s->address.ip6);
    //  if (addr6_len > 0) {
    //    buf[n++] = ' ';
    //    strncat(buf + n, s->address.ip6, addr6_len);
    //    n += addr6_len;
    //  }
    //}

    if (i != c - 1) {
      strncat(buf + n, "  ", 3);
      n += 2;
    }
  }
}

static struct timespec
time_add(struct timespec a, struct timespec b) {
  struct timespec dst;
  dst.tv_sec  = a.tv_sec + b.tv_sec;
  dst.tv_nsec = a.tv_nsec + b.tv_nsec;

  /* larger than 1 second in μsec */
  if (dst.tv_nsec >= 1000000 * 1000) {
    dst.tv_nsec -= 1000000 * 1000;
    dst.tv_sec++;
  }

  return dst;
}

/* Assume that time_t and time64_t are signed (they are on my machine) */
static struct timespec
time_sub(struct timespec a, struct timespec b) {
  struct timespec dst;

  dst.tv_sec  = a.tv_sec - b.tv_sec;
  dst.tv_nsec = a.tv_nsec - b.tv_nsec;

  if (dst.tv_nsec < 0) {
    dst.tv_nsec += 1000000 * 1000;
    dst.tv_sec--;
  }

  return dst;
}

static bool
time_lt(struct timespec a, struct timespec b) {
  if (a.tv_sec == b.tv_sec) {
    return a.tv_nsec < b.tv_nsec;
  }

  return a.tv_sec < b.tv_sec;
}

int
main(void) {
  const int num_elems = sizeof(statusbar) / sizeof(statusbar[0]);
  struct timespec now;
  const struct timespec one_minute = {60, 0};

  memset(interfaces, 0, sizeof(struct interface_status[8]));

  while (true) {
    clock_gettime(CLOCK_REALTIME, &now);
    unsigned i;

    /* Stall updating for at most 1 minute */
    struct timespec next_update = time_add(now, one_minute);

    for (i = 0; i < num_elems; i++) {
      struct element* e = &statusbar[i];
      // Next time this element updates
      struct timespec next_fire = time_add(e->fire_previous, e->fire_interval);

      /* test if this is not to be updated yet */
      if (time_lt(now, next_fire)) {
        /* test if this element is to be updated next */
        if (time_lt(next_fire, next_update)) {
          next_update = next_fire;
        }
        continue;
      }

      /* Otherwise update this element */
      memset(e->buf, 0, ELEMENT_STRBUF_SZ);

      e->f(statusbar[i].buf);
      e->fire_previous = now;

      /* Check if this element needs to be refreshed next, again */
      next_fire = time_add(now, e->fire_interval);
      if (time_lt(next_fire, next_update)) {
        next_update = next_fire;
      }

      /* printf("[%ld.%ld]  %s\n",
       * e->fire_interval.tv_sec,
       * e->fire_interval.tv_nsec,
       * (char*)e->buf);
       */
    }

    /* Copy the statusbar buffers into the final buffer */
    char buf[STATUS_STRBUF_SZ];
    memset(buf, 0, STATUS_STRBUF_SZ);

    for (i = 0; i < num_elems; i++) {
      if (!strlen(statusbar[i].buf))
        continue;

      strcat(buf, statusbar[i].buf);
      if (i != num_elems - 1)
        strcat(buf, ELEMENT_SEPERATOR);
    }

    /* strcat(buf, "\0"); */

    puts(buf);
    fflush(stdout);

    struct timespec sleep_for = time_sub(next_update, now);
    sleep_for                 = time_add(sleep_for, (struct timespec){0, 500});

    /* Replace NULL to get "remaining time", in case we got
     * interrupted / signaled */
    nanosleep(&sleep_for, NULL);
  }

  return 0;
}