]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_temperature.c
Makefile: fix PREFIX usage
[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         for (walk = format; *walk != '\0'; walk++) {
35                 if (*walk != '%') {
36                         putchar(*walk);
37                         continue;
38                 }
39
40                 if (BEGINS_WITH(walk+1, "degrees")) {
41 #if defined(LINUX)
42                         long int temp;
43                         if (!slurp(path, buf, sizeof(buf)))
44                                 goto error;
45                         temp = strtol(buf, NULL, 10);
46                         if (temp == LONG_MIN || temp == LONG_MAX || temp <= 0)
47                                 (void)printf("?");
48                         else
49                                 (void)printf("%ld", (temp/1000));
50 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
51                         int sysctl_rslt;
52                         size_t sysctl_size = sizeof(sysctl_rslt);
53                         if (sysctlbyname(path, &sysctl_rslt, &sysctl_size, NULL, 0))
54                                 goto error;
55
56                         (void)printf("%d.%d", TZ_KELVTOC(sysctl_rslt));
57 #endif
58                         walk += strlen("degrees");
59                 }
60         }
61         return;
62 error:
63 #endif
64         (void)fputs("Cannot read temperature\n", stderr);
65 }