This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
list_bluetooth_devices.py
76 lines (59 loc) · 2.75 KB
/
list_bluetooth_devices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python
# encoding: utf-8
import sys
from workflow import Workflow
log = None
GITHUB_SLUG = 'trietsch/alfred-bluetooth-connector'
def main(wf):
if wf.update_available:
wf.add_item('Update available for Alfred Bluetooth Connector!',
autocomplete='workflow:update',
valid=False)
import json
import sys
from subprocess import check_output, Popen, PIPE
import re
query = wf.args[0] if len(wf.args) else None
bluetooth_devices_pipe = Popen(
["/bin/bash", "-c", "/usr/libexec/PlistBuddy -c \"print :0:_items:0:device_title\" /dev/stdin <<< $(system_profiler SPBluetoothDataType -xml)"], stdout=PIPE)
bluetooth_devices_raw, err = bluetooth_devices_pipe.communicate()
# The following regex is quite complex, though that is due to the fact that the 'Dicts' provided by PlistBuddy are inconsistent in order. Therefore, the two fields we're reading "device_addr" and "device_isconnected" occur twice, in both orders. Below, we decide which of the two contains data and which doesn't.
# Feel free to try it out: https://regex101.com/r/GB5UKd/3
bluetooth_devices = re.findall(
r"(?s).*?(?:Dict\s?\{)\s*(.*?)\s?\=\s?(?:Dict).*?(?:(?:(?:device_isconnected)\s?\=\s?(?:attrib_((?:No|Yes))).*?(?:device_addr)\s?\=\s?((?:[0-9A-F]{2}[:-]){5}(?:[0-9A-F]{2})))|(?:(?:device_addr)\s?\=\s?((?:[0-9A-F]{2}[:-]){5}(?:[0-9A-F]{2})).*?(?:device_isconnected)\s?\=\s?(?:attrib_((?:No|Yes)))))", bluetooth_devices_raw)
normalized_devices = []
for device in bluetooth_devices:
address = device[3] if len(device[2]) == 0 else device[2]
connected = device[4] if len(device[1]) == 0 else device[1]
connected_text = "[Connected]" if connected == "Yes" else "[Disconnected]"
name = device[0] + " " + connected_text
if query:
normalized_devices.append({
'name_connected': name,
'address': address
})
else:
wf.add_item(
type='file',
title=name,
subtitle=address,
uid=address,
arg=address,
valid=True
)
if query:
normalized_devices = wf.filter(query, normalized_devices, key=lambda k: k['name_connected'])
for device in normalized_devices:
wf.add_item(
type='file',
title=device['name_connected'],
subtitle=device['address'],
uid=device['address'],
arg=device['address'],
valid=True
)
wf.send_feedback()
if __name__ == '__main__':
wf = Workflow(update_settings={'github_slug': GITHUB_SLUG})
log = wf.logger
sys.exit(wf.run(main))