Continuously attempt to connect bluetooth socket until connection is successful
<p>I want to keep trying to connect to a bluetooth device until the connection is successful. The code below uses a recursive call, and this could lead to the maximum level of recursion being met.</p>

<p>Does <code>BluetoothSocket.connect()</code> return a value for success or failure?</p>

<pre><code>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
</code></pre>

<p>The documentation states the following:</p>

<pre><code>connect(self, addrport)

connect(addrport)
</code></pre>

<p>availability: GNU/Linux, Windows XP</p>

<p>Connect the socket to a remote device. For L2CAP sockets, <code>addrport</code> is a <code>(host,psm)</code> tuple. For RFCOMM sockets, <code>addrport</code> is a <code>(host,channel)</code> tuple. For SCO sockets, <code>addrport</code> is just the host.</p>

<p><code>BluetoothSocket.connect()</code> does not explicitly return a value that signals success or failure. However, this can be achieved by returning an error flag when <code>bluetooth.btcommon.BluetoothError</code> exception is caught.</p>

<p>So in the except block, instead of trying to connect again right there, we can return an error flag (e.g. <code>self.ERROR = -1</code>)</p>

<pre><code>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
</code></pre>

<p>The above connect method would be called inside of an infinite loop (code shown below) that is broken only when success is returned from the connect function. Otherwise, the connect method will continuously be called.</p>

<pre><code>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"
</code></pre>

python bluetooth