import subprocess import time # [!] To get this to work bluetoothctl needs to connect to the device before using BLE_GATT.connect def ble_ctl(addr:str): """ use bluetoothctl interactively: scan on, ... wait ..., scan off, connect CF:CD:27:79:55:6B, exit subprocess has a relevant bug in line-buffering, see issue 21471 """ ctl = subprocess.Popen(['bluetoothctl'], stdin = subprocess.PIPE) def writeHelper(proc, str, delay = 1): proc.stdin.write(str.encode('utf-8')) proc.stdin.flush() time.sleep(delay) # send bluetoothctl commands interactively writeHelper(ctl, "scan on\n", 4) writeHelper(ctl, "scan off\n") writeHelper(ctl, "connect " + addr + "\n", 3) writeHelper(ctl, "exit\n") # wait for child subprocess to terminate while True: if None != ctl.poll(): break time.sleep(.1) ble_ctl('CF:CD:27:79:55:6B')