KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility Method to Check Mac Laptop Battery
PRODUCT: 4D | VERSION: 15.x | PLATFORM: Mac OS X
Published On: July 6, 2017

Below is a utility method to check the battery life of a Mac Laptop.

// Method: Util_Get_Mac_Battery
//
// Details: Mac Only, Gets the current Machine's Battery Status
//
// Output:
// $0 - Longint
// Returns a Positive number if plugged in/charging
// Returns a Negative number if not plugged in/charging
// Number is a percentage of the current battery life
// Defaults to 0 if any errors occur

C_LONGINT($0)
C_LONGINT($result_l)

C_TEXT($in;$out;$err)
C_TEXT($cmd_t)
C_TEXT($regexPat_t)
C_LONGINT($plug_l)
C_LONGINT($charge_l)
C_LONGINT($foundPos_l)
C_LONGINT($length_l)
C_BOOLEAN($found_b)

$charge_l:=0
$in:=""
SET ENVIRONMENT VARIABLE("_4D_OPTION_HIDE_CONSOLE";"True")
$cmd_t:="pmset -g batt"
LAUNCH EXTERNAL PROCESS($cmd_t;$in;$out;$err)

If($err="")
   $regexPat_t:="AC Power"
   $found_b:=Match regex($regexPat_t;$out;1)
   If ($found_b)
      $plug_l:=1
   Else
      $plug_l:=-1
   End if

   $regexPat_t:="\d\d?\d?%"
   $found_b:=Match regex($regexPat_t;$out;1;$foundPos_l;$length_l)
   If ($found_b)
      $charge_l:=Num(Substring($out;$foundPos_l;$length_l))
   End if
End if
$0:=$charge_l*$plug_l

Example of using the method:
C_LONGINT($battery_l)
$battery_l:=Util_Get_Mac_Battery

Example Results:
100 - A fully charged plugged in laptop
-100 - A fully charged laptop running on battery
-87 - A laptop with 87% battery level running on the battery
0 - Either some error occured or the laptop is somehow at 0% battery life