zoukankan      html  css  js  c++  java
  • java RXTXcomm 串口通信

    另外一篇文章的源代码:https://github.com/shmll/SerialPortDemo

    本篇原文:https://blog.csdn.net/songyulong8888/article/details/78234275?utm_source=blogxgwz3

    RXTXcomm:提供了 Windows x64, x86, ia64 and Linux x86, x86_64等操作系统支持。
    下载地址 http://fizzed.com/oss/rxtx-for-java
    使用RXTXcomm首先要安排JRE环境,开发IED可能eclipse.
    1.下载系统相应的RXTXcomm。
    2.将rxtxSerial.dll、rxtxParallel.dll复制到jrein目录下。
    将RXTXcomm.jar复制到jrelibext目录下。
    可能还需要把rxtxParallel.dll、rxtxSerial.dll拷贝到:C:WINDOWSsystem32下。

    API概述

    接口

    CommDriver 可负载设备(the loadable device)驱动程序接口的一部分
    CommPortOwnershipListener 传递各种通讯端口的所有权事件
    ParallelPortEventListener 传递并行端口事件
    SerialPortEventListener 传递串行端口事件

    CommPort 通讯端口 CommDriver 可负载设备(the loadable device)驱动程序接口的一部分
    CommPortOwnershipListener 传递各种通讯端口的所有权事件
    ParallelPortEventListener 传递并行端口事件
    SerialPortEventListener 传递串行端口事件
    SerialPortEvent 异常类
    NoSuchPortException 当驱动程序不能找到指定端口时抛出
    PortInUseException 当碰到指定端口正在使用中时抛出
    UnsupportedCommOperationException 驱动程序不允许指定操作时抛出

    重要类详述

    CommPort类

    描述被底层系统支持的端口的抽象类。包含一些高层的IO控制方法,这些方法对于所有不同的通讯端口来说是通用的。SerialPort(串口) 和ParallelPort(并口)都是它的子类。
    CommPortIdentifier
    主要用于对串口进行管理和设置,是对串口进行访问控制的核心类。主要方法如下:
    [java] view plain copy
    addPortName(String, int, CommDriver) 添加端口名到端口列表里

    addPortOwnershipListener(CommPortOwnershipListener) 添加端口拥有的监听器

    removePortOwnershipListener(CommPortOwnershipListener) 移除端口拥有的监听器

    getCurrentOwner() 得到当前占有端口的对象或应用程序

    getName() 得到端口名称

    getPortIdentifier(CommPort) 得到参数打开的端口的CommPortIdentifier类型对象

    getPortIdentifier(String) 得到以参数命名的端口的CommPortIdentifier类型对象

    getPortIdentifiers() 得到系统中的端口列表

    getPortType() 得到端口的类型

    isCurrentlyOwned() 判断当前端口是否被占用

    open(FileDescriptor) 用文件描述的类型打开端口

    open(String, int) 打开端口,两个参数:程序名称,延迟时间(毫秒数)

    SerialPort 串口参数的函数

    getBaudRate() 得到波特率

    getParity() 得到检验类型

    getDataBits() 得到数据位数

    getStopBits() 得到停止位数

    setSerialPortParams(int, int, int, int) 设置串口参数依次为(波特率,数据位,停止位,奇偶检验)

    close() 关闭串口

    getOutputStream() 得到OutputStream类型的输出流

    getInputStream() 得到InputStream类型的输入流

    事件及事件方法

    isCD() 是否有载波

    isCTS() 是否清除发送

    isDSR() 数据是否准备就绪

    isDTR() 数据终端是否准备就绪

    isRI() 是否响铃侦测

    isRTS() 是否要求发送

    addEventListener(SerialPortEventListener) 向SerialPort对象中添加串口事件监听器

    removeEventListener() 移除SerialPort对象中的串口事件监听器

    getEventType() 得到发生的事件类型返回值为int型

    sendBreak(int) 设置中断过程的时间,参数为毫秒值

    setRTS(boolean) 设置或清除RTS位

    setDTR(boolean) 设置或清除DTR位

    notifyOnBreakInterrupt(boolean) 设置中断事件

    notifyOnCarrierDetect(boolean) 设置载波监听事件

    notifyOnCTS(boolean) 设置清除发送事件

    notifyOnDataAvailable(boolean) 设置串口有数据的事件

    notifyOnDSR(boolean) 设置数据备妥事件

    notifyOnFramingError(boolean) 设置发生错误事件

    notifyOnOutputEmpty(boolean) 设置发送缓冲区为空事件

    notifyOnParityError(boolean) 设置发生奇偶检验错误事件

    notifyOnRingIndicator(boolean) 设置响铃侦测事件

    串口参数的静态成员变量

    成员变量 说明 成员变量 说明 成员变量 说明
    DATABITS_5 数据位为5 STOPBITS_2 停止位为2 PARITY_ODD 奇检验

    DATABITS_6 数据位为6 STOPBITS_1 停止位为1 PARITY_MARK 标记检验

    DATABITS_7 数据位为7 STOPBITS_1_5 停止为1.5 PARITY_NONE 空格检验

    DATABITS_8 数据位为8 PARITY_EVEN 偶检验 PARITY_SPACE 无检验

    代码实例:

    package javaCOM;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.nio.Buffer;
    import java.util.Enumeration;
    import java.util.TooManyListenersException;
    
    import com.sun.org.apache.bcel.internal.generic.NEW;
    
    import gnu.io.CommDriver;
    import gnu.io.CommPortIdentifier;
    import gnu.io.PortInUseException;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import gnu.io.UnsupportedCommOperationException;
    import javafx.scene.chart.PieChart.Data;
    
    //import com.apple.dnssd.*;
    //import com.sun.org.apache.bcel.internal.generic.I2C;
    //import com.sun.org.apache.bcel.internal.generic.NEW;
    
    /**
     * Created by gbr on 13-12-11.
     */
    public class ReadCom implements SerialPortEventListener {
        //枚举类型
        Enumeration<CommPortIdentifier> portList;
        // 检测系统可用端口
        private CommPortIdentifier portIdentifier;
        // 端口
        private SerialPort port;
        // 输入/输出流
        private InputStream inputStream;
        private OutputStream outputStream;
    
        public void getPortList() {
            // 获得系统支持的所有端口(串口,并口)
            portList = CommPortIdentifier.getPortIdentifiers();
    
            while(portList.hasMoreElements()) {
                portIdentifier = (CommPortIdentifier)portList.nextElement();
                // CommPortIdentifier.PORT_SERIAL :串口
                // CommPortIdentifier.PORT_PARALLEL :并口
                // CommPortIdentifier.PORT_RS485 :RS485
                // CommPortIdentifier.PORT_I2C :I2C
                // CommPortIdentifier.PORT_RAW 
    
                if (portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    System.out.println(portIdentifier.getName());
                    if (portIdentifier.getName().equals("COM3")) {
                    try {
                        // open:打开串口,第一个参数应用程序名称 字符串可随意填写,第二个参数阻塞时等待多少毫秒
                        port = (SerialPort)portIdentifier.open("ReadCom888", 2000);
                        // 串口设置监听
                        port.addEventListener(this);
                        // 设置可监听
                        port.notifyOnDataAvailable(true);
                        // 设置串口通信参数
                        // 波特率,数据位,停止位,校验方式
                        port.setSerialPortParams(115200, 
                                SerialPort.DATABITS_8, 
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                        outputStream = port.getOutputStream();
                        inputStream = port.getInputStream();
    
                    } catch (PortInUseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (TooManyListenersException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (UnsupportedCommOperationException e) { 
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
        }
    
        @Override
        public void serialEvent(SerialPortEvent event) {
            // TODO Auto-generated method stub
            // TODO Auto-generated method stub
             /* 
            *  SerialPortEvent.BI:/*Break interrupt,通讯中断 
            *  SerialPortEvent.OE:/*Overrun error,溢位错误 
            *  SerialPortEvent.FE:/*Framing error,传帧错误 
            *  SerialPortEvent.PE:/*Parity error,校验错误 
            *  SerialPortEvent.CD:/*Carrier detect,载波检测  
            *  SerialPortEvent.CTS:/*Clear to send,清除发送  
            *  SerialPortEvent.DSR:/*Data set ready,数据设备就绪 
            *  SerialPortEvent.RI:/*Ring indicator,响铃指示 
            *  SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,输出缓冲区清空 
            *  SerialPortEvent.DATA_AVAILABLE:
            */  
            switch (event.getEventType()) {
                case SerialPortEvent.BI:
                case SerialPortEvent.OE:
                case SerialPortEvent.FE:
                case SerialPortEvent.PE:
                case SerialPortEvent.CD:
                case SerialPortEvent.CTS:
                case SerialPortEvent.DSR:
                case SerialPortEvent.RI:
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                    break;
                case SerialPortEvent.DATA_AVAILABLE: // 
                    readData();
                    break;
    
                default:
                    break;
            }   
        }
    
    
        public void readData() {
            byte[] rbuff = new byte[1024];
            int hasRead = 0;
            try {
                while((hasRead=inputStream.read(rbuff)) > 0) {
                    System.out.print(new String(rbuff, 0, hasRead));
                    break;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        public void sendData(String data) {
            try {
                outputStream.write(data.getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    
        public static void main(String[] args) {
            new ReadCom().getPortList();
        }
    
    
    }

    运行错误:

    gnu.io.PortInUseException: Unknown Application:串口端口被占用
    一般关掉占用端口的应用即可。

  • 相关阅读:
    centos 安装 redis3.2.0 集群
    CentOS7安装配置redis-3.0.0
    CentOS7/RHEL7安装Redis步骤详解
    鸟哥之安裝 CentOS7.x
    Centos 7 学习之静态IP设置
    CentOS7 下linux不能上网解决方法​,centos7 eth0 没有ip,IP突然丢失
    javamail发送邮件(转)
    Apache James使用的方法及相关心得(转)
    Velocity缓存与穿透(转)
    十分钟搞懂什么是CGI(转)
  • 原文地址:https://www.cnblogs.com/shihaiming/p/13727950.html
Copyright © 2011-2022 走看看