java 操作串口代码

import gnu.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 
 * @create 2020-8-18
 * @since 1.0.0
 */
public class SerialPortManager {
    private String portName = null;
    private SerialPort serialPort = null;
    private int baudrate = 9600;

    private InputStream inputStream;
    private OutputStream outputStream;

    public void init() {
        while (true) {
            try {
                System.out.println("-main-menu----------------------------------------");
                System.out.println("选择指令:");
                System.out.println("1.查询com口");
                System.out.println("2.设置com口");
                System.out.println("3.进入模拟状态");
                System.out.println("4.测试");
                System.out.println("0.关闭");
                System.out.println("-------------------------------------------------");
                Scanner in = new Scanner(System.in);
                String string = in.nextLine();
                switch (Integer.parseInt(string)) {
                    case 1:
                        findAndShowPort();
                        break;
                    case 2:
                        changePort();
                        break;
                    case 3:
                        start();
                        break;
                    case 4:
                        sendToPort(serialPort, "AT+MSG=123".getBytes());
                        break;
                    case 0:
                        closePort(serialPort);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    public void start() {
        if (serialPort != null) {
            serialPort.close();
        }
        if (portName == null) {
            System.out.println("portName is null");
        }
        serialPort = openPort(portName, baudrate);
        addListener(serialPort, new MySerialPortEventListener());
    }

    /**
     * 查找所有可用端口
     *
     * @return 可用端口名称列表
     */
    @SuppressWarnings("unchecked")
    public static final ArrayList<String> findPort() {
        // 获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    public void changePort() {
        System.out.println("请输入com口名称,区分大小写");
        Scanner in = new Scanner(System.in);
        portName = in.nextLine();
        System.out.println("设置成功,当前com口名称为:" + portName);
    }

    public static final ArrayList<String> findAndShowPort() {
        ArrayList<String> list = findPort();
        for (int n = 0; n < list.size(); n++) {
            System.out.println(n + 1 + "." + list.get(n));
        }
        return list;
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @return 串口对象
     * @throws SerialPortParameterFailure 设置串口参数失败
     * @throws NotASerialPort             端口指向设备不是串口类型
     * @throws NoSuchPort                 没有该端口对应的串口设备
     * @throws PortInUse                  端口已被占用
     */
    public SerialPort openPort(String portName, int baudrate) {
        try {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            // 打开端口,设置端口名与timeout(打开操作的超时时间)
            CommPort commPort = portIdentifier.open(portName, 3000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;

                try {
                    // 设置串口的波特率等参数
                    serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                    inputStream = serialPort.getInputStream();
                    outputStream = serialPort.getOutputStream();
                } catch (UnsupportedCommOperationException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return serialPort;
            } else {
                // 不是串口
                System.out.println("不是串口");
            }
        } catch (NoSuchPortException e1) {
            e1.printStackTrace();
        } catch (PortInUseException e2) {
            e2.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭串口
     *
     * @param serialPort 待关闭的串口对象
     */
    public void closePort(SerialPort serialPort) {
        try {
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 向串口发送数据
     *
     * @param serialPort 串口对象
     * @param order      待发送数据
     * @throws SendDataToSerialPortFailure        向串口发送数据失败
     * @throws SerialPortOutputStreamCloseFailure 关闭串口对象的输出流出错
     */
    public void sendToPort(SerialPort serialPort, byte[] order) {
        try {
            outputStream.write(order);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     * @throws ReadDataFromSerialPortFailure     从串口读取数据时出错
     * @throws SerialPortInputStreamCloseFailure 关闭串口对象输入流出错
     */
    public byte[] readFromPort(SerialPort serialPort) {
        byte[] bytes = null;
        try {
            // 获取buffer里的数据长度
            int bufflenth = inputStream.available();
            while (bufflenth != 0) {
                // 初始化byte数组为buffer中数据的长度
                bytes = new byte[bufflenth];
                inputStream.read(bytes);
                bufflenth = inputStream.available();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return bytes;
    }

    public void readComm() {
        StringBuffer readBuffer = new StringBuffer();
        String scannedInput = "";
        Date currentTime = null;
        String TimeStamp = "";
        int c;
        char a;
        try {
            InputStreamReader fis = new InputStreamReader(inputStream, "utf-8");
            while ((c = inputStream.read()) != -1) {
                readBuffer.append((char) c);
            }
            scannedInput = readBuffer.toString().trim();
            System.out.println(scannedInput);
        } catch (IOException ex) {
            ex.printStackTrace();

        } catch (Exception ex) {

            ex.printStackTrace();
        }

    }


    /**
     * 添加监听器
     *
     * @param port     串口对象
     * @param listener 串口监听器
     * @throws
     */
    public static void addListener(SerialPort port, SerialPortEventListener listener) {
        try {
            // 给串口添加监听器
            port.addEventListener(listener);
            // 设置当有数据到达时唤醒监听接收线程
            port.notifyOnDataAvailable(true);
            // 设置当通信中断时唤醒中断线程
            port.notifyOnBreakInterrupt(true);
        } catch (TooManyListenersException e) {
            //监听类对象过多
            e.printStackTrace();
        }
    }

    class MySerialPortEventListener implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                //收到数据
                System.out.println("收到数据:");
                readComm();
            } else {
                System.out.println("sytem info");
                System.out.print(" eventType:" + serialPortEvent.getEventType());
                System.out.print(" NewValue:" + serialPortEvent.getNewValue());
                System.out.print(" OldValue:" + serialPortEvent.getOldValue());
                System.out.print(" Source:" + serialPortEvent.getSource());
                System.out.println("sytem info");
            }

        }
    }
}

以上代码还需要导入jar:

到官网下发这个jar,然后下载的时候还有两个dll,有说明书会告诉你这两个dll放到哪里。我是放到了下面这个位置:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值