OSX Low battery alert for keyboard & mouse

I don’t know if you ever ran out of battery on your Magic Mouse / Magic Keyboard but i did ( pretty much ).
My solution is the below script + crontab which will set a notification trigger as often as you want ( i set mine every 4hours).

note1: despite i am programming for a long time my interactions with bash language it’s totally new so the following code might be optimised … important thing..it’s working!

note2: developed / tested on a mac mini with magin keyboard + mouse

Let’s start:

1. create a script called batteryNotifications.sh in a location of your choice

2. in order to make it executable from terminal run:

chmod +x /path/to/script/batteryNotifications.sh

3. with an editor of you choice, paste the following code inside your file

#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

alert=30

ioreg -r -l -n AppleDeviceManagementHIDEventService > /Users/mc/batteryNotifInfos.txt

IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /Users/mc/batteryNotifInfos.txt))'

for index in "${!XYZ[@]}"
do
    if [[ "${XYZ[index]}" == *\"Product\"* ]]; then
        prod=$(sed 's/"Product" = //' <<< "${XYZ[index]}")
        prod=$(sed -e 's/^"//' -e 's/"$//' <<< $prod)
        fi
    if [[ "${XYZ[index]}" =~ .*SerialNumber.* ]]; then
        serial=$(sed 's/"SerialNumber" = //' <<< "${XYZ[index]}")
        serial=$(sed -e 's/^"//' -e 's/"$//' <<< $serial)
        fi
    if [[ "${XYZ[index]}" =~ .*BatteryPercent.* ]]; then
        battery=$(grep -o '[0-9]\+' <<< "${XYZ[index]}")

        #alertNow = $(($battery - $alert))
        #echo "$alertNow";

        if (($battery < $alert))
        then
        osascript -e "display notification \"Battery level: $battery%\" with title \"$prod\" subtitle \"$serial\" "
        fi
    fi

done

4. now from terminal run command

crontab -e

then press I to enter edit mode ( left bottom corners will show –INSERT– ) and put inside this (only the first line, the graphic is for better understading):

* * * * * /Users/your-username/path/to/script/batteryNotifications.sh
– – – – –
| | | | |
| | | | +—– day of week (0 – 6) (Sunday=0)
| | | +——- month (1 – 12)
| | +——— day of month (1 – 31)
| +———– hour (0 – 23)
+————- min (0 – 59)

For example i set mine to run every 4 hours

0 */4 * * * /Users/your-username/path/to/script/batteryNotifications.sh