Skip to content

Instantly share code, notes, and snippets.

@nbyouri
Last active May 29, 2016 22:55
Show Gist options
  • Save nbyouri/cec6acf4567adb7a0087 to your computer and use it in GitHub Desktop.
Save nbyouri/cec6acf4567adb7a0087 to your computer and use it in GitHub Desktop.
get_battery_percentage_netbsd
/* taken from defora */
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/envsys.h>
#include <fcntl.h>
#include <paths.h>
#include <unistd.h>
static int _get_tre(int fd, int sensor, envsys_tre_data_t * tre) {
memset(tre, 0, sizeof(*tre));
tre->sensor = sensor;
if (ioctl(fd, ENVSYS_GTREDATA, tre) == -1)
return 1;
return !(tre->validflags & ENVSYS_FVALID);
}
int main (void) {
int i;
int fd = -1;
double level;
envsys_basic_info_t info;
envsys_tre_data_t tre;
unsigned int rate = 0;
unsigned int charge = 0;
unsigned int maxcharge = 0;
bool charging;
charging = false;
if(fd < 0 && (fd = open(_PATH_SYSMON, O_RDONLY)) < 0)
{
printf("%s: %s", _PATH_SYSMON,
strerror(errno));
level = -1.0;
return true;
}
for(i = 0; i >= 0; i++)
{
memset(&info, 0, sizeof(info));
info.sensor = i;
if(ioctl(fd, ENVSYS_GTREINFO, &info) == -1)
{
close(fd);
fd = -1;
printf("%s: %s", "ENVSYS_GTREINFO",
strerror(errno));
level = -1.0;
return true;
}
if(!(info.validflags & ENVSYS_FVALID))
break;
if(strncmp("acpibat", info.desc, 7) != 0
|| info.desc[7] == '\0'
|| info.desc[8] != ' ')
continue;
if(strcmp("charge", &info.desc[9]) == 0
&& _get_tre(fd, i, &tre) == 0
&& tre.validflags & ENVSYS_FCURVALID
&& tre.validflags & ENVSYS_FMAXVALID)
{
charge += tre.cur.data_us;
maxcharge += tre.max.data_us;
}
else if(strcmp("charge rate", &info.desc[9]) == 0
&& _get_tre(fd, i, &tre) == 0
&& tre.validflags & ENVSYS_FCURVALID)
rate += tre.cur.data_us;
else if(strcmp("charging", &info.desc[9]) == 0
&& _get_tre(fd, i, &tre) == 0
&& tre.validflags & ENVSYS_FCURVALID
&& tre.cur.data_us > 0)
{
charging = true;
continue;
}
else if(strcmp("discharge rate", &info.desc[9]) == 0
&& _get_tre(fd, i, &tre) == 0
&& tre.validflags & ENVSYS_FCURVALID)
rate += tre.cur.data_us;
}
level = (charge * 100.0) / maxcharge;
printf("%.f%%\n", level);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment