Mac:当设备通过蓝牙连接时启动命令

时间:2017-06-14 13:19:20

标签: macos bluetooth macos-sierra launchd

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

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

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

function updateSVG(e) {
    if (follow) {
      var centerPoint = new Point(center[0].getAttribute("cx"), center[0].getAttribute("cy"));
      var point = new Point(e.clientX, e.clientY);
      var angle = Math.round(100 * getAngleFromPoint(point, centerPoint)) / 100;
      var distance = Math.round(getDistance(point, centerPoint));
      var d = "M " + centerPoint.X + " " + centerPoint.Y + " L " + point.X + " " + point.Y;
      path.attr("d", d);
      txt.attr("x", point.X);
      txt.attr("y", point.Y);
      txt.html(distance + arrows + " (" + angle + degree + ")");
      txt.attr("transform", "rotate(" + angle + " " + point.X + " " + point.Y + ")");
      dynamic.attr("r", distance);
    }
    fitSVG();
  }

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在〜/ Library / LaunchAgents中创建一个包含以下内容的文件:

<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>

在/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