자바 시리얼 통신 예제
SerialEcho.java
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SerialEcho implementsRunnable,SerialPortEventListener{
static CommPortIdentifier portId;
static Enumeration portList;
BufferedReader br;
BufferedWriter bw;
String echoMsg;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
//시스템의 모든 포트 리스트를 가져옴.
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
//현재 포트타입이 시리얼 포트일 경우
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
// MS-windows에서 시리얼 포트 이름은“COM1”,”COM2”…
if (portId.getName().equals("COM1")) {
// if (portId.getName().equals("/dev/term/a")) {àSolaris에서
//시리얼 통신을 위한 포트 생성
SerialEcho reader = new SerialEcho();
}
}
}
}
public SerialEcho() {
try{
serialPort = (SerialPort) portId.open("SerialEcho", 2000);
} catch (PortInUseException e) {}
try {
br = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream()));
} catch (IOException e) {}
try {
//시리얼 포트에 데이터가 수신되기를 기다림.
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
// input data가 들어오면 수신 통보
serialPort.notifyOnDataAvailable(true);
try{
serialPort.setSerialPortParams(19200, // Baud Rate
SerialPort.DATABITS_8, // Data Bits
SerialPort.STOPBITS_1, // Stop Bits
SerialPort.PARITY_NONE); // Parity
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()){
case SerialPortEvent.BI: // Break interrupt
case SerialPortEvent.OE: // Overrun error
case SerialPortEvent.FE: // Framing error
case SerialPortEvent.PE: // Parity error.
case SerialPortEvent.CD: // Carrier detect
case SerialPortEvent.CTS: // Clear to send
case SerialPortEvent.DSR: // Data set ready
case SerialPortEvent.RI: // Ring indicator.
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break; // Output buffer is empty
// Data available at the serial port.
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try{
while(true){
echoMsg = br.readLine();
System.out.println("Echo: " + echoMsg);
bw.write(echoMsg,0,echoMsg.length());
bw.newLine();
bw.flush();
}
}catch (IOException e) {}
break;
}
}