java串口调试

本文展示了如何使用Java进行串口通信,创建条形码阅读器,并通过监听串口数据来处理接收到的信息。代码实现了打开串口、设置监听器和参数、读取数据以及关闭串口的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.giraffe.ipc.hardware;

import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.giraffe.common.netty.BarCodePayBean;
import com.giraffe.common.netty.IpcClientHandler;
import com.giraffe.common.netty.SynchType;
import com.giraffe.common.util.CommonUtil;
import com.giraffe.common.util.SpringUtil;

import gnu.io.*;

/**
 *通过串口创建条形码阅读器
 */
public class ContinueRead extends Thread implements SerialPortEventListener {
    // 监听器,我的理解是独立开辟一个线程监听串口数据
    static CommPortIdentifier portId; // 串口通信管理类
    static Enumeration<?> portList; // 有效连接上的端口的枚举
    InputStream inputStream; // 从串口来的输入流
    static OutputStream outputStream;// 向串口输出的流
    static SerialPort serialPort; // 串口的引用
    
    // 堵塞队列用来存放读到的数据
    private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
    private String parkRecordId;
    private String buildingId;
    
//    @Autowired
//    private IpcClientHandler ipcClientHandler;
    
    /**
     * SerialPort EventListene 的方法,持续监听端口上是否有数据流
     */
    @Override
    public void serialEvent(SerialPortEvent event) {

        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:// 当有可用数据时读取数据
            byte[] readBuffer = new byte[1024];
            try {
                Thread.sleep(100);
                int numBytes = -1;
                String number = "";
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);
                    if (numBytes > 0) {
                        number = StringUtils.trim(number.concat(new String(readBuffer)));
                        if(number.length()>=18) {
                            msgQueue.add(number.toString());
                        }
                        readBuffer = new byte[1024];// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
                    } else {
                        msgQueue.add("没有数据");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        }
    }

    /**
     * 
     * 通过程序打开COM3串口,设置监听器以及相关的参数
     * 
     * @return 返回1 表示端口打开成功,返回 0表示端口打开失败
     */
    public int startComPort() {
        // 通过串口通信管理类获得当前连接上的串口列表
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            // 获取相应串口对象
            portId = (CommPortIdentifier) portList.nextElement();
            // 判断端口类型是否为串口
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                try {
                    // 打开串口名字为COM_3(名字任意),延迟为2毫秒
                    serialPort = (SerialPort) portId.open(portId.getName(), 1000);
                    //将串口放进map中,方便后来关闭该串口
                    CommonUtil.MAPSERIALPORT.put(parkRecordId, serialPort);
                    System.out.println("open " + serialPort + " sucessfully !"); 
                } catch (PortInUseException e) {
                    e.printStackTrace();
                    return 0;
                }
                // 设置当前串口的输入输出流
                try {
                    inputStream = serialPort.getInputStream();
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                    return 0;
                }
                // 给当前串口添加一个监听器
                try {
                    serialPort.addEventListener(this);
                } catch (TooManyListenersException e) {
                    e.printStackTrace();
                    return 0;
                }
                // 设置监听器生效,即:当有数据时通知
                serialPort.notifyOnDataAvailable(true);
                // 设置串口的一些读写参数
                try {
                    // 比特率、数据位、停止位、奇偶校验位
                    serialPort.setSerialPortParams(115200,
                            SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    e.printStackTrace();
                    return 0;
                }
                return 1;
            }
        }
        return 0;
    }

    @Override
    public void run() {
        try {
            IpcClientHandler ipcClientHandler = (IpcClientHandler) SpringUtil.getObject("ipcClientHandler");
            while (true) {
                // 如果堵塞队列中存在数据就将其输出
                if (msgQueue.size() > 0) {
                    String readNumber = msgQueue.take();
                    System.out.println(readNumber);
                    System.out.println("打印了...");
                    BarCodePayBean barCodePayBean = new BarCodePayBean();
                    barCodePayBean.setParkingRecordId(parkRecordId);
                    barCodePayBean.setCode(readNumber);
                    barCodePayBean.setBuildingId(buildingId);
                    System.out.println("构建完成了,准备发送...");
                    //开始发送给ipms,返回用长连接返回
                    ipcClientHandler.channelWrite(SynchType.BARCODEPAY ,barCodePayBean);
                    System.out.println("发送了...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**  
     * 关闭串口  
     * @param serialport 待关闭的串口对象  
     */  
    public static void closePort(SerialPort serialPort) {  
        if (serialPort != null) {  
            serialPort.close();  
            System.out.println("Close " + serialPort + " sucessfully !");  
            serialPort = null;  
        }  
    }

    public static void main(String[] args) {
        ContinueRead cRead = new ContinueRead();
        int i = cRead.startComPort();
        cRead.setParkRecordId(parkRecordId);//附带参数给线程
        cRead.setBuildingId(buildingId);
        if (i == 1) {
            // 启动线程来处理收到的数据
            cRead.start();
//            try {
//                String st = "123456789123456789";
//                System.out.println("发出字节数:" + st.getBytes("gbk").length);
//                outputStream.write(st.getBytes("gbk"), 0,
//                        st.getBytes("gbk").length);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
        } else {
            return;
        }
    }

    public String getParkRecordId() {
        return parkRecordId;
    }

    public void setParkRecordId(String parkRecordId) {
        this.parkRecordId = parkRecordId;
    }

    public String getBuildingId() {
        return buildingId;
    }

    public void setBuildingId(String buildingId) {
        this.buildingId = buildingId;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值