0

I'd like to write an AppleScript that will connect my Magic Mouse 2. Basically, in words, I'd like a script that will show up in "Services" that opens system preferences, goes to Bluetooth, finds the Magic Mouse 2 device and connects this device. Note that in my Bluetooth Devices I have both a Bluetooth Mouse 4.0 and a Magic Mouse 2.

I have tried to use Automator via the record command, but the process doesn't work well. I think if I wrote an AppleScript to do this, I could compile this as a quick action and allow me to do this action from my Touch Bar.

Have researched this and can't seem to find an existing script so I want to try to write one myself. New to both the Mac and AppleScript so taking a long time. I have ordered an AppleScript book, but in meantime wanted to see if I could get some pointers from this site, which is so very helpful.

  • Did you try my script below ? Some feedback would be helpful. – CJK Aug 14 at 0:11
1

It sounds like you know how to create a systemwide Service or Quick Action, and just need a script to open the actual bluetooth connection. Test the script below initially in Script Editor, which requires any device you wish to connect to have already been paired (it sounds like this is the case). All being well, you can be reasonably confident it will work if you transplant it into an Automator workflow (if you first get rid of any sample code that appears, i.e. on run {input, parameters} etc.

use framework "Foundation"
use framework "IOBluetooth"

property this : a reference to the current application
property nil : a reference to missing value
property _1 : a reference to reference

property IOBluetoothDevice : a reference to IOBluetoothDevice of this
property NSPredicate : a reference to NSPredicate of this

property pairedDevices : a reference to IOBluetoothDevice's pairedDevices
property text item delimiters : linefeed & tab & "- "

to deviceWithName(name as text)
    local name
    NSPredicate's predicateWithFormat:"name==[c]%@" argumentArray:[name]
    tell filteredArrayUsingPredicate_(result) of pairedDevices
        if |count|() > 0 then return its firstObject()
        error {"No device by that name. Available devices:", ¬
            getDeviceNames() of me} as text
    end tell
end deviceWithName

to getDeviceNames()
    (pairedDevices's valueForKey:"name") as list
end getDeviceNames


try
    if deviceWithName("Magic Mouse 2")'s openConnection() ≠ 0 ¬
        then error "Could not open connection."
on error E
    return E
end try

true

NB. This script has only been tested in High Sierra

I'm afraid the error messages are not especially forthcoming with information should something not work as expected. But, if the device can connect, the script should be manage it. If it fails to connect, test that you are able to establish a connection manually.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .