]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_temperature.c
implement the 'path' option for cpu temperature
[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         const char *walk;
26         static char buf[16];
27
28         if (path == NULL) {
29                 asprintf(&thermal_zone, THERMAL_ZONE, zone);
30                 path = thermal_zone;
31         }
32
33         for (walk = format; *walk != '\0'; walk++) {
34                 if (*walk != '%') {
35                         putchar(*walk);
36                         continue;
37                 }
38
39                 if (BEGINS_WITH(walk+1, "degrees")) {
40 #if defined(LINUX)
41                         long int temp;
42                         if (!slurp(path, buf, sizeof(buf)))
43                                 die("Could not open \"%s\"\n", path);
44                         temp = strtol(buf, NULL, 10);
45                         if (temp == LONG_MIN || temp == LONG_MAX || temp <= 0)
46                                 (void)printf("?");
47                         else
48                                 (void)printf("%ld", (temp/1000));
49 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
50                         int sysctl_rslt;
51                         size_t sysctl_size = sizeof(sysctl_rslt);
52                         if (sysctlbyname(path, &sysctl_rslt, &sysctl_size, NULL, 0)) {
53                                 (void)printf("No thermal zone found");
54                                 return;
55                         }
56
57                         (void)printf("%d.%d", TZ_KELVTOC(sysctl_rslt));
58 #endif
59                         walk += strlen("degrees");
60                 }
61         }
62 }