①. 是基於modbus通訊協議之間的通訊數組
②. 是十六進制進行通訊的app
③. 可選波特率,數據位 中止位eclipse
④採用CRC校驗工具
界面是用窗體表現的
佈局
界面的實現就不過多的貼代碼和說怎麼去實現了,有個很好用的工具 NETBean,能夠直接拖控件,跟C#作winfrom很像,可是eclipse沒有 要本身佈局的話比較耗時。ok,先說窗體下半部分的實現this
須要用到的jar包:comm.jar ,能夠在網上搜下如何配置spa
void listPort() { CommPortIdentifier portId; //這個類在comm.jar中 Enumeration a = CommPortIdentifier.getPortIdentifiers(); while (a.hasMoreElements()) { portId = (CommPortIdentifier) a.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { list.add(portId.getName()); //這裏的list是個成員變量,add以後再下拉框中刷新進去 } } }
波特率,數據位這些能夠直接事先放在數組裏面,界面一啓動就加 載進去了code
public void selectPort(String portName, int rate, int databit, int stopbit,int parity) { System.out.println("selectPort()"); this.commPort = null; CommPortIdentifier cpid; Enumeration en = CommPortIdentifier.getPortIdentifiers(); // 枚舉出所 有的串口 while (en.hasMoreElements()) { cpid = (CommPortIdentifier) en.nextElement(); if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL && cpid.getName().equals(portName)) { this.commPort = cpid; break; } } openPort(rate, databit, stopbit, parity); } /** * @功能:打開串口 ** **/ private void openPort(int rate, int databit, int stopbit, int parity) { System.out.println("openPort()"); // TODO Auto-generated method stub if (commPort == null) //沒法找到這個端口 else { //成功找到 try { serialPort = (SerialPort) commPort.open(appName, timeout); try { serialPort.setSerialPortParams(rate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//這裏過來參數是int,要轉成16進制,爲了方便看代碼我就不轉化,直接用他的變量了 } catch (UnsupportedCommOperationException e) { // TODO Auto-generated catch block e.printStackTrace(); } log("實例SerialPort成功"); } catch (PortInUseException e) { throw new RuntimeException(String.format("端口爲'%1$s'的串口正在被使用!", commPort.getName())); } } }
到這裏串口就成功打開了orm
在寫上部分如何實現前,先說說掃描槍的工做
至關於最後的字符帶了回車的鍵盤輸入 ,就這樣,圖片
將接收到的字符串轉換成16進制: public static byte[] HexStringBytes(String src) { if (null == src || 0 == src.length()) { return null; } byte[] ret = new byte[src.length()/2]; byte[] tmp = src.getBytes(); // System.out.println("tmp="+Arrays.toString(tmp)); /* * int length = 0; if (tmp.length % 2 != 0) { length=(tmp.length+1)/2; } * length=tmp.length; */ for (int i = 0; i < (tmp.length / 2); i++) { ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); } return ret; } /* * 以字節的形式寫進去 */ public void write(byte[] message) { System.out.println("write()"); checkPort(); try { outputStream = new BufferedOutputStream( serialPort.getOutputStream()); } catch (IOException e) { throw new RuntimeException("獲取端口的輸出流出錯"); } try { outputStream.write(message); log("信息發送成功"); } catch (IOException e) { throw new RuntimeException("向端口發送信息失敗"); } finally { try { outputStream.close(); } catch (Exception e) { } } }