java串列埠通訊例項 -

瓜瓜東西發表於2014-09-19
package com.yuan;


import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;


import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.TooManyListenersException;


public class SerialComm implements SerialPortEventListener, Runnable {
public final static String PORT_OWER = "MonitorApp";
private boolean isOpen;
private boolean isStart;
private boolean isSave;
private boolean isPrint;
private Thread readThread;
private String portName;
private String portAddress;
private CommPortIdentifier portId;
private SerialPort serialPort;
private DataInputStream inputStream;
private OutputStream outputStream;
private SimpleDateFormat formatter;
private String dataProtocol;
private Object readEWriteLock = new Object();
public SerialComm(){
this.isOpen = false;
this.isStart = false;
this.isSave = true;
this.isPrint = false;
formatter = new SimpleDateFormat("[yyyy-MM-dd hh:mm:ss,SSS]");
portName = "COM1";
portAddress = "LOCAL";
dataProtocol = "Gooseli";
}
public void init(String port,String protocol ) throws Exception{
this.portName = port;
this.portAddress = portName;
this.dataProtocol = protocol;
init();
}
public void init(String port,String address,String protocol) throws Exception{
this.portName = port;
this.portAddress =  address;
this.dataProtocol = protocol;
}
public void init()throws IOException,Exception{
if(isOpen){
close();
}
try{
portId = CommPortIdentifier.getPortIdentifier(portName);
serialPort = (SerialPort)portId.open(PORT_OWER,2000);
inputStream = new DataInputStream(serialPort.getInputStream());
outputStream = serialPort.getOutputStream();
isOpen = true;
}catch(NoSuchPortException ex){
throw new Exception(ex.toString());
}
}
public void start()throws Exception{
if(!isOpen){
throw new Exception(portName + " has not bean opened!");
}
try{
readThread = new Thread(this);
readThread.start();
serialPort.notifyOnDataAvailable(true);
serialPort.addEventListener(this);
isStart =  true;
} catch( TooManyListenersException ex){
throw new Exception(ex.toString());
}
}
private void close() {
stop();
if(isOpen){
try{
inputStream.close();
outputStream.close();
serialPort.close();
isOpen = false;
}catch(IOException ex){
}
}
}
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:// 當有可用資料時讀取資料,並且給串列埠返回資料
readComm();
/*byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
System.out.println(inputStream.available());
int numBytes = inputStream.read(readBuffer);
System.out.println(numBytes);
}
data = new String(readBuffer).trim();
System.out.println(new String(readBuffer).trim());
} catch (IOException e) {
e.fillInStackTrace();
}*/
break;
default:break;
}

}


private void readComm() {
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
System.out.println(inputStream.available());
int numBytes = inputStream.read(readBuffer);
}
//data = new String(readBuffer).trim();
System.out.println(new String(readBuffer).trim());
} catch (IOException e) {
e.fillInStackTrace();
}
/*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=fis.read())!=-1){
readBuffer.append((char)c);
}
scannedInput = readBuffer.toString().trim();
currentTime = new Date();
TimeStamp  = formatter.format(currentTime);
} catch(IOException ex ){
ex.printStackTrace();
} catch(Exception exx){
exx.printStackTrace();
}*/
}
public void run() {
/*while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String at = "test";
writeComm(at);
isPrint = true;
}*/
/*String at = "at^hcmgr=1\r";
String strTemp = at+(char)Integer.parseInt("la",16) + "z";
writeComm(strTemp);*/
}
private void writeComm(String outString) {
synchronized(readEWriteLock){
try{
outputStream.write(outString.getBytes());
} catch(IOException ex){
ex.printStackTrace();
}
}
}
public void stop(){
if(isStart){
serialPort.notifyOnDataAvailable(false);
serialPort.removeEventListener();
isStart =false;
}
}
public static void main(String[] args){
SerialComm serialComm = new SerialComm();
try {
serialComm.init("COM2","Air");
serialComm.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

相關文章