📄 pppclient.java
字号:
package com.gaidi.virtualnet.tini;/**************************************************************************** * * Copyright (C) 2001 Dallas Semiconductor Corporation. * All rights Reserved. Printed in U.S.A. * This software is protected by copyright laws of * the United States and of foreign countries. * This material may also be protected by patent laws of the United States * and of foreign countries. * This software is furnished under a license agreement and/or a * nondisclosure agreement and may only be used or copied in accordance * with the terms of those agreements. * The mere transfer of this software does not imply any licenses * of trade secrets, proprietary technology, copyrights, patents, * trademarks, maskwork rights, or any other form of intellectual * property whatsoever. Dallas Semiconductor retains all ownership rights. * * Module Name: PPPClient.java * * *****************************************************************************/import java.io.*;import javax.comm.*;import com.dalsemi.system.*;import com.dalsemi.tininet.ppp.*;import com.gaidi.Log.Log;/** * * PPP dialer * */public class PPPClient extends Thread implements PPPEventListener{ // Serial port object and I/O streams private SerialPort serialPort; private InputStream modemInputStream; private OutputStream modemOutputStream; static private boolean isInitLibrary = false; // Serial port number private int portNumber; // The PPP object PPP ppp = null; // True while connection is established private boolean connected = false; private boolean running = true; // Local and remote peer IP addresses private byte[] localAddress = new byte[] { 0, 0, 0, 0}; private byte[] remoteAddress = new byte[] { 0, 0, 0, 0}; // This will be the network interface name private String interfaceName = "pppClient"; private String username; private String password; private String phoneNumber; private boolean haveControlLines = true; private boolean carrierLost = false; private boolean interfaceActive = false; // Strings used to initialize and dial modem private ModemCommand[] dialSequence = { new ModemCommand("AT\r", "OK", 5), // Get the modems attention new ModemCommand("ATZ\r", "OK", 5) // Soft rest //new ModemCommand("ATM1L0\r", "OK", 5), // Adjust speaker volume and duration //new ModemCommand("AT&K0\r", "OK", 6) // No flow control }; public PPPClient(int portID, String userName, String passWord, String phoneNumber) throws Exception{ // Set options this.portNumber = portID; this.username = userName; this.password = passWord; this.phoneNumber = phoneNumber; initLibrary(); ppp = new PPP(); ppp.addEventListener(this); // Set the local and remote IP address ppp.setLocalAddress(localAddress); ppp.setRemoteAddress(remoteAddress); // Set client peer type options // Set the ACCM to escape all octets ppp.setRemoteAccm(0x00000000); ppp.setLocalAccm(0x00000000); ppp.setAuthenticate(false, true); // Set username and password ppp.setUsername(username); ppp.setPassword(password); openSerialPort(portNumber); // Start client start(); } public int status() { if (running == true && connected == true) return 0; else if (running == true && connected == false) return 1; else return 2; } /** * Thread interface */ public void run() { Log.writeLog("Start PPP"); Log.writeLog(""); while(true){ reset(); pppThread(); running = false; try{ Thread.currentThread().sleep(15000); }catch(Exception _){ } } } public void pppThread() { // Initalize modem Log.writeLog("Dialing"); for (int i = 0; i < dialSequence.length; ++i) { if (!atCommand(dialSequence[i])) { Log.writeLog("Modem did not respond to command " + dialSequence[i].command); return; } } // Dial server if (!atCommand(new ModemCommand("ATDT" + phoneNumber + "\r", "CONNECT", 45))) { Log.writeLog("Modem unable to establish connection"); return; } Log.writeLog("Connected to ISP"); // Set connected flag connected = true; // Issue open command to PPP FSM ppp.up(serialPort); // Keep thread alive while connected while (running) { try { Thread.currentThread().sleep(1000); } catch (Exception e) {} // Check carrier detect if a connection is established and control lines are available if (connected && haveControlLines && !carrierLost) { // If control lines are available check carrier detect if (!serialPort.isCD()) { // Close PPP now that the modem link is down Log.writeLog("iscd"); ppp.close(); // Only do this once carrierLost = true; } } if (!connected) { running = false; } } } public void stopPPP(){ if(running == true && connected == true && carrierLost == false){ ppp.close(); carrierLost = true; } while(true) { if(running == true && connected == true && carrierLost == false) break; try{ Thread.currentThread().sleep(10000); } catch(Exception _){ } } } /** * PPP event listener interface */ public void pppEvent(PPPEvent ev) { switch (ev.getEventType()) { case PPPEvent.UP: // PPP connection is up Log.writeLog("PPP IS UP"); ppp.addInterface(interfaceName); com.dalsemi.tininet.TININet.setPrimaryDNS("202.98.96.68"); com.dalsemi.tininet.TININet.setSecondaryDNS("61.139.2.69"); com.dalsemi.tininet.TININet.setDNSTimeout(25000); interfaceActive = true; break; case PPPEvent.CLOSED: // PPP connection is closed Log.writeLog("PPP IS DOWN"); if (interfaceActive) { interfaceActive = false; ppp.removeInterface(interfaceName); //ppp.freeNativeInterface(); } connected = false; break; default: break; } } /** * Cleanup PPP state */ private void closePPP() { ppp.freePort(); ppp.finish(); // Wait for threads to terminate try { Thread.sleep(2000); } catch (Exception _) { } ppp.removeEventListener(this); } /** * Close serial port */ private void closeSerialPort() { // Reset modem resetModem(); // Close serial port serialPort.close(); // Remove ownership listener //////////////////portId.removePortOwnershipListener(this); } /** * Open serial port */ private boolean openSerialPort(int portNum) { // Enable serial port try { if (portNum > 0 && portNum < 4) // ports 0 and 4 ( on the 400 ) are enabled by defualt TINIOS.setSerial(TINIOS.SERIAL_SET_ENABLE, portNum, true); } catch (UnsupportedCommOperationException _) { Log.writeLog("Exception enabling serial port " + portNum); return false; } try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("serial" + portNum); // Give any current owners 5 seconds to free the port if they want to serialPort = (SerialPort) portId.open(interfaceName, 5000); serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); /////////////portId.addPortOwnershipListener(this); // If control signals are available, configure control signals for serial 0 and 1 then enable flow control if (haveControlLines) { // To garantee that we get the correct port enabled with flow line, disable all ports first then enable ours if (TINIOS.getCPU() == TINIOS.DS80C400) // On the 400 disable flow lines from serial4 TINIOS.setSerial(TINIOS.SERIAL_SET_RTSCTS_FLOW_CONTROL, 4, false); TINIOS.setSerial(TINIOS.SERIAL_SET_RTSCTS_FLOW_CONTROL, 1, false); TINIOS.setSerial(TINIOS.SERIAL_SET_RTSCTS_FLOW_CONTROL, 0, false); TINIOS.setSerial(TINIOS.SERIAL_SET_RTSCTS_FLOW_CONTROL, portNum, true); // Enable RTSCTS flow control serialPort.setFlowControlMode(serialPort.FLOWCONTROL_RTSCTS_IN | serialPort.FLOWCONTROL_RTSCTS_OUT); } // No control lines are available, disable control signals for serial 0 or 1 then disable flow control else { // Disable RTSCTS flow control serialPort.setFlowControlMode(serialPort.FLOWCONTROL_NONE); } modemInputStream = serialPort.getInputStream(); modemOutputStream = serialPort.getOutputStream(); //if(!reset()) // return false; } catch (Exception e) { Log.writeLog(e.toString()); return false; } return true; } private boolean reset(){ connected = false; running = true; carrierLost = false; interfaceActive = false; try{ // Clear any old input data long available = modemInputStream.available(); if (available > 0) modemInputStream.skip(available); // Flush any old output data modemOutputStream.flush(); // Reset modem resetModem(); }catch(IOException e){ Log.writeException(e); return false; } return true; } /** * Wait for a string and send a response */ private boolean waitFor(String expect, String response, int timeout) { boolean done = false; boolean returnValue = false; int numBytes; byte[] readBuffer = new byte[40]; int bytesAvailable; String buffer = new String(); timeout *= 2; while (done == false) { try { // Sleep for one-half second Thread.sleep(500); if ( (bytesAvailable = modemInputStream.available()) > 0) { numBytes = modemInputStream.read(readBuffer, 0, bytesAvailable); buffer = buffer.concat(new String(readBuffer, 0, numBytes)); if (buffer.indexOf(expect) != -1) { try { if (response != null) modemOutputStream.write(response.getBytes()); } catch (Exception e) { Log.writeLog(e.toString() + " during write"); } returnValue = true; done = true; } } else { // An initial timeout value of zero will wait forever if (timeout != 0) { // Decrement seconds counter if (--timeout == 0) { returnValue = true; //false; done = true; } } } } catch (Exception e) { Log.writeLog(e.toString()); } } return returnValue; } /** * Send modem an AT command and wait for response */ public boolean atCommand(ModemCommand mc) { boolean returnValue = false; String response = new String(); int timeout = mc.timeout * 2; try { try { modemOutputStream.write(mc.command.getBytes()); } catch (Exception e) { Log.writeLog("atCommand write " + e.toString()); return false; } boolean done = false; while (done == false) { // Sleep for one-half second Thread.sleep(500); // Get available count int bytesAvailable = modemInputStream.available(); if (bytesAvailable > 0) { // Read available data byte[] readBuffer = new byte[bytesAvailable]; int numBytes = modemInputStream.read(readBuffer, 0, bytesAvailable); // Concat to existing response response = response.concat(new String(readBuffer, 0, numBytes)); // See if expected response is contained in buffer if (response.indexOf(mc.response) != -1) { // Set return value and escape loop returnValue = true; done = true; } } else { // If not waiting forever if (timeout > 0) { // Decrement seconds counter if (--timeout == 0) { returnValue = false; done = true; } } } } } catch (Exception e) { Log.writeLog("atCommand all " + e.toString()); } return returnValue; } /** * If the modem control lines are connected * this should cause the modem to drop any existing * connection and enter command mode. */ private void resetModem() { if (haveControlLines) { serialPort.setDTR(false); serialPort.setRTS(false); try { Thread.sleep(2000); } catch (Exception _) {} serialPort.setDTR(true); serialPort.setRTS(true); try { Thread.sleep(2000); } catch (Exception _) {} } else { try { Thread.sleep(2000); } catch (Exception _) {} atCommand(new ModemCommand("+++", "", 2)); try { Thread.sleep(2000); } catch (Exception _) {} atCommand(new ModemCommand("ATH\r", "OK", 2)); } } public static void initLibrary() { if (isInitLibrary == false) { // Load PPP native library based on which processor we are int cpuType = TINIOS.getCPU(); // Get CPU type switch (cpuType) { case TINIOS.DS80C390: System.loadLibrary("mod_ppp.tlib"); break; case TINIOS.DS80C400: System.loadLibrary("mod_ppp_400.tlib"); break; default: throw new UnsatisfiedLinkError("Load library error, bad CPU type: " + cpuType); } isInitLibrary = true; } } public void close() { ppp.close(); closePPP(); closeSerialPort(); }}//// Modem comamnd//class ModemCommand { // Command to issue String command; // Expected response String response; // Maximum time to wait in seconds int timeout; // Do not allow uninitialized modem commands private ModemCommand() {}; public ModemCommand(String command, String response, int timeout) { this.command = command; this.response = response; this.timeout = timeout; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -