1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2 * vim: ts=4 sw=4 noet ai cindent syntax=c
4 * Conky, a system monitor, based on torsmo
6 * Any original torsmo code is licensed under the BSD license
8 * All code written since the fork of torsmo is licensed under the GPL
10 * Please see COPYING for details
12 * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
13 * Copyright (c) 2007 Toni Spets
14 * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
16 * All rights reserved.
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 #include "temphelper.h"
43 #include <sys/types.h>
44 #include <sys/sysinfo.h>
46 #ifndef HAVE_CLOCK_GETTIME
51 // #include <assert.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <linux/sockios.h>
60 #include <arpa/inet.h>
64 #include <linux/route.h>
68 /* The following ifdefs were adapted from gkrellm */
69 #include <linux/major.h>
71 #if !defined(MD_MAJOR)
75 #if !defined(LVM_BLK_MAJOR)
76 #define LVM_BLK_MAJOR 58
79 #if !defined(NBD_MAJOR)
87 #include <dbus/dbus.h>
97 #define SHORTSTAT_TEMPL "%*s %llu %llu %llu"
98 #define LONGSTAT_TEMPL "%*s %llu %llu %llu "
100 /* This flag tells the linux routines to use the /proc system where possible,
101 * even if other api's are available, e.g. sysinfo() or getloadavg().
102 * the reason for this is to allow for /proc-based distributed monitoring.
103 * using a flag in this manner creates less confusing code. */
104 static int prefer_proc = 0;
106 void prepare_update(void)
110 int update_uptime(void)
114 struct sysinfo s_info;
117 info.uptime = (double) s_info.uptime;
124 if (!(fp = open_file("/proc/uptime", &rep))) {
128 fscanf(fp, "%lf", &info.uptime);
134 int check_mount(char *s)
137 FILE *mtab = fopen("/etc/mtab", "r");
140 char buf1[256], buf2[128];
142 while (fgets(buf1, 256, mtab)) {
143 sscanf(buf1, "%*s %128s", buf2);
144 if (!strcmp(s, buf2)) {
151 NORM_ERR("Could not open mtab");
156 /* these things are also in sysinfo except Buffers:
157 * (that's why I'm reading them from proc) */
159 int update_meminfo(void)
164 /* unsigned int a; */
167 info.mem = info.memmax = info.swap = info.swapfree = info.swapmax = info.bufmem =
168 info.buffers = info.cached = info.memfree = info.memeasyfree = 0;
170 if (!(meminfo_fp = open_file("/proc/meminfo", &rep))) {
174 while (!feof(meminfo_fp)) {
175 if (fgets(buf, 255, meminfo_fp) == NULL) {
179 if (strncmp(buf, "MemTotal:", 9) == 0) {
180 sscanf(buf, "%*s %llu", &info.memmax);
181 } else if (strncmp(buf, "MemFree:", 8) == 0) {
182 sscanf(buf, "%*s %llu", &info.memfree);
183 } else if (strncmp(buf, "SwapTotal:", 10) == 0) {
184 sscanf(buf, "%*s %llu", &info.swapmax);
185 } else if (strncmp(buf, "SwapFree:", 9) == 0) {
186 sscanf(buf, "%*s %llu", &info.swapfree);
187 } else if (strncmp(buf, "Buffers:", 8) == 0) {
188 sscanf(buf, "%*s %llu", &info.buffers);
189 } else if (strncmp(buf, "Cached:", 7) == 0) {
190 sscanf(buf, "%*s %llu", &info.cached);
194 info.mem = info.memmax - info.memfree;
195 info.memeasyfree = info.memfree;
196 info.swap = info.swapmax - info.swapfree;
198 info.bufmem = info.cached + info.buffers;
204 int get_laptop_mode(void)
209 if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != NULL)
210 fscanf(fp, "%d\n", &val);
216 * # cat /sys/block/sda/queue/scheduler
217 * noop [anticipatory] cfq
219 char *get_ioscheduler(char *disk)
225 return strndup("n/a", text_buffer_size);
227 snprintf(buf, 127, "/sys/block/%s/queue/scheduler", disk);
228 if ((fp = fopen(buf, "r")) == NULL) {
229 return strndup("n/a", text_buffer_size);
232 fscanf(fp, "%127s", buf);
234 buf[strlen(buf) - 1] = '\0';
236 return strndup(buf + 1, text_buffer_size);
240 return strndup("n/a", text_buffer_size);
249 #define COND_FREE(x) if(x) free(x); x = 0
250 #define SAVE_SET_STRING(x, y) \
251 if (x && strcmp((char *)x, (char *)y)) { \
253 x = strndup("multiple", text_buffer_size); \
255 x = strndup(y, text_buffer_size); \
258 void update_gateway_info_failure(const char *reason)
263 //2 pointers to 1 location causes a crash when we try to free them both
264 gw_info.iface = strndup("failed", text_buffer_size);
265 gw_info.ip = strndup("failed", text_buffer_size);
269 /* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT */
270 #define RT_ENTRY_FORMAT "%63s %lx %lx %x %*d %*d %*d %lx %*d %*d %*d\n"
272 int update_gateway_info(void)
277 unsigned long dest, gate, mask;
280 COND_FREE(gw_info.iface);
281 COND_FREE(gw_info.ip);
284 if ((fp = fopen("/proc/net/route", "r")) == NULL) {
285 update_gateway_info_failure("fopen()");
289 /* skip over the table header line, which is always present */
290 fscanf(fp, "%*[^\n]\n");
293 if(fscanf(fp, RT_ENTRY_FORMAT,
294 iface, &dest, &gate, &flags, &mask) != 5) {
295 update_gateway_info_failure("fscanf()");
298 if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate) ) {
300 SAVE_SET_STRING(gw_info.iface, iface)
302 SAVE_SET_STRING(gw_info.ip, inet_ntoa(ina))
309 void free_gateway_info(void)
315 memset(&gw_info, 0, sizeof(gw_info));
318 int gateway_exists(void)
320 return !!gw_info.count;
323 void print_gateway_iface(char *p, int p_max_size)
325 snprintf(p, p_max_size, "%s", gw_info.iface);
328 void print_gateway_ip(char *p, int p_max_size)
330 snprintf(p, p_max_size, "%s", gw_info.ip);
333 int update_net_stats(void)
337 static char first = 1;
339 // FIXME: arbitrary size chosen to keep code simple.
341 unsigned int curtmp1, curtmp2;
348 // wireless info variables
349 int skfd, has_bitrate = 0;
350 struct wireless_info *winfo;
355 delta = current_update_time - last_update_time;
356 if (delta <= 0.0001) {
360 /* open file and ignore first two lines */
361 if (!(net_dev_fp = open_file("/proc/net/dev", &rep))) {
366 fgets(buf, 255, net_dev_fp); /* garbage */
367 fgets(buf, 255, net_dev_fp); /* garbage (field names) */
369 /* read each interface */
370 for (i2 = 0; i2 < MAX_NET_INTERFACES; i2++) {
374 long long r, t, last_recv, last_trans;
376 if (fgets(buf, 255, net_dev_fp) == NULL) {
380 while (isspace((int) *p)) {
386 while (*p && *p != ':') {
395 ns = get_net_stat(s, NULL, NULL);
397 memset(&(ns->addr.sa_data), 0, 14);
399 memset(ns->addrs, 0, 17 * MAX_NET_INTERFACES + 1); /* Up to 17 chars per ip, max MAX_NET_INTERFACES interfaces. Nasty memory usage... */
401 last_recv = ns->recv;
402 last_trans = ns->trans;
404 /* bytes packets errs drop fifo frame compressed multicast|bytes ... */
405 sscanf(p, "%lld %*d %*d %*d %*d %*d %*d %*d %lld",
408 /* if recv or trans is less than last time, an overflow happened */
409 if (r < ns->last_read_recv) {
412 ns->recv += (r - ns->last_read_recv);
414 ns->last_read_recv = r;
416 if (t < ns->last_read_trans) {
419 ns->trans += (t - ns->last_read_trans);
421 ns->last_read_trans = t;
423 /*** ip addr patch ***/
424 i = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
426 conf.ifc_buf = malloc(sizeof(struct ifreq) * MAX_NET_INTERFACES);
427 conf.ifc_len = sizeof(struct ifreq) * MAX_NET_INTERFACES;
428 memset(conf.ifc_buf, 0, conf.ifc_len);
430 ioctl((long) i, SIOCGIFCONF, &conf);
432 for (k = 0; k < conf.ifc_len / sizeof(struct ifreq); k++) {
433 struct net_stat *ns2;
435 if (!(((struct ifreq *) conf.ifc_buf) + k))
439 ((struct ifreq *) conf.ifc_buf)[k].ifr_ifrn.ifrn_name, NULL, NULL);
440 ns2->addr = ((struct ifreq *) conf.ifc_buf)[k].ifr_ifru.ifru_addr;
441 sprintf(temp_addr, "%u.%u.%u.%u, ",
442 ns2->addr.sa_data[2] & 255,
443 ns2->addr.sa_data[3] & 255,
444 ns2->addr.sa_data[4] & 255,
445 ns2->addr.sa_data[5] & 255);
446 if(NULL == strstr(ns2->addrs, temp_addr))
447 strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17);
454 /*** end ip addr patch ***/
457 /* calculate speeds */
458 ns->net_rec[0] = (ns->recv - last_recv) / delta;
459 ns->net_trans[0] = (ns->trans - last_trans) / delta;
466 #pragma omp parallel for reduction(+:curtmp1, curtmp2) schedule(dynamic,10)
467 #endif /* HAVE_OPENMP */
468 for (i = 0; i < info.net_avg_samples; i++) {
469 curtmp1 = curtmp1 + ns->net_rec[i];
470 curtmp2 = curtmp2 + ns->net_trans[i];
472 ns->recv_speed = curtmp1 / (double) info.net_avg_samples;
473 ns->trans_speed = curtmp2 / (double) info.net_avg_samples;
474 if (info.net_avg_samples > 1) {
476 #pragma omp parallel for schedule(dynamic,10)
477 #endif /* HAVE_OPENMP */
478 for (i = info.net_avg_samples; i > 1; i--) {
479 ns->net_rec[i - 1] = ns->net_rec[i - 2];
480 ns->net_trans[i - 1] = ns->net_trans[i - 2];
485 /* update wireless info */
486 winfo = malloc(sizeof(struct wireless_info));
487 memset(winfo, 0, sizeof(struct wireless_info));
489 skfd = iw_sockets_open();
490 if (iw_get_basic_config(skfd, s, &(winfo->b)) > -1) {
492 // set present winfo variables
493 if (iw_get_stats(skfd, s, &(winfo->stats),
494 &winfo->range, winfo->has_range) >= 0) {
495 winfo->has_stats = 1;
497 if (iw_get_range_info(skfd, s, &(winfo->range)) >= 0) {
498 winfo->has_range = 1;
500 if (iw_get_ext(skfd, s, SIOCGIWAP, &wrq) >= 0) {
501 winfo->has_ap_addr = 1;
502 memcpy(&(winfo->ap_addr), &(wrq.u.ap_addr), sizeof(sockaddr));
506 if (iw_get_ext(skfd, s, SIOCGIWRATE, &wrq) >= 0) {
507 memcpy(&(winfo->bitrate), &(wrq.u.bitrate), sizeof(iwparam));
508 iw_print_bitrate(ns->bitrate, 16, winfo->bitrate.value);
513 if (winfo->has_range && winfo->has_stats
514 && ((winfo->stats.qual.level != 0)
515 || (winfo->stats.qual.updated & IW_QUAL_DBM))) {
516 if (!(winfo->stats.qual.updated & IW_QUAL_QUAL_INVALID)) {
517 ns->link_qual = winfo->stats.qual.qual;
518 ns->link_qual_max = winfo->range.max_qual.qual;
523 if (winfo->has_ap_addr) {
524 iw_sawap_ntop(&winfo->ap_addr, ns->ap);
528 if (winfo->b.has_essid) {
529 if (winfo->b.essid_on) {
530 snprintf(ns->essid, 32, "%s", winfo->b.essid);
532 snprintf(ns->essid, 32, "off/any");
536 snprintf(ns->mode, 16, "%s", iw_operation_mode[winfo->b.mode]);
538 iw_sockets_close(skfd);
550 int update_total_processes(void)
553 struct dirent *entry;
558 if (!(dir = opendir("/proc"))) {
561 while ((entry = readdir(dir))) {
563 /* Problem reading list of processes */
568 if (sscanf(entry->d_name, "%d%c", &ignore1, &ignore2) == 1) {
576 int update_threads(void)
580 struct sysinfo s_info;
583 info.threads = s_info.procs;
590 if (!(fp = open_file("/proc/loadavg", &rep))) {
594 fscanf(fp, "%*f %*f %*f %*d/%hu", &info.threads);
600 #define CPU_SAMPLE_COUNT 15
602 unsigned long long cpu_user;
603 unsigned long long cpu_system;
604 unsigned long long cpu_nice;
605 unsigned long long cpu_idle;
606 unsigned long long cpu_iowait;
607 unsigned long long cpu_irq;
608 unsigned long long cpu_softirq;
609 unsigned long long cpu_steal;
610 unsigned long long cpu_total;
611 unsigned long long cpu_active_total;
612 unsigned long long cpu_last_total;
613 unsigned long long cpu_last_active_total;
614 double cpu_val[CPU_SAMPLE_COUNT];
616 static short cpu_setup = 0;
618 /* Determine if this kernel gives us "extended" statistics information in
620 * Kernels around 2.5 and earlier only reported user, system, nice, and
621 * idle values in proc stat.
622 * Kernels around 2.6 and greater report these PLUS iowait, irq, softirq,
624 void determine_longstat(char *buf)
626 unsigned long long iowait = 0;
628 KFLAG_SETOFF(KFLAG_IS_LONGSTAT);
629 /* scanf will either return -1 or 1 because there is only 1 assignment */
630 if (sscanf(buf, "%*s %*d %*d %*d %*d %llu", &iowait) > 0) {
631 KFLAG_SETON(KFLAG_IS_LONGSTAT);
635 void get_cpu_count(void)
641 if (info.cpu_usage) {
645 if (!(stat_fp = open_file("/proc/stat", &rep))) {
651 while (!feof(stat_fp)) {
652 if (fgets(buf, 255, stat_fp) == NULL) {
656 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3])) {
657 if (info.cpu_count == 0) {
658 determine_longstat(buf);
663 info.cpu_usage = malloc((info.cpu_count + 1) * sizeof(float));
668 #define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
669 #define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu"
671 int update_stat(void)
675 static struct cpu_info *cpu = NULL;
680 const char *stat_template = NULL;
681 unsigned int malloc_cpu_size = 0;
682 extern void* global_cpu;
684 static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER;
685 static double last_stat_update = 0.0;
687 /* since we use wrappers for this function, the update machinery
688 * can't eliminate double invocations of this function. Check for
689 * them here, otherwise cpu_usage counters are freaking out. */
690 pthread_mutex_lock(&last_stat_update_mutex);
691 if (last_stat_update == current_update_time) {
692 pthread_mutex_unlock(&last_stat_update_mutex);
695 last_stat_update = current_update_time;
696 pthread_mutex_unlock(&last_stat_update_mutex);
698 /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
699 if (!cpu_setup || !info.cpu_usage) {
704 if (!stat_template) {
706 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT;
710 malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
711 cpu = malloc(malloc_cpu_size);
712 memset(cpu, 0, malloc_cpu_size);
716 if (!(stat_fp = open_file("/proc/stat", &rep))) {
717 info.run_threads = 0;
718 if (info.cpu_usage) {
719 memset(info.cpu_usage, 0, info.cpu_count * sizeof(float));
725 while (!feof(stat_fp)) {
726 if (fgets(buf, 255, stat_fp) == NULL) {
730 if (strncmp(buf, "procs_running ", 14) == 0) {
731 sscanf(buf, "%*s %hu", &info.run_threads);
732 } else if (strncmp(buf, "cpu", 3) == 0) {
734 if (isdigit(buf[3])) {
735 idx = atoi(&buf[3]) + 1;
739 sscanf(buf, stat_template, &(cpu[idx].cpu_user),
740 &(cpu[idx].cpu_nice), &(cpu[idx].cpu_system),
741 &(cpu[idx].cpu_idle), &(cpu[idx].cpu_iowait),
742 &(cpu[idx].cpu_irq), &(cpu[idx].cpu_softirq),
743 &(cpu[idx].cpu_steal));
745 cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice +
746 cpu[idx].cpu_system + cpu[idx].cpu_idle +
747 cpu[idx].cpu_iowait + cpu[idx].cpu_irq +
748 cpu[idx].cpu_softirq + cpu[idx].cpu_steal;
750 cpu[idx].cpu_active_total = cpu[idx].cpu_total -
751 (cpu[idx].cpu_idle + cpu[idx].cpu_iowait);
753 delta = current_update_time - last_update_time;
755 if (delta <= 0.001) {
759 cpu[idx].cpu_val[0] = (cpu[idx].cpu_active_total -
760 cpu[idx].cpu_last_active_total) /
761 (float) (cpu[idx].cpu_total - cpu[idx].cpu_last_total);
764 #pragma omp parallel for reduction(+:curtmp) schedule(dynamic,10)
765 #endif /* HAVE_OPENMP */
766 for (i = 0; i < info.cpu_avg_samples; i++) {
767 curtmp = curtmp + cpu[idx].cpu_val[i];
769 /* TESTING -- I've removed this, because I don't think it is right.
770 * You shouldn't divide by the cpu count here ...
771 * removing for testing */
773 info.cpu_usage[idx] = curtmp / info.cpu_avg_samples /
776 info.cpu_usage[idx] = curtmp / info.cpu_avg_samples;
778 /* TESTING -- this line replaces the prev. "suspect" if/else */
779 info.cpu_usage[idx] = curtmp / info.cpu_avg_samples;
781 cpu[idx].cpu_last_total = cpu[idx].cpu_total;
782 cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total;
784 #pragma omp parallel for schedule(dynamic,10)
785 #endif /* HAVE_OPENMP */
786 for (i = info.cpu_avg_samples - 1; i > 0; i--) {
787 cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1];
795 int update_running_processes(void)
801 int update_cpu_usage(void)
807 int update_load_average(void)
809 #ifdef HAVE_GETLOADAVG
814 info.loadavg[0] = (float) v[0];
815 info.loadavg[1] = (float) v[1];
816 info.loadavg[2] = (float) v[2];
823 if (!(fp = open_file("/proc/loadavg", &rep))) {
824 info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0;
827 fscanf(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1],
834 /***********************************************************/
835 /***********************************************************/
836 /***********************************************************/
838 static int no_dots(const struct dirent *d)
840 if (d->d_name[0] == '.') {
846 static int get_first_file_in_a_directory(const char *dir, char *s, int *rep)
848 struct dirent **namelist;
851 n = scandir(dir, &namelist, no_dots, alphasort);
854 NORM_ERR("scandir for %s: %s", dir, strerror(errno));
865 strncpy(s, namelist[0]->d_name, 255);
869 #pragma omp parallel for schedule(dynamic,10)
870 #endif /* HAVE_OPENMP */
871 for (i = 0; i < n; i++) {
880 static int open_sysfs_sensor(const char *dir, const char *dev, const char *type, int n,
881 int *divisor, char *devtype)
888 memset(buf, 0, sizeof(buf));
890 /* if device is NULL or *, get first */
891 if (dev == NULL || strcmp(dev, "*") == 0) {
894 if (!get_first_file_in_a_directory(dir, buf, &rep)) {
900 if (strcmp(dir, "/sys/class/hwmon/") == 0) {
902 /* buf holds result from get_first_file_in_a_directory() above,
903 * e.g. "hwmon0" -- append "/device" */
904 strcat(buf, "/device");
906 /* dev holds device number N as a string,
907 * e.g. "0", -- convert to "hwmon0/device" */
908 sprintf(buf, "hwmon%s/device", dev);
913 /* change vol to in, tempf to temp */
914 if (strcmp(type, "vol") == 0) {
916 } else if (strcmp(type, "tempf") == 0) {
921 snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
923 /* first, attempt to open file in /device */
924 fd = open(path, O_RDONLY);
927 /* if it fails, strip the /device from dev and attempt again */
928 buf[strlen(buf) - 7] = 0;
929 snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
930 fd = open(path, O_RDONLY);
932 CRIT_ERR(NULL, NULL, "can't open '%s': %s\nplease check your device or remove this "
933 "var from "PACKAGE_NAME, path, strerror(errno));
937 strncpy(devtype, path, 255);
939 if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0
940 || strcmp(type, "tempf") == 0) {
945 /* fan does not use *_div as a read divisor */
946 if (strcmp("fan", type) == 0) {
950 /* test if *_div file exist, open it and use it as divisor */
951 if (strcmp(type, "tempf") == 0) {
952 snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n);
954 snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n);
957 divfd = open(path, O_RDONLY);
963 divn = read(divfd, divbuf, 63);
964 /* should read until n == 0 but I doubt that kernel will give these
965 * in multiple pieces. :) */
967 NORM_ERR("open_sysfs_sensor(): can't read from sysfs");
970 *divisor = atoi(divbuf);
978 static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type)
986 lseek(*fd, 0, SEEK_SET);
992 n = read(*fd, buf, 63);
993 /* should read until n == 0 but I doubt that kernel will give these
994 * in multiple pieces. :) */
996 NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype);
1005 *fd = open(devtype, O_RDONLY);
1007 NORM_ERR("can't open '%s': %s", devtype, strerror(errno));
1010 /* My dirty hack for computing CPU value
1011 * Filedil, from forums.gentoo.org */
1012 /* if (strstr(devtype, "temp1_input") != NULL) {
1013 return -15.096 + 1.4893 * (val / 1000.0);
1016 /* divide voltage and temperature by 1000 */
1017 /* or if any other divisor is given, use that */
1018 if (strcmp(type, "tempf") == 0) {
1020 return ((val / divisor + 40) * 9.0 / 5) - 40;
1021 } else if (divisor) {
1022 return ((val / 1000.0 + 40) * 9.0 / 5) - 40;
1024 return ((val + 40) * 9.0 / 5) - 40;
1028 return val / divisor;
1029 } else if (divisor) {
1030 return val / 1000.0;
1037 #define HWMON_RESET() {\
1042 static void parse_sysfs_sensor(struct text_object *obj, const char *arg, const char *path, const char *type)
1044 char buf1[64], buf2[64];
1045 float factor, offset;
1049 if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) found = 1; else HWMON_RESET();
1050 if (!found && sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) found = 1; else if (!found) HWMON_RESET();
1051 if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) found = 1; else if (!found) HWMON_RESET();
1052 if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) found = 1; else if (!found) HWMON_RESET();
1055 NORM_ERR("i2c failed to parse arguments");
1056 obj->type = OBJ_text;
1059 DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, offset);
1060 sf = malloc(sizeof(struct sysfs));
1061 memset(sf, 0, sizeof(struct sysfs));
1062 sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n,
1063 &sf->arg, sf->devtype);
1064 strncpy(sf->type, buf2, 63);
1065 sf->factor = factor;
1066 sf->offset = offset;
1067 obj->data.opaque = sf;
1070 #define PARSER_GENERATOR(name, path) \
1071 void parse_##name##_sensor(struct text_object *obj, const char *arg) \
1073 parse_sysfs_sensor(obj, arg, path, #name); \
1076 PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/")
1077 PARSER_GENERATOR(hwmon, "/sys/class/hwmon/")
1078 PARSER_GENERATOR(platform, "/sys/bus/platform/devices/")
1080 void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size)
1083 struct sysfs *sf = obj->data.opaque;
1088 r = get_sysfs_info(&sf->fd, sf->arg,
1089 sf->devtype, sf->type);
1091 r = r * sf->factor + sf->offset;
1093 if (!strncmp(sf->type, "temp", 4)) {
1094 temp_print(p, p_max_size, r, TEMP_CELSIUS);
1095 } else if (r >= 100.0 || r == 0) {
1096 snprintf(p, p_max_size, "%d", (int) r);
1098 snprintf(p, p_max_size, "%.1f", r);
1102 void free_sysfs_sensor(struct text_object *obj)
1104 struct sysfs *sf = obj->data.opaque;
1110 free(obj->data.opaque);
1111 obj->data.opaque = NULL;
1114 #define CPUFREQ_PREFIX "/sys/devices/system/cpu"
1115 #define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq"
1117 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
1118 char get_freq(char *p_client_buffer, size_t client_buffer_size,
1119 const char *p_format, int divisor, unsigned int cpu)
1127 if (!p_client_buffer || client_buffer_size <= 0 || !p_format
1133 char current_freq_file[128];
1135 snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1,
1137 f = fopen(current_freq_file, "r");
1139 /* if there's a cpufreq /sys node, read the current frequency from
1140 * this node and divide by 1000 to get Mhz. */
1141 if (fgets(s, sizeof(s), f)) {
1142 s[strlen(s) - 1] = '\0';
1143 freq = strtod(s, NULL);
1146 snprintf(p_client_buffer, client_buffer_size, p_format,
1147 (freq / 1000) / divisor);
1152 // open the CPU information file
1153 f = open_file("/proc/cpuinfo", &rep);
1155 perror(PACKAGE_NAME": Failed to access '/proc/cpuinfo' at get_freq()");
1160 while (fgets(s, sizeof(s), f) != NULL) {
1162 #if defined(__i386) || defined(__x86_64)
1163 // and search for the cpu mhz
1164 if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) {
1166 #if defined(__alpha)
1167 // different on alpha
1168 if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) {
1170 // this is different on ppc for some reason
1171 if (strncmp(s, "clock", 5) == 0 && cpu == 0) {
1172 #endif // defined(__alpha)
1173 #endif // defined(__i386) || defined(__x86_64)
1175 // copy just the number
1176 strcpy(frequency, strchr(s, ':') + 2);
1177 #if defined(__alpha)
1179 frequency[strlen(frequency) - 6] = '\0';
1180 // kernel reports in Hz
1181 freq = strtod(frequency, NULL) / 1000000;
1184 frequency[strlen(frequency) - 1] = '\0';
1185 freq = strtod(frequency, NULL);
1189 if (strncmp(s, "processor", 9) == 0) {
1196 snprintf(p_client_buffer, client_buffer_size, p_format,
1197 (float) freq / divisor);
1201 #define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages"
1203 /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something
1213 * Peter Tarjan (ptarjan@citromail.hu) */
1215 /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */
1216 static char get_voltage(char *p_client_buffer, size_t client_buffer_size,
1217 const char *p_format, int divisor, unsigned int cpu)
1223 char current_freq_file[128];
1226 /* build the voltage file name */
1228 snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
1231 if (!p_client_buffer || client_buffer_size <= 0 || !p_format
1236 /* read the current cpu frequency from the /sys node */
1237 f = fopen(current_freq_file, "r");
1239 if (fgets(s, sizeof(s), f)) {
1240 s[strlen(s) - 1] = '\0';
1241 freq = strtod(s, NULL);
1245 fprintf(stderr, PACKAGE_NAME": Failed to access '%s' at ", current_freq_file);
1246 perror("get_voltage()");
1253 snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
1256 /* use the current cpu frequency to find the corresponding voltage */
1257 f = fopen(current_freq_file, "r");
1263 if (fgets(line, 255, f) == NULL) {
1266 sscanf(line, "%d %d", &freq_comp, &voltage);
1267 if (freq_comp == freq) {
1273 fprintf(stderr, PACKAGE_NAME": Failed to access '%s' at ", current_freq_file);
1274 perror("get_voltage()");
1280 snprintf(p_client_buffer, client_buffer_size, p_format,
1281 (float) voltage / divisor);
1285 void print_voltage_mv(struct text_object *obj, char *p, int p_max_size)
1289 ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i);
1293 void print_voltage_v(struct text_object *obj, char *p, int p_max_size)
1297 ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i);
1301 #define ACPI_FAN_DIR "/proc/acpi/fan/"
1303 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
1310 if (!p_client_buffer || client_buffer_size <= 0) {
1314 /* yeah, slow... :/ */
1315 if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) {
1316 snprintf(p_client_buffer, client_buffer_size, "no fans?");
1320 snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf);
1322 fp = open_file(buf2, &rep);
1324 snprintf(p_client_buffer, client_buffer_size,
1325 "can't open fan's state file");
1328 memset(buf, 0, sizeof(buf));
1329 fscanf(fp, "%*s %99s", buf);
1332 snprintf(p_client_buffer, client_buffer_size, "%s", buf);
1335 #define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply"
1336 #define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/"
1337 /* Linux 2.6.25 onwards ac adapter info is in
1338 /sys/class/power_supply/AC/
1339 On my system I get the following.
1340 /sys/class/power_supply/AC/uevent:
1341 PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00
1344 POWER_SUPPLY_NAME=AC
1345 POWER_SUPPLY_TYPE=Mains
1346 POWER_SUPPLY_ONLINE=1
1348 Update: it seems the folder name is hardware-dependent. We add an aditional adapter
1349 argument, specifying the folder name.
1351 Update: on some systems it's /sys/class/power_supply/ADP1 instead of /sys/class/power_supply/AC
1354 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, const char *adapter)
1363 if (!p_client_buffer || client_buffer_size <= 0) {
1368 snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, adapter);
1370 snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR);
1371 if(stat(buf2, &sb) == -1) snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR);
1373 if(stat(buf2, &sb) == 0) fp = open_file(buf2, &rep); else fp = 0;
1375 /* sysfs processing */
1377 if (fgets(buf, sizeof(buf), fp) == NULL)
1380 if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) {
1382 sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online);
1383 snprintf(p_client_buffer, client_buffer_size,
1384 "%s-line", (online ? "on" : "off"));
1390 /* yeah, slow... :/ */
1391 if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) {
1392 snprintf(p_client_buffer, client_buffer_size, "no ac_adapters?");
1396 snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf);
1398 fp = open_file(buf2, &rep);
1400 snprintf(p_client_buffer, client_buffer_size,
1401 "No ac adapter found.... where is it?");
1404 memset(buf, 0, sizeof(buf));
1405 fscanf(fp, "%*s %99s", buf);
1408 snprintf(p_client_buffer, client_buffer_size, "%s", buf);
1413 /proc/acpi/thermal_zone/THRM/cooling_mode
1414 cooling mode: active
1415 /proc/acpi/thermal_zone/THRM/polling_frequency
1417 /proc/acpi/thermal_zone/THRM/state
1419 /proc/acpi/thermal_zone/THRM/temperature
1421 /proc/acpi/thermal_zone/THRM/trip_points
1423 passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0
1426 #define ACPI_THERMAL_DIR "/proc/acpi/thermal_zone/"
1427 #define ACPI_THERMAL_FORMAT "/proc/acpi/thermal_zone/%s/temperature"
1429 int open_acpi_temperature(const char *name)
1435 if (name == NULL || strcmp(name, "*") == 0) {
1438 if (!get_first_file_in_a_directory(ACPI_THERMAL_DIR, buf, &rep)) {
1444 snprintf(path, 255, ACPI_THERMAL_FORMAT, name);
1446 fd = open(path, O_RDONLY);
1448 NORM_ERR("can't open '%s': %s", path, strerror(errno));
1454 static double last_acpi_temp;
1455 static double last_acpi_temp_time;
1457 double get_acpi_temperature(int fd)
1463 /* don't update acpi temperature too often */
1464 if (current_update_time - last_acpi_temp_time < 11.32) {
1465 return last_acpi_temp;
1467 last_acpi_temp_time = current_update_time;
1469 /* seek to beginning */
1470 lseek(fd, 0, SEEK_SET);
1477 n = read(fd, buf, 255);
1479 NORM_ERR("can't read fd %d: %s", fd, strerror(errno));
1482 sscanf(buf, "temperature: %lf", &last_acpi_temp);
1486 return last_acpi_temp;
1490 hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info
1492 design capacity: 4400 mAh
1493 last full capacity: 4064 mAh
1494 battery technology: rechargeable
1495 design voltage: 14800 mV
1496 design capacity warning: 300 mAh
1497 design capacity low: 200 mAh
1498 capacity granularity 1: 32 mAh
1499 capacity granularity 2: 32 mAh
1501 serial number: 16922
1507 hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state
1510 charging state: unknown
1512 remaining capacity: 4064 mAh
1513 present voltage: 16608 mV
1517 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm
1518 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ?
1519 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�)
1520 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm
1521 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ?
1523 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman verkkovirtaa
1524 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? verkkovirralla
1526 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja monitori p��ll�
1527 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? monitori p��ll� mutta ilman verkkovirtaa
1530 /* Kapil Hari Paranjape <kapil@imsc.res.in>
1531 Linux 2.6.24 onwards battery info is in
1532 /sys/class/power_supply/BAT0/
1533 On my system I get the following.
1534 /sys/class/power_supply/BAT0/uevent:
1535 PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00
1537 PHYSDEVDRIVER=battery
1538 POWER_SUPPLY_NAME=BAT0
1539 POWER_SUPPLY_TYPE=Battery
1540 POWER_SUPPLY_STATUS=Discharging
1541 POWER_SUPPLY_PRESENT=1
1542 POWER_SUPPLY_TECHNOLOGY=Li-ion
1543 POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000
1544 POWER_SUPPLY_VOLTAGE_NOW=10780000
1545 POWER_SUPPLY_CURRENT_NOW=13970000
1546 POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000
1547 POWER_SUPPLY_ENERGY_FULL=27370000
1548 POWER_SUPPLY_ENERGY_NOW=11810000
1549 POWER_SUPPLY_MODEL_NAME=IBM-92P1060
1550 POWER_SUPPLY_MANUFACTURER=Panasonic
1551 On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_*
1554 /*on n900 with power kernel: (non power kernel could use "hal-device bme" and do something else)
1555 /sys/class/power_supply/bq27200-0/uevent
1556 PHYSDEVPATH=/class/i2c-adapter/i2c-2/2-0055
1558 PHYSDEVDRIVER=bq27200-battery
1559 POWER_SUPPLY_NAME=bq27200-0
1560 POWER_SUPPLY_TYPE=Battery
1561 POWER_SUPPLY_PRESENT=1 << this is always 1, it means the battery is inserted
1562 POWER_SUPPLY_VOLTAGE_NOW=4039 << this keeps updating during charging, both here and in dbus
1563 POWER_SUPPLY_CURRENT_NOW=1960 << this goes negative when charging!
1564 POWER_SUPPLY_CAPACITY=98 << supposed to be the %, it keeps updating while charging, unlike the dbus vals that freeze
1565 POWER_SUPPLY_TEMP=39 << only temperature sensor in n900 :(
1568 #define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply"
1569 #define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" //not for n900
1570 #define APM_PATH "/proc/apm" //not for n900
1571 #define MAX_BATTERY_COUNT 4 //more like 1
1573 static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1574 //static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1575 //static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1577 static int batteries_initialized = 0;
1578 static char batteries[MAX_BATTERY_COUNT][32];
1580 //static int acpi_last_full[MAX_BATTERY_COUNT];
1581 //static int acpi_design_capacity[MAX_BATTERY_COUNT];
1584 static int last_battery_volts[MAX_BATTERY_COUNT];
1587 static unsigned char last_cell_radio_dbm;
1590 static unsigned char last_cell_radio_percent;
1592 //eg 'full' 'on' 'off'
1593 static char last_batt_charge_status[16];
1596 static int last_battery_temp[MAX_BATTERY_COUNT];
1598 /* e.g. "charging 75%" */
1599 static char last_battery_str[MAX_BATTERY_COUNT][64];
1601 static char last_battery_time_str[MAX_BATTERY_COUNT][64];
1603 static double last_battery_time[MAX_BATTERY_COUNT];
1605 static int last_battery_perct[MAX_BATTERY_COUNT];
1606 static double last_battery_perct_time[MAX_BATTERY_COUNT];
1608 void init_batteries(void)
1612 if (batteries_initialized) {
1616 #pragma omp parallel for schedule(dynamic,10)
1617 #endif /* HAVE_OPENMP */
1618 for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1619 batteries[idx][0] = '\0';
1621 batteries_initialized = 1;
1624 int get_battery_idx(const char *bat)
1628 // for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1629 // if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) {
1634 // /* if not found, enter a new entry */
1635 // if (!strlen(batteries[idx])) {
1636 // snprintf(batteries[idx], 31, "%s", bat);
1642 static int dbus_queue = 0;
1644 void set_dbus_retval(char *buffer, unsigned int n, int item);
1646 DBusConnection *connection;
1648 DBusMessage *message;
1649 DBusMessageIter iter;
1654 void get_dbus_stuff(char *buffer,unsigned int intMax_length, int item)
1660 if (dbus_queue > 10)
1662 fprintf (stderr, "too much dbus queuing\n");
1664 // set_dbus_retval(buffer, intMax_length, item);
1667 dbus_queue++;//prevent a queue from forming on these requests...
1668 //fetch data from dbus, store in here as last_cell_radio_dbm
1669 //return into buffer
1671 type = DBUS_BUS_SYSTEM;
1672 message_type = DBUS_MESSAGE_TYPE_METHOD_CALL;
1673 // print_reply = TRUE;
1674 // print_reply_literal = FALSE;
1675 int reply_timeout_ms = 5000;
1676 dbus_error_init (&error);
1677 connection = dbus_bus_get (type, &error);
1678 if (connection == NULL)
1680 fprintf (stderr, "Failed to open connection to %s message bus: %s\n",
1681 (type == DBUS_BUS_SYSTEM) ? "system" : "session",
1683 dbus_error_free (&error);
1688 snprintf(method,127,"get_signal_strength");
1689 snprintf(path,127,"/com/nokia/phone/net");
1690 snprintf(dest,127,"com.nokia.phone.net");
1691 message = dbus_message_new_method_call (dest,path,"Phone.Net",method);
1692 dbus_message_set_auto_start (message, TRUE);
1694 case DBUS_CELL_PERCENT:
1695 snprintf(method,127,"get_signal_strength");
1696 snprintf(path,127,"/com/nokia/phone/net");
1697 snprintf(dest,127,"com.nokia.phone.net");
1698 message = dbus_message_new_method_call (dest,path,"Phone.Net",method);
1699 dbus_message_set_auto_start (message, TRUE);
1701 case DBUS_HAL_BATTERY_CHRG_STATUS:
1702 // 'full' 'on' 'off'
1703 snprintf(method,127,"GetProperty");
1704 args = "maemo.rechargeable.charging_status";
1705 snprintf(path,127,"/org/freedesktop/Hal/devices/bme");
1706 snprintf(dest,127,"org.freedesktop.Hal");
1707 message = dbus_message_new_method_call (dest,path,"org.freedesktop.Hal.Device",method);
1708 dbus_message_set_auto_start (message, TRUE);
1709 dbus_message_iter_init_append(message, &iter);
1710 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args))
1711 fprintf (stderr, "OOM appending args\n");
1713 case DBUS_HAL_BATTERY_PERCENT:
1715 snprintf(method,127,"GetProperty");
1716 args = "battery.charge_level.percentage";
1717 snprintf(path,127,"/org/freedesktop/Hal/devices/bme");
1718 snprintf(dest,127,"org.freedesktop.Hal");
1719 message = dbus_message_new_method_call (dest,path,"org.freedesktop.Hal.Device",method);
1720 dbus_message_set_auto_start (message, TRUE);
1721 dbus_message_iter_init_append(message, &iter);
1722 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args))
1723 fprintf (stderr, "OOM appending args\n");
1725 case DBUS_HAL_BATTERY_VOLTS_CURRENT:
1727 snprintf(method,127,"GetProperty");
1728 args = "battery.voltage.current";
1729 snprintf(path,127,"/org/freedesktop/Hal/devices/bme");
1730 snprintf(dest,127,"org.freedesktop.Hal");
1731 message = dbus_message_new_method_call (dest,path,"org.freedesktop.Hal.Device",method);
1732 dbus_message_set_auto_start (message, TRUE);
1733 dbus_message_iter_init_append(message, &iter);
1734 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args))
1735 fprintf (stderr, "OOM appending args\n");
1738 fprintf (stderr, "invalid item type in get_dbus_stuff");
1741 if (message == NULL)
1743 fprintf (stderr, "Couldn't allocate D-Bus message\n");
1746 if (!dbus_message_set_destination (message, dest))
1748 fprintf (stderr, "Not enough memory\n");
1752 dbus_error_init (&error);
1753 reply = dbus_connection_send_with_reply_and_block (connection, message, reply_timeout_ms, &error);
1754 if (dbus_error_is_set (&error))
1756 fprintf (stderr, "Error %s: %s\n",error.name,error.message);
1757 //exit (1);//if we set timeout to 30s or something i guess it's okay to exit on "no reply" cuz something is fu*ked;
1761 DBusMessageIter iter;
1762 dbus_message_iter_init (reply, &iter);
1763 //int type = dbus_message_iter_get_arg_type(&iter);
1764 int current_fieldnumber = 0;
1765 while (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INVALID)
1767 //fprintf (stderr,"dbus-monitor too dumb to decipher arg type '%c'\n", type);
1768 current_fieldnumber++;
1771 if (current_fieldnumber == 2)
1774 dbus_message_iter_get_basic(&iter, &val);
1775 last_cell_radio_dbm = val;
1778 case DBUS_CELL_PERCENT:
1779 if (current_fieldnumber == 1)
1782 dbus_message_iter_get_basic(&iter, &val);
1783 last_cell_radio_percent = val;
1786 case DBUS_HAL_BATTERY_CHRG_STATUS:
1787 if (current_fieldnumber == 1)
1790 dbus_message_iter_get_basic(&iter, &val);
1791 snprintf(last_batt_charge_status,16,"%s",val);
1794 case DBUS_HAL_BATTERY_PERCENT:
1795 if (current_fieldnumber == 1)
1798 dbus_message_iter_get_basic(&iter, &val);
1799 last_battery_perct[0] = val;
1802 case DBUS_HAL_BATTERY_VOLTS_CURRENT:
1803 if (current_fieldnumber == 1)
1806 dbus_message_iter_get_basic(&iter, &val);
1807 last_battery_volts[0] = val;
1811 fprintf (stderr, "invalid item type in get_dbus_stuff reply loop");
1814 dbus_message_iter_next (&iter);
1816 dbus_message_unref (reply);
1818 set_dbus_retval(buffer, intMax_length, item);
1819 dbus_message_unref (message);
1820 dbus_connection_unref (connection);
1821 dbus_queue = 0;//reset to zero now that complete
1824 void set_dbus_retval(char *buffer, unsigned int intMax_length, int item)
1828 snprintf(buffer, intMax_length, "%d", last_cell_radio_dbm);
1830 case DBUS_CELL_PERCENT:
1831 snprintf(buffer, intMax_length, "%d", last_cell_radio_percent);
1833 case DBUS_HAL_BATTERY_CHRG_STATUS:
1834 snprintf(buffer, intMax_length, "%s", last_batt_charge_status);
1836 case DBUS_HAL_BATTERY_PERCENT:
1837 snprintf(buffer, intMax_length, "%i", last_battery_perct[0]);
1839 case DBUS_HAL_BATTERY_VOLTS_CURRENT:
1840 snprintf(buffer, intMax_length, "%i", last_battery_volts[0]);
1843 fprintf (stderr, "invalid item type in set_dbus_retval");
1848 void set_return_value(char *buffer, unsigned int n, int item, int idx);
1850 void get_battery_stuff(char *buffer, unsigned int n, const char *bat, int item)
1852 static int idx, rep = 0;
1853 char acpi_path[128];
1854 char sysfs_path[128];
1856 snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
1857 snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
1861 idx = get_battery_idx(bat);
1863 /* don't update battery too often */
1864 if (current_update_time - last_battery_time[idx] < 29.5) {
1865 set_return_value(buffer, n, item, idx);
1869 last_battery_time[idx] = current_update_time;
1871 memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx]));
1872 memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx]));
1874 /* first try SYSFS if that fails try DBUS */
1876 if (sysfs_bat_fp[idx] == NULL) {
1877 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
1880 if (sysfs_bat_fp[idx] != NULL) {
1882 int present_rate = -9999; //we will put "current now" into this. negative when charging!
1883 int remaining_capacity = -1; //in %
1884 char charging_state[64];//can't get this without hal bme
1888 strcpy(present, "no");
1889 strcpy(charging_state, "unknown");
1891 while (!feof(sysfs_bat_fp[idx])) {
1892 //we are looping through the data here
1894 if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
1896 if (strncmp (buf, "POWER_SUPPLY_PRESENT=1", 22) == 0)//does current row match this?
1897 strcpy(present, "yes");//n900 always yes
1898 else if (strncmp(buf, "POWER_SUPPLY_VOLTAGE_NOW=", 25) == 0)//keep checking possible matches
1899 sscanf(buf, "POWER_SUPPLY_VOLTAGE_NOW=%d", &voltage);
1900 else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0)
1901 sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate);
1902 else if (strncmp(buf, "POWER_SUPPLY_CAPACITY=", 22) == 0)
1903 sscanf(buf, "POWER_SUPPLY_CAPACITY=%d", &remaining_capacity);
1904 else if (strncmp(buf, "POWER_SUPPLY_TEMP=", 18) == 0)
1905 sscanf(buf, "POWER_SUPPLY_TEMP=%d", &temp);
1907 fclose(sysfs_bat_fp[idx]);
1908 sysfs_bat_fp[idx] = NULL;
1910 last_battery_volts[idx] = voltage;
1911 last_battery_temp[idx] = temp;
1914 if (present_rate <= 0) {
1915 /* e.g. charging 75% */
1916 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %i%%", remaining_capacity);
1917 snprintf(last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, "unknown");
1920 else if (present_rate > 0) {
1921 /* e.g. discharging 35% */
1922 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "discharging %i%%", remaining_capacity);
1923 snprintf(last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, "unknown");
1926 if (remaining_capacity == 100)
1927 strcpy(last_battery_str[idx], "charged 100%");
1929 //if don't have power kernel, use HAL / dbus
1930 int remaining_capacity = -1; //in %
1932 remaining_capacity = get_battery_perct(bat);
1933 get_dbus_stuff(buffer,n,DBUS_HAL_BATTERY_VOLTS_CURRENT);
1934 get_dbus_stuff(buffer,n,DBUS_HAL_BATTERY_CHRG_STATUS);
1935 if (strncmp(buffer, "on", 2) == 0) {
1936 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %i%%", remaining_capacity);
1938 else if (strncmp(buffer, "off", 3) == 0) {
1939 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "discharging %i%%", remaining_capacity);
1941 else if (strncmp(buffer, "full", 4) == 0) {//no, it won't always be 100%. stupid dbus.
1942 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charged %i%%", remaining_capacity);
1944 last_battery_temp[idx] = temp;
1946 set_return_value(buffer, n, item, idx);
1949 void set_return_value(char *buffer, unsigned int n, int item, int idx)
1952 case BATTERY_STATUS:
1953 snprintf(buffer, n, "%s", last_battery_str[idx]);
1956 snprintf(buffer, n, "%s", last_battery_time_str[idx]);
1959 snprintf(buffer, n, "%i", last_battery_volts[idx]); // voltage
1962 snprintf(buffer, n, "%i", last_battery_temp[idx]); // temperature
1965 fprintf (stderr, "invalid item type in set_return_value");
1970 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
1972 get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
1973 if (0 == strncmp("charging", buffer, 8)) {
1975 memmove(buffer + 1, buffer + 8, n - 8);
1976 } else if (0 == strncmp("discharging", buffer, 11)) {
1978 memmove(buffer + 1, buffer + 11, n - 11);
1979 } else if (0 == strncmp("charged", buffer, 7)) {
1981 memmove(buffer + 1, buffer + 7, n - 7);
1982 } else if (0 == strncmp("not present", buffer, 11)) {
1984 memmove(buffer + 1, buffer + 11, n - 11);
1985 } else if (0 == strncmp("empty", buffer, 5)) {
1987 memmove(buffer + 1, buffer + 5, n - 5);
1988 } else if (0 != strncmp("AC", buffer, 2)) {
1990 memmove(buffer + 1, buffer + 11, n - 11);
1991 } else fprintf (stderr, "invalid input buffer in get_battery_short_status");
1994 int get_battery_perct(const char *bat)
1998 char sysfs_path[128];
1999 int remaining_capacity = -1;
2000 snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
2003 idx = get_battery_idx(bat);
2005 /* don't update battery too often */
2006 if (current_update_time - last_battery_perct_time[idx] < 29.5) {
2007 return last_battery_perct[idx];
2009 last_battery_perct_time[idx] = current_update_time;
2011 /* try SYSFS first */
2012 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
2013 if (sysfs_bat_fp[idx] != NULL) {
2015 while (!feof(sysfs_bat_fp[idx])) {
2017 if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
2019 if (strncmp(buf, "POWER_SUPPLY_CAPACITY=", 22) == 0) {
2020 sscanf(buf, "POWER_SUPPLY_CAPACITY=%d", &remaining_capacity);
2022 // if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) {
2023 // sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
2024 // } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=",25) == 0) {
2025 // sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]);
2026 // } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) {
2027 // sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
2028 // } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=",25) == 0) {
2029 // sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]);
2033 fclose(sysfs_bat_fp[idx]);
2034 sysfs_bat_fp[idx] = NULL;
2035 last_battery_perct[idx] = remaining_capacity;
2041 useless = malloc(128 * sizeof(char));
2042 get_dbus_stuff(useless,128,DBUS_HAL_BATTERY_PERCENT);
2043 //i told you it's useless...
2044 //snprintf(last_battery_perct[idx], 127, "%i", useless);
2045 //guess what? dbus battery % doesn't update while charging
2046 // get_dbus_stuff(useless,n,DBUS_HAL_BATTERY_CHRG_STATUS);
2047 // if (strncmp(useless, "full", 4) == 0)
2052 // else if (acpi_bat_fp[idx] != NULL) {
2054 // /* read last full capacity if it's zero */
2055 // if (acpi_design_capacity[idx] == 0) {
2060 // snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
2061 // fp = open_file(path, &rep2);
2062 // if (fp != NULL) {
2063 // while (!feof(fp)) {
2066 // if (fgets(b, 256, fp) == NULL) {
2069 // if (sscanf(b, "last full capacity: %d",
2070 // &acpi_design_capacity[idx]) != 0) {
2078 // fseek(acpi_bat_fp[idx], 0, SEEK_SET);
2080 // while (!feof(acpi_bat_fp[idx])) {
2083 // if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
2087 // if (buf[0] == 'r') {
2088 // sscanf(buf, "remaining capacity: %d", &remaining_capacity);
2093 /* compute the battery percentage */
2095 //(int) (((float) remaining_capacity / acpi_design_capacity[idx]) * 100);
2096 //if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100;
2097 return last_battery_perct[idx];
2100 int get_battery_perct_bar(const char *bat)
2104 get_battery_perct(bat);
2105 idx = get_battery_idx(bat);
2106 return (int) (last_battery_perct[idx] * 2.56 - 1);
2109 /* On Apple powerbook and ibook:
2110 $ cat /proc/pmu/battery_0
2117 $ cat /proc/pmu/info
2118 PMU driver version : 2
2119 PMU firmware version : 0c
2124 /* defines as in <linux/pmu.h> */
2125 #define PMU_BATT_PRESENT 0x00000001
2126 #define PMU_BATT_CHARGING 0x00000002
2128 static FILE *pmu_battery_fp;
2129 static FILE *pmu_info_fp;
2130 static char pb_battery_info[3][32];
2131 static double pb_battery_info_update;
2133 #define PMU_PATH "/proc/pmu"
2134 void get_powerbook_batt_info(char *buffer, size_t n, int i)
2137 const char *batt_path = PMU_PATH "/battery_0";
2138 const char *info_path = PMU_PATH "/info";
2140 int charge, max_charge, ac = -1;
2143 /* don't update battery too often */
2144 if (current_update_time - pb_battery_info_update < 29.5) {
2145 snprintf(buffer, n, "%s", pb_battery_info[i]);
2148 pb_battery_info_update = current_update_time;
2150 if (pmu_battery_fp == NULL) {
2151 pmu_battery_fp = open_file(batt_path, &rep);
2152 if (pmu_battery_fp == NULL) {
2157 if (pmu_battery_fp != NULL) {
2158 rewind(pmu_battery_fp);
2159 while (!feof(pmu_battery_fp)) {
2162 if (fgets(buf, sizeof(buf), pmu_battery_fp) == NULL) {
2166 if (buf[0] == 'f') {
2167 sscanf(buf, "flags : %8x", &flags);
2168 } else if (buf[0] == 'c' && buf[1] == 'h') {
2169 sscanf(buf, "charge : %d", &charge);
2170 } else if (buf[0] == 'm') {
2171 sscanf(buf, "max_charge : %d", &max_charge);
2172 } else if (buf[0] == 't') {
2173 sscanf(buf, "time rem. : %ld", &timeval);
2177 if (pmu_info_fp == NULL) {
2178 pmu_info_fp = open_file(info_path, &rep);
2179 if (pmu_info_fp == NULL) {
2184 if (pmu_info_fp != NULL) {
2185 rewind(pmu_info_fp);
2186 while (!feof(pmu_info_fp)) {
2189 if (fgets(buf, sizeof(buf), pmu_info_fp) == NULL) {
2192 if (buf[0] == 'A') {
2193 sscanf(buf, "AC Power : %d", &ac);
2197 /* update status string */
2198 if ((ac && !(flags & PMU_BATT_PRESENT))) {
2199 strncpy(pb_battery_info[PB_BATT_STATUS], "AC", sizeof(pb_battery_info[PB_BATT_STATUS]));
2200 } else if (ac && (flags & PMU_BATT_PRESENT)
2201 && !(flags & PMU_BATT_CHARGING)) {
2202 strncpy(pb_battery_info[PB_BATT_STATUS], "charged", sizeof(pb_battery_info[PB_BATT_STATUS]));
2203 } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) {
2204 strncpy(pb_battery_info[PB_BATT_STATUS], "charging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2206 strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2209 /* update percentage string */
2210 if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT)
2211 && !(flags & PMU_BATT_CHARGING)) {
2212 snprintf(pb_battery_info[PB_BATT_PERCENT],
2213 sizeof(pb_battery_info[PB_BATT_PERCENT]), "100%%");
2214 } else if (timeval == 0) {
2215 snprintf(pb_battery_info[PB_BATT_PERCENT],
2216 sizeof(pb_battery_info[PB_BATT_PERCENT]), "unknown");
2218 snprintf(pb_battery_info[PB_BATT_PERCENT],
2219 sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%",
2220 (charge * 100) / max_charge);
2223 /* update time string */
2224 if (timeval == 0) { /* fully charged or battery not present */
2225 snprintf(pb_battery_info[PB_BATT_TIME],
2226 sizeof(pb_battery_info[PB_BATT_TIME]), "unknown");
2227 } else if (timeval < 60 * 60) { /* don't show secs */
2228 format_seconds_short(pb_battery_info[PB_BATT_TIME],
2229 sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2231 format_seconds(pb_battery_info[PB_BATT_TIME],
2232 sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2235 snprintf(buffer, n, "%s", pb_battery_info[i]);
2238 int update_top(void)
2240 process_find_top(info.cpu, info.memu, info.time
2245 info.first_process = get_first_process();
2249 #define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail"
2251 int get_entropy_avail(unsigned int *val)
2256 if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep)))
2259 if (fscanf(fp, "%u", val) != 1)
2266 #define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize"
2268 int get_entropy_poolsize(unsigned int *val)
2273 if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep)))
2276 if (fscanf(fp, "%u", val) != 1)
2283 const char *get_disk_protect_queue(const char *disk)
2289 snprintf(path, 127, "/sys/block/%s/device/unload_heads", disk);
2290 if (access(path, F_OK)) {
2291 snprintf(path, 127, "/sys/block/%s/queue/protect", disk);
2293 if ((fp = fopen(path, "r")) == NULL)
2295 if (fscanf(fp, "%d\n", &state) != 1) {
2300 return (state > 0) ? "frozen" : "free ";
2303 typedef struct DEV_LIST_TYPE
2307 struct DEV_LIST_TYPE *next;
2309 } DEV_LIST, *DEV_LIST_PTR;
2311 /* Same as sf #2942117 but memoized using a linked list */
2312 int is_disk(char *dev)
2314 char syspath[PATH_MAX];
2316 static DEV_LIST_PTR dev_head = NULL;
2317 DEV_LIST_PTR dev_cur, dev_last;
2322 if (strcmp(dev_cur->dev_name, dev) == 0)
2323 return dev_cur->memoized;
2325 dev_cur = dev_cur->next;
2328 dev_cur = (DEV_LIST_PTR)malloc(sizeof(DEV_LIST));
2329 dev_cur->dev_name = (char *)malloc((strlen(dev)+1)*sizeof(char));
2330 strcpy(dev_cur->dev_name,dev);
2331 dev_cur->next = NULL;
2333 while ((slash = strchr(dev, '/')))
2335 snprintf(syspath, sizeof(syspath), "/sys/block/%s", dev);
2336 dev_cur->memoized = !(access(syspath, F_OK));
2339 dev_last->next = dev_cur;
2343 return dev_cur->memoized;
2346 int update_diskio(void)
2350 char buf[512], devbuf[64];
2351 unsigned int major, minor;
2353 struct diskio_stat *cur;
2354 unsigned int reads, writes;
2355 unsigned int total_reads = 0, total_writes = 0;
2358 stats.current_read = 0;
2359 stats.current_write = 0;
2361 if (!(fp = open_file("/proc/diskstats", &rep))) {
2365 /* read reads and writes from all disks (minor = 0), including cd-roms
2366 * and floppies, and sum them up */
2367 while (fgets(buf, 512, fp)) {
2368 col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major,
2369 &minor, devbuf, &reads, &writes);
2370 /* ignore subdevices (they have only 3 matching entries in their line)
2371 * and virtual devices (LVM, network block devices, RAM disks, Loopback)
2373 * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */
2374 if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR
2375 && major != RAMDISK_MAJOR && major != LOOP_MAJOR) {
2376 /* check needed for kernel >= 2.6.31, see sf #2942117 */
2377 if (is_disk(devbuf)) {
2378 total_reads += reads;
2379 total_writes += writes;
2382 col_count = sscanf(buf, "%u %u %s %*u %u %*u %u",
2383 &major, &minor, devbuf, &reads, &writes);
2384 if (col_count != 5) {
2389 while (cur && strcmp(devbuf, cur->dev))
2393 update_diskio_values(cur, reads, writes);
2395 update_diskio_values(&stats, total_reads, total_writes);