2016-09-17 160 views
1

我想继续尝试连接到蓝牙设备,直到连接成功。下面的代码使用递归调用,这可能会导致满足递归的最大级别。连续尝试连接蓝牙套接字直到连接成功

是否BluetoothSocket.connect()返回成功或失败的值?

def connect(self): 

    # the bluetooth device uses port 1 
    port = 1 

    if not self.quit: 
    try: 
     print 'Attempting Connection...' 
     # Create the client socket 
     self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 
     self.socket.connect((self.bt_mac, port)) 
    except bluetooth.btcommon.BluetoothError: 
     self.connect() 
    return self.SUCCESS 

的文档指出以下几点:

connect(self, addrport) 

connect(addrport) 

可用性:GNU/Linux的,Windows XP中

插座连接到远程设备。对于L2CAP套接字,addrport是一个(host,psm)元组。对于RFCOMM插座,addrport是一个(host,channel)元组。对于SCO插座,addrport是房东。

回答

0

BluetoothSocket.connect()未明确返回表示成功或失败的值。但是,当bluetooth.btcommon.BluetoothError异常被捕获时,可以通过返回错误标志来实现。

在except块

因此,而不是试图再次连接在那里,我们可以返回一个错误标志(例如self.ERROR = -1

def connect(self): 
    # the bluetooth device uses port 1 
    port = 1 

    try: 
     print 'Attempting Connection...' 
     # Create the client socket 
     self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 
     self.socket.connect((self.bt_mac, port)) 
     except bluetooth.btcommon.BluetoothError: 
     return self.ERROR 
     return self.SUCCESS 

上述连接方法将一个无限循环的内部调用(代码如下所示),只有从连接功能返回成功时才会中断。否则,连接方法将不断被调用。

while True: 
    # connect to device 
    res = mydevice.connect() 
    # print connection status -1=fail, 0=success 
    if res == SUCCESS: 
     print "Success" 
     # break out of connection loop if success 
     break 
    if res == ERROR: 
     print "Failed"