如何查找某个蓝牙设备是否已连接?

4
我希望使用AppleScript定期(每秒)检查特定蓝牙设备是否连接,并在连接时快速显示弹出通知。简单来说,我想要在我的Airpods连接时弹出一个窗口,因为有时当我拿出它们时,它们会连接到我的电脑,有时则连接到我的iPhone。
我已经把所有的东西都搞定了,除了蓝牙检查部分。我以这个作为起点,但无法使其正常工作。欢迎任何帮助。
repeat
set statusOld to checkStatus()
set statusNew to checkStatus()
repeat while statusOld is equal to statusNew
    delay 1 --for 1 second checks
    set statusNew to checkStatus()
end repeat
if statusNew is true then
    display dialog "Device Added - put some real code here"
else
    display dialog "Device Removed - put some real code here"
end if
end repeat

on checkStatus()

(*Delete the 2 lines below when done testing*)
--set myString to button returned of (display dialog "Connected?" buttons {"Yes", "No"})
--set myString to "name: DR-BT101 Connected: " & myString

(*uncomment line below when done testing*)
set myString to do shell script "system_profiler SPBluetoothDataTyp"

--initial check if it's not even there
if myString does not contain "Christian’s AirPods" then
    return false
else

    --find out if connected/disconnected
    set AppleScript's text item delimiters to "name:"
    set myList to the text items of myString --each item of mylist is now one of the devices

    set numberOfDevices to count of myList
    set counter to 1
    repeat numberOfDevices times --loop through each devices checking for Connected string
        if item counter of myList contains "Christian’s AirPods" then
            if item counter of myList contains "Connected: Yes" then
                return true
            else if item counter of myList contains "Connected: No" then
                return false
            else
                display dialog "Error Parsing" --this shouldn't happen
            end if
        end if
        set counter to counter + 1
    end repeat
end if
end checkStatus

哦,我一直在查看这份文档,但不知道如何实现它:https://developer.apple.com/documentation/iobluetooth/iobluetoothdevice - Christian Stevenson
2个回答

3
您缺少了e
set myString to do shell script "system_profiler SPBluetoothDataType"
                                                                   ^

0

我正在做类似的事情。这似乎在macOS Mojave上运行良好:

use framework "IOBluetooth"
use scripting additions -- https://stackoverflow.com/a/52806598/6962

on isDeviceConnected(substring)
    repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)
        if device's isConnected and (device's nameOrAddress as string) contains substring then return true
    end repeat

    return false
end isDeviceConnected

-- Usage example:
isDeviceConnected("AirPods")

我像这样与启动代理结合使用:https://gist.github.com/henrik/3d4c622a5567cdf2bf461352f48ad4dd


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接