Python PyBluez loses Bluetooth connection after a while

Posted by Travis G. on Ask Ubuntu See other posts from Ask Ubuntu or by Travis G.
Published on 2012-03-20T05:27:11Z Indexed on 2012/03/20 5:39 UTC
Read the original article Hit count: 572

Filed under:
|

I am using Python to write a simple serial Bluetooth script that sends information about my computer stats periodically. The receiving device is a Sparkfun BlueSmirf Silver.

The problem is that, after the script runs for a few minutes, it stops sending packets to the receiver and fails with the error:

(11, 'Resource temporarily unavailable')

Noticing that this inevitably happens, I added some code to automatically try to reopen the connection. However, then I get:

Could not connect:  (16, 'Device or resource busy')

Am I doing something wrong with the connection? Do I need to occasionally reopen the socket? I'm not sure how to recover from this type of error.

I understand that sometimes the port will be busy and a write operation is deferred to avoid blocking other processes, but I wouldn't expect the connection to fail so regularly. Any thoughts?

Here is the script:

import psutil
import serial
import string
import time
import bluetooth

sampleTime = 1
numSamples = 5
lastTemp = 0

TEMP_CHAR = 't'
USAGE_CHAR = 'u'
SENSOR_NAME = 'TC0D'

#gauges = serial.Serial()
#gauges.port = '/dev/rfcomm0'
#gauges.baudrate = 9600
#gauges.parity = 'N'
#gauges.writeTimeout = 0
#gauges.open()

filename = '/sys/bus/platform/devices/applesmc.768/temp2_input'


def parseSensorsOutputLinux(output):
    return int(round(float(output) / 1000))

def connect():
    while(True):    
        try:
            gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            gaugeSocket.connect(('00:06:66:42:22:96', 1))
            break;
        except bluetooth.btcommon.BluetoothError as error:
            print "Could not connect: ", error, "; Retrying in 5s..."
            time.sleep(5)
    return gaugeSocket;

gaugeSocket = connect()
while(1):
    usage = psutil.cpu_percent(interval=sampleTime)
    sensorFile = open(filename)
    temp = parseSensorsOutputLinux(sensorFile.read())
    try:
        #gauges.write(USAGE_CHAR)
        gaugeSocket.send(USAGE_CHAR)
        #gauges.write(chr(int(usage))) #write the first byte
        gaugeSocket.send(chr(int(usage)))
        #print("Wrote usage: " + str(int(usage)))
        #gauges.write(TEMP_CHAR)
        gaugeSocket.send(TEMP_CHAR)
        #gauges.write(chr(temp))
        gaugeSocket.send(chr(temp))
        #print("Wrote temp: " + str(temp))
    except bluetooth.btcommon.BluetoothError as error:
        print "Caught BluetoothError: ", error
        time.sleep(5)
        gaugeSocket = connect()
        pass

gaugeSocket.close()

EDIT: I should add that this code connects fine after I power-cycle the receiver and start the script. However, it fails after the first exception until I restart the receiver.

P.S. This is related to my recent question, Why is /dev/rfcomm0 giving PySerial problems?, but that was more about PySerial specifically with rfcomm0. Here I am asking about general rfcomm etiquette.

© Ask Ubuntu or respective owner

Related posts about python

Related posts about bluetooth