Download Lecture 17 - A Bluetoth example

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming of Handheld and Mobile
Devices
Lecture 17 Bluetooth Example
Rob Pooley [email protected]
Lecture 17
Programming Handheld and
Mobile devices
1
Client server example
• This example is taken from
– Bluetooth Application Programming with the Java
APIs by Kumar, Kline and Thompson, pub. Morgan
Kaufman
• The Client MIDlet discovers a server and sends a string
to be displayed
• The Server MIDlet allows itself to be discovered and
accepts the string to be displayed
Lecture 17
Programming Handheld and
Mobile devices
2
Acknowledgement
/*
* C Bala Kumar, Paul J. Kline & Timothy J. Thompson,
* Bluetooth Application Programming with the Java APIs
* Published By Morgan Kaufmann Publishers
* (c) Motorola, Inc. 2003.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for NON-COMMERCIAL purposes
* and without fee is hereby granted provided that this
* copyright notice appears in all copies.
*
* THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR
* WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
* AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
* BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
Lecture 17
Programming Handheld and
Mobile devices
3
package com.jabwt.book;
import java.lang.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.bluetooth.*;
public class BluetoothMIDlet extends MIDlet implements Runnable, CommandListener {
public BluetoothMIDlet() {}
/**
* Starts a background thread when the MIDlet is
* started.
*/
public void startApp()
throws MIDletStateChangeException {
new Thread(this).start();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void run() {}
/**
* Destroys the MIDlet when a Command occurs.
*/
public void commandAction(Command c, Displayable d) {
notifyDestroyed();
}
}
Lecture 17
Programming Handheld and
Mobile devices
4
BlueToothMIDlet
• This MIDet is used as a comon prefix to both Client and
Server
• It starts up a thread and then runs this
• This avoids the appearance of blocking for some slow
features, especially service discovery
• When any command is received the MIDlet terminates
• Both Client and Server are written as Threads and their
key behaviour starts when their Run() method is called
Lecture 17
Programming Handheld and
Mobile devices
5
Client MIDlet 1
package com.jabwt.book;
import java.lang.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
public class HelloClient extends BluetoothMIDlet {
/**
* Connects to the server and sends 'Hello, World'
* to the server.
*/
public void run() {
// Creates the Form and adds the Exit Command to it
Form f = new Form("Client");
f.addCommand(new Command("Exit", Command.EXIT, 1));
f.setCommandListener(this);
Display.getDisplay(this).setCurrent(f);
try {
// Retrieve the connection string to connect to
// the server
LocalDevice local =
LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
String connString = agent.selectService(
new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
Lecture 17
Programming Handheld and
Mobile devices
6
UUIDGEN(1)
•
UUIDGEN(1)
•
NAME
–
uuidgen - command-line utility to create a new UUID value
•
SYNOPSIS
–
uuidgen [ -r | -t ]
•
DESCRIPTION
The uuidgen program creates a new universally unique identifier (UUID)
using the libuuid(3) library. The new UUID can reasonably be considered unique among all UUIDs created on the local system, and among
UUIDs created on other systems in the past and in the future.
•
There are two types of UUID's which uuidgen can generate: time-based
UUID's and random-based UUID's. By default uuidgen will generate a
random-based UUID if a high-quality random number generator is present.
Otherwise, it will chose a time-based UUID. It is possible to force
the generation of one of these two UUID types by using the -r or -t
options.
It returns a UUID with hyphens, which must be removed before use
Lecture 17
Programming Handheld and
Mobile devices
7
Client MIDlet 2
if (connString != null) {
try {
// Connect to the server and send 'Hello, World'
StreamConnection conn = (StreamConnection)
Connector.open(connString);
OutputStream out = conn.openOutputStream();
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");
} catch (IOException e) {
f.append("IOException: ");
f.append(e.getMessage());
}
} else {
// Unable to locate a service so just print an error
// message on the screen
f.append("Unable to locate service");
}
} catch (BluetoothStateException e) {
f.append("BluetoothStateException: ");
f.append(e.getMessage());
}
}
}
Lecture 17
Programming Handheld and
Mobile devices
8
Server MIDlet 1
package com.jabwt.book;
import java.lang.*;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.bluetooth.*;
public class HelloServer extends BluetoothMIDlet {
/**
* Creates a server object. Accepts a single connection from a client and prints the data
* sent from the client to the screen.
*/
public void run() {
// Create a Form and add the Exit command to the Form
Form f = new Form("Server");
f.addCommand(new Command("Exit", Command.EXIT, 1));
f.setCommandListener(this);
Display.getDisplay(this).setCurrent(f);
try {
// Make the local device discoverable for the client to locate
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
f.append("Failed to change to the " +
"discoverable mode");
return;
}
Lecture 17
Programming Handheld and
Mobile devices
9
Server MIDlet 2
// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier)
Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");
// Accept a connection from the client
StreamConnection conn =
notifier.acceptAndOpen();
// Open the input to read data from
InputStream in =
conn.openInputStream();
ByteArrayOutputStream out = new
ByteArrayOutputStream();
// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
Lecture 17
// Add the text sent from the client to the Form
f.append(out.toString());
// Close all open resources
in.close();
conn.close();
notifier.close();
} catch (BluetoothStateException e) {
f.append("BluetoothStateException: ");
f.append(e.getMessage());
} catch (IOException e) {
f.append("IOException: ");
f.append(e.getMessage());
}
}
}
Programming Handheld and
Mobile devices
10