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

📄 blueclientbt.java

📁 欢迎使用蓝牙联网坦克大战
💻 JAVA
字号:
/*
 * Bluetooth Multiplayer Games Framework
 * Author: Francesco Panciroli (email fif0302@iperbole.bologna.it)
 * Copyright (C) 2006  Francesco Panciroli
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package newpackage;

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

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;

import org.apache.log4j.Category;

/**
 * Note: this client manages both SPP and L2CAP connection protocols!
 * 
 */
public class BlueClientBT
{
	static Category log = Category.getInstance("panci.bluemgf.BlueClientBT");

	/** Describes this service */
	private UUID serviceUUID;

	// timer to schedule task to do service discovery
	// see inquiryCompleted
	Timer timer = new Timer();

	// synchronization lock
	// see DoServiceDiscovery and serviceSearchCompleted
	Object lock = new Object();

	// SELECTED - When user has selected a Bluetooth device for service search
	public static Command SELECTED = new Command("SELECTED", Command.SCREEN, 1);

	// BACK - When user press Back button on Bluetooth Devices screen (RemoteDeviceUI)
	public static Command BACK = new Command("Back", Command.BACK, 1);

	// client GUI reference
	public BlueClientGUI parent;

	// callback CommandListener
	public static CommandListener callback;

	public static Vector devices = new Vector();

	public static Vector deviceClasses = new Vector();

	public Vector services = new Vector();

	public static Vector blueConnections = new Vector();

	// discovery mode in device inquiry
	public int discoveryMode;

	// list of UUID to match during service discovery
	public UUID[] serviceUUIDs = null;

	// Bluetooth return code from device inquiry operation
	// see DiscoveryListener
	public int deviceReturnCode;

	//private RemoteDeviceUI remotedeviceui = null;
	private LocalDevice localDevice;

	private DiscoveryAgent agent;

	/**
	 * Create a new BlueClientBT
	 */
	public BlueClientBT(BlueClientGUI parent) {
    	log.debug("Constructor!");	
		this.parent = parent;
		serviceUUID = parent.getServiceUUID();
		discoveryMode = DiscoveryAgent.GIAC;
		serviceUUIDs = new UUID[] { serviceUUID };

		startInquiry();
	}

	private BlueConnection getBlueConnectionByRemoteDeviceName(String remoteDeviceName) {
		for (int i = 0; i < blueConnections.size(); i++) {
			BlueConnection bconn = (BlueConnection) blueConnections.elementAt(i);
			if (bconn.remoteName == remoteDeviceName)
				return bconn;
		}
		return null;
	}
	
	public BlueConnection getBlueConnectionByServiceRecord(ServiceRecord record) {
		for (int i = 0; i < blueConnections.size(); i++) {
			BlueConnection bconn = (BlueConnection) blueConnections.elementAt(i);
			if (bconn.record == record)
				return bconn;
		}
		return null;
	}
	
	public BlueConnection getBlueConnectionByListIndex(int listIndex) {
		for (int i = 0; i < blueConnections.size(); i++) {
			BlueConnection bconn = (BlueConnection) blueConnections.elementAt(i);
			if (bconn.listIndex == listIndex)
				return bconn;
		}
		return null;
	}
	
	public void openConnection(BlueConnection bconn) {
		ServiceRecord record = bconn.record;
        Thread t = new Thread(new BlueConnectionOpener(record));
        t.start();
	}
	
	public void connectionOpened(BlueConnection bconn) {
		log.debug("Connection to server opened!");
		parent.connectionOpened(bconn);
	}
	
	/**
	 * Start device inquiry. Your application call this method to start inquiry.
	 */
	public void startInquiry() {
		log.debug("startInquiry");
		try {
			// clear previous values first
			devices.removeAllElements();
			deviceClasses.removeAllElements();

			//
			// initialize the JABWT stack
			localDevice = LocalDevice.getLocalDevice(); // obtain reference to singleton
			localDevice.setDiscoverable(discoveryMode); // set Discover Mode
			agent = localDevice.getDiscoveryAgent(); // obtain reference to singleton

			agent.startInquiry(discoveryMode, new Listener());
		} catch (BluetoothStateException e) {
			e.printStackTrace();
		}

	}

	public void searchServices(RemoteDevice remoteDevice) {
		try {
			log.debug("searchServices on " + remoteDevice.getFriendlyName(false));

			agent.searchServices(null, serviceUUIDs, remoteDevice, new Listener());

			// wait until the above service discovery is completed
			// because N6600 cannot handle more than one service discovery
			// request at the same time
			// see serviceSearchCompleted()
			synchronized (lock) {
				try {
					lock.wait();
				} catch (InterruptedException ex) {
				}
			}

		} catch (BluetoothStateException e) {
			log.error("BluetoothStateException in searchServices: " + e.getMessage());
		} catch (IOException e) {
			log.error("IOException in searchServices: " + e.getMessage());
		}
	}

