summaryrefslogtreecommitdiff
path: root/status.c
blob: 43ccfb79276ca1396c23779926e6cf7d3e602ef3 (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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
#include <arpa/inet.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <ifaddrs.h>
#include <linux/if.h>
#include <linux/wireless.h>
#include <mqueue.h>
#include <netinet/in.h>
#include <signal.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>

#include "config.h"

/* Constants */
#define ELEMENT_SEPERATOR "   "

#define STATUS_STRBUF_SZ 512
#define ELEMENT_STRBUF_SZ 128

#define MAX(a, b) ((a) > (b) ? (a) : (b))

/* Type definitions */
typedef int(update_func_t)(char*, char*);

/* Data structures */
struct element {
  update_func_t* f;
  char* a;
  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;
  bool up;
  struct {
    char ip4[INET_ADDRSTRLEN];
    char ip6[INET6_ADDRSTRLEN];
  } address;
  char ssid[IW_ESSID_MAX_SIZE + 1];
  char name[IFNAMSIZ + 1];
};

/* Prototypes */
int element_date(char* buf, char* fmt);
struct battery_status get_battery_status(const char* buf);
int element_battery(char* buf, char* bat);
void get_all_bat_status(char* buf);
void get_net_link_status(char* buf);
int element_wifi(char* buf, char* link_name);
static void update_statusbuffer(char* buf);
int element_command(char* buf, char* command);

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

static struct element statusbar[] = {
  /* Add status elements here */
  /*{update_func_t, {minutes, seconds}, {0}, {0}},*/
  [ELEMENT_INVALID] = {NULL, NULL, {0}, {0}, {0}},

#define ELEMENT(identifier, function, arg, minutes, seconds)                   \
  [ELEMENT_##identifier] = {                                                   \
    element_##function,                                                        \
    arg,                                                                       \
    {(minutes * 60) + ((int)seconds), (long)(seconds * 1000000) % 1000000},    \
    {0},                                                                       \
    {0}},
#include "config.def.h"
#undef ELEMENT
};

static void
cleanup(void) {
  if (mq_unlink("/status") == -1) {
    fprintf(stderr, "Failed to unlink mq: %s\n", strerror(errno));
  }
}

// "fail fast strcmp", neat to find inequalities between strings
static int
ffast_strcmp(char* a, const char* const b) {
  int i = 0;

  while (a[i] == b[i]) {
    if (a[i] == '\0')
      break;
    i++;
  }

  return a[i] - b[i];
}
/* Functions */
int
element_date(char* buf, char* fmt) {
  if (fmt == NULL)
    fmt = "%Y-%m-%d %H:%M";

  time_t now    = time(NULL);
  struct tm* tm = localtime(&now);

  strftime(buf, ELEMENT_STRBUF_SZ, fmt, tm);
  return 0;
}

struct battery_status
get_battery_status(const char* buf) {
  const char path_prefix[]     = "/sys/class/power_supply/";
  struct battery_status status = {.status = bat_unknown, .charge = -1};

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

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

  int charge   = 0;
  int capacity = 0;

  FILE* bat_charge;
  FILE* bat_capacity;
  FILE* bat_status;

  memset(charge_path, 0, 128);
  memset(capacity_path, 0, 128);
  memset(status_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");

  strcat(status_path, path_prefix);
  strcat(status_path, buf);
  strcat(status_path, "/status");

  bat_charge = fopen(charge_path, "r");
  if (!bat_charge) {
    fprintf(stderr, "%d: \"%s\" %s\n", errno, charge_path, strerror(errno));
    return status;
  }

  bat_capacity = fopen(capacity_path, "r");
  if (!bat_capacity) {
    fprintf(stderr, "%d: \"%s\" %s\n", errno, capacity_path, strerror(errno));
    fclose(bat_charge);
    return status;
  }

  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);
  status.charge = (float)charge / capacity;

  // Get battery status
  bat_status = fopen(status_path, "r");
  if (!bat_status) {
    fprintf(stderr, "%d: \"%s\" %s\n", errno, status_path, strerror(errno));
    return status;
  }

  fread(status_str, sizeof(char), 512, bat_status);
  fclose(bat_status);

  // Remove trailing newline
  for (int i = 0; i < 512; i++) {
    if (status_str[i] == '\n') {
      status_str[i] = '\0';
      break;
    }
  }

  if (!strcmp(status_str, "Charging")) {
    status.status = bat_charging;
  } else if (!strcmp(status_str, "Discharging")) {
    status.status = bat_discharging;
  } else if (!strcmp(status_str, "Not charging")) {
    status.status = bat_not_charging;
  }

  return status;
}

int
element_battery(char* buf, char* bat) {
  struct battery_status s = get_battery_status(bat);

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

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

/* 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);
  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) {
    printf("Err: %s\n", strerror(errno));
    close(sock);
    return;
  }

  strncpy(wreq.ifr_name, if_name, l);

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

  // May need to open a new socket, rebind, or something in-between to get both
  // wireless capabilities and essid??

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

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

  close(sock);
}

int
element_wifi(char* buf, char* link_name) {
  struct interface_status if_status;
  struct ifaddrs* if_addr;
  struct ifaddrs* ifa;

  memset(&if_status, 0, sizeof(struct interface_status));
  const int nlen =
    strlen(link_name) > IFNAMSIZ + 1 ? IFNAMSIZ : strlen(link_name);
  strncpy(if_status.name, link_name, nlen);

  getifaddrs(&if_addr);

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

    if (ffast_strcmp(if_status.name, name))
      continue;

    if (ifa->ifa_flags & IFF_LOWER_UP) {
      if_status.up = true;

      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     = if_status.address.ip4;
        } else if (family == AF_INET6) {
          strsize = INET6_ADDRSTRLEN;
          dst     = if_status.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);
      }
    }
  }

  freeifaddrs(if_addr);

  // print interface
  if (!if_status.up)
    return 0;

  get_essid(if_status.name, if_status.ssid);

  strcat(buf, if_status.name);

  if (if_status.ssid[0] != 0) {
    strcat(buf, " (");
    strcat(buf, if_status.ssid);
    strcat(buf, ")");
  }

  return 0;
}

/* external commands */
/* I just couldn't be bothered to learn pipewire */
int
element_command(char* buf, char* command) {
  int output[2];
  if (pipe(output) == -1) {
    err(EXIT_FAILURE, "Failed to create pipe");
  }

  pid_t pid = fork();
  if (pid == -1) {
    err(EXIT_FAILURE, "Failed to fork new process");
  }

  if (!pid) {
    close(output[0]);

    // Redirect stdout to output[1]
    if (dup2(output[1], STDOUT_FILENO) == -1) {
      err(EXIT_FAILURE, "Failed to redirect stdout");
    }

    // Redirect stderr to stdout
    if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1) {
      err(EXIT_FAILURE, "Failed to redirect stderr");
    }

    size_t cmd_orig_len = strlen(command);

    if (cmd_orig_len >= 115) {
      err(EXIT_FAILURE, "Command too long");
    }

    char cmd[128] = "/usr/bin/env ";     // 13 characters
    strncat(cmd, command, 128 - 13 - 1); // copies at most 115 bytes
    size_t cmd_len = strlen(cmd);

    char* args[64];
    size_t argc  = 0;

    char escaped = '\0'; // Bloody hope there's no more nested args than 4

    // Create args from cmd
    // First arg is always the first "word"
    args[argc++] = &cmd[0];

    // Delimeter with zero-bytes at every space, except between single or double
    // quotes.
    size_t i;
    for (i = 0; i < cmd_len; i++) {
      // Reset the escaped character
      if (cmd[i] == escaped) {
        escaped = '\0';
        cmd[i]  = '\0';
        continue;
      }

      // Set escaped character
      if (!escaped && (cmd[i] == '\'' || cmd[i] == '"')) {
        escaped = cmd[i];
        // Remove the escaped character from the argument
        (args[argc - 1])++;
        continue;
      }

      // Don't insert zero-chars until we're un-escaped again
      if (escaped) {
        continue;
      }

      if (cmd[i] == ' ') {
        cmd[i]       = '\0';
        args[argc++] = &cmd[i + 1];
      }
    }

    if (i == 0) {
      err(EXIT_FAILURE, "Empty command");
    }

    // NULL terminated array
    args[argc] = NULL;

    if (execvp(args[0], args) == -1) {
      err(EXIT_FAILURE, "Failed to exec");
    }
    exit(EXIT_FAILURE);
  }

  close(output[1]);
  size_t n = 0;
  size_t m = 0;

  while (m < ELEMENT_STRBUF_SZ &&
         (n = read(output[0], &buf[m], ELEMENT_STRBUF_SZ - 1 - m)) > 0) {
    m += n;
  }

  buf[m] = '\0';

  for (size_t i = 0; buf[i] != '\0'; i++) {
    if (buf[i] == '\n')
      buf[i] = ' ';
  }

  return 0;
}

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;

  // Subtract a second if nanoseconds are negative
  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;
}

