Search code examples
pythonbluetoothpybluez

Connect to local bluetooth


I am using pybluez to develop a bluetooth application on linux in python. I want to know if it is possible to connect to a "localhost" for bluetooth so I can run the client and server on the same machine (as most people do for web development).

If this is not possible, how to most people develop bluetooth applications? Do they just run the client and server on different devices or is there a more clever way to handle this?

Eventually the server will run on a raspberry pi and the client will be any bluetooth enabled device (cell phone, laptop, etc.) but during development it would be great if I could run both on the same machine.

Here is my server:

import bluetooth as bt

socket = bt.BluetoothSocket(bt.RFCOMM)

host = ""
socket.bind((host, bt.PORT_ANY))
port = socket.getsockname()[1]
print("port: " + str(port))
socket.listen(1)

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
# bt.advertise_service(socket, "BTServer", uuid)

print("Listening on " + host + ":" + str(port))

client_sock, addr = socket.accept()
print("Connection accepted from " + addr)

data = client_sock.recv(1024)
print(data)

client_sock.close()
socket.close()

And when I call services = bt.find_service(name=None, uuid=None, address="localhost") on the client it cannot find any services.


Solution

  • Through further research I have found that it is not possible to run a bluetooth client and server on the same device with the same bluetooth adapter. For local testing you can either use two bluetooth enabled computers or get a bluetooth dongle.