摘要: 在系統集成開發過程中,存在著各式的傳輸途徑,其中串口經常因其安全性高獲得了數據安全傳輸的重用,通過串口傳輸可以從硬件上保證數據傳輸的單向性,這是其它介質所不具備的物理條件。下面我就串口java開發的過程分享一下,并分享一個SerialPortHandler串口開發幫助類,以提高串口開發效率。并附帶了一些近期的總結,出差的體會。
關鍵詞: java, 串口, 經驗, 年終總結需求: 開發串口快速上手
3、下面是我優化過后的串口調用處理器:| publicclassSerialPortHandlerimplementsRunnable,SerialPortEventListener{OperationExceptione){thrownewRuntimeException(String.format("端口'%1$s'操作命令不支持!",commPort.getName()));}}}/***@方法名稱:checkPort*@功能描述:檢查端口是否正確連接*@返回值類型:void*/privatevoidcheckPort(){if(commPort==null)thrownewRuntimeException("沒有選擇端口,請使用"+"selectPort(StringportName)方法選擇端口");if(serialPort==null){thrownewRuntimeException("SerialPort對象無效!");}}/***@方法名稱:write*@功能描述:向端口發送數據,請在調用此方法前先選擇端口,并確定SerialPort正常打開!*@返回值類型:void*@parammessage*/publicvoidwrite(Stringmessage){checkPort();try{outputStream=newBufferedOutputStream(serialPort.getOutputStream());}catch(IOExceptione){thrownewRuntimeException("獲取端口的OutputStream出錯:"+e.getMessage());}try{outputStream.write(message.getBytes());log("信息發送成功!");}catch(IOExceptione){thrownewRuntimeException("向端口發送信息時出錯:"+e.getMessage());}finally{try{outputStream.close();}catch(Exceptione){}}}} |
| publicstaticvoidsendBySerialPorts(Stringcontant){contant=contant.replaceAll("http://$","");// 這里使用$符號作為終止符contant=contant.concat("$");SerialPortHandlersph;try{sph=SerialPortHandler.getInstance(DriveOutConductConfig.getPortName(),DriveOutConductConfig.getBitRate());sph.write(contant);}catch(NoSuchPortExceptione){e.printStackTrace();}} |
新聞熱點
疑難解答