在做過一年多的RXTX操作串口項目有現在把一些平時遇到的問題在這裡寫寫:
RXTX是一個開源包,主要是在COMM開源包中做擴張,以前的COMM包只能在Windows下面對串口或並口做操作,擴充後的RXTX可以在Linux和Mac下對串口和並口做操作。 現在跨平台:
在RXTX網站下載JAR包和動態庫
http://users.frii.com/jarvi/rxtx/download.Html
下載後配置環境
Windows
拷貝RXTXcomm.jar 文件到 \jre\lib\ext 目錄下
拷貝rxtxSerial.dll文件到 \jre\bin目錄下
Mac OS X (x86 and ppc) (there is an Installer with the source)
MAC下面我自己沒有配置環境成功,後來找一個Mac下RXTX的安裝把環境配置好的。
http://www.jdivelog.org/how-to/Mac-os-x/下載安裝環境配置文件RXTX_Tiger.pkg
Linux (only x86, x86_64, ia64 here but more in the ToyBox)
拷貝RXTXcomm.jar 文件到 /jre/lib/ext 目錄下
拷貝librxtxSerial.so 文件到 /jre/lib/[Machine type] (i386 for instance)目錄下
並將拷貝文件釋放權限給所有用戶
Solaris (sparc only so far)
拷貝RXTXcomm.jar 文件到 /jre/lib/ext 目錄下
拷貝librxtxSerial.so 文件到 /jre/lib/[Machine type]目錄下
並將拷貝文件釋放權限給所有用戶
環境搭建好後開始寫代碼實現
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import Java.util.TooManyListenersException;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
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;
// prase data with process
private String dataProtocol;
private Object readWriteLock = new Object();
public SerialComm() {
isOpen = false;
isStart = false;
isSave = true;
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
{
portName = port;
portAddress = portName;
dataProtocol = protocol;
init();
}
public void init(String port, String address, String protocol) throws Exception
{
portName = port;
portAddress = address;
dataProtocol = protocol;
init();
}
public void init() throws IOException, Exception, Exception
{
if (isOpen)
{
close();
}
try
{
//傳送串口名創建CommPortIdentifier對象服務。
portId = CommPortIdentifier.getPortIdentifIEr(portName);
//使用portId對象服務打開串口,並獲得串口對象
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());
} catch (PortInUseException ex)
{
throw new Exception(ex.toString());
}
}
public void start() throws Exception
{
if (!isOpen)
{
throw new Exception(portName + " has not been opened.");
}
try
{
//創建對象線程
readThread = new Thread(this);
readThread.start();
//設置串口數據時間有效
serialPort.notifyOnDataAvailable(true);
//增加監聽
serialPort.addEventListener(this);
isStart = true;
} catch (TooManyListenersException ex)
{
throw new Exception(ex.toString());
}
}
public void run()
{
String at = "at^hcmgr=1\r";
String strTemp = at + (char) Integer.parseInt("1a", 16) + "z";
writeComm(strTemp);
isPrint = true;
}
public void stop()
{
if (isStart)
{
serialPort.notifyOnDataAvailable(false);
serialPort.removeEventListener();
isStart = false;
}
}
public 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();
break;
default:
break;
}
}
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 = 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 ex)
{
ex.printStackTrace();
}
}
public void writeComm(String outString)
{
synchronized (readWriteLock)
{
try
{
outputStream.write(outString.getBytes());
} catch (IOException ex)
{
}
}
}
public static void main(String[] args)
{
SerialComm serialcomm = new SerialComm();
try
{
serialcomm.init("COM3", "Air");// Windows下測試端口
// serialcomm.init("/dev/ttyUSB0", "Air");//Linux下測試端口
serialcomm.start();
} catch (Exception ex)
{
}
}
}