Vous êtes sur la page 1sur 58

Programming the Android

Platform
Bluetooth
f
The Bluetooth Core Specification
EDR - enhanced data rate
HS high speed
IEEE 802!" is a #or$ing group of the Institute of Electrical and
Electronics Engineers %IEEE& IEEE 802 standards co''ittee
#hich specifies #ireless personal area net#or$ %()*+&
standards
Bluetooth versions comparison. Whats the
difference between the versions?(Part 1)
Bluetooth v1.2

Backward compatible with v1.1, faster


connection and discover.

!ecovered confrontation to radio


fre"uenc interference b avoidin# the use
of crowded fre"uencies in the hoppin#
se"uence.

$ata transmission speed up to %&1 kbit ' s.


Bluetooth v2.0

Backward compatible with the previous


v1.&.

(nhanced $ata !ate (($!) for faster data


transfer.

)he nominal rate of ($! is about * +bit ' s


Bluetooth v2.1

Backward compatible with v1.&.

,ses secure simple pairin# (--P) to


improve a better pairin# e.perience for
Bluetooth devices.

,ses sniff sub ratin#, which reduces the


power consumption in low/power mode.
Bluetooth versions comparison. Whats the difference between the versions?(Part &)
Bluetooth v3.0

Backward compatible with v&.1.

Bluetooth *.0 provides theoretical data


transfer speeds of up to &1 +bit ' s.

2or hi#h data rate traffic this version uses


the ad3acent 40&.11 link.
Bluetooth versions comparison. Whats the difference between the versions?(Part *)
Bluetooth v4.0

Backward compatible with v*.0.

Provides faster speed in data transmission


than the earlier version.

5t comes with #reatl reduced power


consumin#, as if it does not re"uire an
power at all to function.

5t provides more securit in data


transmission than the earlier version.
Bluetooth Low Energy

6ndroid 1.* (6P5 7evel 14) introduces built/


in platform support for Bluetooth 7ow
(ner# in the central role and provides
6P5s that apps can use to discover devices,
"uer for services, and read'write
characteristics.

5n contrast to 8lassic Bluetooth, Bluetooth


7ow (ner# (B7() is desi#ned to provide
si#nificantl lower power consumption.
)his allows 6ndroid apps to communicate
with B7( devices that have low power
re"uirements, such as pro.imit sensors,
heart rate monitors, fitness devices, and so
on.
Extremely Low Power Consumption
The $e, feature of Bluetooth lo# energ, technolog, is its lo# po#er consu'ption that
'a$es it possi-le to po#er a s'all de.ice #ith a tin, coin cell -atter,/such as a CR2002
-atter,/for "!0 ,ears
*s #ith Classic Bluetooth technolog,1 Bluetooth lo# energ, technolog, operates in the 22
3H4 IS5 -and and has si'ilar radio fre6uenc, %R7& output po#er8 ho#e.er1 -ecause a
Bluetooth lo# energ, de.ice is in sleep 'ode 'ost of the ti'e and onl, #a$es up #hen a
connection is initiated1 the po#er consu'ption can -e $ept to a 'ini'u' )o#er
consu'ption is $ept lo# -ecause the actual connection ti'es are of onl, a fe# 'S The
'a9i'u'1 or pea$1 po#er consu'ption is onl, !" '*1 and the a.erage po#er consu'ption
is of onl, a-out ! u*
Bluetooth Low Energy vs. Classic
Bluetooth(Part 1)
Limitations

)he use of low power consumption and coin cell batter operation also has its limitations.
$ata transfer rates with 8lassic Bluetooth technolo# usin# enhanced data rate (Bluetooth
v&.1 9 ($!) can e.ceed & +b's (actual paload), but practical transfer rates for Bluetooth low
ener# technolo# are below 100 kb's (actual paload of rou#hl 1'&0). )herefore, streamin#
Bluetooth low ener# connections will lose a #reat deal of the hu#e potential power savin#s
as the utili:ation approaches continuous transmission.

5n other words, some applications are better served with a Bluetooth low ener# connection
than others. )he use varies dependin# on the tpe of device a sensor is connected to.
Bluetooth Low Energy vs. Classic Bluetooth(Part 2)
$ifferences in Bluetooth Profile -upport

)he behavior of a Bluetooth connection;whether 8lassic or low ener#;is determined b


the Bluetooth profiles a device has implemented. $evices can onl connect if the both have
the same Bluetooth profile implemented, and there are some important differences between
what profiles are available for 8lassic Bluetooth technolo# and for Bluetooth low ener#
technolo#.

6 #ood e.ample of the differences is seen in serial port emulation. 8lassic Bluetooth
technolo# provides the serial port profile (-PP) for emulation of serial data connections.
Bluetooth low ener# technolo# provides no such support in the standard -pecification v1.0<
althou#h suppliers like connectBlue can provide a #ood level of support.

+an other profiles are not offered for Bluetooth low ener# technolo# because of the
differences in the connection models. )he 8lassic Bluetooth scenarios that are not part of
Bluetooth low ener# technolo# include headset (=-P), ob3ect e.chan#e (>B(?), audio
distribution (6&$P), video distribution (@$P), and file transfer (2)P).
Bluetooth Low Energy vs. Classic Bluetooth(Part 3)
Single!ode and "ual!ode#$hat "oes %hat !ean&
Because the two technolo#ies are fundamentall different, there are the two followin# options
for implementationsA

