이번 시간은 시리얼 통신에 대한 예제 두번째 입니다.


저번과 비슷하지만, 틀린건 이벤트 리스너를 사용 한 예제 입니다.


예제 소스에 내용은 저번과 동일 합니다.


1. 시리얼 포트를 접속

2. 입력 스트림 얻기

3. 출력 스트림 얻기

4. 2번에서 취득한 입력 스트림을 SerialReader클래스로 넘겨

   에서 입력스트림으로 들어온 데이터를 읽는다. 

  Serialreader클래스는 SerialPortEventListener를 implements한다.


5.3번에서 취득한 출력 스트림을 SerialWriter클래스로 넘겨

    독립된 쓰레드에서 키보드 입력을 받아 출력 스트림에 쓰기를 한다.


[샘플 소스]


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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class TwoWaySerialCommEvent {
	public TwoWaySerialCommEvent() {
		super();
	}

	public void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(57600,
											SerialPort.DATABITS_8,
											SerialPort.STOPBITS_1,
											SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

				(new Thread(new SerialWriter(out))).start();

				serialPort.addEventListener(new SerialReader(in));
				serialPort.notifyOnDataAvailable(true);

			} else {
				System.out.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	/**
	 * Handles the input coming from the serial port. A new line character is
	 * treated as the end of a block in this example.
	 */
	public static class SerialReader implements SerialPortEventListener {
		private InputStream in;
		private byte[] buffer = new byte[1024];

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void serialEvent(SerialPortEvent arg0) {
			int data;

			try {
				int len = 0;
				while ( ( data = in.read()) > -1 ) {
			
					// 줄바꿈이 들어오면 while문을 빠져 나감.
					if ( data == '\n' ) {
						break;
					}
					
					buffer[len++] = (byte) data;
				}
				
				System.out.print(new String(buffer,0,len));

			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
		}

	}

	/**
	 *  쓰기 클래스
	 */
	public static class SerialWriter implements Runnable {
		OutputStream out;

		public SerialWriter(OutputStream out) {
			this.out = out;
		}

		public void run() {
			try {
				int c = 0;
                               System.out.println("\nKeyborad Input Read!!!!");
				while ((c = System.in.read()) > -1) {
					this.out.write(c);
				}
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
		}
	}

	public static void main(String[] args) {
		try {
			(new TwoWaySerialCommEvent()).connect("COM5");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}



[실행 결과]


실행 결과는 저번 예제와 동일 합니다.



이번 이벤트 형식과 저번꺼 두개의 예제만 있으면 대충 상황에 따라 적용 할 수 있습니다.



감사합니다.