jma f2005 ebbe elsborg [email protected] programming context aware mobile phones agenda: introduction...
Post on 22-Dec-2015
223 views
TRANSCRIPT
JMA F2005 Ebbe Elsborg [email protected]
Programming context awareMobile Phones
Agenda:
Introduction to Bluetooth Methods for connecting
Importent classes
Service description
JMA F2005 Ebbe Elsborg [email protected]
Server Programming
A mobile application is often a combination of a MIDlet and a server side program
Many technologies on the server side:CGI, PHP, ASP, JSP, …, Servlets, …
JMA F2005 Ebbe Elsborg [email protected]
N-Tier Applications
Presentation Tier – Business Logic Tier – Database Tier
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth
a cable replacement technology
A standard/protocol for a small , cheap short range (10 meter) radio communication to be plugged into computers, printers, mobile phones, etc.
IEEE 802.15 www.bluetooth.org (/spec)
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth - characteristics
• Bluetooth is wireless and automatic.
• Bluetooth is inexpensive.
• The ISM band (2.4 GHz) that Bluetooth uses is
regulated, but unlicensed.
• Bluetooth handles both data and voice.
• Signals are omni-directional and can pass through
walls and briefcases.
• Bluetooth is spread spectrum.
JMA F2005 Ebbe Elsborg [email protected]
Frequency Hopping
Source: http://www.swedetrack.com/images/bluet11.htm
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth, Infrared and WLAN
• Infrared is– Line-of-sight (interference uncommon)– One-to-one (msg. delivery reliable)
• WLAN (IEEE 802.11b) is– Intended for large devices with lots of
power and speed (11 Mbit/sec, 100 meter)– WAN (Wireless) versus PAN (Personal)
• Point: Bluetooth is intended to co-exist with WLAN – not replace it
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth applications
• File transfer• Ad-hoc networking• Device synchronization• Peripheral connectivity• Car kits (hand-free installations)• Mobile payments• …
JMA F2005 Ebbe Elsborg [email protected]
Details
• A master and seven slaves (8 nodes)
• Master initiates communication
• Packets survive five transmission slots
• Time-division multiplexing scheme for full-duplex (master even, slave odd)
• Three power-save modes
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth in J2ME
HTTP:
con= (HttpConnection)Connector.open(url);
L2CAP (Bluetooth):
con= (L2CAPConnection)Connector.open(url);
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth Overview
Device Discovery
Service Discovery
Communication
JMA F2005 Ebbe Elsborg [email protected]
Establishing a network conn.
• Inquire: Device finds access points (ap)• Page: Synchronize device with ap• Establish link: LMP (Link Manager Protocol) does• Discover services: LMP uses SDP (Service
Discovery Protocol) to find ap services• Create L2CAP ch.: Maybe use RFCOMM• Authenticate: Maybe prompt user• Log in: PPP if RFCOMM used• Send and receive data (e.g. TCP/IP)
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth Profiles & Security
• Profiles:– Idea: Ensure interoperability– Generic Access Profile must be supported
by a Bluetooth-enabled device
• Security:– Pseudo-random frequency hopping– Authentication– Encryption
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth system requirements
• Certain profiles must be supported• Communication layers of Bluetooth 1.1
• Bluetooth Control Center (BCC)– Concurrent applications– Sets parameters in Bluetooth stack– May be native app. or group of settings
• OBEX in underlying system or API implementation
JMA F2005 Ebbe Elsborg [email protected]
Packages andApplication Programming• javax.bluetooth• javax.obex
• Five steps in application programming:– Stack initialization (vendor dependent)– Device management– Device discovery– Service discovery– Communication
JMA F2005 Ebbe Elsborg [email protected]
Device Management
... // init stack
LocalDevice local = LocalDevice.getLocalDevice();
String address = local.getBluetoothAddress();
String name = local.getFriendlyName();
...
RemoteDevice remote = RemoteDevice.getRemoteDevice(conn);
JMA F2005 Ebbe Elsborg [email protected]
Device Discovery (1)
class InquiryListener implements DiscoveryListener { // Called each time a device is discovered public void deviceDiscovered(
RemoteDevice btDevice, DeviceClass cod) { … } // Called when inquiry is completed or cancelled public void inquiryCompleted( int discType ) { … } …}
DiscoveryAgent agent= local.getDiscoveryAgent();
// place the device in inquiry mode
boolean complete = agent.startInquiry();
JMA F2005 Ebbe Elsborg [email protected]
Device Discovery (2)
DiscoveryAgent agent = local.getDiscoveryAgent();
// return an array of pre-known (cached) devices RemoteDevice[] devices= agent.retrieveDevices(DiscoveryAgent.CACHED);
JMA F2005 Ebbe Elsborg [email protected]
Service Discovery
DiscoveryAgent agent = local.getDiscoveryAgent();
class ServiceListener implements DiscoveryListener { public void servicesDiscovered(
int transID, ServiceRecord[] servRecord) {
}
public void inquiryCompleted( int discType ) {
} …
}
JMA F2005 Ebbe Elsborg [email protected]
Service Records
public interface ServiceRecord
A ServiceRecord contains a set of service attributes, where each service attribute is an (ID, value) pair.
An SDP Server maintains a Service Discovery Database (SDDB) of service records that describe the services on the local device.
ServiceRecords are made available to a client application via an argument of the servicesDiscovered method of the DiscoveryListener interface.
Before a service can be discovered it must be registered
JMA F2005 Ebbe Elsborg [email protected]
Example
// Create service record that represents the serviceStreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(”someURL”);
// Obtain service record created by the server deviceServiceRecord sr = local.getRecord(service);
// Indicate that service is ready to accept client conn.// acceptAndOpen() blocks until a client connectsStreamConnection connection = (StreamConnection) service.acceptAndOpen();
// When ready to exit close connection and rem. Serviceservice.close();
JMA F2005 Ebbe Elsborg [email protected]
Communication (L2CAP)
// L2CAP: Logical Link Control and Adaption P.L2CAPConnection con;byte[] b
con.send(b);
con.receive(b);
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth Protocols
Source http://www.palowireless.com/infotooth/tutorial.asp
In J2ME API
JMA F2005 Ebbe Elsborg [email protected]
Bluetooth Example
conn= (L2CAPConnection)Connector.open(url);
send("Hello server, my name is: "+getName());
JMA F2005 Ebbe Elsborg [email protected]
Device Discovery in J2ME (1)
DiscoveryAgent disc_agent = local_device.getDiscoveryAgent();
inq_listener = new InquiryListener();
disc_agent.startInquiry(DiscoveryAgent.LIAC, inq_listener);
Enumeration devices = inq_listener.cached_devices.elements();
/* LIAC: Limited inquiry Access Code */
local_device.setDiscoverable
(DiscoveryAgent.NOT_DISCOVERABLE);
synchronized(inq_listener) { // to make wait possible
try {inq_listener.wait(); } catch(InterruptedException e){}
}
JMA F2005 Ebbe Elsborg [email protected]
Device Discovery in J2ME (2)class InquiryListener implements DiscoveryListener {
public Vector cached_devices;
public InquiryListener() { cached_devices = new Vector(); }
public void deviceDiscovered(
RemoteDevice btDevice, DeviceClass cod){
int major = cod.getMajorDeviceClass();
if(! cached_devices.contains(btDevice)) {
cached_devices.addElement(btDevice); }
}
public void inquiryCompleted( int discType ) {
synchronized(this){ this.notify(); }
}
JMA F2005 Ebbe Elsborg [email protected]
Service DiscoveryUUID[] u = new UUID[1]; // UUID: Universal Unique ID
u[0] = new UUID("00000000000010008000006057028A06", false );
int attrbs[] = {0x0100 }; // UUID for L2CAP
serv_listener = new ServiceListener();
while( devices.hasMoreElements() ) {
synchronized(serv_listener) { /* now find on remote dev. */
disc_agent.searchServices(attrbs, u, (RemoteDevice)devices.nextElement(), serv_listener);
try {serv_listener.wait();} catch(InterruptedException e){}
} }
JMA F2005 Ebbe Elsborg [email protected]
Communication (1)
String url = serv_listener.service.getConnectionURL(0, false);
deviceName = LocalDevice.getLocalDevice().getFriendlyName();
conn = (L2CAPConnection) Connector.open( url );
String s = "Hello server, my name is: “ + deviceName;
byte[] b = s.getBytes();
try {conn.send(b);} catch(IOException e){};
JMA F2005 Ebbe Elsborg [email protected]
Communication (2)
byte[] b = new byte[1000]; // actual communication
while (listening) {
if (conn.ready()){
conn.receive(b);
String s = new String(b, 0, b.length);
System.out.println("received from server: “ + s.trim());
listening = false;
}
}
JMA F2005 Ebbe Elsborg [email protected]
Location Based Services
GPS (global)
Local (e.g. within buildings)
Cell based (within cities)
JMA F2005 Ebbe Elsborg [email protected]
L2CAP versus RFCOMM
L2CAP(packetss)
RFCOMM(serial) 00011010101010
JMA F2005 Ebbe Elsborg [email protected]
OBEX
• OBject EXchange• Communication protocol, client/server• Protocol stack:
– ’Applications’– OBEX (OBject EXchange)– SDP (Service Discovery) + RFCOMM– L2CAP (Logical Link Control and Adaption)– HCI (Host Controller Interface), soft/hard– LMP (Link Manager), link setup and piconet– Baseband (control and send data packets)– Radio (physical wireless connection, 79 ch.)
JMA F2005 Ebbe Elsborg [email protected]
OBEX usage
• Used to implement Bluetooth profiles:– Generic Object Exchange– Object Push– Synchronization– File Transfer– Basic Imaging– Basic Printing
• Object model and Session protocol– Objects have headers (e.g. HTTP)– Request-Response (packets) e.g. CONNECT
JMA F2005 Ebbe Elsborg [email protected]
Communication example
• Client: Connect request– Contains operation, packet length, headers
• Server: Success– Contains response code+length+data
• Client: Put/Get• Server: Continue• Client: Put/Get• Server: Success• Client: Disconnect• Server: Success
JMA F2005 Ebbe Elsborg [email protected]
Code anyone?
ClientSession session = (ClientSession)Connector.open(connectURL);
HeaderSet hdr = clientSession.createHeaderSet();// Create header set to request ’Hello.txt’ file from serverhdr.setHeader(HeaderSet.TYPE, ”text/vCard”);hdr.setHeader(HeaderSet.NAME, ”Hello.txt”);// OBEX server can retrieve them by calling getHeader()Operation op = session.put(null);OutputStream out = op.openOutputStream();out.write(”Test”.getBytes());out.close();if(op.getResponseCode() ==
ResponseCodes.OBEX_HTTP_OK){ System.out.println(” PUT operation is success”); }
JMA F2005 Ebbe Elsborg [email protected]
Server side code
• Servers must implement a ServerRequestHandler and a SessionNotifier
public int onGet(Operation op) {try {
HeaderSet hdr = op.getReceivedHeaders();}
SessionNotifier sn = (SessionNotifier)Connector.open(”btgoep://localhost:1106;name=FTP”);sn.acceptAndOpen(serverRequestHandler);
JMA F2005 Ebbe Elsborg [email protected]
The PUT operation
con = (ClientSession)Connector.open(serviceURL);hdr = con.connect(hdr); hdr = con.createHeaderSet();hdr.setHeader(HeaderSet.TYPE, ”text/plain”);hdr.setHeader(HeaderSet.NAME, ”Hello.txt”);Operation op = con.put(hdr);// Sending the bodyOutputStream writeStrm = op.openOutputStream();StreamConnection strmCon = (StreamConnection)
.open(”file://name=” + filename + ”;mode=r”);InputStream readStrm = strmCon.openInputStream();byte[] block = new byte[512]; Int dataSize = -1;while ((dataSize = readStrm.read(block)) != -1)
{ writeStrm.write(block, 0, dataSize); }… // Send END-OF-BODY-HEADER and close streams
JMA F2005 Ebbe Elsborg [email protected]
Relevant Links
Bluetooth APIhttp://jcp.org/en/jsr/detail?id=82
Toolkit extension (Nokia):Series 60 MIDP Concept SDK Beta 0.3.1http://www.forum.nokia.com/main.html
JMA F2005 Ebbe Elsborg [email protected]
The Connector Class
• Used to open a Connection (interface)– open(String name)– open(String name, int mode)– open(String name, int mode, boolean timeouts)
name: scheme:address;parameters (protocol, resource ids, x=y)
mode: Connection attribute (READ, WRITE, READ_WRITE)
timeouts: Can application use timeouts (E.g. to prevent indefinite
blocking)
• Which connection types can we open?
JMA F2005 Ebbe Elsborg [email protected]
Connection types
• The CLDC GCF (super)interface overview:• Connection
– InputConnection/OutputCon. (streams)• StreamConnection (both I/O)
– SocketConnection» SecureConnection (use ’ssl’ scheme)
– CommConnection (logical serial ports)– HttpConnection (request-response protocol)
» HttpsConnection (use ’https’ scheme)
– StreamConnectionNotifier• ServerSocketConnection
– DatagramConnection (discrete packets)• UDPDatagramConnection (User Data Protocol)
• SecurityInfo• PushRegistry Class
JMA F2005 Ebbe Elsborg [email protected]
Client/Server
• Algorithm for communication– Build name and invoke Connector’s open()– Get output stream, send request to server– Open input stream and read response– Close both streams and the socket
• Clean up inside finally block to handle (communication) errors – close I/O
• A server obtains a StreamConnectionNotifier object and calls acceptAndOpen() in a loop, this call returns with a StreamConnection object when a client connects
JMA F2005 Ebbe Elsborg [email protected]
Reading Data
InputStream in = getClass().getResourceAsStream(“/large.txt”);
InputStreamReader r = new InputStreamReader(in);
JMA F2005 Ebbe Elsborg [email protected]
Reading Data Wirelessly
InputStream in = ((HttpConnection)Connector.open
(url)).openInputStream();
while (...) in.read(data);
+
import javax.microedition.io.HttpConnection;import javax.microedition.io.Connector;
String url = "http://www.itu.dk/courses/JMA/F2005/large.txt"
JMA F2005 Ebbe Elsborg [email protected]
Example• void getViaHttpConnection(String url) throws
IOException { HttpConnection c = null; InputStream is = null; int rc; try {
// Get response code, opens connection, // send the request, and read the HTTP // response headers. The headers are // stored until requested. c = (HttpConnection)Connector.open(url); rc = c.getResponseCode(); if (rc != HttpConnection.HTTP_OK) { throw new IOException("HTTP response code: "+ rc);} is = c.openInputStream(); // Get the ContentType String type = c.getType(); … // process data