Python Bluetooth socket gives OSError

Viewed 198

I would like to use sockets in python 3.9 on Windows 10 to connect to a HC-05 module on an arduino and send/read some characters. However, using the following code, I get this error:

import socket
adapter_addr = '00:21:11:01:FA:1C'
port = 1  # Normal port for rfcomm?
buf_size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, 
socket.BTPROTO_RFCOMM)
s.bind((adapter_addr, port))
s.listen(1)
try:
    print('Listening for connection...')
    client, address = s.accept()
    print(f'Connected to {address}')

    while True:
        data = client.recv(buf_size)
        if data:
            print(data)
except Exception as e:
    print(f'Something went wrong: {e}')
    client.close()
    s.close()
line 30, in <module>
    s.bind((adapter_addr, port))
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I've also tried using the PyBluez library, but it gives similar errors. Thanks in advance for any help

1 Answers

It looks like your problem might be to do with the RFCOMM channel number (what you refer to as port). I suggest you first read up on that say here, because your code otherwise looks fine at least as far as listening. The reason channel 1 is giving you those problems (and I had the same problem when testing your code) is there's probably already another service like say a virtual COM port using that channel number. If you try some other numbers you should find it doesn't fail. The winsock library Python uses in turn has a constant BT_PORT_ANY you can use to automatically assign it but Python doesn't seem to expose this. Through trial and error it seems to be defined to -1.

Given you're using RFCOMM you might want to look at using the virtual serial ports Windows already makes for you (COMx). Something like pyserial for instance. This would be a lot simpler, and you can avoid everything Bluetooth related as long as you can identify your clients' serial ports.

Related