Skip to content

Instantly share code, notes, and snippets.

@fserafin
Created October 20, 2024 09:54
Show Gist options
  • Select an option

  • Save fserafin/8b3290ed52f11948f6b4a4ee0f6c07c8 to your computer and use it in GitHub Desktop.

Select an option

Save fserafin/8b3290ed52f11948f6b4a4ee0f6c07c8 to your computer and use it in GitHub Desktop.
Checks the Magic Mouse and Magic Keyboard battery on MacOS and shows a notification when it goes under a certain value
#!/bin/bash
# Set the threshold percentage (default is 20%)
THRESHOLD=${1:-20}
# Function to get battery percentage of a device
get_battery() {
local device=$1
local result=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i "$device" -A 20 | grep BatteryPercent | cut -d= -f2 | tr -d '%')
if [ -n "$result" ]; then
echo $((1 * $result))
else
echo "0"
fi
}
# Get battery percentages
mouse_battery=$(get_battery "MOConnected")
keyboard_battery=$(get_battery "KBConnected")
# echo "Mouse battery: $mouse_battery%"
# echo "Keyboard battery: $keyboard_battery%"
# Check if devices are found
if [ "$mouse_battery" = "0" ] && [ "$keyboard_battery" = "0" ]; then
echo "No mouse or keyboard found."
exit 1
fi
# Compare batteries and send notification if below threshold
if (( $(echo "$mouse_battery < $THRESHOLD" | bc -l) )); then
osascript -e "display notification \"Mouse battery is $mouse_battery% !\" with title \"Battery Alert\""
fi
if (( $(echo "$keyboard_battery < $THRESHOLD" | bc -l) )); then
osascript -e "display notification \"Keyboard battery is $keyboard_battery%!\" with title \"Battery Alert\""
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment