Xinqi Bao's Git

Get rid of err.h as it is not portable
[slstatus.git] / components / wifi.c
index 30b57ab..500332e 100644 (file)
@@ -1,5 +1,5 @@
 /* See LICENSE file for copyright and license details. */
-#include <err.h>
+#if defined(__linux__)
 #include <ifaddrs.h>
 #include <linux/wireless.h>
 #include <sys/socket.h>
@@ -14,7 +14,9 @@
 const char *
 wifi_perc(const char *iface)
 {
-       int i, perc;
+       int i, cur;
+       float perc;
+       int total = 70; /* the max of /proc/net/wireless */
        char *p, *datastart;
        char path[PATH_MAX];
        char status[5];
@@ -23,7 +25,7 @@ wifi_perc(const char *iface)
        snprintf(path, sizeof(path), "%s%s%s", "/sys/class/net/", iface, "/operstate");
        fp = fopen(path, "r");
        if (fp == NULL) {
-               warn("Failed to open file %s", path);
+               fprintf(stderr, "Failed to open file %s", path);
                return NULL;
        }
        p = fgets(status, 5, fp);
@@ -34,7 +36,7 @@ wifi_perc(const char *iface)
 
        fp = fopen("/proc/net/wireless", "r");
        if (fp == NULL) {
-               warn("Failed to open file /proc/net/wireless");
+               fprintf(stderr, "Failed to open file /proc/net/wireless");
                return NULL;
        }
 
@@ -50,9 +52,11 @@ wifi_perc(const char *iface)
                return NULL;
 
        datastart = (datastart+(strlen(iface)+1));
-       sscanf(datastart + 1, " %*d   %d  %*d  %*d                %*d      %*d          %*d              %*d      %*d            %*d", &perc);
+       sscanf(datastart + 1, " %*d   %d  %*d  %*d                %*d      %*d          %*d              %*d      %*d            %*d", &cur);
 
-       return bprintf("%d", perc);
+       perc = (float)cur / total * 100.0;
+
+       return bprintf("%.0f", perc);
 }
 
 const char *
@@ -67,12 +71,13 @@ wifi_essid(const char *iface)
        snprintf(wreq.ifr_name, sizeof(wreq.ifr_name), "%s", iface);
 
        if (sockfd == -1) {
-               warn("Failed to get ESSID for interface %s", iface);
+               fprintf(stderr, "Failed to get ESSID for interface %s", iface);
                return NULL;
        }
        wreq.u.essid.pointer = id;
        if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
-               warn("Failed to get ESSID for interface %s", iface);
+               fprintf(stderr, "Failed to get ESSID for interface %s", iface);
+               close(sockfd);
                return NULL;
        }
 
@@ -83,3 +88,4 @@ wifi_essid(const char *iface)
        else
                return id;
 }
+#endif