Javaシリアル通信RXTX



Java Serial Communication Rxtx



消費、読み取り、書き込みのためにカードをデバッグしますが、最速は何ですか?最も効率的なものは何ですか?

コードをノックしてコンパイルしてダウンロードし、テストを繰り返しますか?もちろん、それは良いツールです。



ここでは、作成したツールを使用して、カード全体の読み取り、書き込み、および検証を行います。このツールは、Javaシリアル通信を使用します。

RXTXcomm.jarこのシリアルライブラリはとても良いです! 32ビットまたは64ビットシステムで使用できます。



私は以前、Sunが提供するcomm.jarを使用し、カードを読み書きするためのツールとして彼を使用していました。結果は32ビットシステムでのみ利用可能です。

後でRXTXが発見され、インターフェイスとcomm.jarはほぼ同じように提供されましたが、パッケージ名は同じではありません。

このようにして、私のツールは再パッケージせずに使用できます。



ツールのスクリーンショット:

ツールソースのダウンロードアドレス:

https://download.csdn.net/download/qq8864/11045997

RXTXは、シリアルポートとパラレルポートの通信を提供するオープンソースのJavaクラスライブラリです。このプロジェクトによって公開されたファイルは、LGPLプロトコルに従います。
RXTXプロジェクトは、Windows、Linux、Mac os X、およびSolarisオペレーティングシステム用の互換性のあるjavax.commシリアル通信パッケージAPIの実装を提供し、他の開発者がそのようなシステムでシリアルアプリケーションを開発できるようにします。かなりの利便性を提供します。
RXTXの使用法は、基本的にsunのcomm.jarの使用法と同じです。プログラミングの最も明らかな違いは、含まれるパッケージ名がjavax.comm。*からgnu.io. *に変更されていることです。
RxtxAPIのコアは、抽象CommPortクラス(基盤となるシステムでサポートされるポートを記述する抽象クラスであり、すべての異なる通信ポート用の高レベルIO制御メソッドが含まれています。これは汎用です)とその2つのサブクラスであるSerialPortクラスです。およびParallePortクラス。その中で、SerialPortクラスはシリアル通信用のクラスであり、ParallePortクラスはパラレルポート通信用のクラスです。 CommPortクラスは、ポート上のデバイスと通信するように設計されたgetInputStream()メソッドやgetOutputStream()メソッドなどの一般的な通信モードとメソッドも提供します。

使い方もとても便利です。

RXTXのダウンロードと構成:

mfz-rxtx-2.2-20081207-win-x64
ダウンロードアドレス: https://download.csdn.net/download/m0_37487097/9823685
RXTXComm.jarのAPIドキュメント
まず、インストールしたJDKの数を確認し、対応するビット数でjarをインストールします。
rxtxSerial.dll、rxtxParallel.dllを jre binディレクトリにコピーします
RXTXcomm.jarを jre lib extディレクトリにコピーします
Eclipseでプロジェクトを右クリック--->ビルドパス--->ビルドパスの構成->ライブラリ->外部JARの追加...---> RXTXcomm.jarが見つかりました--->開く-> OK / jre / lib / extディレクトリにあります。

シリアルポート操作コードの場合:

