Here is a sample script to connect your iPhone to Bluetooth. It took a lot of trial and error and thanks to others on this forum for posting their code. I even found some good help on Google Code. So, here’s my finished product. I hope that it helps others trying to accomplish the same thing.
The logic is: When I connect to my iPhone, I want to turn off the wi-fi connection to save the battery and make sure bluetooth is on, turn it on if its not, and then connect to my phone. I modified this script to disconnect the iPhone too.
One cool thing to note, is that you don’t have to use the Show command for system preferences. If you omit that step, the script still runs but you don’t see the changes occurring in the system preferences window. It looks cleaner.
Good luck!!
– Created by Chad Carney on 3/8/12.
– iPhone Connect
TurnBluetoothOn()
TurnWifiOff()
CleanUp()
on Bluetooth()
set AppleScript’s text item delimiters to “.”
set btooth to “Bluetooth”
set netWorkPane to “com.apple.preference.network”
set winNetwork to “Network”
tell application "System Preferences"
set current pane to pane netWorkPane
end tell
tell application "System Events" to tell process "System Preferences"
set theRow to row 1 of table 1 of scroll area 1 of window winNetwork whose value of static text 1 contains btooth
select theRow --clicks the bluetooth row
--If Bluetooth is already connected, the button will say Disconnect, so we don't want to turn it off:
try
click (button 1 of group 1 of window winNetwork whose title is "Connect")
end try
end tell
end Bluetooth
on TurnWifiOff()
set AppleScript’s text item delimiters to “.”
set wifi to “Wi-Fi”
set winNetwork to “Network”
set netWorkPane to “com.apple.preference.network”
tell application "System Preferences"
set current pane to pane netWorkPane
end tell
tell application "System Events" to tell process "System Preferences"
--Click on Network in the left scroll area:
set theRow to row 1 of table 1 of scroll area 1 of window winNetwork whose value of static text 1 contains wifi
select theRow
-- use the try block in case wi-fi is already off, then it moves on w/ no error message:
try
click button "Turn Wi-Fi Off" of group 1 of window winNetwork
end try
end tell
end TurnWifiOff
on TurnBluetoothOn()
set AppleScript’s text item delimiters to “.”
set btooth to “Bluetooth”
set winBtooth to “Bluetooth”
–NOTE: Notice that there is an “s” in preference for Bluetooth. That will mess you up!:
set bToothPane to “com.apple.preferences.Bluetooth”
tell application "System Preferences"
set current pane to pane bToothPane
end tell
--See if Bluetooth is off. If it is turn it on:
tell application "System Events" to tell process "System Preferences"
set chkBoxState to value of checkbox "On" of window winBtooth
if chkBoxState = 0 then
click checkbox "On" of window winBtooth
end if
end tell
end TurnBluetoothOn
on CleanUp()
tell application “System Preferences”
quit
end tell
end CleanUp