-in#le/mode $evices. )hese devices are stand/alone Bluetooth low ener# devices (also
known as B-martC devices) optimi:ed for small batter/operated devices with low cost
and low power consumption in focus. 6 tpical sin#le/mode device is a heart rate sensor.

$ual/mode $evices. )hese devices (also known as B-mart !eadC devices) include both
Bluetooth low ener# technolo# and 8lassic Bluetooth technolo#. $ual/mode devices
will rarel #ain in power savin# because the need to support both technolo#
implementations< the power savin#s will onl be achieved with the sin#le/mode option.
6 tpical dual/mode device is a mobile phone or P8.
Bluetooth Low Energy vs. Classic Bluetooth(Part 3)
Bluetooth .2 Core Specification
:a,ers
Bluetooth low ener# / Profile developmentB

What is a profile?

Bluetooth low ener# profile

=ow to create a Bluetooth low ener# profiles

+akin# Bluetooth low ener# devices


B7( D What is a profile?

Wh the are needed?


D )o make devices interoperable

=ow profiles are created?


D Based on markets needs

Who is makin# them?


D +ember companies of Bluetooth -5E under workin# #roups
8an be a slow process.
D What if companies or even individuals could make profiles
b themselves if market demands for it?
Profiles in Bluetooth B!(basic rate)'($!(enhanced data rate)

D -pecifies low level protocol (7&86P, !28>++, -8>)

D -pecified hi#h level protocol (6)/commands, 5r>B(?, -B8

codec)

D Proprietar profiles closed (tpicall runnin# on top of

!28>++)

Profile are essentiall a lar#e concept


D 5nvolves ver detailed and lar#e specifications
specification work takes time
D 5mplementation and testin# slow process
adaption of new profiles takes time
D -pecifies data structures
D Fo definition of protocol needed
,sed over a sin#le protocol (6)))

Profiles re"uire ver little specification to be written


D Profiles can be described usin# ?+7 schema
,nified structure for interpretin# the data specified b profiles
Profiles can be downloaded from 5nternet
D Proprietar profiles can be adopted'interpreted b others easil
Bluetooth lo# energ, profile

Bluetooth low ener# profiles are li#htwei#ht


D 6none can create a new profile
D -mall profile footprint makes it usable in applications with memor constraints

Bluetooth low ener# profiles are reusable


D Fo need to rewrite complete profiles
5nclude services from e.istin# profiles
(.tend with the features ou need
Bluetooth lo# energ, profile
Ho# to create Bluetooth lo# energ,
profiles;
6ll profiles build on top of
D 7&86P
-e#mentation and reassembl of packets
D 6))
6bilit to read'write attribute values
D E6))
Eroupin# of attributes as services
*ttri-ute )rotocol %*TT )art !&
)he onl protocol used in Bluetooth low
ener#
,ses client server architecture