struct mq_data {
  mqd_t mqfd;
  struct timespec next_update;
  char* dstbuffer;
};

static void
update_element_thread(union sigval sv) {
  struct mq_attr attr;
  ssize_t nr;
  struct message_t msg;
  struct mq_data mq_data = *((struct mq_data*)sv.sival_ptr);

  if (mq_getattr(mq_data.mqfd, &attr) == -1) {
    fprintf(stderr, "Failed to get mq attributes: %s\n", strerror(errno));
    return;
  }

  if (attr.mq_msgsize != sizeof(struct message_t)) {
    fprintf(stderr, "Misconfigured message queue!\n");
    return;
  }

  // It is apparently the way to ensure continued notifications to register for
  // further notifications before emptying the queue.
  // Makes you wonder if you should've used a named pipe + signals instead :)
  struct sigevent sev = (struct sigevent){
    .sigev_notify            = SIGEV_THREAD,
    .sigev_notify_function   = update_element_thread,
    .sigev_notify_attributes = NULL,
    .sigev_value             = sv,
  };

  if (mq_notify(mq_data.mqfd, &sev) == -1) {
    fprintf(stderr, "Failed to register mq_notify: %s\n", strerror(errno));
  }

  // Empty queue
  while (mq_receive(mq_data.mqfd, (char*)&msg, sizeof(struct message_t),
                    NULL) != -1) {
    //fprintf(stderr, "%d on %d\n", msg.action, msg.element);
    if (msg.action != update || msg.element <= ELEMENT_INVALID ||
        msg.element > ELEMENT_MAX) {
      fprintf(stderr, "Invalid action/element\n");
      continue;
    }

    if (msg.element == ELEMENT_MAX) {
      for (int i = 1; i < ELEMENT_MAX; i++) {
        struct element* e = &statusbar[i];
        assert(e->f != NULL);
        struct timespec now;
        struct timespec next_fire;
        clock_gettime(CLOCK_REALTIME, &now);

        memset(e->buf, 0, ELEMENT_STRBUF_SZ);

        e->f(e->buf, e->a);
        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,
                    ((struct mq_data*)(sv.sival_ptr))->next_update)) {
          ((struct mq_data*)(sv.sival_ptr))->next_update = next_fire;
        }
      }
    } else {
      struct element* e = &statusbar[msg.element];
      assert(e->f != NULL);
      struct timespec now;
      struct timespec next_fire;
      clock_gettime(CLOCK_REALTIME, &now);

      memset(e->buf, 0, ELEMENT_STRBUF_SZ);

      e->f(e->buf, e->a);
      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, ((struct mq_data*)(sv.sival_ptr))->next_update)) {
        ((struct mq_data*)(sv.sival_ptr))->next_update = next_fire;
      }
    }
  }

  update_statusbuffer(mq_data.dstbuffer);

  // EAGAIN indicates the queue is empty
  if (errno != EAGAIN) {
    fprintf(stderr, "Failed to receive mq message: %s\n", strerror(errno));
  }
}

