상세 컨텐츠

본문 제목

시리얼 포트로 시간 전송하기

카테고리 없음

by 붉은지니 2021. 10. 4. 21:30

본문

● USB Serial로 연결된 시간표시장치에 현재시간을 설정하는 코드입니다.

package com.genie;
import java.lang.*;
import java.util.*;
import java.io.*;
public class SetClock {
	public static void main(String[] args) {
		String cmdStr;
		Scanner scanner = new Scanner(System.in);
		PipedInputStream pi = null;
		PipedOutputStream po = null;
		DataOutputStream theOutput = null;
		try {
			pi = new PipedInputStream();
			po = new PipedOutputStream(pi);
			theOutput = new DataOutputStream(po);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul"));
		Runnable putCMD = new PutCMD(pi);
		Thread comThread = new Thread(putCMD);
		comThread.setName("PutCMD");
		comThread.start();
		do {
			System.out.println("Input Command : ");
			System.out.println("\t[1] Set Clock");
			System.out.println("\t[q] quit");
			cmdStr = scanner.nextLine();
			if (cmdStr.equals("1"))
			{
				try {
					theOutput.writeUTF("SendClock");
				} catch (IOException ex) {
					System.err.println(ex);
				}
			}
		} while (!cmdStr.equals("q"));
		try {
			theOutput.writeUTF("StopThread");
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}

○ 장치로부터 전송되어온 현재시간 전송요청을 받거나 임의로 전송명령을 보낼 수 있습니다.

package com.genie;
import java.lang.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.fazecast.jSerialComm.*;
public class PutCMD implements Runnable {
	final String devName = "/dev/ttyUSB0";
	private SerialPort comPort;
	private DataInputStream theInput;
	private boolean mode = true;
	private StringBuilder sb = new StringBuilder();
	public PutCMD(PipedInputStream in) {
		theInput = new DataInputStream(in);
	}
	@Override
	public void run() {
		comPort = SerialPort.getCommPort(devName);
		comPort.setComPortParameters(9600, 8, 1, 0);
		comPort.openPort();
		if (comPort.isOpen())
		{
			System.out.println(devName + " is opened!");
			comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 500, 0);
			comPort.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 500, 0);
			while (mode)
			{
				/* Serial Port */
				byte[] readBuffer = new byte[comPort.bytesAvailable()];
				int numRead = comPort.readBytes(readBuffer, readBuffer.length);
				if (numRead > 0)
				{
					StringBuilder cb = new StringBuilder();
					for (int j = 0; j < numRead; j++)
					{
						cb.append((char)readBuffer[j]);
					}
					sb.append(cb.toString());
					if (sb.toString().contains("}"))
					{
						String buffer = sb.toString();
						sb.setLength(0);
						JSONObject jsonObj = objConvert(buffer);
						if (jsonObj != null)
						{
							if (jsonObj.get("command") != null)
							{
								String cmdStr = jsonObj.get("command").toString();
								System.out.println(cmdStr);
								if (cmdStr.equals("GetClock"))
									sendClock();
							}
						}
					}
				}
				/* Command Pipe */
				try {
					if (theInput.available() > 0)
					{
						String pipeBuffer = theInput.readUTF();
						if (!pipeBuffer.isEmpty())
						{	
							if (pipeBuffer.equals("SendClock"))
								sendClock();
							else if (pipeBuffer.equals("StopThread"))
								mode = false;
						}
					}
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		} else System.out.println("Serial COM Port is not opened!");
		comPort.closePort();
	}
	private JSONObject objConvert(String jsonString)
	{
		JSONObject jsonObj = null;
		try {
			JSONParser parser = new JSONParser();
			jsonObj = (JSONObject) parser.parse(jsonString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return jsonObj;
	}
	private void sendClock()
	{
		ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
		DateTimeFormatter fmtDate = DateTimeFormatter.ofPattern("MMM dd YYYY").withLocale(Locale.ENGLISH);
		DateTimeFormatter fmtTime = DateTimeFormatter.ofPattern("HH:mm:ss").withLocale(Locale.ENGLISH);
		JSONObject cmdObj = new JSONObject();
		cmdObj.put("command", "SetClock");
		cmdObj.put("date", now.format(fmtDate));
		cmdObj.put("time", now.format(fmtTime));
		cmdObj.put("runtime", new Integer(0));
		String jsonCmd = cmdObj.toJSONString();
		System.out.println(jsonCmd);
		comPort.writeBytes(jsonCmd.getBytes(), jsonCmd.length());
	}
}

○ Thread는 USB Serial로 전송되어 온 시간요청 명령 또는 Pipe로 전송된 시간전송 명령을 처리합니다.