0
votes

I am developing a Linux app that uses serial ports to communicate with some devices. I'm using usb-to-serial converters for all my devices, so all serial ports are connected through usb.

Currently I am using each port's name to identify it (ttyAM0 or ttyUSB1 etc), however this is very problematic, since ports enumaration keeps changing.

I cannot create a udev rule, in fact nothing should be changed to the OS itself, since it is considered that the end user will not be able/skillful to do so. (It is a commercial app).

So the question is: How can I uniquely identify each serial port and store this information to be used after next reboot?

1
Create a udev rule and modify your installer (or installation directions) to create said udev rule.Elliott Frisch
Ports can be changed in settings. PID and VID may not be known since the devices are many, and still under developement. I am targeting also in not giving root privilages to the app.Fotis Panagiotopoulos

1 Answers

0
votes

Ok I found the solution...
Since I am interested in Linux only, I check the folder /dev/serial/by-id for unique id for each device. The files there are links to the serial ports.

So...
Reading file names in that folder gives you id's.
Reading the target of each link gives you the port name.

Here is a piece of my working code:

    HashMap<String, String> portsMap = new HashMap<>();

    File serialFolder = new File("/dev/serial/by-id");
    File[] listOfDevices = serialFolder.listFiles();

    for (int i = 0; i < listOfDevices.length; i++)
    {
        if (Files.isSymbolicLink(listOfDevices[i].toPath()))
        {
            try
            {
                String portName = listOfDevices[i].getName();
                String id = Files
                        .readSymbolicLink(listOfDevices[i].toPath())
                        .toString()
                        .substring(
                        Files.readSymbolicLink(listOfDevices[i].toPath())
                        .toString().lastIndexOf("/") + 1);
                portsMap.put(id, portName);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }