+#include <sys/types.h>
+#include <dirent.h>
+
+unsigned int use_acpi;
+unsigned int monitor_bat;
+unsigned int bat_percentage;
+unsigned int bat_time;
+unsigned int bat_available;
+unsigned int bat_ac;
+unsigned int bat_charging;
+unsigned int bat_full_capacity[3]; // I doubt a machine has more than 3 batteries...
+
+void update_battery_time()
+{
+ DIR *batteries, *ac_adapters;
+ struct dirent *this_battery, *this_adapter;
+ FILE *acpi;
+ char battery_state[PATH_MAX];
+ int rate = 1, remain = 0, current = 0;
+ static int total_remain = 0, total_cap = 0;
+ int batno = 0;
+ const int info_res = 5;
+ static int info_timer = 0;
+ char buf[256];
+
+ ac_adapters = opendir("/proc/acpi/ac_adapter");
+
+ while (ac_adapters != NULL && ((info_timer % info_res) == 0) &&
+ ((this_adapter = readdir(ac_adapters)) != NULL)) {
+ if (this_adapter->d_name[0] == '.')
+ continue;
+ // safe overloaded use of battery_state path var
+ snprintf(battery_state, sizeof(battery_state),
+ "/proc/acpi/ac_adapter/%s/state", this_adapter->d_name);
+ if ((acpi = fopen(battery_state, "r")) == NULL)
+ continue;
+ if (acpi != NULL) {
+ while(fgets(buf, 128, acpi)) {
+ if (strstr(buf, "on-line") != NULL)
+ bat_ac = 1;
+ else
+ bat_ac = 0;
+ }
+ fclose(acpi);
+ }
+ }
+
+ if (ac_adapters != NULL)
+ closedir(ac_adapters);
+
+ batteries = opendir("/proc/acpi/battery");
+
+ if (batteries == NULL)
+ bat_available = 0;
+ else
+ bat_available = 1;
+
+ if (!bat_available || ((info_timer % info_res) == 0)) {
+ bat_percentage = 0;
+ bat_time = 0;
+ bat_charging = 0;
+ total_remain = total_cap = 0;
+ }
+
+ while (batteries != NULL && ((info_timer % info_res) == 0) &&
+ ((this_battery = readdir(batteries)) != NULL)) {
+ if (this_battery->d_name[0] == '.')
+ continue;
+ snprintf(battery_state, sizeof(battery_state),
+ "/proc/acpi/battery/%s/state", this_battery->d_name);
+ if ((acpi = fopen(battery_state, "r")) == NULL)
+ continue;
+ while (fgets(buf, 128, acpi))
+ {
+ if (strncmp(buf, "present:", 8 ) == 0)
+ {
+ // No information for this battery
+ if (strstr(buf, "no" ))
+ continue;
+ }
+ else if (strncmp(buf, "charging state:", 15) == 0)
+ {
+ // the space makes it different than discharging
+ if (strstr(buf, " charging" ))
+ bat_charging = 1;
+ }
+ else if (strncmp(buf, "present rate:", 13) == 0)
+ rate = atoi(buf + 25);
+ else if (strncmp(buf, "remaining capacity:", 19) == 0)
+ {
+ remain = atoi(buf + 25);
+ total_remain += remain;
+ }
+ else if (strncmp(buf, "present voltage:", 17) == 0)
+ current = atoi(buf + 25);
+ }
+ total_cap += bat_full_capacity[batno];
+ fclose(acpi);
+ if (bat_charging)
+ bat_time += (((float)(bat_full_capacity[batno] - remain) /
+ rate) * 3600);
+ else
+ bat_time += (((float)(remain) / rate) * 3600);
+ batno++;
+ }
+ if (total_cap > 0)
+ bat_percentage = ((float)(total_remain) / total_cap) * 100;
+ info_timer++;
+
+ if (batteries != NULL)
+ closedir(batteries);
+}
+