bluetooth connection using pybluez

Posted by srj0408 on Super User See other posts from Super User or by srj0408
Published on 2014-06-11T20:55:08Z Indexed on 2014/06/11 21:28 UTC
Read the original article Hit count: 181

Filed under:
|
|

I am working on bluetooth not exactly on bluetooth stack-development but to use bluetooth in one of my project. I had done all that before using some of the py-bluez commands like hciconfig, hcitool scan , then simple-agents and using serial module inside python. But that was quite random. We were able to connect only one specific device based on its bluetooth address and there was no facility of reconnection once the devices are disconnected.

Now i want to try out this stuff in a sequential manner like this (i am doing that all on a RPI and for at present on ubuntu 12.04.)

i) Store some names in a file along with some other information with respect to that device. ii) Run a script to find out the device in locality with those names and if any one if found, report that. For this step, i had taken a reference from BTBook , made available from MIT. Below is the script for the same, but that script only search for the single name.

from bluetooth import *

target_name = "XT1033"
target_address = None
nearby_devices = discover_devices()

for address in nearby_devices:
    if target_name == lookup_name( address ):
            target_address = address
    break

if target_address is not None:
    print "found target bluetooth device with address ", target_address
        connect_socket(target_address);

else:
    print "could not find target bluetooth device nearby"

iii) Connect the device using client sock. But i dont have any device on which i can write a simple python script. My client can be any device that will be publishing data.

Now i came through a script in the same book, that actually connect to a client requesting permission to connect to server.

from bluetooth import *
port = 1
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",port))
server_sock.listen(1)
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
data = client_sock.recv(1024)
print "received [%s]" % data
client_sock.close()
server_sock.close()

here client_sock, client_info = server_sock.accept() provide the client address and port requested to be connected. Can i pass address obtained from the earlier script to this, so that it connect server to the client?

iv) Then if client get disconnected, re-connect(a simple polling can be used.)

All this stuff can be done using bash and py-bluez functions but i want to do that in a sequential manner.I am not a master in python but i can do some small stuff. Can any one guide me for the same or can direct me to more usefull resource through which i can continue my coding part after finding the "X", "Y" named devices.

© Super User or respective owner

Related posts about python

Related posts about bluetooth