servers store data

clients re"uest data from server

clients writes data to server


Protocol +ethods

8lient to serverA !ead, write

-erver to clientA Fotif, indicate


)he data is e.posed as attributes

6ttributes have values

0 to G1& octets

2i.ed or variable len#th

6ttributes have handles

,sed to address individual attributes

!ead 0.00&& /H 0.01


*ttri-ute )rotocol %*TT )art 2&
6ttributes have a tpe

5dentified b ,,5$s

,,5$s are 1I bit or 1&4 bit

)pes are defined is specifications

8haracteristics specifications

Eeneric 6ccess Profile

Eeneric 6ttribute Profile


*ttri-ute )rotocol %*TT )art 0&

6ttributes have permissionsA

!eadable ' not readable

Writeable ' not writeable

!eadable J writeable ' not readable


J not writeable

6ttribute values ma re"uireA

6uthentication to read ' write

6uthori:ation to read ' write

(ncrption ' pairin# to read ' write

)hese are defined in Bluetooth 7( profile


specifications
6ttribute Protocol is stateless

)ransactionsA

!e"uest /H !esponse

8ommand

Fotification

5ndication /H 8onfirmation

6ttribute Protocol is se"uential

>nl one re"uest at a time


*ttri-ute )rotocol %*TT )art 2&
Attri'ute o(erations) read
D 8lient re"uests data when it needs it
D 8lient polls server for attribute value
D )his ma be inefficient if data doesnt
chan#e often
D -houldnt be used for fre"uentl chan#in#
data that ou are monitorin#
Attri'ute o(erations) write
D 8lient can set attributes to confi#ure a server
D (.#. set the room temperature to &&K8
Attri'ute o(erations) notify
D -erver sends the data when it chan#es
Attri'ute o(erations) indi*ate
D -erver sends the data when it chan#es
D 8lient confirms that is has received the data
*ttri-ute )rotocol %*TT )art "&
E6))
3*TT is an acron,' for the 3eneric *ttri-ute )rofile1 and it defines the #a, that t#o
Bluetooth
:o# Energ, de.ices transfer data -ac$ and forth using concepts called Ser.ices and
Characteristics It 'a$es use of a generic data protocol called the *ttri-ute )rotocol
%*TT&1 #hich is used to store Ser.ices1 Characteristics and related data in a si'ple loo$up
ta-le using !<--it IDs for each entr, in the ta-le
3*TT co'es into pla, once a dedicated connection is esta-lished -et#een t#o de.ices1
'eaning that ,ou ha.e alread, gone through the ad.ertising process go.erned -, 3*)
The 'ost i'portant thing to $eep in 'ind #ith 3*TT and connections is that connections
are
e9clusi.e (hat is 'eant -, that is that a B:E peripheral can onl, -e connected to
one central de.ice %a 'o-ile phone1 etc& at a ti'e= *s soon as a peripheral
connects to a central de.ice1 it #ill stop ad.ertising itself and other de.ices #ill no longer
-e
a-le to see it or connect to it until the e9isting connection is -ro$en
Esta-lishing a connection is also the onl, #a, to allo# t#o #a, co''unication1 #here the
central de.ice can send 'eaningful data to the peripheral and .ice .ersa
Eeneric attribute profile
Attri'ute Proto*ol is +ust a flat stru*ture
D Profiles re"uire hierarchical structures

Same *lient server ar*hite*ture as in A%%,
e-*e(t)
D $ata is encapsulated in services
D $ata is e.posed in characteristics
The 3*TT defines a fra'e#or$ that uses
the *TT for the disco.er, of ser.ices1 and
the e9change of characteristics fro' one
de.ice to another
* characteristic is a set of data #hich
includes a .alue and properties The data
related to ser.ices and characteristics are
stored in attri-utes 7or e9a'ple1 a
ser.er that runs a >te'perature sensor?
ser.ice 'a, account #ith a >te'perature?
characteristic that uses an attri-ute for
descri-ing the sensor1 another attri-ute
for storing te'perature 'easure'ent
.alues and a further attri-ute for
specif,ing the 'easure'ent units
Eeneric attribute profile(Part &)
Eeneric attribute profile(Part *)
-ervices
Are a *olle*tion of *hara*teristi*s
.as an //0"
D Eeneric 6ccess 1400
D $evice 5nformation 1406
D =eart !ate 140$
D Proprietar services have 1&4 bit ,,5$
8an be #enerated online A www.uuid#enerator.com
Primary Servi*e
D (.poses primar usable functionalit of this device
D 8an be included b another service
Se*ondary Servi*e
D 5s subservient to another secondar service or primar
service
D 5s onl relevant in the conte.t of another service
Ser.ices are used to -rea$
data up into logic entities1 and
contain specific chun$s of data
called
characteristics * ser.ice can
ha.e one or 'ore
characteristics1 and each
ser.ice distinguishes
itself fro' other ser.ices -,
'eans of a uni6ue nu'eric ID
called a @@ID1 #hich can -e
either
!<--it %for officiall, adopted
B:E Ser.ices& or !28--it %for
custo' ser.ices&
E6)) services
8haracteristic(Part 1)
1hara*teristi* "e*laration
$escribes the properties of characteristic value (read, write, indicate etc.), characteristic value
handle and characteristic value tpe (,,5$)

1hara*teristi* 2alue
8ontains the value of the characteristic.
1hara*teristi* "es*ri(tor3s4
Provide additional information about the characteristic (characteristic user description,
characteristic client confi#uration, vendor specific information etc.)
//0" for ea*h *hara*teristi* ty(e
D $evice name &600
D $ate time &604
D )emperature in 8elsius &612
D Proprietar characteristics a#ain have 1&4/bit ,,5$

5ou *an use already s(e*ified *hara*teristi*s
D httpA''developer.bluetooth.or#
D +akes profile development faster
D 6llows better interoperabilit
8haracteristic(Part &)
Profile vs -ervices
!a6ing BLE ena'led devi*e
Lou need
D Bluetooth low ener# radio
D Bluetooth low ener# stack
D 6 Profile for our application

What if there is no profile that would suit our
needs?
D +ake our own oneM
!a6ing your own (rofile
What information do ou want to transfer
D -ensor readin#s
D Ne presses
D 6larms
5s there an e.istin# service for some of the features?
httpsA''developer.Bluetooth.or#'#att'services
5s there an e.istin# characteristic for measurements?
httpsA''developer.Bluetooth.or#'#att'characteris
tics
-treamin# or read once?
D 5ndicate or Fotif or !ead
5s securit re"uired?
5a$ing Bluetooth lo# energ, de.ices
)hermometer e.ample
5nformation (E6P) 1400 (Primar service)
D $evice name &600 (8haracteristic)
!eadable, constant
D 6ppearance &601 (8haracteristic)
!eadable, constant
?+7 description
=ealth )hermometer 140O (Primar service)
D 8elsius temperature &a18 (8haracteristic)
5ndicate

?+7 description
)hermometer ?+7 schema
Blue%ooth

Wireless networkin# technolo#

7imited broadcast ran#e (P 10 meters)

(.ample uses include

8onnectin# headsets to phones, keboard'mouse


to desktop computer, medical devices to
controllers, etc.
Bluetooth 3*ont.4

-ome ke classesA

Bluetooth6dapter / )he local Bluetooth radio

Bluetooth$evice / 6 remote Bluetooth


device

Bluetooth-erver-ocket / 6n open server


socket that listens for incomin# re"uests

Bluetooth-ocket / 8ommunication endpoint


Bluetooth Permissions

android.permission.B7,()>>)=

6llow connections J data transfer

android.permission.B7,()>>)=Q6$+5F

)urn on Bluetooth radio J discover local devices


Bluetooth /sage

-et up Bluetooth

2ind devices
alread paired or
available in the
local area

