⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spotworld.java

📁 无线传感器网络节点Sun SPOT管理工具
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved.  *  * Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is * described in this document. In particular, and without limitation, these intellectual property rights may * include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents * or pending patent applications in the U.S. and in other countries. *  * U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. * standard license agreement and applicable provisions of the FAR and its supplements. *  * Use is subject to license terms.  *  * This distribution may include materials developed by third parties. Sun, Sun Microsystems, the Sun logo and * Java are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.  *  * Copyright (c) 2006 Sun Microsystems, Inc. Tous droits r?serv?s. *  * Sun Microsystems, Inc. d?tient les droits de propri?t? intellectuels relatifs ? la technologie incorpor?e dans * le produit qui est d?crit dans ce document. En particulier, et ce sans limitation, ces droits de propri?t? * intellectuelle peuvent inclure un ou plus des brevets am?ricains list?s ? l'adresse http://www.sun.com/patents * et un ou les brevets suppl?mentaires ou les applications de brevet en attente aux Etats - Unis et dans les * autres pays. *  * L'utilisation est soumise aux termes du contrat de licence. *  * Cette distribution peut comprendre des composants d?velopp?s par des tierces parties. * Sun, Sun Microsystems, le logo Sun et Java sont des marques de fabrique ou des marques d?pos?es de Sun * Microsystems, Inc. aux Etats-Unis et dans d'autres pays. */package com.sun.spot.spotworld;import com.sun.spot.spotworld.common.SPOTWorldLoader;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.Hashtable;import com.sun.spot.spotworld.usb.USBSpotChecker;import com.sun.spot.spotworld.usb.checkbasestation.CheckBasestation;import com.sun.spot.io.j2me.radiogram.Radiogram;import com.sun.spot.peripheral.TimeoutException;import com.sun.spot.spotworld.participants.Application;import com.sun.spot.spotworld.participants.SquawkHost;import com.sun.spot.util.Utils;import java.awt.Component;import java.io.File;import java.io.FilenameFilter;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.net.JarURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.Calendar;import java.util.HashMap;import java.util.Map;import java.util.Random;import javax.microedition.io.Connector;import javax.microedition.io.Datagram;import javax.microedition.io.DatagramConnection;import com.sun.spot.io.j2me.radiogram.RadiogramConnection;import com.sun.spot.spotworld.common.LocaleUtil;//import com.sun.spot.spotworld.engine.ISWDaemon;//import com.sun.spot.spotworld.engine.SWEngine;import com.sun.spot.spotworld.gui.ISpotWorldViewer;import com.sun.spot.spotworld.participants.ESpotBasestation;import com.sun.spot.spotworld.participants.Group;import com.sun.spot.spotworld.virtualobjects.IVirtualObject;import com.sun.spot.spotworld.virtualobjects.VirtualObject; import java.util.Iterator;import java.util.Vector; import java.util.jar.Attributes.Name;import javax.swing.JScrollPane;/** * a collection of Proxies to your Kami-enabled SPOTs. * Note SPOTWorld isn't a GUI, that is independent. See SPOTWorldPortal * * major aspects of a world are *  *   - broadcasts and collects replies from SPOTs. Once received tries to find the appropriate proxy class to instantiate *      and add the resulting instance to its collection. *   - looks for jar files defining proxies and dynamically loads them from the virtualObjects/ directory. *      This would be a way to make your own kind of device apper in SPOTWorld. * * @author randy, arshan, robert */public class SpotWorld extends VirtualObject {     Vector<ISpotWorldViewer> viewers = new Vector<ISpotWorldViewer>();    RadiogramConnection SPOTCastsRxConn;        private DatagramConnection SPOTCastTxConn; //broadcast connection    boolean SPOTCastTxing = false;    private boolean readyToAddVirtualObjects = false; //This is set to true when the views are safely created.        private static byte SPOTWORLD_BEACON_PACKET = 0x0;    private static byte SPOTWORLD_REPLY_PACKET = 0x1;    RadiogramConnection spotCastReplyConn = null;            private static boolean isSocketServerRunning = false;       // Used to create a unique ID of this instance of SPOT World -- Robert    private long spotWorldID = Calendar.getInstance().getTimeInMillis();        private Vector<Vector<String>> voClassesWithViews = null;        // Loader for loading classes -- Robert    private SPOTWorldLoader loader = new SPOTWorldLoader();    public void init(){        super.init();                /* A thread to wait for isReadyToAddVirtualObject before starting spotcasts */        Runnable rnnbl3 = new Runnable() {            public void run() {                boolean shouldWait = ! isReadyToAddVirtualObjects();                 while(shouldWait){                    try {                        Thread.sleep(1000);                    } catch (InterruptedException ex) {                        ex.printStackTrace();                    }                    shouldWait = ! isReadyToAddVirtualObjects();                 }                   Group group = new Group("All");                addVirtualObject(group);                listenForParticipants();                msg("SPOTWorld started");            }        };        (new Thread(rnnbl3)).start();    }        public String getUniqueID(){        return "" + spotWorldID;    }        /*     * General registration stuff happens here. Start listening for     * SpotHosts and SquawkHosts. -- Robert     */    private void listenForParticipants() {      //  startSPOTSocket();        startSPOTCastRxThread();        startSPOTCastTxThread();         msg("Started sending SPOTCasts and listening for replies.");    }      public void startSPOTSocket() {        if (!isSocketServerRunning) {            isSocketServerRunning = true;            (new Thread(new Runnable() {                public void run() {                    while (true) {                        try {                            ServerSocket serverSocket = new ServerSocket(3000);                            (new SPOTSocketHandler(serverSocket.accept())).start();                            serverSocket.close();                        } catch (IOException ex) {                            ex.printStackTrace();                        }                    }                }            })).start();            msg("Server socket has started");        } else            msg("Server socket is already running");    }        class SPOTSocketHandler extends Thread {        private Socket socket = null;                public SPOTSocketHandler(Socket socket) {            this.socket = socket;        }                public void run() {            BufferedReader in = null;            PrintWriter out = null;            try {                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                out = new PrintWriter(socket.getOutputStream());                                String msg = in.readLine();                System.out.println("Read in : " + msg);                           } catch (IOException ex) {                ex.printStackTrace();            } finally {                try {                    out.close();                    in.close();                    socket.close();                } catch (IOException ex) {                    ex.printStackTrace();                }            }        }    }        private Vector<String> knownMACAddresses = new Vector<String>();        /*     * Big method, probably should refactor. Forks a new thread that listens     * for spot cast replies at a fixed interval. When a reply is heard the     * method first checks to see if the device is already known. If it is the     * corresponding vo is found and refreshed. If the device is unknown, a new     * vo is created, passed to registered views and its current state noted     * e.g. see if any apps are currently running, it's name etc. -- Robert     */    public void startSPOTCastRxThread() {        Runnable rxRunnable = new Runnable() {            public void run() {                try {                    if(spotCastReplyConn == null) spotCastReplyConn = (RadiogramConnection) Connector.open("radiogram://:48");                } catch (IOException ex) {                    msg("Could not open reply receive connection");                    ex.printStackTrace();                }                                while (true) {                    try {                        spotCastReplyConn.setTimeout(2000);                        Radiogram rdg = (Radiogram) spotCastReplyConn.newDatagram(spotCastReplyConn.getMaximumLength());                        try {                            rdg.reset();                            spotCastReplyConn.receive(rdg);           // listen for a packet                            byte packetType = rdg.readByte();                            if (packetType == SPOTWORLD_REPLY_PACKET) {                                                                String address = rdg.getAddress();                                String deviceType = rdg.readUTF();                                                                msg("Received a SPOTCast reply");                                while (! isReadyToAddVirtualObjects()) {                                    msg(" but not ready to add VirtualObjects yet, (SpotWorldPortal not yet fully initialized.)");                                    Thread.yield(); //Just to be safe                                    Utils.sleep(300);                                }                                                                if (isReadyToAddVirtualObjects()) {                                    if (knownMACAddresses.contains(address)) {  // We've heard something                                        // We've already heard from this device                                        msg("SpotCast reply, already contained: " + deviceType + ", " + address);                                        // get the virtual object for this device                                        for (IVirtualObject sh : getVirtualObjectsCopy()) {                                            if(sh.getUniqueID().equals(address)){                                                sh.refresh();                                            }                                        }                                    } else { // This is a new device                                        msg("SpotCast reply, new object: " + deviceType + ", " + address + " ...");                                        knownMACAddresses.addElement(address); // add this device to our known devices                                                                                // Try and match the new device against vos we know about                                        for (Vector<String> vec : getVOClassesWithViews()) {                                            for (String participantName : vec) {                                                String[] shortName = participantName.split("\\.");                                                if (shortName[shortName.length - 1].toLowerCase().equals(deviceType.toLowerCase())) {                                                    // We've found it                                                    msg(" ..... identifed " + address + " as a " + participantName);                                                     try {                                                        Class vo = Class.forName(participantName);                                                         Constructor constructor = vo.getConstructor(new Class[] {String.class});                                                        IVirtualObject device = (IVirtualObject) constructor.newInstance(address);                                                        addVirtualObject(device);                                                        device.refresh();                                                    } catch (ClassNotFoundException ex) {                                                        ex.printStackTrace();                                                    } catch (SecurityException ex) {                                                        ex.printStackTrace();                                                    } catch (NoSuchMethodException ex) {                                                        ex.printStackTrace();                                                    } catch (IllegalArgumentException ex) {                                                        ex.printStackTrace();                                                    } catch (InvocationTargetException ex) {                                                        ex.printStackTrace();                                                    } catch (InstantiationException ex) {                                                        ex.printStackTrace();                                                    } catch (IllegalAccessException ex) {                                                        ex.printStackTrace();                                                    }                                                }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -