]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_temperature.c
Implement the i3bar JSON protocol
[i3/i3status] / src / print_cpu_temperature.c
1 // vim:ts=8:expandtab
2 #include <stdlib.h>
3 #include <limits.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include "i3status.h"
8
9 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
10 #include <err.h>
11 #include <sys/types.h>
12 #include <sys/sysctl.h>
13 #define TZ_ZEROC 2732
14 #define TZ_KELVTOC(x) (((x) - TZ_ZEROC) / 10), abs(((x) - TZ_ZEROC) % 10)
15 #endif
16
17 static char *thermal_zone;
18
19 /*
20  * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
21  * returns the temperature in degree celcius.
22  *
23  */
24 void print_cpu_temperature_info(int zone, const char *path, const char *format) {
25 #ifdef THERMAL_ZONE
26         const char *walk;
27         static char buf[16];
28
29         if (path == NULL) {
30                 asprintf(&thermal_zone, THERMAL_ZONE, zone);
31                 path = thermal_zone;
32         }
33
34         if (output_format == O_I3BAR)
35                 printf("{\"name\":\"cpu_temperature\", \"instance\": \"%s\", \"full_text\":\"", path);
36
37         for (walk = format; *walk != '\0'; walk++) {
38                 if (*walk != '%') {
39                         putchar(*walk);
40                         continue;
41                 }
42
43                 if (BEGINS_WITH(walk+1, "degrees")) {
44 #if defined(LINUX)
45                         long int temp;
46                         if (!slurp(path, buf, sizeof(buf)))
47                                 goto error;
48                         temp = strtol(buf, NULL, 10);
49                         if (temp == LONG_MIN || temp == LONG_MAX || temp <= 0)
50                                 (void)printf("?");
51                         else
52                                 (void)printf("%ld", (temp/1000));
53 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
54                         int sysctl_rslt;
55                         size_t sysctl_size = sizeof(sysctl_rslt);
56                         if (sysctlbyname(path, &sysctl_rslt, &sysctl_size, NULL, 0))
57                                 goto error;
58
59                         (void)printf("%d.%d", TZ_KELVTOC(sysctl_rslt));
60 #endif
61                         walk += strlen("degrees");
62                 }
63         }
64
65         if (output_format == O_I3BAR)
66                 printf("\"}");
67
68         return;
69 error:
70 #endif
71         (void)fputs("Cannot read temperature\n", stderr);
72 }