Python I have device ID how to get dev address

2.9k Views Asked by At

I have a USB device, it may not be connected to the same port everytime it is plugged into the PC, how can i find it's dev-address given that I have its UID ?

import serial.tools.list_ports as port

portlist = list(port.comports())
for p in portlist:
  print p

gives me the output :

/dev/ttyS0 - ttyS0
/dev/ttyUSB1 - USB2.0-Serial
/dev/ttyUSB0 - FT232R USB UART

my device is FT232R USB UART ,currently whose dev address is /dev/ttyUSB0 ,and I need this in my program for serial r/w (ser = serial.Serial(port, baud)).But if multiple devices are connected previously and I plug in this device, it changes this address, my question is how can I find out this address every time I plug my device?

1

There are 1 best solutions below

0
On

You do not need to use pyusb. If your system uses udev to manage hot-plug devices (like most Linux distributions do nowadays) you could use pyudev library to look up your device. Or even simpler, find your device in /dev/serial/by-id and use that symlink instead of /dev/ttyUSBx in your code. It is guaranteed to stay the same regardless of the order of connection as long you do not connect another device with the same serial number.

Otherwise:

import serial

UID = '12345678'
ports = {p.serial_number:p.device for p in serial.tools.list_ports.comports() if p.serial_number}
if UID in ports:
    port = serial.Serial(ports[UID], ...)