Reputation: 226
I'm writing a python script that is running on a raspberry pi. An android app needs to be able to connect to the raspberry pi through bluetooth and send it some data.
I am not sure how to connect them because the server (pi) will not know the name of the android, and client (application) won't know the address and port of the raspberry pi. Is there a clean solution to the bluetooth connection?
Here is the current server code. The current solution is have the server run on a specific port, but this doesn't seem very clean as the mac address/port may be different each time.
import bluetooth
hostMACAdress = '' # need to fill this in
port = 3
backlog = 1
size = 1024
socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
socket.bind((hostMACAdress, port))
socket.listen(backlog)
try:
client, clientInfo = socket.accept()
while True:
data = client.recv(size)
if data:
print(data)
client.send(data) # Echo
Upvotes: 1
Views: 998
Reputation: 8004
The host MAC address in your script on the RPi will be the address of the RPi. You will have to declare a port, but many Android apps e.g. Serial Bluetooth Terminal will search for the port.
You will need to pair the RPi and the Android phone first. There is a good procedure at: https://bluedot.readthedocs.io/en/latest/pairpiandroid.html
There is an issue on recent versions of the RPi OS where PulseAudio can be using the RFCOMM Serial Port Profile (SPP) so you may have to stop PulseAudio if it is complaining about rfcomm already in use.
Finally, you don't need to use the bluetooth
dependency. It can be done using the standard Python socket library. More details at: https://blog.kevindoran.co/bluetooth-programming-with-python-3/
Upvotes: 2