Serial ports are older technology. However, they e still found on a lot of equipment that might want to run or communicate with J2ME devices, such as multimeters, GPS receivers, printers, ham radios, and more. Furthermore, sometimes other less standard ports are made to look like serial ports to the operating system. For instance, some i-mate smart phones have an SDIO port thats mapped to a virtual serial port on COM7. IRDA infrared devices are also often treated as RS-232 serial ports.
MIDP 2.0 includes a CommConnection subinterface of StreamConnection suitable for talking to devices hooked up to serial ports. It is actually quite a bit easier to use than the Java Communications API discussed in Chapter 22.
public interface CommConnection extends StreamConnection
Not all small devices have serial ports, so not all support CommConnection even if they support MIDP 2.0. You can test for the presence of CommConnection by checking the microedition.commports system property. If it is nonnull, comm connections are supported:
if (System.getProperty("microedition.commports") != null) { //... }
Theres no standard form for a serial port URL, so one was invented. The scheme is comm, followed by the port number, followed by any parameters. For example, these are all serial port URLs:
The host device defines the logical port names that follow the scheme. More often than not, these are just simple numbers: 1 for COMM port 1, 2 for COMM port 2, and so on. However, some devices may use more descriptive names. Sometimes COM1, COM2, and so forth are used for genuine RS-232 ports while IR1, IR2, and so on are used for IRDA ports. The microedition.commports system property contains a comma-separated list of all the identifiers valid for the current host.
The name/value parameters that follow the port name are just the standard serial port options discussed previously in Chapter 22. Table 24-1 summarizes them.
To open a connection to a serial port-attached external device, just pass a URL configured with the necessary parameters to the usual Connector.open( ) method. For example, this opens a connection to the device attached to serial port 0 with a 9,600-baud rate:
Connection conn = Connector.open("comm:0;baudrate=9600");
Mostly, you just use the input streams and output streams returned by openInputStream( ) and openOutputStream( ) to talk to serial ports. CommConnection adds only two methods beyond those defined in StreamConnection, getBaudRate( ) and setBaudRate( ):
public int getBaudRate( ) public int setBaudRate(int baudrate)
If the URL did not specify a baud rate, getBaudRate( ) lets you determine the default speed for the device. setBaudRate( ) lets you change this speed. Not all speeds are available for any given device. If you try to set an unsupported speed, setBaudRate( ) may throw an exception, or it may pick a supported speed instead.