This is the error I am getting when I connect to my mobile phone using the connect method in this documentation: https://gist.github.com/egorf/66d88056a9d703928f93,

raise TIMEOUT(msg)
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0xb62e3ab0>
command: /usr/bin/bluetoothctl
args: ['/usr/bin/bluetoothctl']
buffer (last 100 chars): 'mCHG\x1b[0m] Device 98:5F:D3:57:1A:BD RSSI: -47\r\n[\x 1b[0;93mCHG\x1b[0m] Device 98:5F:D3:57:1A:BD TxPower: 4\r\n'
before (last 100 chars): 'mCHG\x1b[0m] Device 98:5F:D3:57:1A:BD RSSI: -47\r\n[\x 1b[0;93mCHG\x1b[0m] Device 98:5F:D3:57:1A:BD TxPower: 4\r\n'
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 544
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
0: re.compile("Failed to connect")
1: re.compile("Connection successful")
2: EOF

The connection is supposed to fail since my phone is connected to another device, however it should return "Failed to connect" and move on to the next paired-device that I have in my loop which calls the connect method. Unfortunately I cannot show my code. What should I do in the connect method to bypass the exception and return false for Failed to connect?


The pexpect library has thrown the pexpect.exceptions.TIMEOUT error which is not caught by the code in BluetoothCtl. So you can catch it yourself instead - wrap your call to connect, just like the linked gist does for Bluetooth Errors.

import the pexpect exceptions

import pexpect.exceptions

Add the following method to your calling code and pass it the BluetoothCtl object you were using for connect. Then you can call this method instead of connect to handle the timeout case.

def connect2(macAddress, controller):
        return controller.connect(macAddress)
    except pexpect.exceptions.TIMEOUT:
        print("timed out connecting to {}".format(macAddress))
        return False
  • I'm getting an error on the controller.connect(macAddress) call because the compiler thinks that controller is a String, do I need to pass in a controller object? If so, how?
    – nenur
    Jan 19 '18 at 17:08
  • your original code i'd imagine would have been something like controller.connect(macAddress) instead use connect2(macAddress, controller). I don't know what you called your BluetoothCtl instance though.
    – tobyd
    Jan 19 '18 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.