I found a way of figuring out whether the mains cable is plugged in:
Code:
lshal | grep ac.adapter.present
I'm gonna check this value every 30 seconds.
If it's true, I'll do nothing.
If it's false, I'll check it again in another 30 seconds' time. If it's
still false, then I'll set the machine to hibernate.
Here's the C code I've got so far:
Code:
#include <stdio.h> /* popen, pclose, fgets */
#include <string.h> /* strchr */
#include <unistd.h> /* sleep */
int Is_AC_Unplugged(void)
{
char line[200];
/* Run the command, take one line from it, then close the opened stream */
FILE *pfile = popen("lshal | grep ac.adapter.present", "r");
fgets(line, sizeof line, pfile);
pclose(pfile);
/* Find the position of the '=' sign in the line of text */
char const *p = strchr(line,'=');
if (!p)
{
/* Dodgy reading, there's no '=' sign */
return 0;
}
/* Now check for the first 't' or 'f' after the '=' sign */
for (;;)
{
++p;
if (!*p)
{
/* We've already reached the null terminator, must be a dodgy reading! */
return 0;
}
if ( (*p == 't') || (*p == 'T') )
{
/* The power adapter is plugged in, no need to do anything */
return 0;
}
else if ( (*p == 'f') || (*p == 'F') )
{
/* Oh shit the power adapter is unplugged */
return 1;
}
}
}
void Deal_With_Unplugged_AC_Adapter(void)
{
puts("We've lost AC power. Now we wait 30 seconds to see if it's still gone.");
sleep(30);
if (!Is_AC_Unplugged())
{
/* The power must be back, abort the Hibernation */
puts("Wahey the power's back, no need to hibernate!");
return;
}
/* OK so the power is still gone, let's Hibernate */
puts("HIBERNATING. . . ");
/* Insert code here to make computer hibernate */
}
int main(void)
{
for ( ; ; sleep(30))
{
if (Is_AC_Unplugged())
{
Deal_With_Unplugged_AC_Adapter();
}
else
puts("We still have AC. . .");
}
}