Title: Programming context aware Mobile Phones
1Programming context awareMobile Phones
Agenda Introduction to Bluetooth
Methods for connecting Importent classes
Service description
2Server 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,
3N-Tier Applications
- Presentation Tier
Business Logic Tier -
Database Tier
4Bluetooth
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)
5Bluetooth - 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.
6Frequency Hopping
Source http//www.swedetrack.com/images/bluet11.h
tm
7Bluetooth, 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
8Bluetooth applications
- File transfer
- Ad-hoc networking
- Device synchronization
- Peripheral connectivity
- Car kits (hand-free installations)
- Mobile payments
9Piconets and Scatternets
10Details
- 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
11Bluetooth in J2ME
HTTP con (HttpConnection)Connector.open(url)
L2CAP (Bluetooth) con (L2CAPConnection)Connecto
r.open(url)
12Bluetooth Overview
Device Discovery
13Establishing 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)
14Bluetooth Profiles Security
- Profiles
- Idea Ensure interoperability
- Generic Access Profile must be supported by a
Bluetooth-enabled device - Security
- Pseudo-random frequency hopping
- Authentication
- Encryption
15Bluetooth 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
16Packages andApplication Programming
- javax.bluetooth
- javax.obex
- Five steps in application programming
- Stack initialization (vendor dependent)
- Device management
- Device discovery
- Service discovery
- Communication
17Device Management
... // init stack LocalDevice local
LocalDevice.getLocalDevice() String address
local.getBluetoothAddress() String name
local.getFriendlyName() ...
18Device Discovery (1)
DiscoveryAgent agent local.getDiscoveryAgent()
// place the device in inquiry mode boolean
complete agent.startInquiry()
19Device Discovery (2)
20Service Discovery
DiscoveryAgent agent local.getDiscoveryAgent()
class ServiceListener implements
DiscoveryListener public void
servicesDiscovered( int transID, ServiceRecord
servRecord) public void
inquiryCompleted( int discType )
21Service Records
Before a service can be discovered it must be
registered
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.
22Example
- // Create service record that represents the
service - StreamConnectionNotifier service
- (StreamConnectionNotifier) Connector.open(someUR
L) - // Obtain service record created by the server
device - ServiceRecord sr local.getRecord(service)
- // Indicate that service is ready to accept
client conn. - // acceptAndOpen() blocks until a client connects
- StreamConnection connection
- (StreamConnection) service.acceptAndOpen()
- // When ready to exit close connection and rem.
Service - service.close()
23Communication (L2CAP)
// L2CAP Logical Link Control and Adaption
P. L2CAPConnection con byte b con.send(b)
con.receive(b)
24Bluetooth Protocols
Source http//www.palowireless.com/infoto
oth/tutorial.asp
In J2ME API
25Bluetooth Example
26Device Discovery in J2ME (1)
DiscoveryAgent disc_agent local_device.getDiscov
eryAgent() 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)
27Device 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()
28Service Discovery
UUID u new UUID1 // UUID Universal Unique
ID u0 new UUID("00000000000010008000006057028A
06", 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(att
rbs, u, (RemoteDevice)devices.nextEl
ement(), serv_listener) try
serv_listener.wait() catch(InterruptedException
e)
29Communication (1)
String url serv_listener.service.getConnectionUR
L(0, false) deviceName LocalDevice.getLocalDevi
ce().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)
30Communication (2)
byte b new byte1000 // 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
31Source Code for Example
32Location Based Services
33L2CAP versus RFCOMM
L2CAP (packetss)
RFCOMM (serial)
00011010101010
34OBEX
- 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.)
35OBEX 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
36Communication example
- Client Connect request
- Contains operation, packet length, headers
- Server Success
- Contains response codelengthdata
- Client Put/Get
- Server Continue
- Client Put/Get
- Server Success
- Client Disconnect
- Server Success
37Code anyone?
- ClientSession session
- (ClientSession)Connector.open(connectURL)
- HeaderSet hdr clientSession.createHeaderSet()
- // Create header set to request Hello.txt file
from server - hdr.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)
38Server 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//localhost1106nameFTP)
- sn.acceptAndOpen(serverRequestHandler)
39The 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 body
- OutputStream writeStrm op.openOutputStream()
- StreamConnection strmCon (StreamConnection)
- .open(file//name filename moder)
- InputStream readStrm strmCon.openInputStream()
- byte block new byte512 Int dataSize -1
- while ((dataSize readStrm.read(block)) ! -1)
- writeStrm.write(block, 0, dataSize)
- // Send END-OF-BODY-HEADER and close streams
40Relevant Links
Bluetooth API http//jcp.org/en/jsr/detail?id82
Toolkit extension (Nokia) Series 60 MIDP Concept
SDK Beta 0.3.1 http//www.forum.nokia.com/main.htm
l
41Break
42The Connector Class
- Used to open a Connection (interface)
- open(String name)
- open(String name, int mode)
- open(String name, int mode, boolean timeouts)
- name schemeaddressparameters
- (protocol, resource ids, xy)
- mode Connection attribute
- (READ, WRITE, READ_WRITE)
- timeouts Can application use timeouts
- (E.g. to prevent indefinite blocking)
- Which connection types can we open?
43Connection 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
44Client/Server
- Algorithm for communication
- Build name and invoke Connectors 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
45Reading Data
InputStream in getClass().getResourceAsStream(/
large.txt) InputStreamReader r new
InputStreamReader(in)
46Reading Data Wirelessly
String url "http//www.itu.dk/courses/JMA/F2005/
large.txt"
InputStream in ((HttpConnection)Connector.open
(url)).openInputStream() while (...)
in.read(data)
import javax.microedition.io.HttpConnection im
port javax.microedition.io.Connector
47Example
- 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