Search code examples
clinuxdebianraspbian

Using access to check usb port by path fails because of port0 suffix


I want to be able to check if there is something plugged into a specific USB port in a C program. Currently I used

ls /dev/serial/by-path

to get the path to the device. I hardcoded the path in the program and use the "access" function with F_OK to check if it exists. this works fine when i tested it with one device but when i tried another device it fails because "-port0" gets added at the end of the path when this device is plugged in.

The output looks like this - device 1:

$ls /dev/serial/by-path/
platform-3f980000.usb-usb-0:1.2:1.0

Device 2:

$ls /dev/serial/by-path/
platform-3f980000.usb-usb-0:1.2:1.0-port0

I would like to know what causes this, if there are other variations of this and if there are other solutions besides checking both paths. the OS is raspbian 12 running on a raspberry pi 3


Solution

  • i solved the problem by using a udevadm to link the two different paths to a single symbol. i made a file named usb-serial.rules in /etc/udev/rules.d/ the rules i used are

    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.1-usb-0:1:1.0", SYMLINK+="STATICUSBPORT1"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.0-usb-0:1:1.0", SYMLINK+="STATICUSBPORT2"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.0-usb-0:2:1.0", SYMLINK+="STATICUSBPORT3"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.1-usb-0:2:1.0", SYMLINK+="STATICUSBPORT4"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.1-usb-0:1:1.0-port0", SYMLINK+="STATICUSBPORT1"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.0-usb-0:1:1.0-port0", SYMLINK+="STATICUSBPORT2"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.0-usb-0:2:1.0-port0", SYMLINK+="STATICUSBPORT3"
    SUBSYSTEM=="tty", ENV{ID_PATH}=="platform-xhci-hcd.1-usb-0:2:1.0-port0", SYMLINK+="STATICUSBPORT4"
    

    which gives me access to the device at /dev/STATICUSBPORT# when either is plugged in. the ID_PATH's are for the raspberry pi 5 so it might be slightly different for the raspberry pi 3. the correct path can be found with udevadm info /dev/ttyUSB0 | grep "ID_PATH="