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