Skip to content

Instantly share code, notes, and snippets.

@matthew-brett
Last active April 29, 2021 09:41
Show Gist options
  • Save matthew-brett/7826f1f3f4758b77aa96be8f4f8c0a07 to your computer and use it in GitHub Desktop.
Save matthew-brett/7826f1f3f4758b77aa96be8f4f8c0a07 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
""" Show bluetooth power for named device on macOS
"""
import sys
import json
from subprocess import check_output, DEVNULL
from argparse import ArgumentParser, RawDescriptionHelpFormatter
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 get_devices(dt_profiles):
devices = {}
for dt_p in dt_profiles:
for d in dt_p['device_title']:
for key in d:
if key in devices:
raise RuntimeError(f'Duplicate device name {key}')
devices[key] = d[key]
return devices
def get_device(devices, device_name):
found = [d for d in devices if list(d) == [device_name]]
if not found:
dev_names = sum([list(d) for d in devices], [])
raise RuntimeError(f'Could not find device "{device_name}"\n'
'Options are:\n' + '; '.join(dev_names))
if len(found) > 1:
raise RuntimeError(f'More than one device "{device_name}"')
def extract_attr(devices, device_name, attr='device_RSSI'):
device = devices.get(device_name)
if device_name is None:
raise RuntimeError(f'Could not find device "{device_name}"\n'
'Options are:\n' + '; '.join(devices))
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 get_parser():
parser = ArgumentParser(description=__doc__, # Usage from docstring
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('bt_device_name', nargs='?',
help='Bluetooth device name')
return parser
def main():
parser = get_parser()
args = parser.parse_args()
bt_p = get_profile_dt('SPBluetoothDataType')
devices = get_devices(bt_p)
if args.bt_device_name is None:
print('Specify device name. One of:\n' +
'; '.join(get_devices(bt_p)), file=sys.stderr)
return(1)
print(extract_attr(devices, 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