Thursday, January 5, 2017

Applescript control of bluetooth and wifi - ADVANCED

I made a more advanced script for controlling (not flipping) the bluetooth and wifi power states (see previous post for finding the correct menus).
This script is looking for a certain USB device that will indicate whether the computer is docked or not.


-- Applescript that searches connected USB devices and determines if this means the computer is docked or not.
-- In docked mode bluetooth should be On and wifi Off, and vice versa for undocked.

------- BEGIN USER CONFIG -------
set list_cmd to "system_profiler SPUSBDataType"
set search_str to "AX80_EXT_HUB"
-------- END USER CONFIG --------


---------- BEGIN SCRIPT ----------
set shellOut to ""
try
set shellOut to do shell script list_cmd & " | grep " & quoted form of search_str
end try
if shellOut contains search_str then
set state_docked to true
else
set state_docked to false
end if

if state_docked is true then
set state_bluetooth to "On"
set state_wifi to "Off"
else
set state_bluetooth to "Off"
set state_wifi to "On"
end if

set menu_bluetooth to 0
set menu_wifi to 0
tell application "System Events" to tell the front menu bar of process "SystemUIServer"
set menu_extras to description of menu bar items
repeat with x from 1 to the length of menu_extras
if item x of menu_extras is "bluetooth" then
set menu_bluetooth to x
exit repeat
end if
end repeat
repeat with x from 1 to the length of menu_extras
if item x of menu_extras starts with "Wi-Fi" then
set menu_wifi to x
exit repeat
end if
end repeat
if menu_bluetooth is greater than 0 then
tell menu bar item menu_bluetooth
click
if name of menu item 2 of front menu ends with state_bluetooth then
tell menu item 2 of front menu
click
end tell
else
tell application "System Events"
key code 53
end tell
end if
end tell
end if
if menu_wifi is greater than 0 then
tell menu bar item menu_wifi
click
if name of menu item 2 of front menu ends with state_wifi then
tell menu item 2 of front menu
click
end tell
else
tell application "System Events"
key code 53
end tell
end if
end tell
end if
end tell


----------- END SCRIPT -----------

No comments: