Cours Bluetooth JSR82 Android
Cours Bluetooth JSR82 Android
Cours Bluetooth JSR82 Android
1
BT_java
Sommaire
Le contexte
Bluetooth, caractristiques, brve prsentation
Les protocoles et profils
JSR82, Principes
Deux paquetages,
Usage identique pour J2SE et J2ME
Dcouverte
Des priphriques BT et des services
Communication
RFComm btspp://
OBEX btgoep://
2
BT_java
Bibliographie utilise
http://www.bluetooth.com
http://www.newlogic.com
http://developer.android.com/guide/topics/wireless/bluetooth.html
3
BT_java
Prambule
Le contexte
Les MIDlet
Outils NetBeans 6.5, WTK 2.5.2
CLDC1.1, MIDP2.0
sur PC avec le micro-emulator
http://www.microemu.org/
sur mobiles :
sony ericsson S500i, W580i, Motorola K1 KRZR
Note: priori, le WTK ne permet quune mulation du BT
Vocable habituel :
Dcouverte multicast des services
Client/serveur, serveur/serveur
6
BT_java
Mesures, vrifier
Figures extraites
de http://www.licm.sciences.univ-metz.fr/IMG/pdf/Cours_Bluetooth.pdf
http://www.dandu.be/article/article-bluetooth-comparaison-dongles-46.html
http://www.sena.com/blog/?p=74
BT 2.0 10-100m
Performances : vrifier
7
BT_java
Des chiffres
8
BT_java
Principe : des ondes autour de nous
9
BT_java
Principe : des ondes autour de nous
10
BT_java
Vocabulaire : Piconet
http://www.acm.org/crossroads/xrds9-4/blue.html
13
BT_java
Combien ?
14
BT_java
Protocoles et profils
L2CAP
Logical Link Control and adaptation Protocol
Envoi de paquets avec un protocole donn vers le gestionnaire
appropri.
RFCOMM
mulation de ports sries au dessus de L2CAP.
OBEX
Object Exchange Protocol.
Analogue HTTP/GET-POST, FTP
SDP
Service Discovery Protocol (SDP).
TCS
telephony control specification
15
BT_java
O sommes nous ?
www.cs.umu.se/kurser/TDBD16/VT07/Bluetooth-Tutorial-2001.pdf
16
BT_java
Profils
Applications ddies
17
BT_java
De la documentation originale
18
BT_java
En rsum
www.bluetooth.com/.../Technology/Works/OBEX.htm
19
BT_java
Bluetooth, existentiel
Qui suis-je ?
Je me prsente
Quels protocoles ?
O suis-je, o vais-je ?
pas facile voir blipnet ericsson
http://www.blipsystems.com/files/filer/technical_overview.pdf
20
BT_java
J2SE / JSR82
Deux paquetages
http://java.sun.com/javame/reference/apis/jsr082/javax/bluetooth/package-summary.html
http://www.jsr82.com
http://www.bluecove.org/
21
BT_java
Android
android.bluetooth
http://developer.android.com/guide/topics/wireless/bluetooth.html
22
BT_java
Qui suis-je ?
Chaque priphrique BT
possde
23
BT_java
Premier exemple : quelle est mon adresse BT ?
import javax.bluetooth.LocalDevice;
http://www.bluecove.org/bluecove/apidocs/
24
BT_java
Sur simulateur de mobile et sur mobile : QuiSuisJe
Puis excutez
> run_microemulateur.bat
25
BT_java
Sur Android *
QuiSuisJe ?
26
BT_java
Bluetooh et nommage
0019EF0117DA
Devrons nous connatre les adresses physiques ?
Non merci
Sauf les fixes
Dcouverte de priphriques BT
Aux alentours
Nommage/UUID Universally Unique IDentifier (128 bits),
existe en version courte
Communication
java.io.*, etc
28
BT_java
Un service se trouve sur ce priphrique
Il nous faut
UUID (128bits)
Qui identifie le service
("10203040-5060-7080-90A0-B0C0D0E0F0FF");
29
BT_java
Android
Architecture retenue
30
BT_java
Sous-classe dAsyncTask
Proposition
31
BT_java
Exemple
private UUID MY_UUID = UUID.fromString("10203040-5060-7080-90A0-B0C0D0E0F0FF");
32
BT_java
Communication sur os : dans un Thread
public class Sender extends Thread{
private BlockingQueue<byte[]> queue;
public Sender(){
queue = new SynchronousQueue<byte[]>();
this.start();
}
}
}
}
}
33
BT_java
J2SE/Un client
// la dcouverte du service
connString = agent.selectService(new UUID("102030405060708090A0B0C0D0E0F0BB", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// dans un Thread
private static String readFile(InputStream in) throws IOException {
StringWriter data = new StringWriter();
int aByte;
while((aByte = in.read())!=-1){
data.write( (byte)aByte);
}
return data.toString();
}
34
BT_java
Parmi mes voisins
Un service : un UUID
new UUID("102030405060708090A0B0C0D0E0F011" ,false)
128 bits pourquoi pas celui-ci
35
BT_java
A typical usecase
36
BT_java
A la dcouverte de obtention dun agent
import javax.bluetooth.LocalDevice;
import javax.bluetooth.DiscoveryAgent;
local.setDiscoverable( DiscoveryAgent.GIAC );
// GIAC General inquire Access Code
DiscoveryAgent agent = local.getDiscoveryAgent();
Un exemple daffichage :
connString:
btspp://0019EF01194C:1;authenticate=false;encrypt=false;master=false
Nous avons
Une communication
Un flux doctets, btspp://
Un flux structur, btgeop://
39
BT_java
Exemple de service/UUID/J2SE
StreamConnectionNotifier notifier =
(StreamConnectionNotifier)Connector.open(
"btspp://localhost:102030405060708090A0B0C0D0E0F010");
40
BT_java
Un serveur au complet
public class SimpleBTSPPServer {
(StreamConnectionNotifier)Connector.open(
"btspp://localhost:" + "102030405060708090A0B0C0D0E0F010");
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
System.out.println(" message recu : " + out.toString());
in.close();
conn.close();
notifier.close();
}
note : ci-dessus vous avez un serveur dune seule connexion cest peu
41
BT_java
Le client la recherche de cet UUID
Les essentiels
agent .selectService
StreamConnection
42
BT_java
Un exemple de client de ce service
}
}
43
BT_java
Android, mme principe
Extrait de http://developer.android.com/guide/topics/wireless/bluetooth.html
BluetoothServerSocket btServerSocket;
btServerSocket =
mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
44
BT_java
Un premier exemple : une passerelle BT/HTTP
HTTP://
BT/Web
Pourquoi faire ?
45
BT_java
Autre exemple une borne Bluetooth/HTTP
Un client Bluetooth
Recherche ce service
Envoie une URL
Affiche le rsultat
46
BT_java
Dmonstration : le serveur
Le Proxy BT<->HTTP
est une application JavaWebStart
Il suffit de cliquer ici
http:/jfod.cnam.fr/SEJA/jnlp/BTProxyHTTP.jnlp
UUID = 102030405060708090A0B0C0D0E0F0A
47
BT_java
Dmonstration : Ct client
Ct client un navigateur ?
Sur mobile
http://sourceforge.net/search/?type_of_search=soft&words=browser+j2ME
Opera mini, sources java disponibles ?
Analogue lusage dun proxy mais au protocole btspp://
48
BT_java
Ct client/mobile
49
BT_java
Une Variante de BTProxyHTTP
BTProxyHTTP2
http://jfod.cnam.fr/SEJA/jnlp/BTProxyHTTP2.jnlp
50
BT_java
Quelques traces
Ct serveur
http://jfod.cnam.fr/SEJA/jnlp/BTProxyHTTP2.jnlp
Ct client
http://jfod.cnam.fr/SEJA/jnlp/MiniBrowser.jnlp
un autre exemple voir page suivante
Application extraite de
http://www.java-tips.org/java-se-tips/javax.swing/how-to-create-a-simple-browser-in-swing-3.html
51
BT_java
Un client du classique
// la dcouverte du service
connString = agent.selectService(new UUID("102030405060708090A0B0C0D0E0F0BB", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
52
BT_java
Le serveur en quelques lignes
StreamConnectionNotifier notifier =
(StreamConnectionNotifier)Connector.open("btspp://localhost:" +
"102030405060708090A0B0C0D0E0F0BB" + ";name=BTProxyHTTP2");
while(true){
StreamConnection conn = notifier.acceptAndOpen();
new ConnexionBT(conn).start();
}
Protocole :
envoi de lURL http:// puis attente du rsultat
53
BT_java
Le serveur suite, classe interne ConnexionBT
private static class ConnexionBT extends Thread{
private StreamConnection conn;
private String url;
this.url = readLine(in);
if (url!=null) {
ConnexionHTTP connect = new ConnexionHTTP(url);
System.out.print(" -> une requete en " + this.url);
String result = connect.result();
System.out.println(", page lue et envoye : " + result.length() + " octet(s), iso-8859-1");
54
BT_java
Dcouverte suite
55
BT_java
Quels sont les services aux alentours ?
Tout dabord
quels sont les priphriques BT aux alentours ?
Grce mon agent
agent.startInquiry() : patience au moins 10 secondes
ensuite
Recherche des services bien connus ?
OBEX : push obex, ftp,
Etc
56
BT_java
Obtention de la liste de tous les priphriques
bluetooth aux alentours
57
BT_java
Comment ? startInquiry deviceDiscovered
58
BT_java
En Java : un listener appel par lAPI
Linterface DiscoveryListener
4 mthodes,
2 pour la dcouverte des priphriques
2 pour la dcouverte des services
59
BT_java
Exemple : Liste des priphriques BT, startInquiry
60
BT_java
Exemple suite : le listener
private static class DeviceDiscover implements DiscoveryListener{
61
BT_java
Dmonstration
62
BT_java
Un schma/rsum extrait de la bibliographie
http://www.usc.edu/dept/ee/scip/assets/001/57411.pdf
63
BT_java
Un autre exemple plus compact
public static void main(String[] args) throws Exception{
LocalDevice localDevice = LocalDevice.getLocalDevice();
64
BT_java
Quels services ?, filtrage possible ?
bluecove.inquiry.duration
Device Inquiry time in seconds defaults to 11 seconds.
65
BT_java
Exemple : PREKNOW / CACHED
private void addDevices_PREKNOW_AND_CACHED(){
RemoteDevice[] list = null;
list = agent.retrieveDevices(DiscoveryAgent.PREKNOWN);
if(list!=null){
System.out.println(list.length + " preknow");
for(int i = 0; i < list.length; i++){
devices.addElement(list[i]);
}
}
list = agent.retrieveDevices(DiscoveryAgent.CACHED);
if(list!=null){
System.out.println(list.length + " devices cached");
for(int i = 0; i < list.length; i++){
devices.addElement(list[i]);
}
}
}
66
BT_java
Cached
CACHED
Dtect lors dun prcdent inquiry
67
BT_java
Diagramme dtats, ou un rsum
La suite
68
BT_java
Services -> Nouvelles questions ?
Dmonstration
Autorisez le bluetooth de vos mobiles
http://jfod.cnam.fr/SEJA/jnlp/BTServiceBrowser.jnlp
69
BT_java
la recherche des services (famille listener)
http://www.usc.edu/dept/ee/scip/assets/001/57411.pdf
70
BT_java
Exemple, UUID et plus
Avec
UUID[] uuidSet = {new UUID(0x0100)};
// 0x0100 au dessus de L2CAP
// 0x105 only searches btspp services
http://www.avetana-gmbh.de/avetana-gmbh/produkte/doc/javax/bluetooth/UUID.html
// 0x0100 ProtocolDescriptorList
// 0x0003 ServiceID UUID
// 0x0004 ProtocolDescriptorList
http://www.forum.nokia.com/document/Java_Developers_Library_v2/GUID-9F75713D-5642-4C39-9A33-
C20928F37BF7/javax/bluetooth/ServiceRecord.html
71
BT_java
Un lundi aprs-midi au Cnam, 3me tage
72
BT_java
Exemple liste de tous les services
http://jfod.cnam.fr/SEJA/jnlp/BTServiceBrowser.jnlp
73
BT_java
Comment ?
str.append(services.elementAt(i).getHostDevice().getBluetoothAddress());
try{
DataElement nameElement =
(DataElement)services.elementAt(i).getAttributeValue(SERVICE_NAME_ATTRID);
str.append(",");
if ( nameElement != null )
str.append((String)nameElement.getValue());
else str.append("_");
str.append(",");
str.append(services.elementAt(i).getConnectionURL(
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
}catch(Exception e){}
str.append(">\n");
}
return str.toString();
75
BT_java
Lire les rsultats retourns
Comment ?
0x4:
DATSEQ {
DATSEQ {
UUID 0000010000001000800000805f9b34fb
}
DATSEQ {
UUID 0000000300001000800000805f9b34fb
U_INT_1 0x10
}
}
0x1:
DATSEQ {
UUID 102030405060708090a0b0c0d0e0f088
UUID 0000110100001000800000805f9b34fb
}
0x0:
U_INT_4 0x10100
}
76
BT_java
Comment ? suite
http://www.bluecove.org/bluecove/apidocs/
77
BT_java
http://www.bluecove.org/bluecove/apidocs/ voir UUID
78
BT_java
Autre exemple
79
BT_java
Exemple : Remote Control
sourceforge.net/projects/blurc
80
BT_java
Mise en uvre Prise de contrle distant
HTTP://
81
BT_java
Dmonstration
Ct serveur
http://jfod.cnam.fr/SEJA/jnlp/BTServerVNC2.jnlp
Usage de java.awt.Robot
Avec microemulator
Tlcharger ces fichiers
http://jfod.cnam.fr/SEJA/jnlp/midlet/BTClientVNC/
Puis >run_microemulateur
82
BT_java
Dmonstration suite
83
BT_java
Un schma / rsum
84
BT_java
En rsum
http://developers.sun.com/mobility/apis/articles/bluetoothobex/
http://www.ibm.com/developerworks/java/library/wi-boogie1/index.html
http://wiki.forum.nokia.com/index.php/Using_Bluetooth_obex_server_in_Java_ME
87
BT_java
OBEX Client/Server
Le Serveur
UUID uuid = new UUID("8841", true);
String url = "btgoep://localhost:" + uuid +
";name=FTP;authenticate=false;master=false;encrypt=false";
import javax.obex.Operation;
import javax.obex.HeaderSet;
import javax.obex.ResponseCodes;
import javax.obex.ServerRequestHandler;
import javax.obex.SessionNotifier;
88
BT_java
OBEX : les UUID
http://www.bluecove.org/bluecove/apidocs/
Lire le Quick Tutorial
0x1105
Ou
0000110500001000800000805F9B34FB en version longue
89
BT_java
Une session Client, ici un envoi dun fichier
1. Recherche du bon service ici serverURL
2. Puis tablissement dune connexion au protocole OBEX
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Connect Error " + hsConnectReply.getResponseCode());
}
po.close();
HeaderSet hsDisconnect = clientSession.disconnect(null);
// hsDisconnect.getResponseCode() == ResponseCodes.OBEX_HTTP_OK
90
BT_java
ObexTypes.getObexFileType, apparent mimes
static {
types.put("jpg", "image/jpeg");
types.put("jpeg", "image/jpeg");
types.put("gif", "image/gif");
types.put("mp3", "audio/mpeg");
types.put("txt", "text/plain");
types.put("jar", "application/java-archive");
}
91
BT_java
Le service
Inscription du service
SessionNotifier serverConnection = (SessionNotifier)
Connector.open("btgoep://localhost:"+ serverUUID + ";name=ObexPutServer2");
A chaque client
Une requte/un thread
92
BT_java
Le service : RequestHandler
private class RequestHandler extends ServerRequestHandler {
InputStream is = op.openInputStream();
StringBuffer buf = new StringBuffer();
int data;
while ((data = is.read()) != -1) {
buf.append((char) data);
}
op.close();
synchronized(lock){notify();}
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
e.printStackTrace();
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
}
}}
93
BT_java
Un client OBEX du serveur au complet
private static class ClientObex extends Thread{
private Connection conn;
private SessionNotifier serverConnection;
private Object lock;
94
BT_java
Applications, c.f. bluecove
http://jfod.cnam.fr/SEJA/jnlp/OBEX_client.jnlp
http://www.bluecove.org/bluecove/apidocs/
95
BT_java
Dmonstration BTFileUpload
http://jfod.cnam.fr/SEJA/jnlp/BTFileUpLoad.jnlp
96
BT_java
Un petit outil trs contagieux
Hypothse :
Une Midlet capable de diffuser une Midlet capable de diffuser une
Usage du service OBEX Push Object prdfini
Comment ?
Une archive contenue dans le .jar de la midlette est envoye tous ses voisins
Le voisin reoit une archive soit une midlette qui contient une archive
Viable ?
TTL dguis
Fonctionne quelque soit le mobile ?
97
BT_java
Petit outil de diffusion suite
La Midlette BTFileUpLoad
Contient une archive BTFileUpLoad.jar qui contient son tour
98
BT_java
Petit Outil en dmonstration
Prambule
Ok
Avec le micro-mulateur !
Motorola K1,
envoi ok,
rception incorrecte
La Midlette est l
http://jfod.cnam.fr/SEJA/jnlp/midlet/BTFileUpload/
99
BT_java
Dmo du WTK
Voir obexdemo
Et le sous rpertoire j2seObexDemo
Et surtout http://wiki.forum.nokia.com/index.php/Using_Bluetooth_obex_server_in_Java_ME
100
BT_java
Dmo microemulator/ pile bluecove
server
http://wiki.forum.nokia.com/index.php/Using_Bluetooth_obex_server_in_Java_ME
Installes ici http://jfod.cnam.fr/SEJA/projet/obex_midlet/
101
BT_java
Le patron/observateur/Observ-MVC
HTTP
Observateurs/Observ
modele
2,mise jour)
http://vue1/update/?temperature=300
http://vue2/update/?temperature=300
0,init) http://modele/addObserver/http://vue1/update/
102
BT_java
MVC HTTP+BT
HTTP/BT
Observateurs/Observ
Midlettes
BTProxyHTTP
modele
BTServerHTTP 2,mise jour)
http://vue1/update/?temperature=300
http://vue2/update/?temperature=300
http://modele/addObserver/uuid=11223344556677889900 103
BT_java
Patrons Observateur + Fabrique
ObservableServer
addObserver, notifyObservers comme services Web/HTTP
ObserverServer
Update comme service Web
ObserversHTTPList
La liste des observateurs
ConnectionFactory
Une fabrique de Connexion
104
BT_java
Un exemple avec Httpunit
public void test_notifyBTObservers(){
try{
new Thread(new Runnable(){ // cration de lobservable
public void run(){
ObservableServer.main(new String[]{"8226"});
}}).start();
Dmonstration en ligne :
http://jfod.cnam.fr/SEJA/jnlp/TestsObervable.html
Traces ct Observable
BlueCove version 2.1.0 on winsock
Request: GET /notifyObservers/?temperature=200&capteur=DS1922 HTTP/1.1
Request: GET /addObserver/?uuid=102030405060708090A0B0C0D0E0F088 HTTP/1.1
addObserver : 102030405060708090A0B0C0D0E0F088
Request: GET /notifyObservers/?temperature=300&capteur=DS1921 HTTP/1.1
Request: GET /notifyObservers/?temperature=200&capteur=DS1922 HTTP/1.1
Ct Mobile, bluetooth
106
BT_java
Petite conclusion
Mobiles
Contrles/ Vue
En quelques lignes
Abstraction des distances
terminer
107
BT_java
Conclusion plus grande ?
Bluetooth
Mobile/java
Motorola K1, Sony Ericsson
tester : http://www.opera.com/mini/download/all/
108
BT_java
Conclusion
http://www.bluecove.org/
vrifier sur dautres priphriques
109
BT_java
Annexes
UbiqMuseum
Rseaux adhoc broadcast
Tlcommandes
110
BT_java
UbiqMuseum comme projet
http://monet.knu.ac.kr/~cktoh/data/Springer_jucano_pmanzoni_Toh.pdf
111
BT_java
UbiqMuseum
Mode connect
< 8 priphriques simultans
Mode de type Session
Ct client
RFComm
OBEX
112
BT_java
UbiqMuseum
Discussion
113
BT_java
Annexe javawebStart
http://jfod.cnam.fr/SEJA/jnlp/mode_emploi_jnlp.html
Un certificat
> keytool -genkey -alias jmd -keypass PASSWORD -keystore jmdstore -storepass PASSWORD
jar cvf MiniBrowser.jar webBrowser/*.class
jarsigner -keystore jmdstore MiniBrowser.jar jmd
<jnlp spec="1.0+"
codebase="http://jfod.cnam.fr/SEJA/jnlp/"
href="MiniBrowser.jnlp">
<information>
<title>MiniBrowser</title>
<vendor>SEJA Cnam</vendor>
<description>MiniBrowser</description>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.5+"/>
<jar href="MiniBrowser.jar"/>
<jar href="bluecove-2.1.0.jar"/>
</resources>
<application-desc main-class="webBrowser.MiniBrowser"/>
</jnlp>
http://jfod.cnam.fr/SEJA/jnlp/BTProxyHTTP2.jnlp
114
BT_java
Annexe : MIDlet javax.bluetooth.*
JSR82
javax.bluetooth
115
BT_java
Device Management
Device Management
LocalDevice() appel par lapplication cliente
setDiscoverable()
updateRecord()
getBluetoothAddress()
getProperty()
RemoteDevice() informations du fournisseur
getBluetoothAddress()
authenticate()
authorize()
isEncrypted()
116
BT_java
Rsum Communication
- Eg: btspp://hostname;authenticate=true;authorize=true;encrypt=true
117
BT_java
Annexe Klings
118
BT_java
BTBrowserMIDlet de klings
http://wireless.klings.org/main.php/BTBrowser/
Avec le microemulateur*
Pile bluecove et avetana
119
BT_java
BTBrowser, avec un autre mulateur
http://kobjects.sourceforge.net/me4se/
120
BT_java