Code Search for Developers
 
 
  

BluetoothBrowser.java from GridBlocks at Krugle


Show BluetoothBrowser.java syntax highlighted

/*
 * Copyright (c) 2005
 * Helsinki Institute of Physics
 * see LICENSE file for details 
 * 
 * BluetoothBrowser.java
 * Created on Mar 7, 2004
 */

package fi.hip.gb.client;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;

import fi.hip.gb.bluetooth.BTListener;
import fi.hip.gb.bluetooth.BTService;
import fi.hip.gb.bluetooth.EndPoint;
import fi.hip.gb.bluetooth.GPSResult;
import fi.hip.gb.bluetooth.Service;
import fi.hip.gb.midlet.core.LiteResult;
import fi.hip.gb.midlet.core.LiteStorage;

/**
 * User interface for browsing bluetooth network and
 * viewing bluetooth server activities.
 * 
 * @author Juho Karppinen
 */
public class BluetoothBrowser extends Form implements CommandListener,	BTListener
{
	/** send the message to the selected device */
	private Command cmdSend = new Command("Connect", Command.SCREEN, 1);
	/** send the message to all known devices */
	private Command cmdSendAll = new Command("Send all", Command.SCREEN, 2);
	/** command for canceling inquiry operation */
	private Command cmdCancel = new Command("Cancel", Command.SCREEN, 1);
	/** command for updating the list of devices */
    private Command cmdRefresh = new Command("Refresh", Command.SCREEN, 3);
    /** command for saving the default service */
	private Command cmdSave = new Command("Set as default", Command.SCREEN, 3);
	/** close the connection for selected device */
	private Command cmdClose = new Command("Close connections", Command.SCREEN, 3);
	
	/** label for the list when seaching devices */
	private final static String SEARCH_DEVICES = "Searching devices...";
	/** label for the list when seaching services */
	private final static String SEARCH_SERVICES = "Searching services...";

	/** list of available devices */
	private ChoiceGroup devices = new ChoiceGroup("[press refresh]", Choice.EXCLUSIVE);
	/** maps the device names to corresponding endpoints */
	private Vector endPoints = new Vector();
	
	/** item to be sended */
	private LiteStorage sendQueue;
	
	/** shows GPS data */
	private GPSForm gpsForm;
    
    /** are we entering the form first time */
    private boolean firstTime = true;
	
	/**
	 * Initializes the bluetooth network browser
	 * @param serverEnabled should the server be started
	 */
	public BluetoothBrowser(boolean serverEnabled) {
		super("Bluetooth network");
		// initialize commands
		append(devices);
		addCommand(new Command("Back", Command.BACK, 1));
		setCommandListener(this);
		
		addCommand(cmdRefresh);
		try {
			BTService btServer = BTService.getInstance();
            if(btServer != null) {
    			setTitle("BT on " + BTService.localName);
    			if(serverEnabled) {
    			    btServer.startServer();
    			}
            }
		}catch(Exception e) {
			removeCommand(cmdRefresh);
			devices.setLabel("not supported");
		}
	}

	/**
	 * Adds a item into the sending queue.
	 * <p>
	 * TODO: currently queue length is one
	 * @param item item to be sended
	 */
	public void addToQueue(LiteStorage item) {
		this.sendQueue = item;
	}
	
