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:
JavaScript
x
7
1
import bluetooth
2
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
3
port = 19
4
host = "MACADDR"
5
s.connect((host,port))
6
client, badr = s.accept()
7
Advertisement
Answer
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:
JavaScript
1
9
1
import bluetooth
2
3
def client(remote_addr: str, remote_port: int):
4
client_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
5
print(f'Establishing connection to {remote_addr}:{remote_port}')
6
client_sock.connect((remote_addr, remote_port))
7
print('Connection established')
8
return client_sock
9
and here is an example of the server side implementation:
JavaScript
1
12
12
1
import bluetooth
2
3
def server(local_addr: str, local_port: int):
4
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
5
server_sock.bind((local_addr, local_port))
6
server_sock.listen(1)
7
8
print('Listening for connection on {local_addr}:{local_port}...')
9
client_sock, remote_addr = server_sock.accept()
10
print(f'Device {remote_addr} connected')
11
return (server_sock, client_sock)
12
You can run server()
on the raspberry and client()
on the phone, or vice versa.