Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@matthew-brett
Created April 11, 2021 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthew-brett/761b37d70f083d72466187fc6a9d505c to your computer and use it in GitHub Desktop.
Save matthew-brett/761b37d70f083d72466187fc6a9d505c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
import json
from subprocess import check_output, DEVNULL
from argparse import ArgumentParser, RawDescriptionHelpFormatter
def get_parser():
parser = ArgumentParser(description=__doc__, # Usage from docstring
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('bt_device_name',
help='Bluetooth device name')
return parser
def get_profile_dt(data_type):
output = check_output(['system_profiler', data_type, '-json'],
encoding=sys.getdefaultencoding(),
stderr=DEVNULL)
jdict = json.loads(output)
return jdict.pop(data_type)
def extract_attr(dt_profile, device_name, attr='device_RSSI'):
assert len(dt_profile) == 1 # More than one BT interface?
devices = dt_profile[0]['device_title']
found = [d for d in devices if list(d) == [device_name]]
if not found:
raise RuntimeError(f'Could not find device "{device_name}"')
if len(found) > 1:
raise RuntimeError(f'More than one device "{device_name}"')
device = found[0][device_name]
connected = device.get('device_isconnected')
if connected is None:
raise RuntimeError(f'No connection information for "{device_name}"')
if connected == 'attrib_No':
raise RuntimeError(f'Device "{device_name}" not connected')
data = device.get(attr)
if data is None:
raise RuntimeError(f'No attribute "{attr}" for "{device_name}"')
return data
def main():
parser = get_parser()
args = parser.parse_args()
bt_p = get_profile_dt('SPBluetoothDataType')
print(extract_attr(bt_p, args.bt_device_name, 'device_RSSI'))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment