package tools.ChuanKou; import gnu.io.*; import index.JPanelMoudle.ComMoudleComp; import tools.ShowMessage; import tools.Tools; import javax.tools.Tool; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.TooManyListenersException; /** * @name: SerialPortUtil * @author: tuacy. * @date: 2019/6/26. * @version: 1.0 * @Description: 串口工具类 */ @SuppressWarnings("unused") public class SerialPortUtil { /** * 获得系统可用的端口名称列表(COM0、COM1、COM2等等) * * @return List可用端口名称列表 */ // 输入流 private static InputStream inputStream; // 输出流 private static OutputStream outputStream; private static String data; // 保存串口返回信息十六进制 private static String dataHex; @SuppressWarnings("unchecked") public static List getSerialPortList() { List systemPorts = new ArrayList<>(); //获得系统可用的端口 Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { String portName = portList.nextElement().getName();//获得端口的名字 systemPorts.add(portName); } return systemPorts; } /** * 打开串口 * * @param serialPortName 串口名称 * @return SerialPort 串口对象 * @throws NoSuchPortException 对应串口不存在 * @throws PortInUseException 串口在使用中 * @throws UnsupportedCommOperationException 不支持操作操作 */ public static SerialPort openSerialPort(String serialPortName) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException { SerialPortParameter parameter = new SerialPortParameter(serialPortName); return openSerialPort(parameter); } /** * 打开串口 * * @param serialPortName 串口名称 * @param baudRate 波特率 * @return SerialPort 串口对象 * @throws NoSuchPortException 对应串口不存在 * @throws PortInUseException 串口在使用中 * @throws UnsupportedCommOperationException 不支持操作操作 */ public static SerialPort openSerialPort(String serialPortName, int baudRate) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException { SerialPortParameter parameter =new SerialPortParameter(serialPortName, baudRate); return openSerialPort(parameter); } /** * 打开串口 * * @param serialPortName 串口名称 * @param baudRate 波特率 * @param timeout 串口打开超时时间 * @return SerialPort 串口对象 * @throws NoSuchPortException 对应串口不存在 * @throws PortInUseException 串口在使用中 * @throws UnsupportedCommOperationException 不支持操作操作 */ public static SerialPort openSerialPort(String serialPortName, int baudRate, int timeout) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException { SerialPortParameter parameter = new SerialPortParameter(serialPortName, baudRate); return openSerialPort(parameter, timeout); } /** * 打开串口 * * @param parameter 串口参数 * @return SerialPort 串口对象 * @throws NoSuchPortException 对应串口不存在 * @throws PortInUseException 串口在使用中 * @throws UnsupportedCommOperationException 不支持操作操作 */ public static SerialPort openSerialPort(SerialPortParameter parameter) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException { return openSerialPort(parameter, 2000); } /** * 打开串口 * * @param parameter 串口参数 * @param timeout 串口打开超时时间 * @return SerialPort串口对象 * @throws NoSuchPortException 对应串口不存在 * @throws PortInUseException 串口在使用中 * @throws UnsupportedCommOperationException 不支持操作操作 */ public static SerialPort openSerialPort(SerialPortParameter parameter, int timeout) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException { //通过端口名称得到端口 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(parameter.getSerialPortName()); //打开端口,(自定义名字,打开超时时间) CommPort commPort = portIdentifier.open(parameter.getSerialPortName(), timeout); //判断是不是串口 if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; //设置串口参数(波特率,数据位8,停止位1,校验位无) serialPort.setSerialPortParams(parameter.getBaudRate(), parameter.getDataBits(), parameter.getStopBits(), parameter.getParity()); ShowMessage.zidingyi(parameter.getSerialPortName()+"打开成功!"); //System.out.println("开启串口成功,串口名称:" + parameter.getSerialPortName()); return serialPort; } else { //是其他类型的端口 throw new NoSuchPortException(); } } /** * @throws Exception * 关闭串口 * @author LinWenLi * @date 2018年7月21日下午3:45:43 * @Description: 关闭串口 * @param: * @return: void * @throws */ public static void closeSerialPort(SerialPort serialPort) throws Exception { if (serialPort != null) { serialPort.notifyOnDataAvailable(false); serialPort.removeEventListener(); if (inputStream != null) { try { inputStream.close(); inputStream = null; } catch (IOException e) { ShowMessage.zidingyi("关闭输入流时发生IO异常"); } } if (outputStream != null) { try { outputStream.close(); outputStream = null; } catch (IOException e) { ShowMessage.zidingyi("关闭输入流时发生IO异常"); } } serialPort.close(); serialPort = null; ShowMessage.zidingyi("串口关闭成功"); } } /** * 发送信息到串口 * @author LinWenLi * @date 2018年7月21日下午3:45:22 * @param: serialPort 串口对象 * @return: data 发送的数据 * @throws */ public static void sendData(SerialPort serialPort, byte[] data) { try { outputStream = serialPort.getOutputStream(); outputStream.write(data); outputStream.flush(); } catch (NullPointerException e) { try { throw new Exception("找不到串口"); } catch (Exception e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } } catch (IOException e) { try { throw new Exception("发送信息到串口时发生IO异常"); } catch (Exception e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } }finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 读取串口返回信息 * @author LinWenLi * @date 2018年7月21日下午3:43:04 * @return: byte[] */ public static byte[] readData(SerialPort serialPort) { byte[] bytes=null; try { Thread.sleep(10); inputStream = serialPort.getInputStream(); // 通过输入流对象的available方法获取数组字节长度 bytes = new byte[inputStream.available()]; // 从线路上读取数据流 int len = 0; while ((len = inputStream.read(bytes)) != -1) {// 直接获取到的数据 data = new String(bytes, 0, len).trim();// 转为十六进制数据 dataHex = Tools.Bytes2HexString(bytes); inputStream.close(); inputStream = null; break; } } catch (IOException e) { try { SerialPortUtil.closeSerialPort(serialPort); ShowMessage.zidingyi_24("串口通信异常已关闭!"); SerialPortUtil.getSerialPortList().clear(); System.exit(-1); } catch (Exception e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } } catch (InterruptedException e) { //throw new RuntimeException(e); } return bytes; } /** * 给串口设置监听 * * @param serialPort serialPort 要读取的串口 * @param listener SerialPortEventListener监听对象 * @throws TooManyListenersException 监听对象太多 */ public static void setListenerToSerialPort(SerialPort serialPort, SerialPortEventListener listener) throws TooManyListenersException { //给串口添加事件监听 if(serialPort!=null) { serialPort.addEventListener(listener); //串口有数据监听 serialPort.notifyOnDataAvailable(true); //中断事件监听 serialPort.notifyOnBreakInterrupt(true); } } }