I have no intention to describe the usage of each class and interface of comm API in detail here, but I will introduce the class structure of comm API and several important API usage.
All comm APIs are located under the javax. Comm package. From the javadoc of comm API, it only introduces the following 13 classes or interfaces:
Javax. comm. commdriver javax. comm. comport javax. comm. parallelport javax. comm. serialPort javax. comm. commp ortidentifier javax. comm. commp ortownershiplistener javax. comm. parallelportevent javax. comm. serialportevent javax. comm. parallelporteventlistener (ExtendsJava. util. eventlistener) javax. Comm. serialporteventlistener (ExtendsJava. util. eventlistener) javax. Comm. nosuchportexception javax. Comm. portinuseexception javax. Comm. unsupportedcommoperationexception
The following describes several main classes or interfaces.
1. enumerate all RS232 ports of the system
Before using RS232 port communication, we want to know which ports are available in the system.CodeList all available RS232 ports in the system:
Enumeration en =Comatrix ortidentifier. getportidentifiers (); comatrix ortidentifier portid;While(EN. hasmoreelements () {portid=(Commp ortidentifier) en. nextelement ();/*If the port type is serial port, the port information is printed.*/If(Portid. getporttype () =Commp ortidentifier. port_serial) {system. Out. println (portid. getname ());}}
Above on my computerProgramOutput the following results:
COM1
Com2
The getportidentifiers method of the comatrix ortidentifier class allows you to find all the serial ports of the system. Each serial port corresponds to an instance of the comatrix ortidentifier class.
2. open the port
If you use a port, open it first.
try {comatrix ORT SerialPort = portid. open ("My app", 60 ); /* read data from the port */ inputstream input = SerialPort. getinputstream (); input. read (...); /* write data to the port */ outputstream output = SerialPort. getoutputstream (); output. write (...)...} catch (portinuseexception ex) {...}
You can use the open method of comatrix ortidentifier to return a comatrix object. The open method has two parameters. The first parameter is string, which is usually set to your application name. The second parameter is time, that is, the number of milliseconds for enabling port timeout. When the port is occupied by another application, a portinuseexception is thrown.
What is the difference between the comatrix ortidentifier class and the comatrix class? In fact, they have a one-to-one relationship. Commp ortidentifier is mainly responsible for port initialization and enabling, and managing their possession. The comport is related to the actual input and output functions. You can use getinputstream () of comport to obtain the input stream of the port. It is an instance of the Java. Io. inputstream interface. We can use the standard inputstream operation interface to read the data in the stream, just like reading the file content through fileinputsteam. Correspondingly, the getoutputstream of comport can obtain the output stream of the port, so that data can be output to the serial port.
3. Close the port
You must close the used port so that other programs can use it. Otherwise, an error may occur when other programs use the port. It is strange that the comatrix ortidentifier class only provides the method to enable the port. to disable the port, call the close () method of the comatrix class.
The reading method of the input stream of comport is different from that of the input stream of the file, that is, you may never know when the inputstream ends, unless the other party's outputstream sends you a specific data to indicate that the sending is complete, after receiving this specific character, you can disable your inputstream. Comm. Jar provides two flexible methods for you to read data.
1. Polling)
For example, if you meet GF to go out for a movie, but your GF looks good, it may be half an hour or more. At this time, you can't bear it anymore. every two minutes, you will ask "Okay ?", In this case, it is not until your GF says OK. This is called polling ).
In a program, polling is usually designed as a closed loop. When a condition is met, the loop ends. In that example, your GF said "OK !", This is the condition for ending your round-robin. In a single-threaded program, when the loop continues to execute a task and cannot predict when it will end, your program may look like a dead machine. In the vbprogram, this problem can be solved by inserting a doevent statement in the loop structure. In Java, the best way is to use a thread, just like the following code snippet.
Public Testport extend thread {... inputstream Input = SerialPort. getinputstream (); stringbuffer Buf = New Stringbuffer (); Boolean Stopped = False ;... Public Void Run (){ Try { While (! Stopped) Int Ch = Input. Read (); If (CH = 'q' | CH = 'Q' ){ /* Stop reading and close the port... */ Stopped = True ;...} Else {Buf. append (( Char ) CH );...}} Catch (Interruptedexception e ){}}}
2. Listening)
Comm API supports standard Java Bean-type event models. That is to say, you can use methods like addxxxlistener to register your own listener for a serial port and read data in the listener mode.
To listen to a port, you must first obtain an instance of the commp ortidentifier class,
Commp ORT SerialPort = portid. Open ("My app", 60 );
To get the SerialPort, and then call its addeventlistener method to add a listener to it,
SerialPort. addeventlistener (New myportlistener ());
The SerialPort listener must inherit from the serialporteventlistener interface. When any SerialPort event occurs, the serialevent method in the listener is automatically called. Serial events can be of the following types:
Bi-Communication interruption.
CD-carrier detection.
CTS-clear sending.
Data_available-data arrives.
DSR-data device preparation.
Fe-frame error.
OE-overflow error.
Output_buffer_empty-the output buffer has been cleared.
Pe-parity error.
Ri-ringing indicator.
The following is an example of a listener:
Public Void Myportlistener Implements Serialporteventlistener { Public Void Serialevent (serialportevent EVT ){ Switch (EVT. geteventtype ()){ Case Serialportevent. CTS: system. Out. println ( "CTS event occured ." ); Break ; Case Serialportevent. CD: system. Out. println ( "CD event occured ." ); Break ; Case Serialportevent. BI: system. Out. println ( "Bi event occured ." ); Break ; Case Serialportevent. DSR: system. Out. println ( "DSR event occured ." ); Break ; Case Serialportevent. Fe: system. Out. println ( "Fe event occured ." ); Break ; Case Serialportevent. OE: system. Out. println ( "Oe event occured ." ); Break ; Case Serialportevent. PE: system. Out. println ( "PE event occured ." ); Break ; Case Serialportevent. Ri: system. Out. println ( "RI event occured ." ); Break ; Case Serialportevent. output_buffer_empty: system. Out. println ( "Output_buffer_empty event occured ." ); Break ; Case Serialportevent. data_available: system. Out. println ( "Data_available event occured ." ); Int Ch; stringbuffer Buf = New Stringbuffer (); inputstream Input = SerialPort. getinputstream Try { While (CH = input. Read ()> 0 ) {Buf. append (( Char ) CH);} system. Out. Print (BUF );} Catch (Ioexception e ){} Break ;}}
This listener simply prints the name of each event. For most applications, the typical concern is the data_available event. This event is triggered when data is transferred from an external device to a port. Now you can use the method mentioned above, SerialPort. getinputstream (), to read data from inputstream.