Change named colors to hex values
[sysstatus.git] / src / status / cpuusage.c
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5
6 #include "common.h"
7 #include "config.h"
8
9 #ifndef NUM_CPUS
10   #define NUM_CPUS 1
11 #endif
12 #ifndef CPU_HISTORY_SIZE
13   #define CPU_HISTORY_SIZE 1
14 #endif
15 #if CPU_HISTORY_SIZE < 1
16   #define CPU_HISTORY_SIZE 1
17 #endif
18
19
20 unsigned long last_cpu_used = 0;
21 unsigned long last_cpu_total = 0;
22 float cpu_history[CPU_HISTORY_SIZE]; // don't care about init values
23
24 void status_cpuusage(GlobalData *g)
25 {
26   StatusItem s;
27   char text[32] = { 0 };
28
29   double loadavg[3] = { -13.37, -13.37, -13.37 } ;
30
31   char *stline = NULL;
32   size_t stlen;
33   FILE *stfile;
34
35   unsigned long cpu_user;
36   unsigned long cpu_nice;
37   unsigned long cpu_sys;
38   unsigned long cpu_used;
39   unsigned long cpu_idle;
40   unsigned long cpu_total;
41   int i;
42
43
44   statusitem_init(&s);
45   s.text = text;
46
47   // Error signaling color
48   s.color = "#FFFF00";  // yellow
49
50   stfile = fopen("/proc/stat", "r");
51   if (stfile != NULL) {
52     for(i = CPU_HISTORY_SIZE - 1; i > 0; i--) {
53       cpu_history[i] = cpu_history[i - 1];
54     }
55
56     stlen = getline(&stline, &stlen, stfile);
57     fclose(stfile);
58
59     if ( 4 == sscanf(stline, "%*s %ld %ld %ld %ld",
60                     &cpu_user, &cpu_nice, &cpu_sys, &cpu_idle) ) {
61       cpu_used = cpu_user + cpu_nice + cpu_sys;
62       cpu_total = cpu_used + cpu_idle;
63
64       // Now do the percentage
65       cpu_history[0] = (float)(cpu_used - last_cpu_used) /
66                         (float)(cpu_total - last_cpu_total);
67
68       last_cpu_used = cpu_used;
69       last_cpu_total = cpu_total;
70
71
72       if (cpu_history[0] < 0.4) {
73         // CPU idling OK
74         s.color = "#0077FF";
75       } else {
76         // CPU busy
77         s.color = "#FF00FF";
78       }
79     }
80
81     free(stline);
82   }
83
84
85   if (getloadavg(loadavg, 3) > 0) {
86     snprintf(text, sizeof(text),
87               "%s%.0f,%.0f,%.0f,%.0f",
88               cpu_history[0] < 0.1000 ? " " : "",
89               cpu_history[0] * 100,
90               loadavg[0] * (100 / 1),
91               loadavg[1] * (100 / 1),  // (100 / NUM_CPUS)
92               loadavg[2] * (100 / 1));
93   }
94
95   line_append_item(g, &s);
96 }