JAVA编写DLT 645串口程序

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
/*串口工具类*/
public class SerialUtil implements SerialPortEventListener {
	private ArrayList portList;
	private CommPortIdentifier portId;
	private SerialPort serialPort;
	private OutputStream outputStream;
	private InputStream inputStream;
	private int packetlength=0;

	static final char[] HEX_CHAR_TABLE = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * 扫描本机的所有COM端口
	 * 
	 */
	public void scanPorts() {
		portList = new ArrayList();
		Enumeration en = CommPortIdentifier.getPortIdentifiers();
		CommPortIdentifier portId;
		while (en.hasMoreElements()) {
			portId = (CommPortIdentifier) en.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				String name = portId.getName();
				if (!portList.contains(name)) {
					portList.add(name);
				}
			}
		}
		if (null == portList || portList.isEmpty()) {
			System.out.println("未找到可用的串行端口号,程序无法启动!");
		}
	}

	/**
	 * 打开串行端口
	 * 
	 */
	public void openSerialPort(String portname) {
		// 获取要打开的端口
		try {
			portId = CommPortIdentifier.getPortIdentifier(portname);
		} catch (NoSuchPortException e) {
			System.out.println("抱歉,没有找到" + portname + "串行端口号!");
			return;
		}
	}

	/**
	 * 设置端口参数
	 * 
	 * @param rate
	 * @param data
	 * @param stop
	 * @param parity
	 */
	public void setSeriaPortParam(int rate, int data, int stop, int parity) {
		// 打开端口
		try {
			serialPort = (SerialPort) portId.open("test", 2000);
		} catch (PortInUseException e) {
			System.out.println(serialPort.getName() + "端口已被占用,请检查!");
			return;
		}
		// 设置端口参数
		try {
			serialPort.setSerialPortParams(rate, data, stop, parity);
		} catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
		}

		// 打开端口的IO流管道
		try {
			outputStream = serialPort.getOutputStream();
			inputStream = serialPort.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 给端口添加监听器
		try {
			serialPort.addEventListener(this);
		} catch (TooManyListenersException e) {
			e.printStackTrace();
		}

		serialPort.notifyOnDataAvailable(true);

	}

	/**
	 * 给串行端口发送数据
	 * 
	 */
	public void sendDataToSeriaPort(byte[] b) {
		try {
			outputStream.write(b);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭串行端口
	 * 
	 */
	public void closeSerialPort() {
		try {
			if (outputStream != null)
				outputStream.close();
			if (inputStream != null)
				inputStream.close();
			if (serialPort != null)
				serialPort.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 事件监听
	 */
	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:
			//数据处理
			String data=toHexString(getPack(packetlength));
			System.out.println("返回数据"+data);			
		}
	}

	public byte[] getPack(int packetlength) {
		while (true) {
			// PacketLength为数据包长度
			byte[] msgPack = new byte[packetlength];
			for (int i = 0; i < packetlength; i++) {
				int newData = 0;
				try {
					if ((newData = inputStream.read()) != -1) {
						msgPack[i] = (byte) newData;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return msgPack;
		}
	}

	public String toHexString(byte[] data) {
		if (data == null || data.length == 0)
			return null;
		byte[] hex = new byte[data.length * 2];
		int index = 0;
		for (byte b : data) {
			int v = b & 0xFF;
			hex[index++] = (byte) HEX_CHAR_TABLE[v >>> 4];
			hex[index++] = (byte) HEX_CHAR_TABLE[v & 0xF];
		}
		return new String(hex);
	}

	public int getPacketlength() {
		return packetlength;
	}

	public void setPacketlength(int packetlength) {
		this.packetlength = packetlength;
	}
	
}

你可能感兴趣的:(工具类方法)