	/**
	 * Bluetooth listener object.
	 * Register this listener object to DiscoveryAgent in device inqury and service discovery.
	 */
	class Listener implements DiscoveryListener {

		public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
			String remoteDeviceName = "";
			try {
				remoteDeviceName = remoteDevice.getFriendlyName(false);
			} catch (IOException e) {
				log.error("Error in deviceDiscovered: " + e.getMessage());
			}
			log.debug("deviceDiscovered: " + remoteDeviceName);
			Utility.printRemoteDevice(remoteDevice, deviceClass);

			// same device may found several times during single search
	        if (devices.indexOf(remoteDevice) == -1) {
				devices.addElement(remoteDevice);
				deviceClasses.addElement(deviceClass);
	        } else {
	        	log.debug("Device " + remoteDeviceName + " already found! Skipped!");
	        }
		}

		public void inquiryCompleted(int returnCode) {
			log.debug("inquiryCompleted with result: " + Utility.getInquiryCompletedResultMessage(returnCode));
			log.debug(devices.size() + " devices discovered");
			deviceReturnCode = returnCode;
			timer.schedule(new DoServiceDiscovery(), 100);
		}

		public void servicesDiscovered(int transId, ServiceRecord[] records) {
			log.debug("servicesDiscovered: transId = " + transId);
			int i;
			// Note: there should be only one service record (because we looked for a specific service)!
			for (i = 0; i < records.length; i++) {
				ServiceRecord record = records[i];
				Utility.printServiceRecord(record);
				RemoteDevice remoteDevice = record.getHostDevice();
				String remoteDeviceName;
				try {
					remoteDeviceName = remoteDevice.getFriendlyName(false);
					BlueConnection bc = getBlueConnectionByRemoteDeviceName(remoteDeviceName);
					if (bc == null) {
						services.addElement(record);
						BlueConnection blueConnection = new BlueConnection(transId, record, services.size() - 1, remoteDevice, remoteDeviceName);
						blueConnections.addElement(blueConnection);
					} else {
						log.debug("Found the same service another time on device " + remoteDeviceName + ". Skipped.");
					}
				} catch (IOException e) {
					log.error("servicesDiscovered: getFriendlyName: " +  e.getMessage());
				}
			}
			if (i > 1) {
				log.error("Warn, servicesDiscovered found more than one ServiceRecord!");
			}
		}

		public void serviceSearchCompleted(int transId, int returnCode) {
			// note: we do not use transId because we only have one search at a time
			log.debug("serviceSearchCompleted with result: " + Utility.getSearchServicesResultMessage(returnCode));
			log.debug(services.size() + " services discovered");
			//serviceReturnCode = returnConde;
			parent.serviceSearchCompleted(returnCode);

	        synchronized (lock) {
				// unlock to proceed to service search on next device
				// see DoServiceDiscovery.run()
				lock.notifyAll();
			}
		}

	} // Listener

	class DoServiceDiscovery extends TimerTask {
		public void run() {
			for (int i = 0; i < devices.size(); i++) {
				RemoteDevice remoteDevice = (RemoteDevice) devices.elementAt(i);
				searchServices(remoteDevice);
			}
		}
	}

	class BlueConnectionOpener implements Runnable {
		public ServiceRecord record;

		public BlueConnectionOpener(ServiceRecord r) {
			record = r;
		}

		public void run() {
			try {
				String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
				log.debug("BlueConnectionOpener: url = " + url);
				Connection conn = (Connection) Connector.open(url);
				BlueConnection bconn = getBlueConnectionByServiceRecord(record);
				bconn.conn = conn;

				connectionOpened(bconn);
			} catch (Exception e) {
				e.printStackTrace();
				log.debug(e.getClass().getName() + " " + e.getMessage());
				try {
					String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
					log.debug("Retry 2");
					Thread.sleep(500);
					log.debug("BlueConnectionOpener: url = " + url);
					Connection conn = (Connection) Connector.open(url);
					BlueConnection bconn = getBlueConnectionByServiceRecord(record);
					bconn.conn = conn;

					connectionOpened(bconn);
				} catch (Exception e2) {
					e2.printStackTrace();
					log.debug(e2.getClass().getName() + " " + e2.getMessage());
					try {
						String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
						log.debug("Retry 3");
						Thread.sleep(500);
						log.debug("BlueConnectionOpener: url = " + url);
						Connection conn = (Connection) Connector.open(url);
						BlueConnection bconn = getBlueConnectionByServiceRecord(record);
						bconn.conn = conn;

						connectionOpened(bconn);
					} catch (Exception e3) {
						e3.printStackTrace();
						log.debug(e3.getClass().getName() + " " + e3.getMessage());
					}
				}
			}
		}
	}
}

⌨️ 快捷键说明

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