package javaapplication1 import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.Enumeration import java.util.TooManyListenersException import java.util.ArrayList import gnu.io.CommPortIdentifier import gnu.io.PortInUseException import gnu.io.SerialPort import gnu.io.SerialPortEvent import gnu.io.SerialPortEventListener import gnu.io.UnsupportedCommOperationException /** * @Project name :illegalsms * @ :SerialPort.java * @ :org.serial * @Feature Description: * Serial port class * @creator : * @Created Date :2012-9-13 * @ : */ public class DSerialPort implements Runnable, SerialPortEventListener { Private String appName = 'Serial Communication Test' Private int timeout = 0//wait time for open port private int threadTime = 0 public ArrayList listPort public StringBuilder recvStr private CommPortIdentifier commPort private SerialPort serialPort private InputStream inputStream private OutputStream outputStream public javax.swing.JTextArea jTshow public javax.swing.JTextArea jTlog public byte[] recvdata public DSerialPort() { listPort=new ArrayList() recvStr=new StringBuilder() } /** * @ :listPort * @ : List all available serial ports * @return value type :void */ @SuppressWarnings('rawtypes') public void listPort(){ CommPortIdentifier cpid Enumeration en = CommPortIdentifier.getPortIdentifiers() log('now to list all Port of this PC:' +en) while(en.hasMoreElements()){ cpid = (CommPortIdentifier)en.nextElement() if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL){ log(cpid.getName() + ', ' + cpid.getCurrentOwner()) listPort.add(cpid.getName()) } } } /** * @ :selectPort * @ : Select a port, for example: COM1 * @return value type :void * @param portName */ @SuppressWarnings('rawtypes') public boolean selectPort(String portName){ 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 } } return openPort() } /** * @ :openPort * @Feature Description : Open SerialPort * @return value type :void */ private boolean openPort(){ if(commPort == null) { Log(String.format('Unable to find serial port with name '%1$s'!', commPort.getName())) return false } else{ Log('Port selected successfully, current port: '+commPort.getName()+', now instantiate SerialPort:') try{ serialPort = (SerialPort)commPort.open(appName, timeout) Log('Instance SerialPort Success!') // return true }catch(PortInUseException e){ Log(String.format('Port '%1$s' is in use!', commPort.getName())) return false } try { serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE) //serialPort. } catch(UnsupportedCommOperationException e) { Log(String.format('Port '%1$s' parameter is not valid!', commPort.getName())) return false } return true } } /** * @ :checkPort * @ : Check if the port is connected correctly * @return value type :void */ private void checkPort(){ if(commPort == null) Throw new RuntimeException('No port selected, please use ' + 'selectPort(String portName) method selects port') if(serialPort == null){ Throw new RuntimeException('SerialPort object is invalid!') } } /** * @ :write * @ : Send data to the port, please select the port before calling this method, and make sure that SerialPort is open normally! * @return value type :void * @param message */ public void write(String message) { checkPort() try{ outputStream = new BufferedOutputStream(serialPort.getOutputStream()) }catch(IOException e){ Throw new RuntimeException('Error getting the OutputStream of the port: '+e.getMessage()) } try{ outputStream.write(message.getBytes()) Log('Information sent successfully!') }catch(IOException e){ Throw new RuntimeException('Error sending message to port: '+e.getMessage()) }finally{ try{ outputStream.close() }catch(Exception e){ } } } /** * @ :startRead * @ : Start listening to data received from the port * @return value type :void * @param time The lifetime of the listener, in seconds, 0 is always listening */ public void startRead(int time){ checkPort() try{ inputStream = new BufferedInputStream(serialPort.getInputStream()) }catch(IOException e){ Throw new RuntimeException('Error getting the InputStream of the port: '+e.getMessage()) } try{ serialPort.addEventListener(this) }catch(TooManyListenersException e){ throw new RuntimeException(e.getMessage()) } serialPort.notifyOnDataAvailable(true) Log(String.format('Start listening for data from '%1$s' --------------', commPort.getName())) if(time > 0){ this.threadTime = time*1000 Thread t = new Thread(this) t.start() Log(String.format('The listener will close after %1$d seconds. . . . , threadTime)) } } /** * @ :close * @Feature Description : Turn off SerialPort * @return value type :void */ public void close(){ if(serialPort!=null) { serialPort.close() serialPort = null commPort = null } } /** * * @param msg */ public void log(String msg){ System.out.println(appName+' --> '+msg) } public void log2(String msg){ System.out.println(appName+' --> '+msg) } /** * Listening handler for data reception */ @Override public void serialEvent(SerialPortEvent arg0) { switch(arg0.getEventType()){ Case SerialPortEvent.BI:/*Break interrupt, communication interruption*/ Case SerialPortEvent.OE:/*Overrun error, overflow error*/ Case SerialPortEvent.FE:/*Framing error, frame error*/ Case SerialPortEvent.PE:/*Parity error, checksum error*/ Case SerialPortEvent.CD:/*Carrier detect, carrier detection*/ Case SerialPortEvent.CTS:/*Clear to send, clear send*/ Case SerialPortEvent.DSR: /*Data set ready, data device ready*/ Case SerialPortEvent.RI:/*Ring indicator, ringing indication*/ Case SerialPortEvent.OUTPUT_BUFFER_EMPTY: /*Output buffer is empty, output buffer is cleared*/ break Case SerialPortEvent.DATA_AVAILABLE: /*Data available at the serial port, the port has data available. Read the buffer array and output to the terminal*/ byte[] readBuffer = new byte[1024] int readDataLength = 0 String s2 try { while (inputStream.available() > 0) { readDataLength=inputStream.read(readBuffer) //readStr += new String(readBuffer).trim() } / / Save the real data to the zero-hour array recvdata = new byte[readDataLength] System.arraycopy(readBuffer, 0, recvdata, 0, readDataLength) s2 = new String(readBuffer).substring(0, readDataLength) jTshow.append(s2.toUpperCase()) jTshow.setCaretPosition(jTshow.getText().length()) recvStr.append(s2) String str str = '' for(int i=0iReceived port return data (length is '+readDataLength+'):'+str.toUpperCase() +' ') jTlog.setCaretPosition(jTlog.getText().length()) Log2 ('Received port return data (length is '+readDataLength+'): '+s2) log2(s2) } catch (IOException e) { } } } @Override public void run() { try{ Thread.sleep(threadTime) serialPort.close() Log(String.format('port''listen is off!', commPort.getName())) }catch(Exception e){ } } }