🌐 이 글의 한국어 원문이 있습니다.한국어 원문 보기 →
Controlling Bluetooth with Python on Ubuntu
When I set up a vacuum tube amp in my father's room, I connected the amp to his computer over Bluetooth audio. But then the Bluetooth connection dropped every time the computer shut down, and since he found it hard to reconnect, he always called me. After some thought, I figured I could control Bluetooth from the CLI and simply reconnect it whenever it dropped. My father's computer runs Ubuntu.
#! /usr/bin/env python3
import subprocess
import re
import time
remove_color_code_regex = re.compile(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))')
# Bluetooth audio module
device_mac = '00:00:00:00:00:00'
device = 'hci0'
waiting_time = 30
def execute(cmd, pipe=False):
if isinstance(cmd, str):
cmd_list = cmd.split(' ')
elif isinstnace:
cmd_list = cmd
if pipe:
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0].decode()
else:
output = subprocess.check_output(cmd_list).decode()
return remove_color_code_regex.sub('', output)
def check_paired_device(device_mac):
cmd = 'echo "paired-device" | bluetoothctl'
output = execute(cmd, pipe=True)
device_map = {}
for mac, name in re.findall(r'\[NEW\] Device (.+) (.+)', output):
device_map[mac] = name
# check paired_list
for name in re.findall(r'\[(.+)\]# paired-device', output):
for dev_mac, dev_name in device_map.items():
if dev_name == name and device_mac == dev_mac:
return True
return False
def check_device_alive(device_mac):
cmd = 'echo "paired-device" | bluetoothctl'
output = execute(cmd, pipe=True)
for mac, name in re.findall(r'\[NEW\] Device (.+) (.+)', output):
if mac == device_mac:
return True
return False
def scan_device(device_mac):
if check_paired_device(device_mac):
return True
# only unparied device is scaned.
output = execute(f"hcitool -i {device} scan")
p = re.compile(r'((?:[0-9a-fA-F]:?){12})\t(.+)')
for mac, name in re.findall(p, output):
print(mac, device_mac)
if mac == device_mac:
return True
return False
def connect_device(device_mac):
cmd = f'echo "connect {device_mac}" | bluetoothctl'
output = execute(cmd, pipe=True)
str_time = time.time()
while not check_paired_device(device_mac):
time.sleep(0.3)
if 3 < time.time() - str_time:
return False
return True
def disconnect_device(device_mac):
cmd = f'echo "disconnect {device_mac}" | bluetoothctl'
output = execute(cmd, pipe=True)
str_time = time.time()
while check_paired_device(device_mac):
time.sleep(0.3)
if 5 < time.time() - str_time:
return False
return True
def main():
while True:
try:
if not check_paired_device(device_mac):
connect_device(device_mac)
except Error as e:
print(e)
time.sleep(waiting_time)
if __name__ == '__main__':
main()
passI implemented the functions I thought I'd need, but once I actually tried it, it seemed that since I'm just reconnecting an already-registered module, checking the connection and attempting to connect would be enough. It checks every 30 seconds and reconnects if the connection has dropped. It's Python, but the actual control is done by the bluetoothctl and hcitool commands. The script parses their output to check the status and issues control commands accordingly.
I could have written it in bash, but I'm more comfortable with Python, so I implemented it in Python.

