I'm connecting to a custom BLE enabled board. Running bluetoothctl, I can pair and connect no problem from the command line.
I've been attempting to script it using Python and pexpect. Pexpect spawns a bluetoothctl instance, and then sends commands to and reads info from the bluetoothctl process.
I can interact with this process no problem, until I issue the command to connect to BLE peripheral. As soon as it connect, I can no longer interact with the process. Any attempts to read info from it time out, sending it commands has no effect.
Pexpect usage is based on this guys script.
Here's what my code looks like:
class Bluetoothctl:
"""A wrapper for bluetoothctl utility."""
def __init__(self):
subprocess.check_output("rfkill unblock bluetooth", shell=True)
self.process = pexpect.spawnu("bluetoothctl", echo=False)
def send(self, command, pause=0):
self.process.send(f"{command}\n")
time.sleep(pause)
if self.process.expect(["bluetooth", pexpect.EOF]):
raise Exception(f"failed after {command}")
def get_output(self, *args, **kwargs):
"""Run a command in bluetoothctl prompt, return output as a list of lines."""
self.send(*args, **kwargs)
return self.process.before.split("\r\n")
def get_device_info(self, mac_address):
"""Get device info by mac address."""
try:
out = self.get_output(f"info {mac_address}")
except Exception as e:
logger.error(e)
return False
else:
return out
def connect(self, mac_address):
"""Try to connect to a device by mac address."""
try:
self.send(f"connect {mac_address}", 2)
except Exception as e:
logger.error(e)
return False
else:
res = self.process.expect(
["Failed to connect", "Connection successful", pexpect.EOF]
)
return res == 1
bl = Bluetoothctl()
print( bl.get_device_info( [mac] ) ) // THIS RETURNS INFO SUCCESSFULLY
bl.connect( [mac] ) // CONNECTS SUCESSFULLY
print( bl.get_device_info( [mac] ) ) // This fails by timing out
So before I connect, I get the device info, then I connect successfully, then I try the same command to get device info, and it fails (returns no response after 30 seconds)
What's going wrong? How can I find out more info about this? Thanks.