	/**
	 * Handle event/activity from Bluetooth Network layer. This class is an
	 * implementation of BTListener; therefore, it handles all the bluetooth
	 * network event that received by NetLayer. The list of possible event are
	 * defined in BTListener.EVENT_XXX.
	 * 
	 * @see fi.hip.gb.bluetooth.BTListener#handleAction(String,EndPoint,Object)
	 */
	public void handleAction(String action, EndPoint endpt, Object data) {
		log("action=" + action);
		boolean finished = false;
		if (action.equals(BTListener.EVENT_SENT)) {
			// nothing to do
		} else if (action.equals(BTListener.EVENT_RECEIVED)) {
		    //if(endpt.isAgentService()) {
				// a new message has received from a remote user
		    	GPSResult res = (GPSResult)data;
				//log(endpt + ": " + lr.getDescription().getJobname());
				//MIDui.showStatus((LiteStorage)data);
				//LiteStatus status = new LiteStatus(new Long(-1), LiteStatus.RESULT_STATE, null, null, null, null, null, new LiteResult[] {result});
				//status.setJobName("name");
				//MIDui.instance.showBroadcasts(status);
		    //} else if(data.getResult().size() > 0){
                
                // convert from GPS result
                LiteResult lr = new LiteResult();
                lr.setName(res.getName());
                lr.setType(res.getType());
                lr.writeObject(res.getFlags());
		        if(this.gpsForm == null) {
		            this.gpsForm = new GPSForm(lr);
		            MIDui.next(this.gpsForm);
		        } else {
		            this.gpsForm.update(lr);
		        }
		    //}
		} else if(action.equals(BTListener.EVENT_FINISHED)) {
			removeCommand(cmdCancel);
			addCommand(cmdRefresh);
			finished = true;
		} else if(action.equals(BTListener.EVENT_SERVICES)) {
			devices.setLabel(SEARCH_SERVICES);
		} else {
			// add/remove/change the device on the list
			setDevice(endpt, action);
		}

		// somehow getLabel() returns null when called from server thread
		if(finished || devices.getLabel() == null || 
				!devices.getLabel().equals(SEARCH_DEVICES)
				&& !devices.getLabel().equals(SEARCH_SERVICES)) {
			if(devices.size() > 0) {
				addCommand(cmdSend);
				addCommand(cmdSendAll);
                addCommand(cmdSave);
				addCommand(cmdClose);
				devices.setLabel("Found " + devices.size() + " devices");
                /*
                String defaultService = Configs.readString(Configs.INDEX_BLUETOOTSERVICE);
                for(int i=0; i < this.devices.size(); i++) {
                    devices.setSelectedIndex();
                    String deviceName = devices.getString(devices.getSelectedIndex());
                    if(this.devices.)
                }*/
			} else {
				removeCommand(cmdSend);
				removeCommand(cmdSendAll);
                removeCommand(cmdSave);
				removeCommand(cmdClose);
				devices.setLabel("No devices found");
			}
		}
	}
	
	/**
	 * Commands from menu
	 * @param c command where the event originates
	 * @param disp display where the event was created
	 */
	public void commandAction(final Command c, Displayable disp) {
		if(c == cmdSend || c == cmdSendAll) {
			new Thread(new Runnable() {
				public void run() {
					EndPoint endpt = null;
					//if(c == cmdSend && devices.getSelectedIndex() != -1) {
						// select the endpoint
						endpt = (EndPoint)endPoints.elementAt(devices.getSelectedIndex());
					//}
					if(endpt.getConnections().length > 0) {
                        Service[] srv = endpt.getConnections();
                        for(int i=0; i <  srv.length; i++) {
                            try {
                                srv[i].openConnection();
                            } catch (IOException e) {
                                log(e.getMessage());
                            }
                        }
					    //endpt.readMessages();
					}/* else {
					    if(sendQueue == null) {
							InputUI input = null;
							// ask the message
							if(endpt == null) {
								input = new InputUI("Broadcast message", "Broadcast");
							} else {
								input = new InputUI("Msg to " + endpt, "Send");
							}
							
							String msg = input.getMessage();
							if(msg != null){
								LiteResult result = new LiteResult(BTService.localName, "", 
								        msg.length(), 
								        new Properties(), 
								        msg.getBytes());
								sendQueue = new LiteStorage(new Long(-1), result);
								sendQueue.getDescription().setJobname("msg");
							}
						}
						if(sendQueue != null) {
							if(endpt == null) {
								// send the message to all connected remote EndPoints
								BTService.getInstance().sendMessage(sendQueue);
								log("> " + sendQueue.getDescription().getJobname());
							} else {
								endpt.putMessage(BTService.SIGNAL_MESSAGE, sendQueue);
								log("> " + endpt + ": " + sendQueue.getDescription().getJobname());
							}
							sendQueue = null;
						}
					}*/
				}				
			}).start();
			
			/*
			} else {
				MIDui.showAlert("Not a valid device", 
					"Device " + devices.getString(devices.getSelectedIndex()) 
						+ " constains no GBAgent services", AlertType.WARNING, this);
			}
			*/
        } else if (c == cmdSave) {
            String deviceName = devices.getString(devices.getSelectedIndex());
            EndPoint endpt = (EndPoint)endPoints.elementAt(devices.getSelectedIndex());
            if(endpt.getConnections().length > 0) {
                Service[] srv = endpt.getConnections();
                for(int i=0; i <  srv.length; i++) {
                    String url = srv[i].getURL();
                    Configs.storeString(Configs.INDEX_BLUETOOTSERVICE, url);
                    log("saved " + deviceName + " url " + url);
                }
            }
		} else if (c == cmdRefresh) {
            if(this.firstTime) {
                // add the listener when first time updating
                BTService.getInstance().addListener(this);
                this.firstTime = false;
            }
			this.devices.setLabel(SEARCH_DEVICES);
		    
			// first clear the debug messages
			while(size()>1)
				delete(1);
			// remove the non GBAgent devices (ones without the icon)
			for(int i=0; i < endPoints.size();) {
				if(devices.getImage(i) == null) {
					devices.delete(i);
					endPoints.removeElementAt(i);
				} else {
					i++;
				}
			}
			
			addCommand(cmdCancel);
			removeCommand(cmdRefresh);
			removeCommand(cmdSend);
			removeCommand(cmdSendAll);
			try {
                BTService.getInstance().query();
            } catch (BluetoothStateException e) {
                e.printStackTrace();
                log("Query failed: " + e.getMessage());
            }
		} else if (c == cmdCancel) {
		    BTService.getInstance().cancel();
			addCommand(cmdRefresh);
			removeCommand(cmdCancel);
		} else if( c== cmdClose) {
		    if(this.devices.getSelectedIndex() != -1) {
				// select the endpoint
				EndPoint endpt = (EndPoint)endPoints.elementAt(devices.getSelectedIndex());
				Service[] conns = endpt.getConnections();
                for(int i=0; i<conns.length; i++) {
                    if(conns[i].getConnection() != null)
                    conns[i].closeConnection();
                }
			}
		}else if ((c.getCommandType() == Command.BACK)) {
			// first close all connections
            if(this.devices.getSelectedIndex() != -1) {
    			EndPoint endpt = (EndPoint)endPoints.elementAt(devices.getSelectedIndex());
    			Service[] conns = endpt.getConnections();
                for(int i=0; i<conns.length; i++) {
                    if(conns[i].getConnection() != null)
                    conns[i].closeConnection();
                }
            }

		    /*
			for(int i=0; i < endPoints.size(); i++) {
				EndPoint endpt = (EndPoint) endPoints.elementAt(i);
				endpt.closeConnection();
			}
			*/
			BTService.getInstance().cancel();
			BTService.getInstance().removeListener(this);

			MIDui.back(true);
		}
	}

