BioRich

Q: AppleScript Bluetooth on/off

Hi folks.

 

Just looking for a way to toggle Bluetooth on and off using a single AppleScript.  Any takers?  I've tried some of the scripts posted here, but they were posted in 2006 or so, and all don't work...that I have found. 

 

Cheers

Mac Pro, Mac OS X (10.6.7), Hypercard UG!

Posted on Jul 15, 2011 9:04 AM

Close

Q: AppleScript Bluetooth on/off

  • All replies
  • Helpful answers

Previous Page 2
  • by Stupudmunkee,

    Stupudmunkee Stupudmunkee Jun 1, 2014 1:05 AM in response to BioRich
    Level 1 (0 points)
    Jun 1, 2014 1:05 AM in response to BioRich

    I realize you may have found a happy solution at this point, but I was having a similar problem to solve in getting my Target Display Mode to work the I feel that it should. If I plug my Macbook Air into my 27" imac, I want my imac to do two things:

     

    1) Hit Command+F2 

    2) Release the Bluetooth Keyboard and Mouse/Trackpad so that my macbook can pair them

     

    I came across a github project by a developer named Duane Fields. Being a developer, I think he just coughed and built the solution.

     

    Anyways, you'd have to download Xcode from the app store (large program, but useful) and the source code from github. If you have never used xcode, this might take a bit longer (as it did for me) to figure out how to install the dependencies correctly. In the end, I think it is worthwhile because the app works pretty well. It isn't perfect, but it solves an annoying problem for me.

     

    https://github.com/duanefields/VirtualKVM

     

    After you compile the VirtualKVM application, you could add it as a startup item (Users & Groups) so you wouldn't have to run it manually.

     

    - Your macbook is running. (No app required here)

    - Your 27" iMac is running, and so is VirtualKVM.

    - You connect your MB to your iMac via the Thunderbolt cable

    - VirtualKVM recognizes the Thunderbolt Connection and starts Target Display Mode (Command+F2)

    - VirtualKVM disables bluetooth (No option to select specific devices; bummer)

    - Your MB, if BT is on and previously paired with the BT Keyboard/Mouse, will pair with the devices (might have to push the power device, maybe)

    - You are now in Target Display Mode with your Bluetooth Keyboard/Mouse paired to the Macbook (YaY!)

     

    - Exiting Target Display Mode: (how I do it)

    - Disable bluetooth or Disconnect the Keyboard/Mouse from the Macbook (your applescript might be useful here)

    - Disconnect the Thunderbolt cable from one of the machines, or both if you want to.

    - VirtualKVM (on the iMac) will end the Target Display Mode and turn bluetooth back on.

    - After a second or two, your iMac and Macbook displays will return to their primary roles.

    - A few seconds later (10-20 maybe?) your iMac should recognize the now free bluetooth keyboard/mouse and pair with them (might have to press the power button on your mouse/trackpad)

    - Both systems should now be operating independently; can do it again just for giggles if you'd like.

     

    As I said, it's not perfect but it does take some of the frustration out of the problem. If someone were to ask, he might even take the app a few steps further and include a feature to poll the Bluetooth Devices and disconnect specific items. That would be pretty cool.

     

    Well, I hope that helped someone but I think it's a much cleaner solution than my Automator/Applescript fix I was trying to do when I came across this forum post.

     

    Aloha!

     

    Jeremy

  • by optimusic,

    optimusic optimusic Oct 23, 2014 5:02 AM in response to Pierre L.
    Level 1 (0 points)
    Oct 23, 2014 5:02 AM in response to Pierre L.
    tell application "System Preferences"
        set the current pane to pane id "com.apple.preferences.Bluetooth"
        tell application "System Events"
            tell process "System Preferences"
                tell window "Bluetooth"
                    tell button 6
                        if name is "Turn Bluetooth Off" then click
                    end tell
                end tell
            end tell
        end tell
        quit
    end tell

     

    Hi, Pierre,

    In my case, this Script doesn't work with Yosemite OS X 10.10. If it is common issue on Yosemite, have you a solution?

  • by Pierre L.,

    Pierre L. Pierre L. Oct 23, 2014 8:40 AM in response to optimusic
    Level 5 (4,484 points)
    Oct 23, 2014 8:40 AM in response to optimusic

    Unfortunately, I haven't installed OS X Yosemite yet.

  • by Pierre L.,

    Pierre L. Pierre L. Oct 27, 2014 7:51 PM in response to optimusic
    Level 5 (4,484 points)
    Oct 27, 2014 7:51 PM in response to optimusic

    Try just replacing “button 6” with “button 3”.

  • by optimusic,

    optimusic optimusic Oct 28, 2014 1:52 AM in response to Pierre L.
    Level 1 (0 points)
    Oct 28, 2014 1:52 AM in response to Pierre L.

    Merci, Pierre!

    It's works now!

  • by Siam.Y,

    Siam.Y Siam.Y Mar 15, 2015 9:22 PM in response to Pierre L.
    Level 1 (0 points)
    Mar 15, 2015 9:22 PM in response to Pierre L.

    Hello Pierre,

     

    I am on 10.10.2 and somehow, having a 'quit' in the script makes it fail for me.

    I lose BT connection, but BT does not turn off.  I can still reconnect.

     

    Without the 'quit' things work as expected, but this leaves the System Preferences window open.

     

    Any ideas?

  • by Pierre L.,

    Pierre L. Pierre L. Mar 16, 2015 6:38 AM in response to Siam.Y
    Level 5 (4,484 points)
    Mar 16, 2015 6:38 AM in response to Siam.Y

    The following should do the trick:

     

    tell application "System Preferences"

         -- activate

         set the current pane to pane id "com.apple.preferences.Bluetooth"

         tell application "System Events"

               tell process "System Preferences"

                     tell window "Bluetooth"

                           tell button 3

                                 if name is "Turn Bluetooth Off" then

                                       click

                                       repeat until name is "Turn Bluetooth On"

                                       end repeat

                                 end if

                           end tell

                     end tell

               end tell

         end tell

         quit

    end tell


    The second line of code has been commented out in order to keep the Bluetooth window invisible.

  • by Siam.Y,

    Siam.Y Siam.Y Mar 16, 2015 7:22 AM in response to Pierre L.
    Level 1 (0 points)
    Mar 16, 2015 7:22 AM in response to Pierre L.

    Pierre,

    FIrst of all, thank you. Your solution suggests that SysPref is quitting before BT has been effectively toggled.

    Second, how did you identify the id number for the button?

  • by Pierre L.,

    Pierre L. Pierre L. Mar 16, 2015 7:37 AM in response to Siam.Y
    Level 5 (4,484 points)
    Mar 16, 2015 7:37 AM in response to Siam.Y

    Siam.Y wrote:

     

    Pierre,

    FIrst of all, thank you. Your solution suggests that SysPref is quitting before BT has been effectively toggled.

    Second, how did you identify the id number for the button?

     

    You can proceed as follows:

     

    tell application "System Preferences"

         activate

         set the current pane to pane id "com.apple.preferences.Bluetooth"

    end tell

     

    tell application "System Events"

         tell process "System Preferences"

               name of buttons of window "Bluetooth"

         end tell

    end tell

     

    --> {missing value, "Advanced…", "Turn Bluetooth On", missing value, missing value, missing value}


  • by VikingOSX,

    VikingOSX VikingOSX Mar 16, 2015 8:51 AM in response to BioRich
    Level 7 (21,576 points)
    Mac OS X
    Mar 16, 2015 8:51 AM in response to BioRich

    Here is another approach if you have enabled the bluetooth icon in your menu bar. The following code will toggle bluetooth on/off each time it is run. It is accompanied by a notification panel telling you of the change in bluetooth power state. Do not run this if you do not have a wired counterpart to your bluetooth keyboard, or mouse connected. Pierre's code gets the job done too.

     

    -- Source: MacScripter: http://macscripter.net/viewtopic.php?id=22219

    -- The following code is a modification to the original Source

     

    tell application "System Events" to tell the front menu bar of process "SystemUIServer"

          set menu_extras to value of attribute "AXDescription" of menu bar items

          -- log menu_extras

          repeat with x from 1 to the length of menu_extras

                if item x of menu_extras contains "bluetooth" then exit repeat

          end repeat

          tell menu bar item x

               click

               tell 2nd menu item of front menu

                   -- log name

                   if name ends with "Off" then

                       set btStatus to "OFF"

                   else

                       set btStatus to "On"

                   end if

                   click

               end tell

          end tell

          tell application "Finder"

               display notification with title "Bluetooth Power Status" subtitle "Status: " & btStatus sound name "pop.aiff"

          end tell

    end tell

  • by Pierre L.,

    Pierre L. Pierre L. Mar 16, 2015 11:16 AM in response to VikingOSX
    Level 5 (4,484 points)
    Mar 16, 2015 11:16 AM in response to VikingOSX

    I'd like to clarify a point here.

     

    Although the OP (BioRich) was actually “just looking for a way to toggle Bluetooth on and off using a single AppleScript”, it seems that optimusic and Siam.Y were rather looking for a script similar to the one asked for by willthefirst:

    willthefirst wrote:

     

    Thanks, that almost works. The only problem is that it will turn bluetooth back on if it is disabled. How would you insert a 'check' that says: 'if it's on, turn it off, but if it's off, leave it off'?

     

    Of course, my last version of such a script can easily be modified in order to just toggle Bluetooth on and off:

     

    tell application "System Preferences"

         -- activate

         set the current pane to pane id "com.apple.preferences.Bluetooth"

         tell application "System Events"

               tell process "System Preferences"

                     tell window "Bluetooth"

                           tell button 3

                                 click

                                 if name is "Turn Bluetooth Off" then

                                       repeat until name is "Turn Bluetooth On"

                                       end repeat

                                 else

                                       repeat until name is "Turn Bluetooth Off"

                                       end repeat

                                 end if

                           end tell

                     end tell

               end tell

         end tell

         quit

    end tell

  • by VikingOSX,

    VikingOSX VikingOSX Mar 16, 2015 12:41 PM in response to Pierre L.
    Level 7 (21,576 points)
    Mac OS X
    Mar 16, 2015 12:41 PM in response to Pierre L.

    Wasn't competing Pierre. We are showing alternatives. Don't due much GUI scripting anymore, as Apple has this bad habit of changing application design layout. Bookmarked this post as reference to your code.

  • by Hiroto,

    Hiroto Hiroto Mar 17, 2015 11:55 AM in response to VikingOSX
    Level 5 (7,348 points)
    Mar 17, 2015 11:55 AM in response to VikingOSX

    Hello

     

    Here's yet another approach using rubycocoa, which is invoking the same private functions of IOBluetooth.framework as blueutil [1].

     

    The following AppleScript script is a wrapper of rubycocoa script. Tested under OS X 10.6.8. I'd think it should work under OS X 10.5 through 10.9 as well, but not sure.

     

    Under OS X 10.10+, you'd need to manually install RubyCocoa 1.2.0 [2] which supports Ruby 2.0 or later.

     

     

    [1] http://www.frederikseiffert.de/blueutil/

     

    [2] http://rubycocoa.sourceforge.net/

        http://sourceforge.net/projects/rubycocoa/files/RubyCocoa/1.2.0/

     

     

    All the best,

    Hiroto

     

     

    --APPLESCRIPT
    --return bluetooth_powerstate(0) -- off
    --return bluetooth_powerstate(1) -- on
    return bluetooth_powerstate(-1) -- toggle
    --return bluetooth_powerstate(9) -- query
    
    on bluetooth_powerstate(s)
        (*
            integer s : operation mode; 0 = off, 1 = on, -1 = toggle, 9 = query
            return integer : resulting power state
        *)
        considering numeric strings
            if (system info)'s system version < "10.10" then
                set ruby to "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby"
            else
                --set ruby to "/usr/bin/ruby"
                set ruby to "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby"
                (*
                    Under OS X 10.10+, install rubycocoa 1.2.0 or later which supports ruby 2.0 or later.
                        http://rubycocoa.sourceforge.net/
                        http://sourceforge.net/projects/rubycocoa/files/RubyCocoa/1.2.0/
                *)
            end if
        end considering
        if s = 9 then set s to ""
        do shell script ruby & " -w <<'EOF' - " & s & "
    #
    #   bluetooth_powerstate.rb
    #       
    #   Usage:
    #       bluetooth_powerstate.rb [mode]
    #         mode: 0 = off, 1 = on, -1 = toggle, (none) = query
    # 
    #   * using IOBluetooth.framework undocumented functions
    #       extern int IOBluetoothPreferenceGetControllerPowerState (void)
    #       extern int IOBluetoothPreferenceSetControllerPowerState (int)
    # 
    #   v0.10
    #   written by Hiroto, 2015-03
    # 
    require 'osx/cocoa'
    include OSX
    OSX.require_framework '/System/Library/Frameworks/IOBluetooth.framework'
    
    while File.exist?(BSFILE = \"/tmp/IOBluetooth.#{rand(1e10)}.bridgesupport\") do end
    Signal.trap('EXIT') { File.delete BSFILE if File.exist? BSFILE }
    File.open(BSFILE, \"w\") { |f| f.print DATA.read }
    OSX.load_bridge_support_file BSFILE
    File.delete BSFILE if File.exist? BSFILE
    
    def set_ioblpstate(s)
        #   int s : 0 = off, 1 = on
        IOBluetoothPreferenceSetControllerPowerState(s)
        sleep 1
        unless (s1 = get_ioblpstate()) == s
            $stderr.puts \"unable to set bluetooth power %s\" % s == 0 ? 'off' : 'on'
            exit 2
        end
        s1
    end
    
    def get_ioblpstate()
        IOBluetoothPreferenceGetControllerPowerState()
    end
    
    def main(argv)
        #   array argv : operation mode; ['0'] = off, ['1'] = on, ['-1'] = toggle, [] = query
        puts case argv
        when ['0']  then set_ioblpstate(0)
        when ['1']  then set_ioblpstate(1)
        when ['-1'] then set_ioblpstate(get_ioblpstate() == 0 ? 1 : 0)
        when []     then get_ioblpstate()
        else
            $stderr.puts \"Usage: #{File.basename($0)} [mode]\\n\\t%s, %s, %s, %s\\n\" %
                ['mode: 0 = off', '1 = on', '-1 = toggle', '(none) = query']
            exit 1
        end
    end 
    
    main(ARGV)
    
    __END__
    <?xml version=\"1.0\" standalone=\"yes\"?>
    <!DOCTYPE signatures SYSTEM \"file://localhost/System/Library/DTDs/BridgeSupport.dtd\">
    <signatures version=\"0.9\">
        <function name=\"IOBluetoothPreferenceGetControllerPowerState\">
            <retval type=\"i\"></retval>
        </function>
        <function name=\"IOBluetoothPreferenceSetControllerPowerState\">
            <arg type=\"i\"></arg>
            <retval type=\"i\"></retval>
        </function>
    </signatures>
    EOF"
        result as number
    end bluetooth_powerstate
    --END OF APPLESCRIPT
    
  • by Emanavas,

    Emanavas Emanavas Dec 8, 2015 11:09 AM in response to BioRich
    Level 1 (0 points)
    Dec 8, 2015 11:09 AM in response to BioRich

    OK you can use that code

     

    tell application "System Preferences"

      -- activate

      set the current pane to pane id "com.apple.preferences.Bluetooth"

      tell application "System Events" to tell process "System Preferences"

      click button 3 of window "Bluetooth"

      end tell

     

              end tell    

     


    you need give access to security and privacity, search and check automator access.


    h

Previous Page 2