cbattery/cbattery

114 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
function usage() {
cat << EOF
usage: ${0##*/} [command]
charging [on|off] - Toggle charging
adapter [on|off] - Toggle adapter connection
status - Get status information
revert - Revert to default settings
help - Display this help message
EOF
}
function enable_discharging() {
echo "Enabling battery discharging"
sudo smc -k CH0I -w 01
}
function disable_discharging() {
echo "Disabling battery discharging"
sudo smc -k CH0I -w 00
}
function enable_charging() {
echo "Enabling battery charging"
sudo smc -k CH0B -w 00
sudo smc -k CH0C -w 00
disable_discharging
}
function disable_charging() {
echo "Disabling battery charging"
sudo smc -k CH0B -w 02
sudo smc -k CH0C -w 02
}
function get_smc_charging_hex() {
smc -k CH0B -r | awk '{print $4}' | sed 's:\)::'
}
function get_smc_charging_status() {
hex_status=$(get_smc_charging_hex)
if [[ "$hex_status" == "00" ]]; then
echo "enabled"
else
echo "disabled"
fi
}
function get_smc_discharging_status() {
hex_status=$(smc -k CH0I -r | awk '{print $4}' | sed 's:\)::')
if [[ "$hex_status" == "0" ]]; then
echo "not discharging"
else
echo "discharging"
fi
}
function get_battery_percentage() {
battery_percentage=$(pmset -g batt | tail -n1 | awk '{print $3}' | sed 's:%\;::')
echo "$battery_percentage"
}
function get_remaining_time() {
time_remaining=$(pmset -g batt | tail -n1 | awk '{print $5}')
echo "$time_remaining"
}
action=$1
setting=$2
if [ -z "$action" ] || [[ "$action" == "help" ]]; then
usage
exit 0
fi
if [[ "$action" == "revert" ]]; then
enable_charging
disable_discharging
exit 0
fi
if [[ "$action" == "charging" ]]; then
echo "Setting $action to $setting"
if [[ "$setting" == "on" ]]; then
enable_charging
elif [[ "$setting" == "off" ]]; then
disable_charging
fi
exit 0
fi
if [[ "$action" == "adapter" ]]; then
echo "Setting $action to $setting"
if [[ "$setting" == "on" ]]; then
enable_discharging
elif [[ "$setting" == "off" ]]; then
disable_discharging
fi
exit 0
fi
if [[ "$action" == "status" ]]; then
if [[ "$setting" == "charging" ]]; then
exit "$(get_smc_charging_hex)"
else
echo "Battery at $(get_battery_percentage)% ($(get_remaining_time) remaining), smc charging $(get_smc_charging_status)"
fi
exit 0
fi