Home > Articles > Networking > Network Design & Architecture

  • Print
  • + Share This

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:

  1. Reset the modem.

  2. Wait for a ring.

  3. 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 value—six seconds in this case—a 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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020