applescript

Display Magic Mouse Battery in Touch bar using BetterTouchTool


I'm using this BetterTouchToll for make my touch bar more interesting, what is very cool.

He accept some Apple Scripts for more dynamic, so I start to study this scripts.

Now I wanna to display my Magic Mouse Battery on my touch bar, for this I was trying this code, but is not working.

if application "Mouse" is running then
    tell application "Mouse"
        return (get Battery)
    end tell
end if
return "no mouse"

My guess is that Mouse is not a application, but don't know what to put in the place


Solution

  • The traditional means of getting the battery level is to use ioreg on the command line. However, the traditional means of doing this no longer seem to work as of at least macOS High Sierra/10.13.4; that is, they no longer allow choosing to display just the battery percentage of a single bluetooth device.

    So this is a hack that assumes that the Magic Mouse is always the last device displayed by ioreg. This is likely to fail, if not across different installations of macOS, then across different versions.

    ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'
    

    In an AppleScript, this would be:

    do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'"
    

    You have your code setup to also detect when the Magic Mouse is not connected. The product name is in the property “Product” in ioreg. For example:

    ioreg -c AppleDeviceManagementHIDEventService | grep '"Product" ='
    

    So to make sure that this final device is the Mouse, you could do:

    set finalDevice to do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep '\"Product\" =' | tail -1"
    if finalDevice contains "Magic Mouse" then
        set remaining to do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'"
        remaining & "%"
    else
        "no mouse"
    end if
    

    The basic logic:

    1. Grab the list of all products using ioreg.
    2. Use tail to get only the final product in the list.
    3. If the final product is a Magic Mouse, then:
      1. Grab the list of all battery percentages using ioreg.
      2. Use tail to get only the final battery percentage in the list.
      3. Use sed to get only the actual number from that line.
      4. Append a percentage symbol to the number.
    4. Otherwise, there is no mouse. (Or the mouse is not the final item in the list.)

    For the older means of using ioreg, see, for example: