📄 serialconnection.java
字号:
package com.sensevision.reader;/** * * RF Dump V1.2 * @author Boris Wolf, Lukas Grunwald * @version 07/12/2004 * */import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.TooManyListenersException;import javax.comm.CommPortIdentifier;import javax.comm.NoSuchPortException;import javax.comm.PortInUseException;import javax.comm.SerialPort;import javax.comm.SerialPortEvent;import javax.comm.SerialPortEventListener;import javax.comm.UnsupportedCommOperationException;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class SerialConnection implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; InputStream inputStream; static OutputStream outputStream; SerialPort serialPort; Thread readThread; StringBuffer inputBuffer; static ArrayList pendingLines; private static short frameNo=0;//帧编号 protected final Log logger = LogFactory.getLog(getClass()); public static void main(String[] args) { } public SerialConnection() {// openPort(portName); } public void close() { try { if(inputStream!=null) inputStream.close(); if(outputStream!=null) outputStream.close(); } catch (Exception e) { System.err.println("Error: " + e); } if(serialPort!=null) serialPort.close(); } public void write(String msg) { try { outputStream.write(msg.getBytes()); // java.io.BufferedWriter write=new BufferedWriter(new OutputStreamWriter(outputStream)); // write.write(msg); outputStream.flush(); } catch(java.io.IOException e) { System.err.println("Error: " + e); } } public String readNextLine() { // while (pendingLines.size() == 0) {} int count=0; while (pendingLines.size() == 0&&count<60) { try { count++; Sleep.toSleep(20); } catch (InterruptedException e) { logger.error("while wait return value faild..." + e.getMessage()); } } if(pendingLines.isEmpty()){ return null; } String line = (String)pendingLines.remove(0); return line; } public void resetLineBuffer() { pendingLines = new ArrayList(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) {} } 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: int newData = 0;int i=0; // while (newData != -1) { try { // newData = inputStream.read();// if(':'==newData ){// inputBuffer.append(':');// continue;// }else// if (':'!=newData && newData != '\n') {// String hexValue = Integer.toHexString(newData);// if (hexValue.length() == 1) {// hexValue = '0' + hexValue;// }// inputBuffer.insert(0,hexValue);// } else if ('\r' == (char)newData || '\n' == (char)newData) {// pendingLines.add(new String(inputBuffer.toString()));// inputBuffer = new StringBuffer();// //// } else// {// String v = String.valueOf(newData);// if (v.length() == 1) {// v = '0' + v;// }// inputBuffer.insert(0, v);//// } //i++;// newData = inputStream.read();// // if (newData == -1) {// break;// }//// if ('\r' == (char)newData || '\n' == (char)newData) {//// pendingLines.add(new String(inputBuffer.toString()));// inputBuffer = new StringBuffer();//// } else {// inputBuffer.append((char)newData);// } BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); if(reader.ready()){ pendingLines.add(reader.readLine());// reader.readLine(); } } catch (IOException e) { System.err.println("Error: " + e); return; } } // } } public String getFrameNo(){ if(frameNo==255){//控制frameNo值范围为0~255 frameNo=-1; } String no=Integer.toHexString(frameNo++); if(no.length()!=1){ return no; } return "0"+no; } public void openPort(String portName) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException{ System.out.print("Trying to open port " + portName + "..."); boolean failed = false; inputBuffer = new StringBuffer(); pendingLines = new ArrayList(); try { portId = CommPortIdentifier.getPortIdentifier(portName); } catch (NoSuchPortException e) { System.err.println("Error: " + e); failed = true; throw e; } if (!failed) { try { serialPort = (SerialPort)portId.open("RFIDReader", 2000); System.out.println(serialPort.getBaudRate());//打印波特率 } catch (PortInUseException e) { System.err.println("Error: " + e); failed = true; throw e; } } if (!failed) { try { inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); } catch (IOException e) { System.err.println("Error: " + e); failed = true; } } if (! failed) { try { serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) { System.err.println("Error: " + e); failed = true; } } if (! failed) { try { serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); System.out.println(serialPort.getBaudRate());//打印波特率 logger.info(serialPort.isReceiveThresholdEnabled()); } catch (UnsupportedCommOperationException e) { System.err.println("Error: " + e); failed = true; throw e; } } if (failed) { System.out.println("failed"); } else { System.out.println("ok"); readThread = new Thread(this); readThread.start(); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -