Pages

Monday, June 13, 2011

Programmatically Calculate Battery Charge

This is a cool way to determine what the charge of your battery is on a Mac laptop using Perl. Basically we execute the command ioreg -l in a shell and filter out all the results except MaxCapacity and CurrentCapacity, then we use regular expressions to parse out just the values. From there it's just a matter of calculating what percentage current capacity is of the max capacity and printing out the results.

#!/usr/bin/perl -w

my $MaxCapacity = `ioreg -l | grep 'MaxCapacity'`;
my $CurrentCapacity = `ioreg -l | grep 'CurrentCapacity'`;

$MaxCapacity =~ /(\d+)/;
$MaxCapacity = $1;

$CurrentCapacity =~ /(\d+)/;
$CurrentCapacity = $1;

printf("Battery Charge: %d %%" . "\n", (($CurrentCapacity / $MaxCapacity) * 100));

Executing the script produces something similar to:

Battery Charge: 90 %

If you execute this on a Mac that doesn't have a battery you will probably get a division by zero error.

No comments:

Post a Comment