#! /bin/zsh # # battery # MacOs X/Darwin command line tool showing battery status. # version 1.0 - 05/03/04 # # Inspired from the command line tool "Battery" @ http://www.mitt-eget.com/ IOREG="/usr/sbin/ioreg" # Define a global string for all the properties local IO_battery_info # Properties for each batteries local capacity1 amperage1 current1 voltage1 flags1 local capacity2 amperage2 current2 voltage2 flags2 # --- get_battery_info() { # Check if ioreg program is avaible if [ ! -x $IOREG ]; then echo "battery: can not execute $IOREG" exit 1 fi # Get batteries informations $IOREG -p IODeviceTree -n "battery" -w 0 | grep IOBatteryInfo | { read IO_battery_info IO_battery_info=${IO_battery_info:s/IOBatteryInfo/ BATTERY 1 /} IO_battery_info=${IO_battery_info:s/\}\,\{/ BATTERY 2 /} IO_battery_info="${IO_battery_info//[|\"\(\)\,\=\{\} ]/ }" } } # --- parse_battery_info() { # Get properties from IO_battery_info echo ${=IO_battery_info} | xargs -n 2 echo | while read name value; do case ${name:l} in battery) battery=$value ;; voltage|flags|amperage|capacity|current) eval ${name:l}$battery=$value ;; esac done } # --- display_info() { # Check the option to display informations case $# in 0) display_short_info ;; 1) case $1 in long|short) display_$1_info ;; *) usage ;; esac ;; *) usage ;; esac } # --- display_short_info() { typeset -F 3 capacity typeset -F 3 amperage typeset -F 3 current for i in 1 2; do # Verify if battery is installed parse_flags_info $[flags$i] 6 if [[ $? = 1 ]]; then # Verify if battery is connected parse_flags_info $[flags$i] 8 if [[ $? = 0 ]] then capacity=$[capacity$i] amperage=$[amperage$i] current=$[current$i] (( capacity /= 1000 )) (( amperage /= 1000 )) (( current /= 1000 )) # Calculate the percentage if [[ $capacity != 0.000 ]]; then typeset -i percentage (( percentage = 100 * current / capacity )) fi # Approximative time remaining if [[ $amperage != 0.000 ]]; then typeset -i total_m h typeset -Z 2 m (( total_m = 60 * current / amperage )) (( h = total_m / 60 )) (( m = total_m - h * 60 )) fi parse_flags_info $[flags$i] 4 if [[ $? = 0 ]]; then echo "Battery: ${percentage}% - approx ${h}:${m}" else echo "Battery: ${percentage}% - warning level" fi fi fi done } # --- display_long_info() { echo "hum ! I need time for this option..." } # --- parse_flags_info() { typeset -i 2 flags=$1; typeset -Z 8 flag_byte=${flags/2#/} typeset _byte=$flag_byte # mask bit index meaning # 0x01 0 8 charger is connected # 0x02 1 7 battery is charging # 0x04 2 6 battery is installed # 0x08 3 5 UPS is installed # 0x10 4 4 battery at or below warning level # 0x20 5 3 battery depleted # 0x40 6 2 no charging capability # 0x80 7 1 raw low battery signal from battery return $_byte[$2] } # --- usage() { echo "usage: battery" # by default = short option echo " battery short" # display something only if the battery is used echo " battery long" exit 1 } # --- main() { get_battery_info parse_battery_info display_info $@ } #-- main $@; exit 0