	/**
	 * Adds a device or changes the state of existing device 
	 * @param endpt remote endpoint
	 * @param eventType state of the connection, one of the BTListener.EVENT_XXX
	 * types
	 */
	private void setDevice(EndPoint endpt, String eventType) {
		Image icon = null;
		try {
			if(eventType.equals(EVENT_COMPATIBLE))
				icon = Image.createImage("/resources/bt_compatible.png");
			else if (eventType.equals(EVENT_JOIN))
				icon = Image.createImage("/resources/bt_connected.png");
		} catch(IOException ioe) {
		}
		for(int i=0; i < endPoints.size(); i++) {
			if(endpt.equals(endPoints.elementAt(i))) {
				//log("exists " + endpt.getRemoteName());
				if(eventType.equals(EVENT_LOST)) {
					devices.delete(i);
					endPoints.removeElementAt(i);
				} else {
					devices.set(i, endpt.toString(), icon);
					endPoints.setElementAt(endpt, i);
				}
				return;
			}
		}
		devices.append(endpt.toString(), icon);
		endPoints.addElement(endpt);
		//log("new item " + endpt.getRemoteName());
	}

	/**
	 * Appends a log message to the form 
	 * @see fi.hip.gb.bluetooth.BTListener#log(java.lang.String)
	 */
	public void log(String message) {
		append("\n" + message);
	}
}



See more files for this project here

GridBlocks

GridBlocks builds a grid application framework via easy-to-use building blocks in distributed environment. The framework offers components for Grid security, distributed storage, computing, and Portlet web interfaces.

Project homepage: http://sourceforge.net/projects/gridblocks
Programming language(s): Java,JSP,XML
License: other

  BluetoothBrowser.java
  Broadcasts.java
  CameraCanvas.java
  Configs.java
  DispatchForm.java
  GPSForm.java
  GenericImageCanvas.java
  GenericResultForm.java
  GraphicsCanvas.java
  InfoForm.java
  InputUI.java
  JobsForm.java
  Logging.java
  MIDui.java
  MediaPlayer.java
  PictureCanvas.java
  ProgressForm.java
  Results.java
  StatusForm.java
  TextForm.java
  Thumbnails.java