I wanna make a simple connection between raspberry and phone but every time i write .accept() i get [Errno 77] File descriptor in bad state. Here is the code:
import bluetooth
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 19
host = "MACADDR"
s.connect((host,port))
client, badr = s.accept()
The problem is that you mixed up both client and server logic in the given code snippet. Once connect()
is called the socket becomes a client, so indeed trying to call accept()
after that would fail. Simply remove client, badr = s.accept()
to make the client side work.
Below is an example of the client side implementation:
import bluetooth
def client(remote_addr: str, remote_port: int):
client_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
print(f'Establishing connection to {remote_addr}:{remote_port}')
client_sock.connect((remote_addr, remote_port))
print('Connection established')
return client_sock
and here is an example of the server side implementation:
import bluetooth
def server(local_addr: str, local_port: int):
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind((local_addr, local_port))
server_sock.listen(1)
print('Listening for connection on {local_addr}:{local_port}...')
client_sock, remote_addr = server_sock.accept()
print(f'Device {remote_addr} connected')
return (server_sock, client_sock)
You can run server()
on the raspberry and client()
on the phone, or vice versa.