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

Bluetooth 如何查找某个蓝牙设备是否已连接?,bluetooth,applescript,Bluetooth,Applescript,我想使用applescript定期(每秒)检查特定的蓝牙设备是否已连接,如果已连接,则快速弹出通知。为了构建它,我希望在我的Airpods连接时弹出一个窗口,因为有时当我拉出它们时,会连接到我的计算机,有时连接到我的iPhone 我把一切都搞定了,除了蓝牙检查部分。我曾以此为出发点,但无法让它发挥作用。任何帮助都将不胜感激 repeat set statusOld to checkStatus() set statusNew to checkStatus() repeat while statu

我想使用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

您缺少
e

set myString to do shell script "system_profiler SPBluetoothDataType"
                                                                   ^

我正在做类似的事情。这似乎对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")

我将它与一个launch agent组合在一起,如下所示:

哦,我已经阅读了此文档,但不了解如何实现它: