Как запустить Bluetooth-модем с помощью командной строки?


8

Я бы хотел быстро подключиться к своему iPhone, надеюсь, просто с помощью клавиатуры. Используя меню Bluetooth, я могу выбрать опцию «Подключиться к сети» в подменю для моего устройства, но возможно ли это автоматизировать?

В конечном итоге я хочу назначить это ярлыку в (очень крутом) Alfred.app, но все, что использует командную строку или AppleScript, будет работать.

Это возможно? Спасибо!!

Ответы:


3

Не похоже, что есть прямой словарь AppleScript для работы с Bluetooth таким образом.

Вы можете использовать GUI-скрипты, которые в основном используют функцию специальных возможностей Mac OS для выбора пунктов меню и т. Д.

Отличная статья о том, как начать с графического интерфейса AppleScript, доступна на MacOSAutomation.com .

Автоматизация графического интерфейса может быть сложной, если у вас постоянно меняется список вещей, но если у вас обычно есть список подключенных элементов Bluetooth, который остается неизменным, с вами все должно быть в порядке.

Затем вы можете вызвать этот AppleScript через Альфреда.


1

http://macscripter.net/viewtopic.php?id=38559

В приведенной выше ссылке есть очень хороший скрипт, который я только что немного обновил. Обратите внимание, что он использует blueutil [ git repo ] [ website / binaries ].

Включить Bluetooth:

-- Enable Bluetooth and Connect to iPhone

property blueutilPath : "/opt/local/bin/blueutil"

-- Turn on bluetooth.
if execBlueutil("status") contains "Status: off" then
    execBlueutil("on")

    connectDevice()

    doGrowl()

end if

on execBlueutil(command)
    set res to do shell script blueutilPath & " " & command
    if res contains "Error" then
        display dialog res
        quit
    end if
    return res
end execBlueutil

-- Connect Device
on connectDevice()
    tell application "System Preferences"
        activate
        set AppleScript's text item delimiters to "."
        set current pane to pane "com.apple.preference.network"
        set winNetwork to "Network"
        set btooth to "Bluetooth"

        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
        tell application "System Preferences"
            quit
        end tell
    end tell
end connectDevice

on doGrowl()
    tell application "System Events"
        set isRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
    end tell
    if isRunning then
        tell application id "com.Growl.GrowlHelperApp"
            set the allNotificationsList to ¬
                {"Bluetooth Setting"}
            set the enabledNotificationsList to ¬
                {"Bluetooth Setting"}
            register as application ¬
                "AppleScript - Bluetooth" all notifications allNotificationsList ¬
                default notifications enabledNotificationsList

            notify with name ¬
                "Bluetooth Setting" title ¬
                "Bluetooth is On & iPhone Connected" description ¬
                "Bluetooth has been enabled with iPhone tethered." application name "AppleScript - Bluetooth" icon of file (path to me)
        end tell
    end if
end doGrowl

Отключить Bluetooth:

property blueutilPath : "/opt/local/bin/blueutil"

-- Turn off Bluetooth.
if execBlueutil("status") contains "Status: on" then
    execBlueutil("off")

    doGrowl()
end if
on execBlueutil(command)
    set res to do shell script blueutilPath & " " & command
    if res contains "Error" then
        display dialog res
        quit
    end if
    return res
end execBlueutil

on doGrowl()
    tell application "System Events"
        set isRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
    end tell
    if isRunning then
        tell application id "com.Growl.GrowlHelperApp"
            set the allNotificationsList to ¬
                {"Bluetooth Setting"}
            set the enabledNotificationsList to ¬
                {"Bluetooth Setting"}
            register as application ¬
                "AppleScript - Bluetooth" all notifications allNotificationsList ¬
                default notifications enabledNotificationsList

            notify with name ¬
                "Bluetooth Setting" title ¬
                "Bluetooth Off" description ¬
                "Bluetooth has been disabled." application name "AppleScript - Bluetooth" icon of file (path to me)
        end tell
    end if
end doGrowl

0

Я бы порекомендовал использовать automator для этого, вы можете позвонить из Альфреда, чтобы было проще :)

Мой текущий рабочий процесс автоматизатора делает это:

Click the "bluetooth" menu bar item.
Connect to Network

Используя этот метод, вы можете автоматизировать практически все в течение минуты

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.