Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which device is attached to a USB-serial port in Linux using C?

Tags:

c

We are making a device and it has 8 serial ports. It runs on the Monta Vista Pro5 kernel. And we are working in C.

Suppose: A device gets attached to ttyUSB0, ttyUSB1 and ttyUSB2. The next device gets connected to ttyUSB3 and another to ttyUSB4. How can I know which device gets attached to which port ?? ie ttyUSB0 or ttyUSB1 or so on. Is there a way to directly query the device and find which port it is attached to. Or, in C, open ttyUSB0, query it somehow and get some reply as to which device it is ??

A rather complicated way: do a stat of, say /dev/ttyUSB0. Get the device number. And search for this in /proc/bus/usb/devices and find the vendor id or something to identify the device.

Or: Is there some way to reserve ttyUSB0,ttyUSB1 and ttyUSB2 for one device, ttyUSB3 for another and so on when they are plugged in ? This way I will know which device is connected to which port.

Help please..... :)

Thanks in advance. Nubin Stanley

like image 698
stanzlavos Avatar asked Nov 16 '10 10:11

stanzlavos


1 Answers

You can use udev rules to create symbolic links just to your device:

(these rules go in /etc/udev/rules.d/-name.rules -- look at your udev documentation

KERNEL=="ttyUSB*", ATTRS{idVendor}=="<vendorid>", MODE="0666", SYMLINK+="mydev"

You have to specify your vendor id and/or product id for your device. Then those devices will be available at /dev/mydev in the above example.

You can also use various other parameters to create appropriate unique symbolic links for your use. Check udev man page.

like image 119
rsmoorthy Avatar answered Oct 12 '22 23:10

rsmoorthy