7.6 Managing the PPP Data Link
The PPP daemon we implemented in the previous section maintained a reference to an instance of a class that implemented the PPPDataLink interface. This reference is used by the server to control the data link. Now we'll create the PPPDataLink interface shown in Listing 7.14. Both of the link management classes we will create in this section will implement this interface.
Listing 7.14 PPPDataLink
import javax.comm.SerialPort; public interface PPPDataLink { public SerialPort getPort(); public void initializeLink() throws DataLinkException; }
The initializeLink method is used to perform any specific setup required to use that data link. After the link has been successfully initialized, the PPP daemon invokes getPort to acquire a reference to the link's serial port. This reference is transferred to the native PPP implementation and is used for all PPP communication. Other than during construction and execution of the initializeLink method, the data link classes should not access the serial port.
Because data link errors can occur asynchronously and without the knowledge of the underlying native PPP implementation, an object that owns the data link needs a mechanism for notifying PPPDaemon that an error has occurred. The most common example of a link error is the modem hanging up. This results in loss of carrier detect from the modem. We'll discuss this further in Section 7.6.2. The interface DataLinkListener shown in Listing 7.15 defines the method dataLinkError that will be invoked by the object controlling the data link upon detection of an unrecoverable error.
Listing 7.15 DataLinkListener
public interface DataLinkListener { public void dataLinkError(String error); }
When the listener's dataLinkError (see Listing 7.16) is invoked, it will typically set some internal state and call the close method on the PPP object. The internal state allows the CLOSED event code to determine why the CLOSED event was generated. In the case of a link error, it will invoke the down method on the PPP object, freeing the serial port and forcing a transition to the START state. This provides a clean way to reset the link and hopefully clear the condition that generated the error.
Listing 7.16 dataLinkError
public void dataLinkError(String error) { System.err.println("Error in data link:"+error); ++linkErrors; ppp.close(); }
In our example PPP server, we maintain a retry count and put an upper limit on the number of retries that can be caused by a persistent error in either the data link or the underlying PPP object. The retry count is reset to 0 after every successful transition to the UP state.
7.6.1 The Serial Link
All PPP traffic flows over a serial port. The serial port may or may not have a modem attached. Now we'll create a class named PPPSerialLink that provides functionality that is common to both hard-wired serial and modem configurations. PPPSerialLink is shown in Listing 7.17. Notice first that PPPSerialLink implements the PPPDataLink interface providing implementations for the initializeLink and getPort methods. These are the only public methods needed by PPPDaemon to manage the data link.
During construction, PPPSerialLink creates a new serial port object and uses that object to configure the physical port. In this example, we set the port for 8 data bits, 1 stop bit, and no parity. This is a very common configuration and shouldn't cause us any problems in communicating with other modems or directly with another serial port. We also select the use of RTS/CTS (Request to Send/Clear to Send) hardware flow control (see Section 3.2.2), assuming that the underlying physical port has support for the necessary hardware flow control lines.4 Finally, the constructor creates input and output streams for reading from and writing to the serial port, respectively. Note that this class could be made more flexible by adding parameters to the constructor that allowed for the selection of either hardware or software flow control as well as other data transfer settings.
Listing 7.17 PPPSerialLink
import javax.comm.*; import java.io.*; public class PPPSerialLink implements PPPDataLink { protected DataLinkListener listener; protected SerialPort sp; protected InputStream in; protected OutputStream out; public PPPSerialLink(String portName, int speed, DataLinkListener listener) throws DataLinkException { this.listener = listener; try { // Create and initialize serial port sp = (SerialPort) CommPortIdentifier.getPortIdentifier(portName).open( "PPPDataLink", 5000); sp.setSerialPortParams(speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); TINIOS.setRTSCTSFlowControlEnable(0, true); sp.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT); in = sp.getInputStream(); out = sp.getOutputStream(); } catch (Exception e) { throw new DataLinkException("Error configuring serial port"+ e.getMessage()); } } public void initializeLink() throws DataLinkException { } public SerialPort getPort() { return sp; } }
If the constructor fails to properly acquire ownership or properly initialize the specified serial port for any reason, it throws a DataLinkException. Typical causes of failure would be that the port is already owned by another process or it doesn't support one of the selected options.
A PPPSerialLink object doesn't need to do much after it has initialized the port. The initializeLink method simply returns because the link is always ready for data traffic.5 In the next section, when we add modem support, we'll have to do a bit of work in initializeLink.
The PPPSerialLink class implements the functionality needed to provide PPP communication over a hard-wired serial link. This type of connectivity is useful as a quick and simple mechanism for testing PPP code written for TINI. No modem is required in this configuration, and it allows for a faster connection because you don't have to wait for normal modem delays such as dialing and answering the phone. In practice, it is probably most useful for direct communication between TINI and a hand-held PDA that supports PPP connections such as the Palm Pilot or Visor.
7.6.2 Controlling the Modem
Most practical uses of PPP on TINI require the use of an external serial modem. Ultimately, if an application similar to DataLogger is deployed in an Ethernet challenged location, its only connection to a TCP/IP network could be using the public phone network. A hardware configuration of TINI plus a serial modem allow applications to either accept or make dial-up network connections with remote clients or servers.
Since all communication with the modem will be over a serial port, we can create the class to manage modem communications as a subclass of PPPSerialLink, defined in the previous section. The class PPPModemLink is shown in Listing 7.18. Upon construction PPPModemLink invokes its superclass's constructor to acquire and initialize the serial port. It also creates a ModemCommand object to manage sending commands to and receiving responses from the modem. The ModemCommand class is described later in this section.
Listing 7.18 PPPModemLink
import javax.comm.*; import java.io.*; import java.util.TooManyListenersException; public class PPPModemLink extends PPPSerialLink implements SerialPortEventListener { private ModemCommand mc; public PPPModemLink(String portName, int speed, DataLinkListener listener) throws DataLinkException { super(portName, speed, listener); mc = new ModemCommand(sp, in, out); try { sp.addEventListener(this); } catch (TooManyListenersException tmle) { throw new DataLinkException( "Unable to register for serial events"); } } ... public void serialEvent(SerialPortEvent ev) { if ((ev.getEventType() == SerialPortEvent.CD) && !ev.getNewValue()) { listener.dataLinkError("Lost carrier detect"); } } }
PPPModemLink implements the SerialPortEventListener interface. In this case we're specifically interested in the SerialPortEvent.CD (Carrier Detect) event because we need to be notified if and when the modem hangs up. When the modem hangs up, the CD signal transitions from high (carrier present) to low (carrier not present). If this happens, the serialEvent method is invoked by the serial port event daemon notification thread. serialEvent checks the event type to see if it is a carrier detect change event. All other events are ignored. If the returned event value is false, this signals that the modem has indeed hung up, and serialEvent invokes the DataLinkListener's (PPPDaemon in this case) dataLinkError method, notifying the listener that the data link is no longer valid. The PPP daemon then closes the underlying PPP connection and frees any resources that were consumed.
Initializing the modem link involves the following three steps:
Reset the modem.
Wait for a ring.
Answer the phone.
Both the initializeLink and resetModem methods are shown in Listing 7.19. The modem reset is initiated by dropping the DTR (Data Terminal Ready) line low, delaying for a couple of seconds, and then raising DTR back high. After toggling DTR, resetModem sends the string "AT\r" to the modem and waits for a response string of "OK." If the expected response is received, resetModem returns normally. If the response is not received within the specified time-out valuesix seconds in this casea DataLinkException is thrown by the sendCommand method of the ModemCommand class. This exception is allowed to propagate up the call stack to notify the method that invoked initializeLink of the failure to initialize the modem.
Listing 7.19 initializeLink and resetModem
public void initializeLink() throws DataLinkException { resetModem(); mc.receiveMatch("RING", null, 0); mc.sendCommand("ATA\r", "CONNECT", 25); } private void resetModem() throws DataLinkException { // Clear RTS and DTR sp.setDTR(false); sp.setRTS(false); try { Thread.sleep(2000); } catch (InterruptedException ie) {} // Set RTS and DTR sp.setDTR(true); sp.setRTS(true); try { Thread.sleep(2000); } catch (InterruptedException ie) {} // Sync modem to serial port baud rate mc.sendCommand("AT\r", "OK", 6); }
Note that depending on the specific modem you're using, you may have to do more or different work in initializeLink. For example, the modems used to test this class all autobaud by default when the "AT\r" string is transmitted immediately after the DTR reset. If your modem initializes to some predefined hard-coded speed after a DTR reset, initializeLink would have to transmit a command at the predefined speed, setting the new desired speed. Other commands may also be required to correctly reset and initialize the modem.
After successfully resetting the modem, initializeLink waits for a ring. When the modem detects a ring on the phone line, it transmits the string "RING." initializeLink blocks indefinitely by specifying a time-out value of 0, waiting for this string. Once it receives the string, it sends the "ATA" command to the modem, instructing it to answer the incoming call. After answering the phone, the modem will respond with the string "CONNECT." We allow a 25-second time-out for the modem to answer the phone and respond because this is a time-consuming process. It should typically complete within 10 or 15 seconds of ring detection. After receiving the "CONNECT" string from the modem, the communication channel is fully established and initializeLink returns normally.
The ModemCommand class, partially shown in Listing 7.20, is a utility class used by PPPModemLink to handle the details of serial communication with the modem. It is passed references to the serial port as well as serial port input and output streams for the actual data transfer. ModemCommand provides these two public methods.
public void sendCommand(String command, String response, int timeout) throws DataLinkException public void receiveMatch(String match, String response, int timeout) throws DataLinkException
The sendCommand method converts command to a byte array and transmits the result over the serial port to the attached modem. After transmitting the command string, sendCommand invokes the waitForResponse method (described below) to wait for the modem to transmit a response equal (ignoring case) to the value supplied in response. If no response is expected from the modem, null can be supplied for the response String. In this case, sendCommand returns immediately after transmitting the command. The receiveMatch command has the opposite sense. It first waits for a transmission from the modem equal (again ignoring case) to the supplied value of match and then transmits a response to the modem. If nothing is to be transmitted to the modem after receipt of the desired match String, null is passed for the response. Both methods throw DataLinkException in the event of a time-out waiting for the desired response.
Listing 7.20 ModemCommand
import javax.comm.*; import java.io.*; public class ModemCommand { private SerialPort sp; private InputStream in; private OutputStream out; public ModemCommand(SerialPort sp, InputStream in, OutputStream out) { this.sp = sp; this.in = in; this.out = out; } public void sendCommand(String command, String response, int timeout) throws DataLinkException { try { // Transmit the command out.write(command.getBytes()); } catch (IOException ioe) { ioe.printStackTrace(); throw new DataLinkException( "Error sending command to modem"); } waitForMatch(response, timeout); } public void receiveMatch(String match, String response, int timeout) throws DataLinkException { try { waitForMatch(match, timeout); if ((response != null) && (response.length() > 0)) { out.write(response.getBytes()); } } catch (IOException ioe) { ioe.printStackTrace(); throw new DataLinkException( "IO Error receiving a match to:"+match); } } ... }
The waitForMatch method, shown in Listing 7.21, takes a String used for the desired pattern match. The pattern match is performed in a case insensitive manner. It also takes an integer number of seconds used as a time-out value, where a value of 0 seconds is used to specify an infinite time-out. It uses both serial port receive time-outs and thresholds to control the reading of data and manage a timer. The receive time-out is set to 100 milliseconds and the threshold to the number of bytes equal to the length of the match String. The overall time that has elapsed is tracked using System.currentTimeMillis.
Listing 7.21 waitForMatch
private void waitForMatch(String match, int timeout) throws DataLinkException { try { sp.enableReceiveTimeout(100); sp.enableReceiveThreshold(match.length()); byte[] mb = new byte[match.length()]; long timer = 0; if (timeout > 0) { // Time out when timer > currentTimeMillis timer = timeout*1000+System.currentTimeMillis(); } StringBuffer modemSpew = new StringBuffer(); while ((timer == 0) || (System.currentTimeMillis() < timer)) { int count = in.read(mb); if (count > 0) { modemSpew.append((new String(mb,0,count)).toUpperCase()); if (modemSpew.toString().indexOf( match.toUpperCase()) >= 0) { return; } } } throw new DataLinkException("Timed out waiting for match:"+ match); } catch (Exception e) { e.printStackTrace(); throw new DataLinkException("IO Error receiving a match to:"+ match); } }
The trick here is that the modem might send other unwanted bytes of information in the same stream of data that has the pattern that we're trying to match. To deal with this problem, waitForMatch reads all serial bytes and stores them in a StringBuffer. Each time data is available, the new bytes are appended to the end of the StringBuffer. To check for a match, the StringBuffer is converted to a String, and the indexOf method is used to check to see if the desired response is contained anywhere within the resulting String. If a match is found, waitForMatch returns normally. Otherwise, it performs another blocking read until either the number of bytes equal to the length of the match String is available or until 100 milliseconds elapses. If no match is found within the specified overall time-out, a DataLinkException is thrown. The DataLinkException propagates up the call stack eventually notifying the PPP daemon of the modem's failure to respond.