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

📄 bluetooth.java

📁 1、手持设备机器人——应用端; 2、基于蓝牙传输;
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*************************************************************
 *
 * The Mobile Robotics Project
 * - mobilerobotics.sourceforge.net
 *
 * This file was created 2005-01-07
 * More information in MobileRoboticsMidlet.java
 *
 *************************************************************/

/*

  Bluetooth.java::v1.0::1
  This class main purpose is to initiate*, hold and handle
  the bluetooth communication to the hand-held.

  	*: When initiating it will search every nearby devices, store it in a
  	   list (Array) and when all nearby devices are found search in the
  	   list (Array) for a device with our service.

  It also loads the SplashScreen upon initialization, Bluetooth:initiate(),
  so the user sees the SplashScreen and is told the current
  step and progress.

  Part of the Bluetooth Discovery and methods were inspired by Jason Lam,
  www.jasonlam604.com

  Please note, this is no sourcecode to learn Bluetooth from.
               this code is structured to fit our purpose.
               And it does. But if you are new to bluetooth,
               please check http://www.jasonlam604.com/articles_introduction_to_bluetooth_and_j2me_part2.php

  However it might be a good example on how bluetooth may work in reality,
  not just on paper. I really have no more comments on this, except on thing.

  If you want to retrieve the bluetooth name of the device you use:

   "The remote device".getFriendlyName(true);

  This must be in a try {} and most importantly, it can NEVER be done while
  searching for devices. The logic part would be to insert it in
  the method deviceDiscovered(). This will throw an exception because it can only
  do one bluetooth thing at a time.

  You must put every found device in an array (wich would look something like):

    private RemoteDevice remoteDevices[] = new RemoteDevice[10];

  And then, after inquiryCompleted() you can just do a while loop to find out
  the device name and/or search for services. Whatever may suit you.

 */


import java.io.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.*;
import javax.bluetooth.*;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.lang.Thread;
import java.lang.Runnable;

public class Bluetooth extends GameCanvas implements DiscoveryListener, Runnable {


  private MobileRoboticsMidlet mobileRoboticsMidlet;  								// The midlet
  private Display display;               									// The display
  private String bterror = "";        										// Errormsg.
  private SplashScreen splash;
  private boolean wait;
  private int direction;													// Hold the current direction. Used to keep tracks..


 // Fonts. Check J2ME Gaming book (see MobileRobticsMidlet.java for more information)
 static final Font boldFont    = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_BOLD, Font.SIZE_SMALL);
 static final Font regularFont = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_SMALL);

  /* Se the method initiate() for explanation */

  private int p1;
  private int p2;
  private int p3;
  private int p4;

  /* Images */
  public Image start;
  public Image stopped;
  public Image running;
  public Image logo;
  public Image Left;
  public Image right;
  public Image forward;
  public Image backward;
  public Image nowhere;
  public Image clear;
  public Image run;
  public Image about;
  public Sprite wheel;
  public Image Wheel;

  /* Bluetooth */
  private DiscoveryAgent discoveryAgent;
  private UUID[] uuidSet;
  private String serviceUrl     = null;
  private int lastSentCommand   = 0;


  OutputStream os = null;

  public static final UUID RFCOM_UUID = new UUID("716441D9D19641A980D8DCC753ADEC59", false);

  	// Mobile Robotics is using UUID 0x716441D9D19641A980D8DCC753ADEC59, why?
  	// The UUID was generated to fit our services name, it is random.
  	// For more info read up on how to generate UUIDs.

  public StreamConnection connection;

  private int status;
  private String data;
  boolean discoveryWhile = false;
  boolean servicesWhile  = false;
  boolean tempBoolean    = false;


 public StreamConnectionNotifier notifier;

  // We will, later on, put every nearby Bluetooth device in an array.
  private RemoteDevice remoteDevices[] = new RemoteDevice[10];

  // Number of devices in the array
  private int nrRemoteDevices = 0;

 public Bluetooth(MobileRoboticsMidlet mobileMidlet, Display disp)
  {

    super(true);
    System.err.println(" Initied: Bluetooth");

    display              = disp;
    mobileRoboticsMidlet = mobileMidlet;

  }



public void stop()
 {
  cleanUp();
 }


public void start() {				/* Not in use */							 }
public void run()   {   			/* Not in use */							 }


/*

 Bluetooth::initiate()
 This method initiaties the Bluetooth connection and loads the splashScreen.
 The method is divided into two parts, the graphical part and the connection.

 The graphical part is the splashScreen (SplashScreen.java) wich shows the progress
 to the user upon starting the midlet. This is so that the users see's more than
 simply a blank screen. The splashScreen knows the current step due to the variables
 (int) p1, p2, p3, p4. P stands for part.

 pX variable is either 0, 1 or 2. 0 is none-initiated, 1 is active and 2 is finished.
 the variable will first have 0, turn to 1 when it is running and 2 when it is finished.

 The connection part is used to initiate, find and connect to the handheld (Palm).

 */


	public boolean initiate() {

	  System.err.println(" Init: SplashScreen Thread");  		// Initiating splashScreen (loading)
          Graphics g = getGraphics();

	  p1 = 0;
	  p2 = 0;
	  p3 = 0;
	  p4 = 0;

	  SplashScreen splashScreen = new SplashScreen ( this );    // Initiating our SplashScreen.
	  splashScreen.start();
	  splash = splashScreen; 				    // For other methods needing splashscreen
	  display.setCurrent( splashScreen );




	  /* Part one, init, we check for the needed functions */
	  	   p1 = 1;
		   neededFunctions();
		   p1 = 2;

	  /* Part two, start the device discovery              */
		   p2 = 1;
			mobileRoboticsDeviceDiscovery();


			// We must use synchronized to be able to use wait();
			// Later on we call notifyAll() to continue

			while (discoveryWhile != true)
			 {
				// We will wait for the device discovery to be finished
			 }
		   p2 = 2;

	   /* Part three, we search for our service            */
		   p3 = 1;
			try
			 {
				/*
				   Bluetooth name: "The remote device".getFriendlyName(true)

                   Note: These values _must_ be retrieved after device discovered is finished. It will throw a bluetooth
				   exception if it is used when searching for devices. Read comments on the top of this file for more info.
				*/

				// Our UUID
				uuidSet    = new UUID[1];
				uuidSet[0] = RFCOM_UUID;

				// We need to search for services in every device in our array. Therefor, loop it.
				for (int i = 0; i < nrRemoteDevices; i++)
				{
					servicesWhile = false;
					int searchID = discoveryAgent.searchServices(null,uuidSet,remoteDevices[i],this);

					while (servicesWhile != true)
					 {
						// Wait for service discovery to be finished
					 }
			        }
			 }catch (Exception e)
			 {
						// We don't want the exceptions since it may come from any bluetooth device.
						// If it is from ours we will notice it due to no serviceUrl a couple of lines later
			 }

			p3 = 2;


	  /* Part four, open bluetooth connection and load images              */
			p4 = 1;
				if(serviceUrl != null)
				 {
						   	try {
								/* Open bluetooth connection */
						 	 	connection = (StreamConnection)Connector.open(serviceUrl);

							}catch (Exception exception)
							{

								bterror  = "Could not open a connection";
								fatalError();
							}

							/* We want to open an OutputStream so we can actually send data */
							try {
								    os             = connection.openOutputStream();

							}catch (Exception e)
							{
								bterror = "Could not open output stream";
								fatalError();
							}


				 }else{

					bterror  = "Could not find the hand held";
					fatalError(); // Print error message
				 }

			loadImages();
		p4 = 2;

		/* Just to make sure */

⌨️ 快捷键说明

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