简体   繁体   English

Java中的串行端口唯一标识

[英]Serial port unique identification in Java

I am developing a Linux app that uses serial ports to communicate with some devices. 我正在开发使用串行端口与某些设备进行通信的Linux应用程序。 I'm using usb-to-serial converters for all my devices, so all serial ports are connected through usb. 我为所有设备使用USB到串行转换器,因此所有串行端口都通过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. 当前,我正在使用每个端口的名称进行标识(ttyAM0或ttyUSB1等),但是这非常有问题,因为端口的枚举不断变化。

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. 我无法创建udev规则,实际上不应更改操作系统本身,因为认为最终用户将无能力/没有技能。 (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? 因此,问题是:如何唯一标识每个串行端口并存储此信息以在下次重新启动后使用?

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. 因为我仅对Linux感兴趣,所以我检查/dev/serial/by-id文件夹中每个设备的唯一ID。 The files there are links to the serial ports. 那里的文件有到串行端口的链接。

So... 所以...
Reading file names in that folder gives you id's. 读取该文件夹中的文件名即可获得ID。
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();
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM