Mac : Launch command when device connected by bluetooth

别等时光非礼了梦想. 提交于 2019-12-08 01:59:54

问题


I would like to launch a shell command when a specific external bluetooth device is connected to my Mac.

A nice way (without installing third party software) to do that is by adding a plist file in ~/Library/LaunchAgents

On this page, there is an example of launching an event when the wifi connects to a specific location. It is done by watching a specific file :

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

Do you think it'd possible to do the same with bluetooth events ?

Thanks for your help !


回答1:


Create a file in ~/Library/LaunchAgents containing :

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

And in /Users/USERNAME/Library/Scripts/script.bash we can test if the connected device is the right one :

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

Launch the service using

launchctl load ~/Library/LaunchAgents/yourscript


来源:https://stackoverflow.com/questions/44546021/mac-launch-command-when-device-connected-by-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!