« Back to Index

macOS: Custom wireless battery alerts for mouse and keyboard

View original Gist on GitHub

Tags: #macos #automator #notifications #battery

README.md

[!NOTE] The whole reason I bothered doing this is because I hate it when macOS notifies me that my mouse is “critically” low on charge, as it forces me to have to stop work for charging my mouse. I’d prefer to know at around 50% charge so I can continue working but stick my mouse on charge when I go for lunch or finish my day.

Start by writing an AppleScript file that is essentially just a wrapper around a bash script…

do shell script "
# Get the battery percentage for the Magic Mouse
mouseBattery=$(ioreg -c AppleDeviceManagementHIDEventService -r | grep -i '\"Product\" = \"Magic Mouse\"' -A 20 | grep '\"BatteryPercent\" =' | awk '{print $NF}')

# Get the battery percentage for the Magic Keyboard
keyboardBattery=$(ioreg -c AppleDeviceManagementHIDEventService -r | grep -i '\"Product\" = \"Magic Keyboard\"' -A 20 | grep '\"BatteryPercent\" =' | awk '{print $NF}')

# Check if mouse battery is found and notify if it's below 50%
if [[ -n \"$mouseBattery\" && \"$mouseBattery\" -lt 50 ]]; then
    osascript -e \"display notification \\\"Mouse battery is at $mouseBattery%\\\" with title \\\"Battery Alert\\\"\"
fi

# Check if keyboard battery is found and notify if it's below 50%
if [[ -n \"$keyboardBattery\" && \"$keyboardBattery\" -lt 50 ]]; then
    osascript -e \"display notification \\\"Keyboard battery is at $keyboardBattery%\\\" with title \\\"Battery Alert\\\"\"
fi
"

…in the above I’m checking if my mouse and keyboard charge is less than 50%. If so, display a notification to let me know.

Now open up the Automator.app application and type “Run AppleScript” into the “Actions” box to find that action.

Paste the above AppleScript into the input and then %S to save the application as BatteryAlert.app.

Now to automate running the application…

cd ~/Library/LaunchAgents/
touch com.integralist.batteryalert.plist
vim com.integralist.batteryalert.plist # HERE IS WHERE YOU PASTE IN THE BELOW FILE CONTENTS
launchctl load ~/Library/LaunchAgents/com.integralist.batteryalert.plist # SCHEDULE THE APP TO BE RUN
launchctl list | grep batteryalert # SHOW THAT THE APP IS RUNNING
log show --predicate 'eventMessage contains "com.integralist.batteryalert"' --info # SHOW ANY APP LOGS

Here’s the plist file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.integralist.batteryalert</string>

    <key>ProgramArguments</key>
    <array>
        <string>/Applications/BatteryAlert.app/Contents/MacOS/applet</string>
    </array>

    <key>StartInterval</key>
    <integer>3600</integer> <!-- Run every 3600 seconds = 60 minutes -->

    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>