Search code examples
portpyserialio-redirection

How to obtain bluetooth port direction with pyserial?


I'm trying to connect to an RN42, module through python. When the RN42 pairs with W10 it creates two virtual COM ports(outgoing and incoming). I need to connect to the outgoing port.

I'm trying to do this automatically. I've tried:

import serial
import serial.tools.list_ports as port_lst

ports = list(port_lst.comports())
bluetooth_ports = []
for p in ports:
    if 'Bluetooth' in p.description:
        bluetooth_ports += [p.device]
bluetooth_com = serial.Serial(bluetooth_ports[0],115200)

I thought that the first port was usually the outgoing one, but I've paired the module to another computer, and this didn't apply (the second port was the outgoing one). Is there a way to find out the direction of the COM ports?

Thanks!!!


Solution

  • Although this is an antique question, I have been searching for the answer to this for some time myself and since I finally figured it out I wanted others to be able to find the answer. With help from a blog entry at in the hand and its accompanying gist:

    The trick is to acquire the hwid using pySerial, then parse the address. The incoming port in a pair has an address of zero and the outgoing port has a nonzero address. Here is some ugly Python code that decodes it:

    import serial.tools.list_ports
    cp=serial.tools.list_ports.comports()
    for p in cp:
        if "BTHENUM" in p.hwid:
            start_of_address=p.hwid.rfind("&")
            end_of_address=p.hwid.rfind("_")
            address=p.hwid[start_of_address+1:end_of_address]
            if int(address,16)==0:
                port_type="incoming"
            else:
                port_type="outgoing"
            print(p.hwid)
            print(p.name, address, port_type)
    

    And the output:

    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\7&CC47540&0&000000000000_000000A8
    COM4 000000000000 incoming
    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002\7&CC47540&0&209BA5420081_C00000000
    COM5 209BA5420081 outgoing