8onnect devices
via a
Bluetooth-ocket

)ransfer data
BluetoothAda(ter

Eet Bluetooth6dapter instance with

Bluetooth6dapter.#et$efault6dapter()<
A
!eturns null if Bluetooth is not available

8heck whether Bluethooth is enabled with

Bluetooth6dapter.is(nabled()
A
!eturns true if Bluetooth is on< false otherwise
BluetoothAda(ter 3*ont.4

8an use built/in 5ntent to enable Bluetooth

Bluetooth6dapter.68)5>FQ!(R,(-)Q(F6B7(

Presents users a dialo# askin# whether the


#ive permission for Bluetooth to be enabled
7et BluetoothAda(ter
public class $ata)ransfer6ctivit e.tends 6ctivit S
T
public void on8reate(Bundle saved5nstance-tate) S
T
mBluetooth6dapter U Bluetooth6dapter.#et$efault6dapter()<
if (mBluetooth6dapter UU null) S
'' Fo Bluetooth support
finish()<
V
T
Ena'le Bluetooth
T
if (MmBluetooth6dapter.is(nabled()) S
5ntent enableBluetooth5ntent U
new 5ntent(Bluetooth6dapter.68)5>FQ!(R,(-)Q(F6B7()<
start6ctivit2or!esult(
enableBluetooth5ntent,!(R,(-)Q(F6B7(QB))<
V
T
8inding "evi*es

Paired devices are devices that have alread


consented to interact with the local device

Bluetooth6dapter.#etBonded$evices()<

8an discover new devices with

Bluetooth6dapter.start$iscover()<

!emote devices must be discoverable


A
+ust #o throu#h pairin# process

8an stop discover process with

Bluetooth6dapter.cancel$iscover()
8ind 9 Sele*t "evi*e
private void select-erver() S
-etPBluetooth$eviceH paired$evices U
mBluetooth6dapter.#etBonded$evices()<
6rra7istP-trin#H paired$evice-trin#s U new 6rra7istP-trin#H()<
if (paired$evices.si:e() H 0) S
for (Bluetooth$evice device A paired$evices) S
paired$evice-trin#s.add(device.#etFame() 9 WXnC 9 device.#et6ddress())<
V
V
5ntent show$evices5ntent U new 5ntent(this, -how$evices.class)<
show$evices5ntent.put-trin#6rra7ist(.tra(WdevicesW, paired$evice-trin#s)<
start6ctivit2or!esult(show$evices5ntent, -(7(8)Q-(!@(!)<
V
8ind 9 Sele*t "evi*e 3*ont.4
public class -how$evices e.tends 7ist6ctivit S
T
protected void on8reate(Bundle saved5nstance-tate) S
T
'' search for more devices
mBluetooth6dapter.start$iscover()<
T
'' user selects one device
Bluetooth$evice device U
mBluetooth6dapter.#et!emote$evice('Y mac addr -trin# Y')<
5ntent data U new 5ntent()<
data.put(.tra(Bluetooth$evice.(?)!6Q$(@58(, device)<
set!esult(!(-,7)Q>N, data)<
finish()<
T
"evi*e "is*overy

5ntent broadcast on device discover

Bluetooth$evice.68)5>FQ2>,F$

$evice info contained in Bluetooth$evice


instance

intent.#etParcelable(.tra(
Bluetooth$evice.(?)!6Q$(@58()
"evi*e "is*overy 3*ont.4
final Broadcast!eceiver m!eceiver U new Broadcast!eceiver() S
public void on!eceive(8onte.t conte.t, 5ntent intent) S
-trin# action U intent.#et6ction()<
if (Bluetooth$evice.68)5>FQ2>,F$.e"uals(action)) S
Bluetooth$evice device U intent
.#etParcelable(.tra(Bluetooth$evice.(?)!6Q$(@58()<
'' update displa
V
V
V<
1onne*ting "evi*es

8lient J server need the same ,,5$

1&4/bit ,niversall ,ni"ue 5dentifier

+an freel/available #enerators e.ist

8lient creates
BluetoothServerSo*6et

-erver creates Bluetooth-erver-ocket with

Bluetooth6dapter
.listen,sin#!fcommWith-ervice!ecord(name, uuid)

7isten for incomin# connection with


Bluetooth-erver-ocket.accept()

!eturns a Bluetooth-ocket on connection


BluetoothServerSo*6et
class 6ccept)hread e.tends )hread S
public 6ccept)hread(=andler handler) S
T
tr S
m-erver-ocket U mBluetooth6dapter
.listen,sin#!fcommWith-ervice!ecord(WBluetooth $emoW,
$ata)ransfer6ctivit.APP_UUID);
V catch (5>(.ception e) SV
V
T
BluetoothServerSo*6et 3*ont.4
T
public void run() S
while (true) S
tr S
mBluetooth-ocket U m-erver-ocket.accept()<
mana#e8onnected-ocket()<
m-erver-ocket.close()<
break<
V catch (5>(.ception e1) S T V
V
V
T
BluetoothSo*6et

8lient creates a Bluetooth-ocket with

Bluetooth$evice
.create!fcomm-ocket)o-ervice!ecord(uuid)

+ake connection on Bluetooth-ocket with

Bluetooth-ocket.connect()
BluetoothSo*6et 3*ont.4
public class 8onnect)hread e.tends )hread S
T
public 8onnect)hread(-trin# device5$, =andler handler) S
m$evice U mBluetooth6dapter.#et!emote$evice(device5$)<
tr S
mBluetooth-ocket U m$evice
.create!fcomm-ocket)o-ervice!ecord($ata)ransfer6ctivit.6PPQ,,5$)<
V catch (5>(.ception e) S T V
V
T
BluetoothSo*6et 3*ont.4
public void run() S
mBluetooth6dapter.cancel$iscover()<
tr S
mBluetooth-ocket.connect()<
mana#e8onnected-ocket()<
V catch (5>(.ception connect(.ception) S T V
V
"ata %ransfer
private void mana#e8onnected-ocket() S
8onnection)hread conn U
new 8onnection)hread(mBluetooth-ocket, m=andler)<
m=andler.obtain+essa#e(
$ata)ransfer6ctivit.->8N()Q8>FF(8)($, conn)
.send)o)ar#et()<
conn.start()<
V
"ata %ransfer 3*ont.4
public class 8onnection)hread e.tends )hread S
T
8onnection)hread(Bluetooth-ocket socket, =andler handler)S
super()<
mBluetooth-ocket U socket<
m=andler U handler<
tr S
m5n-tream U mBluetooth-ocket.#et5nput-tream()<
m>ut-tream U mBluetooth-ocket.#et>utput-tream()<
V catch (5>(.ception e) S T V
V
T
"ata %ransfer 3*ont.4
T
public void run() S
bteZ[ buffer U new bteZ10&1[<
int btes<
while (true) S
tr S
btes U m5n-tream.read(buffer)<
-trin# data U new -trin#(buffer, 0, btes)<
m=andler.obtain+essa#e(
$ata)ransfer6ctivit.$6)6Q!(8(5@($,data).send)o)ar#et()<
V catch (5>(.ception e) S break< V
V
V
T
"ata %ransfer 3*ont.4
T
public void write(bteZ[ btes) S
tr S
m>ut-tream.write(btes)<
V catch (5>(.ception e) S T V
V
V
"ata %ransfer 3*ont.4
'' =andler in $ata)ransfer6ctivit
public =andler m=andler U new =andler() S
public void handle+essa#e(+essa#e ms#) S
switch (ms#.what) S
case SOCKET_CONNECTED: {
mBluetooth8onnection U (8onnection)hread) ms#.ob3<
if (Mm-erver+ode)
mBluetooth8onnection.write(Wthis is a messa#eW.#etBtes())<
break<
V
case DATA_RECEIVED: {
data U (-trin#) ms#.ob3<
tv.set)e.t(data)<
if (m-erver+ode)
mBluetooth8onnection.write(data.#etBtes())<
V
T

Vous aimerez peut-être aussi