static void
update_statusbuffer(char* buf) {
  static const int num_elems = sizeof(statusbar) / sizeof(statusbar[0]);

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

  for (int i = 1; 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);
}

int
main(void) {
  char buf[STATUS_STRBUF_SZ];
  //// ("/status", max(argv[identifier], XDG_SEAT, DISPLAY, WAYLAND_DISPLAY))
  const char* queue_identifier     = "/status";
  const struct timespec one_minute = {60, 0};
  struct timespec now;
  clock_gettime(CLOCK_REALTIME, &now);

  struct mq_attr attr = {
    .mq_flags  = 0,  // ignored for mq_open
    .mq_maxmsg = 10, // must be [1;10], default value can be read from
                     // /proc/sys/fs/mqueue/msg_default
    .mq_msgsize = sizeof(struct message_t),
    .mq_curmsgs = 0, // ignored for mq_open
  };

  struct mq_data mq_data;
  mq_data.dstbuffer   = buf;
  mq_data.next_update = time_add(now, one_minute);
  ;

  mq_data.mqfd = mq_open(queue_identifier,
                         O_RDONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK,
                         // 600
                         S_IRUSR | S_IWUSR,
                         &attr); // O_NONBLOCK
  if (mq_data.mqfd == -1) {
    fprintf(stderr, "Failed to open mq: %s\n", strerror(errno));
    // Make this check a flag
    if (errno == EEXIST) {
      if (mq_unlink(queue_identifier) == -1) {
        fprintf(stderr, "Failed to unlink mq: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
      } else {
        fprintf(stderr, "Unlinked %s\n", queue_identifier);

        // Retry
        mq_data.mqfd =
          mq_open(queue_identifier,
                  O_RDONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK,
                  S_IRUSR | S_IWUSR, &attr);
        if (mq_data.mqfd == -1) {
          fprintf(stderr, "Failed to open mq: %s\n", strerror(errno));
          exit(EXIT_FAILURE);
        }
      }
    } else {
      exit(EXIT_FAILURE);
    }
  }

  atexit(&cleanup);

  // We need to run update_element_thread in the first place to make sure we
  // empty the queue
  update_element_thread((union sigval){.sival_ptr = &mq_data});

  const int num_elems = sizeof(statusbar) / sizeof(statusbar[0]);

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

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

    for (i = 1; i < num_elems; i++) {
      struct element* e = &statusbar[i];
      assert(e->f != NULL);
      // 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, mq_data.next_update)) {
          mq_data.next_update = next_fire;
        }
        continue;
      }

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

      e->f(e->buf, e->a);
      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, mq_data.next_update)) {
        mq_data.next_update = next_fire;
      }

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

    update_statusbuffer(buf);

    struct timespec sleep_for = time_sub(mq_data.next_update, now);

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

  return 0;
}