netadapter.java
来自「这是一个以JAVA编写的程序,本人还没有试过,是一个简单的温度控制系统」· Java 代码 · 共 2,064 行 · 第 1/5 页
JAVA
2,064 行
/*--------------------------------------------------------------------------- * Copyright (C) 2002 Dallas Semiconductor Corporation, All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of Dallas Semiconductor * shall not be used except as stated in the Dallas Semiconductor * Branding Policy. *--------------------------------------------------------------------------- */package com.dalsemi.onewire.adapter;import java.io.*;import java.net.*;import java.util.*;import com.dalsemi.onewire.*;import com.dalsemi.onewire.utils.*;import com.dalsemi.onewire.adapter.NetAdapterConstants.*;/** * <P>NetAdapter is a network-based DSPortAdapter. It allows for the use of * an actual DSPortAdapter which isn't on the local machine, but rather is * connected to another device which is reachable via a TCP/IP network * connection.</P> * * <P>The syntax for the <code>selectPort(String)</code> command is the * hostname of the computer which hosts the actual DSPortAdapter and the * TCP/IP port that the host is listening on. If the port number is not * specified, a default value of 6161 is used. Here are a few examples to * illustrate the syntax: * <ul> * <li>my.host.com:6060</li> * <li>180.0.2.46:6262</li> * <li>my.host.com</li> * <li>180.0.2.46</li> * </ul></P> * * <P?The use of the NetAdapter is virtually identical to the use of any * other DSPortAdapter. The only significant changes are the necessity * of the 'host' component (see NetAdapterHost) * and the discovery of hosts on your network. There are currently two * techniques used for discovering all of the hosts: The look-up of each host * from the onewire.properties file and the use of multicast sockets for * automatic discovery.</P> * * <P>In the onewire.properties file, you can add a host to your list of valid * hosts by making a NetAdapter.host with an integer to distinguish the hosts. * There is no limit on the number of hosts which can appear in this list, but * the first one must be numbered '0'. These hosts will then be returned in * the list of valid 'ports' from the <code>selectPortNames()</code> method. * Note that there do not have to be any servers returned from * <code>selectPortNames()</code> for the NetAdapter to be able to connect * to them (so it isn't necessary to add these entries for it to function), * but applications which allow a user to automatically select an appropriate * adapter and a port from a given list will not function properly without it. * For example: * <ul> * <li>NetAdapter.host0=my.host.com:6060</li> * <li>NetAdapter.host1=180.0.2.46:6262</li> * <li>NetAdapter.host2=my.host.com</li> * <li>NetAdapter.host3=180.0.2.46</li> * </ul></P> * * <P>The multicast socket technique allows you to automatically discover * hosts on your subnet which are listening for multicast packets. By * default, the multicast discovery of NetAdapter hosts is disabled. * When enabled, the NetAdapter creates a multicast socket and looks for servers * every time you call <code>selectPortNames()</code>. This will add a * 1 second delay (due to the socket timeout) on calling the method. If you'd * like to enable this feature, add the following line to your * onewire.properties file: * <ul> * <li>NetAdapter.MulticastEnabled=true</li> * </ul> * The port used and the multicast group used for multicast sockets can * also be changed. The group however, must fall withing a valid range. * For more information about multicast sockets in Java, see the Java * tutorial on networking at <A HREF="http://java.sun.com/docs/books/tutorial/"> * http://java.sun.com/docs/books/tutorial/</A>. Change the defaults in the * onewire.properties file with the following entries: * <ul> * <li>NetAdapter.MulticastGroup=228.5.6.7</li> * <li>NetAdapter.MulticastPort=6163</li> * </ul> * </P> * * <P>Once the NetAdapter is connected with a host, a version check is performed * followed by a simple authentication step. The authentication is dependent * upon a secret shared between the NetAdapter and the host. Both will use * a default value, that each will agree with if you don't provide a secret * of your own. To set the secret, add the following line to your * onewire.properties file: * <ul> * <li>NetAdapter.secret="This is my custom secret"</li> * </ul> * Optionally, the secret can be specified on a per-host basis by simply * adding the secret after the port number followed by a colon. If no port * number is specified, a double-colon is required. Here are examples: * <ul> * <li>my.host.com:6060:my custom secret</li> * <li>180.0.2.46:6262:another custom secret</li> * <li>my.host.com::the custom secret without port number</li> * <li>180.0.2.46::another example of a custom secret</li> * </ul></P> * * <P>All of the above mentioned properties can be set on the command-line * as well as being set in the onewire.properties file. To set the * properties on the command-line, use the -D option: * java -DNetAdapter.Secret="custom secret" myApplication</P> * * <P>The following is a list of all parameters that can be set for the * NetAdapter, followed by default values where applicable.<br> * <ul> * <li>NetAdapter.secret=Adapter Secret Default</li> * <li>NetAdapter.secret[0-MaxInt]=[no default]</li> * <li>NetAdapter.host[0-MaxInt]=[no default]</li> * <li>NetAdapter.MulticastEnabled=false</li> * <li>NetAdapter.MulticastGroup=228.5.6.7</li> * <li>NetAdapter.MulticastPort=6163</li> * </ul></P> * * <p>If you wanted added security on the communication channel, an SSL socket * (or similar custom socket implementation) can be used by circumventing the * standard DSPortAdapter's <code>selectPort(String)</code> and using the * NetAdapter-specific <code>selectPort(Socket)</code>. For example: * <pre> * NetAdapter na = new NetAdapter(); * * Socket secureSocket = // insert fancy secure socket implementation here * * na.selectPort(secureSocket); * <pre></P> * * <P>For information on setting up the host component, see the JavaDocs * for the <code>NetAdapterHost</code> * * @see NetAdapterHost * * @author SH * @version 1.00, 9 Jan 2002 */public class NetAdapter extends DSPortAdapter implements NetAdapterConstants{ /** Error message when neither RET_SUCCESS or RET_FAILURE are returned */ protected static final String UNSPECIFIED_ERROR = "An unspecified error occurred."; /** Error message when I/O failure occurs */ protected static final String COMM_FAILED = "IO Error: "; /** constant for no exclusive lock */ protected static final Integer NOT_OWNED = new Integer(0); /** Keeps hash of current thread for exclusive lock */ protected Integer currentThreadHash = NOT_OWNED; /** instance for current connection, defaults to EMPTY*/ protected Connection conn = EMPTY_CONNECTION; /** portName For Reconnecting to Host */ protected String portNameForReconnect = null; /** secret for authentication with the server */ protected byte[] netAdapterSecret = null; /** if true, the user used a custom secret */ protected boolean useCustomSecret = false; //------- //------- Multicast variables //------- /** indicates whether or not mulicast is enabled */ protected Boolean multicastEnabled = null; /** The multicast group to use for NetAdapter Datagram packets */ protected String multicastGroup = null; /** The port to use for NetAdapter Datagram packets */ protected int datagramPort = -1; /** * Creates an instance of NetAdapter that isn't connected. Must call * selectPort(String); or selectPort(Socket); */ public NetAdapter () { try { resetSecret(); } catch(Throwable t) { setSecret(DEFAULT_SECRET); } } /** * Sets the shared secret for authenticating this NetAdapter with * a NetAdapterHost. * * @param secret the new secret for authenticating this client. */ public void setSecret(String secret) { if(secret!=null) { this.netAdapterSecret = secret.getBytes(); } else resetSecret(); } /** * Resets the secret to be the default stored in the onewire.properties * file (if there is one), or the default as defined by NetAdapterConstants. */ public void resetSecret() { String secret = OneWireAccessProvider.getProperty("NetAdapter.Secret"); if(secret!=null) this.netAdapterSecret = secret.getBytes(); else this.netAdapterSecret = DEFAULT_SECRET.getBytes(); } /** * Checks return value from input stream. Reads one byte. If that * byte is not equal to RET_SUCCESS, then it tries to create an * appropriate error message. If it is RET_FAILURE, it reads a * string representing the error message. If it is neither, it * wraps an error message indicating that an unspecified error * occurred and attemps a reconnect. */ private void checkReturnValue(Connection conn) throws IOException, OneWireException, OneWireIOException { byte retVal = conn.input.readByte(); if(retVal!=RET_SUCCESS) { // an error occurred String errorMsg; if(retVal==RET_FAILURE) { // should be a standard error message after RET_FAILURE errorMsg = conn.input.readUTF(); } else { // didn't even get RET_FAILURE errorMsg = UNSPECIFIED_ERROR; // that probably means we have a major communication error. // better to disconnect and reconnect. freePort(); selectPort(portNameForReconnect); } throw new OneWireIOException(errorMsg); } } /** * Sends a ping to the host, just to keep the connection alive. Although * it currently is not implemented on the standard NetAdapterHost, this * command is used as a signal to the NetAdapterSim to simulate some amount * of time that has run. */ public void pingHost() throws OneWireException, OneWireIOException { try { synchronized(conn) { // send beginExclusive command conn.output.writeByte(CMD_PINGCONNECTION); conn.output.flush(); checkReturnValue(conn); } } catch(IOException ioe) { throw new OneWireException(COMM_FAILED + ioe.getMessage()); } } //-------- //-------- Methods //-------- /** * Detects adapter presence on the selected port. * * @return <code>true</code> if the adapter is confirmed to be connected to * the selected port, <code>false</code> if the adapter is not connected. * * @throws OneWireIOException * @throws OneWireException */ public boolean adapterDetected () throws OneWireIOException, OneWireException { synchronized(conn) { return conn!=EMPTY_CONNECTION && conn.sock!=null; } } /** * Retrieves the name of the port adapter as a string. The 'Adapter' * is a device that connects to a 'port' that allows one to * communicate with an iButton or other 1-Wire device. As example * of this is 'DS9097U'. * * @return <code>String</code> representation of the port adapter. */ public String getAdapterName () { return "NetAdapter"; } /** * Retrieves a description of the port required by this port adapter. * An example of a 'Port' would 'serial communication port'. * * @return <code>String</code> description of the port type required. */ public String getPortTypeDescription () { return "Network 'Hostname:Port'"; } /** * Retrieves a version string for this class. * * @return version string */ public String getClassVersion () { return ""+versionUID; } //-------- //-------- Port Selection //-------- /** * Retrieves a list of the platform appropriate port names for this * adapter. A port must be selected with the method 'selectPort' * before any other communication methods can be used. Using * a communcation method before 'selectPort' will result in * a <code>OneWireException</code> exception. * * @return <code>Enumeration</code> of type <code>String</code> that contains the port * names */ public Enumeration getPortNames () { Vector v = new Vector(); // figure out if multicast is enabled if(multicastEnabled == null) { String enabled = null; try { enabled = OneWireAccessProvider.getProperty( "NetAdapter.MulticastEnabled"); } catch(Throwable t){;} if(enabled!=null) multicastEnabled = Boolean.valueOf(enabled); else multicastEnabled = Boolean.FALSE; } // if multicasting is enabled, we'll look for servers dynamically // and add them to the list if(multicastEnabled.booleanValue()) { // figure out what the datagram listen port is if(datagramPort==-1) { String strPort = null; try { strPort = OneWireAccessProvider.getProperty("NetAdapter.MulticastPort"); } catch(Throwable t){;} if(strPort==null) datagramPort = DEFAULT_MULTICAST_PORT; else datagramPort = Integer.parseInt(strPort); }
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?