1

So I just registered and have not enough Kharma to comment on the original post (but I can ask a new question and this makes no sense to me; go figure), but I got this excellent script from Will Cain from here (Get low battery notifications for mouse earlier), and I modified it a little.

The intention is to keep the battery between 20 and 80%, but I don't want the messages to keep appearing, for example, if the battery is lower then 20% but is already charging; or if the battery is highter then 80% and it's not charging anymore.

I'm pretty noob when it comes to bash scripting, though. But here's the general idea:

#!/usr/bin/env bash
PATH=/usr/local/bin:/usr/local/sbin:~/bin:/usr/bin:/bin:/usr/sbin:/sbin

# actual battery level
BATT=`ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i keyboard -A 20 | grep BatteryPercent | cut -d= -f2 | cut -d' ' -f2`

#Device is charging
CHARG=`ioreg -p IOUSB -l -w 0 | grep -i "magic keyboard"`

# defaults to warn at 20%; accepts other number as 1st argument (useful for testing)
MIN=${1:-20}

# defaults to warn at 20%; accepts other number as 1st argument (useful for testing)
MAX=${1:-80}

if [ -z "$BATT" ]; then
  echo 'No keyboard found.'
  exit 0
fi

if (( BATT < MIN )); then
  osascript -e "display notification \"Keyboard battery is at ${BATT}%.\" with title \"Keyboard Battery Low\""
fi

if ((( BATT > MAX )) && ((CHARG != null))); then
  osascript -e "display notification \"Keyboard battery is at ${BATT}%.\" with title \"Keyboard Battery High\""
fi

(Updated to reflect last version, as suggested by @mspasov in a comment, but which throws a syntax error at line 25 (the last "if").

  • One way would be to charge it via the usb of the Mac and check if it's attached via ioreg. And welcome :) – mspasov Sep 27 '20 at 0:44
  • 1
    Thanks @mspasov, that's a good idea indeed. Now can you help me understand why this: #Device is charging CHARG='ioreg -p IOUSB -l -w 0 | grep -i "magic keyboard"' if ((( BATT > MAX )) && ((CHARG != null))); then osascript -e "display notification \"Keyboard battery is at ${BATT}%.\" with title \"Keyboard Battery High\"" fi is returning a syntax error on this last "if" line? :( – Guilherme Mauricio Sep 28 '20 at 3:34

You must log in to answer this question.

Browse other questions tagged .