java - Ubuntu RXTX 无法识别 USB 串口设备

标签 java ubuntu serial-port usb rxtx

我正在将带有 librxtx-java 的设备连接到 Ubuntu。该代码之前在10.04中有效,但在12.04中它无法发现连接到计算机的usb-serial。

java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while ( portEnum.hasMoreElements() )
{
    CommPortIdentifier portIdentifier = portEnum.nextElement();
    System.out.println( portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()) );
}

这部分代码永远不会进入 while 循环,尽管安装了适当的 librxtx-java 库,并且设备被识别(dmesg | tail 在一行中显示 USB“检测到串行设备转换器”)。

更新:

看来 Ubuntu 12.04 64 位无法与任何 USB 串行设备一起使用(尽管它们出现在 dmesg 中并显示为/dev/ttyUSB,这似乎不仅仅是 Java 的问题。

最佳答案

我安装了 Ubuntu 11.10 内核 3.0.0-12-generic-pae 和 librxtx-java 版本 2.2pre2-8。使用下面的代码,它可以正确列出我的串行端口。现在你已经正确安装了 usb 到串口转换器了吗?您需要检查转换器使用哪个端口。使用下面的示例应用程序,您可以尝试类似 java -cp/usr/share/java/RXTXcomm.jar: 的操作。获取通信端口 2

请确保您对/dev/中的 ttySXX 或 ttyUSBXX 文件具有正确的权限。

crw-rw---- 1 root dialout 4, 65 2012-02-29 01:08 /dev/ttyS1
crw-rw---- 1 root dialout 4, 66 2012-02-29 01:08 /dev/ttyS2

这些串行端口显示在我的系统中,想要运行该应用程序的用户应该在组拨出下。要添加您自己,请使用:

sudo usermod -a -G dialout username

您现在应该在“拨出”组中。

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

public class GetCommPorts
{
    static Enumeration<CommPortIdentifier>            portList;
    static CommPortIdentifier portId;
    static SerialPort                 serialPort;
    static OutputStream          outputStream;
    static boolean                    outputBufferEmptyFlag = false;    


    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader(InputStream in)
        {           
            this.in = in;           
        }

        @Override
        /** 
         *  treat \n as end of block.
         */
        public void serialEvent(SerialPortEvent ev)
        {
            int data;

            try
            {
                int len = 0;
                while ( (data = in.read()) > -1)
                {
                    if (data == '\n')
                    {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.println(new String(buffer, 0, len));
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(-1);
            }           
        }       
    }

    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter(OutputStream out)
        {
            this.out = out;
        }

        @Override
        public void run()
        {           
            try
            {
                int c = 0;
                while ( (c = System.in.read()) > -1)
                {
                    this.out.write(c);
                }
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(-1);
            }

        }

    }

    private static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
        case CommPortIdentifier.PORT_I2C:
            return "I2C";
        case CommPortIdentifier.PORT_PARALLEL:
            return "Parallel";
        case CommPortIdentifier.PORT_RAW:
            return "Raw";
        case CommPortIdentifier.PORT_RS485:
            return "RS485";
        case CommPortIdentifier.PORT_SERIAL:
            return "Serial";
        default:
            return "unknown type";
        }
    }

    private static void listPorts()
    {
        @SuppressWarnings("unchecked")
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();

        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );           

            if (portIdentifier.getPortType() == 1)
            {
                try
                {
                    serialPort =  (SerialPort) portIdentifier.open(portIdentifier.getName(), 3000);
                }
                catch (PortInUseException e)
                {
                    System.err.print("port in use");
                    continue;
                }

                System.out.println("Baud is " + serialPort.getBaudRate());    
                System.out.println("Bits is " + serialPort.getDataBits());    
                System.out.println("Stop is " + serialPort.getStopBits());    
                System.out.println("Par is " + serialPort.getParity());
                serialPort.close();
            }
        }
    }

    private static int doReadWrite(String portName)
    {
        CommPortIdentifier portIdentifier;

        try
        {
            portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

            if (portIdentifier.isCurrentlyOwned())
            {
                System.err.println("error: port is currently in use");
                return -1;
            }

            SerialPort sport = (SerialPort) portIdentifier.open(portName, 3000);
            sport.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            InputStream in = sport.getInputStream();
            OutputStream out = sport.getOutputStream();         

            (new Thread(new SerialWriter(out))).start();

            sport.addEventListener(new SerialReader(in));
            sport.notifyOnDataAvailable(true);
        }
        catch (NoSuchPortException e)
        {
            e.printStackTrace();
            return -1;
        } 
        catch (PortInUseException e)
        {
            e.printStackTrace();
            return -1;
        }
        catch (UnsupportedCommOperationException e)
        {
            e.printStackTrace();
            return -1;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return -1;
        }
        catch (TooManyListenersException e)
        {
            e.printStackTrace();
            return -1;
        }

        return 0;       
    } 

    static void showHelp()
    {
        System.out.println("Usage " + GetCommPorts.class.getName() + "N");
        System.out.println("1 read and write from the serial port");
        System.out.println("2 list all serial ports in the system");
        System.out.println("default show this help ");
    }


    public static void main(String[] args)
    {
        int operation = 0;

        try
        {
            if (args.length != 1)
            {
                showHelp();
                return;
            }
            operation = Integer.parseInt(args[0]);
        }
        catch (NumberFormatException e)
        {

        }       

        switch (operation)
        {
        case 1:
            doReadWrite("/dev/ttyUSB0");
            break;
        case 2:
            listPorts();
            break;
        default:
            showHelp();
        }

    }


}

此应用程序的输出:

$ java -cp /usr/share/java/RXTXcomm.jar:. GetCommPorts 2
/dev/ttyS1 - Serial
Baud is 9600
Bits is 8
Stop is 1
Par is 0
/dev/ttyS0 - Serial
Baud is 9600
Bits is 8
Stop is 1
Par is 0

关于java - Ubuntu RXTX 无法识别 USB 串口设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628988/

相关文章:

java - 这是单例延迟初始化吗?

c# - 使用 Android 模拟器从外部应用程序通过 COM 测试 AT 命令

ubuntu - docker 的 daemon.json 在哪里? (失踪)

linux - 从 bash 脚本设置串口流量控制线?

linux - 我们有什么东西可以检查嵌入式 linux 的 UART 端口中的数据是否可用吗?

java - 对属性键使用常量有什么意义?

java - 使用字符串生成器或存储过程进行单行选择

java - Spring-WS - 如何使用 Maven 插件通过 JAXB 启用 MTOM

linux - 如何使用 bash shell 创建新的启动器?

ubuntu - Cloudflare nginx 服务器 nodejs 应用 SSL 错误