Created
May 31, 2021 08:35
-
-
Save edwios/b9ed5bc52558c1aec10253b0c8aa5172 to your computer and use it in GitHub Desktop.
Script to optimise MBP battery life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
sleeptime=60 | |
BatteryAlert(){ | |
percentage=$(pmset -g batt | egrep "([0-9]+\%).*" -o | cut -f1 -d';' | sed 's/%//' | bc) | |
charging=`pmset -g batt | egrep "([0-9]+\%).*" -o | cut -f2 -d';' | tr -d ' \n'` | |
alertlevel=10 | |
chargelevel=75 | |
prefchargelevel=85 | |
MQTT_USER=user | |
MQTT_PASS=password | |
if [ "$percentage" -le "$alertlevel" ] | |
then | |
if [ ! -f "./batteryalert_lock" ] | |
then | |
/usr/bin/osascript <<-EOF | |
tell application "System Events" | |
activate | |
display dialog "Your battery is at $percentage%. It is recommended you plug into a power outlet, or shut down!" | |
end tell | |
EOF | |
touch ./batteryalert_lock | |
fi | |
echo "Battery life is at $percentage%. Battery is running low." | |
elif [ "$percentage" -le "$chargelevel" ] | |
then | |
if [ "$charging" != "charging" ] | |
then | |
mosquitto_pub --url "mqtt://${MQTT_USER}:${MQTT_PASS}@10.0.1.250/sensornet/BleuSkyV2/command" -m "MBP Charger/on" | |
echo "Battery life is at $percentage%. Turning on charger." | |
if [ -f "./batterycharge_lock" ] | |
then | |
if [ ! -f "./batterychargealert_lock" ] | |
then | |
/usr/bin/osascript <<-EOF | |
tell application "System Events" | |
activate | |
display dialog "Your battery is at $percentage%. It is recommended you plug into a power outlet." | |
end tell | |
EOF | |
touch ./batterychargealert_lock | |
fi | |
fi | |
touch ./batterycharge_lock | |
fi | |
if [ -f "./batteryalert_lock" ] | |
then | |
rm ./batteryalert_lock | |
fi | |
elif [ "$percentage" -gt "$prefchargelevel" ] | |
then | |
echo "Battery life is at $percentage%. Charged." | |
if [ "$charging" == "charging" ] | |
then | |
mosquitto_pub --url mqtt://mqtt:[email protected]/sensornet/BleuSkyV2/command -m "MBP Charger/off" | |
echo "Battery life is at $percentage%. Turning OFF charger." | |
touch ./batterycharge_lock | |
fi | |
if [ -f "./batteryalert_lock" ] | |
then | |
rm ./batteryalert_lock | |
fi | |
if [ -f "./batterycharge_lock" ] | |
then | |
rm ./batterycharge_lock | |
fi | |
else | |
echo "Error" | |
# Do nothing | |
fi | |
} | |
while (true) | |
do | |
BatteryAlert; | |
sleep $sleeptime; | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment