【问题标题】:Mac : Launch command when device connected by bluetoothMac:设备通过蓝牙连接时启动命令
【发布时间】:2025-12-03 14:00:01
【问题描述】:

我想在特定的外部蓝牙设备连接到我的 Mac 时启动 shell 命令。

一个不错的方法(无需安装第三方软件)是在 ~/Library/LaunchAgents 中添加一个 plist 文件

this page 上,有一个当 wifi 连接到特定位置时启动事件的示例。这是通过观看特定文件来完成的:

<key>WatchPaths</key>
<array>
   <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
</array>

您认为可以对蓝牙事件做同样的事情吗?

感谢您的帮助!

【问题讨论】:

  • 我找到了 /Library/Preferences/com.apple.Bluetooth.plist 文件。但是这个文件改动有点太大了

标签: macos bluetooth macos-sierra launchd


【解决方案1】:

在 ~/Library/LaunchAgents 中创建一个文件,其中包含:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

    <key>Label</key>
    <string>Smartcard reader</string>

    <key>ProgramArguments</key>
    <array>
        <string>/Users/USERNAME/Library/Scripts/script.bash</string>
    </array>

    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/com.apple.Bluetooth.plist</string>
    </array>

</dict>
</plist>

在 /Users/USERNAME/Library/Scripts/script.bash 我们可以测试连接的设备是否正确:

if [ $(system_profiler SPBluetoothDataType | grep "Smart Reader 2501" | wc -l) -eq 1 ] ; then
    echo "Smartcard connected"
fi

使用

启动服务
launchctl load ~/Library/LaunchAgents/yourscript

【讨论】:

  • 我不相信“测试”代码就足够了。 system_profiler 输出将包含设备的名称,即使它没有连接。您需要解析输出或运行一些 AppleScript。见*.com/q/48327866/6962
  • 我无法确认这是否适用于使用节点 js 文件观察器的 MacOS 12。即使移除蓝牙设备也不会触发更改事件。在 2 个州中区分它们也没有任何区别。