Created
November 16, 2018 10:04
-
-
Save gxfxyz/f49585d2eedf84bfb259c57312bf5ef3 to your computer and use it in GitHub Desktop.
Check if a bluetooth device is connected or not on macOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Check if a bluetooth device is connected or not on macOS. | |
Command-line usage: | |
$ python check_bluetooth_connection.py bluetooth_device_name | |
Library usage: | |
from check_bluetooth_connection import check_bluetooth_connection | |
is_connected = check_bluetooth_connection(device_name) | |
""" | |
import sys | |
import subprocess | |
PY3K = sys.version_info >= (3, 0) | |
if PY3K: | |
from plistlib import loads as read_plist_from_string | |
else: | |
from plistlib import readPlistFromString as read_plist_from_string | |
def check_bluetooth_connection(device_name): | |
output = subprocess.check_output(["system_profiler", | |
"-xml", | |
"-detailLevel", | |
"basic", | |
"SPBluetoothDataType"]) | |
plist = read_plist_from_string(output) | |
devices = plist[0]['_items'][0]['device_title'] | |
for d in devices: | |
if device_name in d.keys(): | |
device_info = d[device_name] | |
break | |
else: | |
msg = u"\"{}\" not found".format(device_name) | |
if not PY3K: | |
msg = msg.encode('utf-8') | |
raise ValueError(msg) | |
if device_info['device_isconnected'] == "attrib_Yes": | |
return True | |
else: | |
return False | |
def main(): | |
if len(sys.argv) <= 1: | |
print("Usage: python check_bluetooth_connection.py " | |
"bluetooth_device_name") | |
return | |
device_name = sys.argv[1] | |
if not PY3K: | |
device_name = device_name.decode('utf-8') | |
try: | |
is_connected = check_bluetooth_connection(device_name) | |
except (OSError, subprocess.CalledProcessError) as e: | |
print(e) | |
print("----") | |
print("Failed to run \"system_profiler -xml -detailLevel basic " | |
"SPBluetoothDataType\"") | |
sys.exit(1) | |
except ValueError as e: | |
print(e) | |
sys.exit(1) | |
if is_connected: | |
print("Connected") | |
else: | |
print("Disconnected") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment