java串口通信

protected void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException{
        String msgStr = forPara(req, "description");
        String s16 = SerialTool.encode(msgStr, "GBK");
        
        SerialPortTest sp = new SerialPortTest();
        sp.init();        
        String commType = forPara(req, "commType");
        String commCode = forPara(req, "commCode");
        sp.sendMsg(SerialTool.HexToByte(
                commType, 
                commCode, 
                forPara(req, "hCode"), 
                forPara(req, "lCode"), s16));        
        theSleep();        
       
        byte[] sByte = new byte[6];
        sByte[0] = (byte) 0xFD;
        sByte[1] = 0x03;
        sByte[2] = 0x03;
        sByte[4] = (byte) 0x00;
        sByte[5] = (byte) 0x00;
        
        if("00".equals(commType)){
            byte[] tmpByte = new byte[]{(byte) 0x0A,(byte) 0x0B,(byte) 0x0C,(byte) 0x0D,(byte) 0x0E};
            for(int j=0; j<5; j++){
                sByte[3] = tmpByte[j];
                sp.sendMsg(sByte);
                theSleep();
            }
        }else if("01".equals(commType)){//选播不给串口发送03指令
            sByte[3] = (byte) Integer.valueOf(commCode, 16).byteValue();
            sp.sendMsg(sByte);
        }
        /* 以上为给串口发指令 */
        
        theSleep();
        /* 以下为读取串口收到的指令 */
        String ms = "";
        String resultStr = sp.getReadStr();
        if(resultStr != null && !"".equals(resultStr)){
       commType = resultStr.substring(2, 4);        
       
       if("04".equals(commType)){//通播\分区播时,回执
ms = resultStr.charAt(7)+"区上报回执,总" + Integer.valueOf(resultStr.substring(8, 10), 16)
+ "包,第" + Integer.valueOf(resultStr.substring(10, 12), 16) +  "包。共收到"
+ (resultStr.length()/4 - 3) + "个用户的回执。";  
       }else if("08".equals(commType)){//选播用户发的回执
        String uc = Integer.valueOf(resultStr.substring(8, 12), 16)+"";
        if(uc.length()==1){
        uc = "00"+uc;
        }else if(uc.length()==2){
        uc = "0"+uc;
        }
        ms = "收到"+resultStr.charAt(7)+"区用户"+uc+"的回执。";
       }
       
        }
        req.setAttribute("msgStr", ms);                                        
        RequestDispatcher dispatcher = req.getRequestDispatcher("index.jsp");    // 使用req对象获取RequestDispatcher对象
        dispatcher.forward(req, res); 
        //sp.closeSerialPort();

    }

private void theSleep() {
        try {
            Thread.sleep(500);
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }        
    }
    String forPara(HttpServletRequest request, String paraName){
        if(request.getParameter(paraName) != null && !"".equals(request.getParameter(paraName))){
            String s = (String)request.getParameter(paraName);
            try {
                s = new String(s.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return s;
        }else{
            return "";
        }
    }


public class SerialPortTest implements SerialPortEventListener {
static String readStr;

    // 检测系统中可用的通讯端口类   
    private CommPortIdentifier portId;
    // 枚举类型  
    private Enumeration<CommPortIdentifier> portList;
  
    // RS232串口  
    private SerialPort serialPort;
  
    // 输入输出流  
    private InputStream inputStream;
    private OutputStream outputStream;
  
    // 保存串口返回信息  
    private String test;  
    
    // 初始化串口  
    @SuppressWarnings("unchecked")  
    public void init() {  
        // 获取系统中所有的通讯端口  
        portList = CommPortIdentifier.getPortIdentifiers();  
        
        // 循环通讯端口  
        while (portList.hasMoreElements()) {  
            portId = portList.nextElement();
            // 判断是否是串口  
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {  
                
                if ("COM1".equals(portId.getName())) {
                    System.out.println("找到串口COM1");
                    // 打开串口  
                    try {
                    test = "";
                        serialPort = (SerialPort) portId.open(portId.getCurrentOwner(), 200);
                        System.out.println("获取到串口对象,COM1");
                        inputStream = serialPort.getInputStream(); 
                        outputStream = serialPort.getOutputStream();  
                        
                        serialPort.addEventListener(this);//设置串口监听  
                        serialPort.notifyOnDataAvailable(true);//设置当有数据到达时唤醒监听接收线程
                        serialPort.notifyOnBreakInterrupt(true);//设置当通信中断时唤醒中断线程
                        
                        // 设置串口通讯参数   
                        // 波特率,数据位,停止位和校验方式  
                        // 波特率9600,偶校验   
                        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);  
  
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }  
  
                }  
            }  
        }  
    }  
    
    public String readFromPort(SerialPort serialPort) throws ReadDataFromSerialPortFailure, SerialPortInputStreamCloseFailure {
    byte[] readBuffer = null;  
        try {
            inputStream = serialPort.getInputStream();  
            // 从线路上读取数据流  
            int len = inputStream.available(); 
            while (len != 0) {  
            readBuffer = new byte[len]; 
            inputStream.read(readBuffer);
                //test += new String(readBuffer, 0, len).trim();  
                len = inputStream.available(); 
            }
                
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{
        closeSerialPort();
        }
        return intoTest(readBuffer);
    }
  
    //实现接口SerialPortEventListener中的方法 读取从串口中接收的数据  
    @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:    //有数据到达  
        try {
readStr = readFromPort(serialPort);
} catch (ReadDataFromSerialPortFailure e) {
e.printStackTrace();
} catch (SerialPortInputStreamCloseFailure e) {
e.printStackTrace();
}            
            break;  
        default:  
            break;  
        }  
    }  
    
public String intoTest(byte[] rb){
    String s = "";
    String sta = "FD";
        for(int i=1; i<rb.length; i++){
             s = Integer.toHexString(rb[i]);
             if(s.length()==1){
            s = "0" + s;
             }
             sta = sta + s;
        }
        return sta.toUpperCase();
    }
  
    //向串口发送信息方法 
    public void sendMsg(byte[] s){  
        try {
            outputStream.write(s);  
        } catch (IOException e) {
            e.printStackTrace();  
        }
    }
  
    // 关闭串口  
    public void closeSerialPort() {  
        if (serialPort != null) {
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            if (inputStream != null) {
                try {  
                    inputStream.close();
                    inputStream = null;
                }  
                catch (IOException e) {}
            }
            if (outputStream != null) {
                try {  
                    outputStream.close();  
                    outputStream = null;  
                }  
                catch (IOException e) {}  
            }
            serialPort.close();  
            serialPort = null;
        }
    }

public String getReadStr() {
return readStr;
}
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值