Вы находитесь на странице: 1из 12

BLE y WIFI

Francisco Javier Castañeta Mancilla


Universidad Mayor de San Andrés, Bolivia
Junio 11, 2019

Resumen
El manejo de tecnologia bluetooth es imperativo al momento de rea-
lizar conexiones de manera rapida entre dispositivos en este documento
analizaremos los beneficios de el manejo del BLE o Bluetooth de baja
energia, posteriormente se hara un analisis de la libreria WIFI.h para la
elaboracion de futuros proyectos

1. BLE
El ESP32 no solo viene con Wi-Fi sino también con Bluetooth y Bluetooth
de baja energı́a (BLE). Esta es una introducción rápida a BLE con el ESP32.
Primero, exploraremos qué es BLE y para qué se puede usar, y luego echare-
mos un vistazo a algunos ejemplos con el ESP32 utilizando Arduino IDE. Para
una introducción simple, crearemos un servidor BLE ESP32 y un escáner BLE
ESP32 para encontrar ese servidor. Bluetooth Low Energy, BLE para abreviar,
es una variante de Bluetooth que ahorra energı́a. La aplicación principal de
BLE es la transmisión a corta distancia de pequeñas cantidades de datos (bajo
ancho de banda). A diferencia de Bluetooth que siempre está encendido, BLE
permanece en modo de suspensión constantemente, excepto cuando se inicia
una conexión.Esto hace que consuma muy poca potencia. BLE consume apro-
ximadamente 100 veces menos energı́a que Bluetooth (según el caso de uso).
Ademas que esta pensado para ser usado en topologias tipo punto a punto o
broadcasting.

1.1. GATT
GATT significa atributos genéricos y define una estructura de datos jerárqui-
ca que está expuesta a dispositivos BLE conectados. Esto significa que GATT
define la forma en que dos dispositivos BLE envı́an y reciben mensajes estándar.
Comprender esta jerarquı́a es importante, ya que hará que sea más fácil entender
cómo usar BLE y escribir sus aplicaciones.

1
Figura 1: Jeraraquias del UUID dentro del GATT

1.2. Servicio BLE


El nivel superior de la jerarquı́a es un perfil, que se compone de uno o más
servicios. Por lo general, un dispositivo BLE contiene más de un servicio.
Cada servicio contiene al menos una caracterı́stica, o también puede ha-
cer referencia a otros servicios. Un servicio es simplemente una recopilación de
información, como las lecturas de sensores, por ejemplo.
Existen servicios predefinidos para varios tipos de datos definidos por el
SIG (Grupo de Interés Especial de Bluetooth) como: Nivel de baterı́a, Presión
arterial, Ritmo cardı́aco, Escala de peso, etc.

Figura 2: Servicios que puede empeñar el BLE

2
1.3. Caracterı́stica BLE
La caracterı́stica siempre es propiedad de un servicio, y es donde los datos
reales están contenidos en la jerarquı́a (valor). La caracterı́stica siempre tiene
dos atributos: declaración de caracterı́stica (que proporciona metadatos sobre
los datos) y el valor de caracterı́stica. Además, el valor de la caracterı́stica puede
ir seguido de descriptores, que amplı́an aún más los metadatos contenidos en
la declaración de la caracterı́stica. Las propiedades describen cómo se puede
interactuar con el valor caracterı́stico. Básicamente, contiene las operaciones y
procedimientos que se pueden usar con la caracterı́stica:

Emisión
Leer

Escribir sin respuesta


Escribir
Notificar
Indicar

Escrituras firmadas autenticadas


Propiedades extendidas

2. UUID
Cada servicio, caracterı́stica y descriptor tiene un UUID (identificador úni-
co universal). Un UUID es un número único de 128 bits (16 bytes). Por ejemplo:

55072829-bc9e-4c53-938a-74a6d4c78776

Hay UUID abreviados para todos los tipos, servicios y perfiles especificados
en el SIG (Grupo de Interés Especial de Bluetooth) .

Pero si su aplicación necesita su propio UUID, puede generarlo utilizando


este sitio web del generador de UUID .

En resumen, el UUID se utiliza para identificar información de manera úni-


ca. Por ejemplo, puede identificar un servicio particular proporcionado por un
dispositivo Bluetooth.

3
3. Programa para el manejo BLE en el ESP 32

#include <BLEDevice . h>


#include <BLEServer . h>
#include <BLEUtils . h>
#include <BLE2902 . h>

B L E C h a r a c t e r i s t i c ∗ c h a r a c t e r i s t i c T X ; // A t r a v e z de e s t e o b j e t o s e

b o o l d e v i c e C o n n e c t e d = f a l s e ; // c o n t r o l de d i s p o s i t i v o c o n e c t a d o

const int LED = 2 ; //LED i n t e r n o d e l ESP32

const int BUZZER = 2 3 ; // p i n d e l BUZZER

#define SERVICE UUID ” 0000180D−0000−1000−8000−00805 f 9 b 3 4 f b ”


#define CHARACTERISTIC UUID RX ” 00002A37−0000−1000−8000−00805 f 9 b 3 4 f b ”
#define CHARACTERISTIC UUID TX ” 0000180D−0000−1000−8000−00805 f 9 b 3 4 f b ”

// c a l l b a c k para r e c e b i r l o s e v e n t o s de c o n e x i o n de d i s p o s i t i v o s
c l a s s S e r v e r C a l l b a c k s : p u b l i c BLEServerCallbacks {
void onConnect ( BLEServer ∗ p S e r v e r ) {
deviceConnected = true ;
};

void o n D i s c o n n e c t ( BLEServer ∗ p S e r v e r ) {
deviceConnected = f a l s e ;
}
};

// c a l l b a c k para e n v e n t o s de l a s c a r a c t e r i s t i c a s
c l a s s CharacteristicCallbacks : public BLECharacteristicCallbacks {
void onWrite ( B L E C h a r a c t e r i s t i c ∗ c h a r a c t e r i s t i c ) {
// r e t o r n a p u n t e r o para e l r e g i s t r a d o r c o n t e n i e n d o e l v a l o r
a c t u a l de l a c a r a c t e r i s t i c a
s t d : : s t r i n g rxValue = c h a r a c t e r i s t i c −>g e t V a l u e ( ) ;
// v e r i f i c a s i e x i s t e d a t o s ( tamano mayor que c e r o )
i f ( rxValue . l e n g t h ( ) > 0 ) {
S e r i a l . p r i n t l n ( ” ∗∗∗∗∗∗∗∗∗ ” ) ;

4
S e r i a l . p r i n t ( ” R e c e i v e d Value : ” ) ;

f o r ( int i = 0 ; i < rxValue . l e n g t h ( ) ; i ++) {


S e r i a l . p r i n t ( rxValue [ i ] ) ;
}

Serial . println ();

// Accion g e n e r a d a cuando s e r e c i b e e l comando a s i g n a d o


i f ( rxValue . f i n d ( ”L1” ) != −1) {
S e r i a l . p r i n t ( ”Led Encendido ! ” ) ;
d i g i t a l W r i t e (LED, HIGH ) ;
}
e l s e i f ( rxValue . f i n d ( ”L0” ) != −1) {
S e r i a l . p r i n t ( ”Led Apagado ! ” ) ;
d i g i t a l W r i t e (LED, LOW) ;
}
// Accion g e n e r a d a cuando s e r e c i b e e l comando a s i g n a d o
e l s e i f ( rxValue . f i n d ( ”B1” ) != −1) {
S e r i a l . p r i n t ( ” Buzzer Encendido ! ” ) ;
d i g i t a l W r i t e (BUZZER, HIGH ) ;
}
e l s e i f ( rxValue . f i n d ( ”B0” ) != −1) {
S e r i a l . p r i n t ( ” Buzzer Apagado ! ” ) ;
d i g i t a l W r i t e (BUZZER, LOW) ;
}

Serial . println ();


S e r i a l . p r i n t l n ( ” ∗∗∗∗∗∗∗∗∗ ” ) ;
}
}
};

void s e t u p ( ) {
S e r i a l . begin (115200);

pinMode (LED, OUTPUT) ;


pinMode (BUZZER, OUTPUT) ;

// C r e a t e t h e BLE D e vi c e
BLEDevice : : i n i t ( ”ESP32−BLE” ) ; // Nombre d e l d i s p o s i t i v o B l u e t o o t h
// C r e a t e t h e BLE S e r v e r
BLEServer ∗ s e r v e r = BLEDevice : : c r e a t e S e r v e r ( ) ; // c r e a un BLE s e r v e r
s e r v e r −>s e t C a l l b a c k s ( new S e r v e r C a l l b a c k s ( ) ) ; // a c t i v a c a l l b a c k d e l s e r v e r
// C r e a t e t h e BLE S e r v i c e
BLEService ∗ s e r v i c e = s e r v e r −>c r e a t e S e r v i c e (SERVICE UUID ) ;

5
// C r e a t e a BLE C h a r a c t e r i s t i c para e n v i o de d a t o s
c h a r a c t e r i s t i c T X = s e r v i c e −>c r e a t e C h a r a c t e r i s t i c (CHARACTERISTIC UUID TX,

c h a r a c t e r i s t i c T X −>a d d D e s c r i p t o r ( new BLE2902 ( ) ) ;

// C r e a t e a BLE C h a r a c t e r i s t i c para r e c e b i r d a t o s
B L E C h a r a c t e r i s t i c ∗ c h a r a c t e r i s t i c = s e r v i c e −>c r e a t e C h a r a c t e r i s t i c (
CHARACTERISTIC UUID RX,
B L E C h a r a c t e r i s t i c : : PROPERTY WRITE
);

c h a r a c t e r i s t i c −>s e t C a l l b a c k s ( new C h a r a c t e r i s t i c C a l l b a c k s ( ) ) ;
// S t a r t t h e s e r v i c e
s e r v i c e −>s t a r t ( ) ;
// S t a r t a d v e r t i s i n g ( Muestra e l ESP32 )
s e r v e r −>g e t A d v e r t i s i n g ()−> s t a r t ( ) ;

S e r i a l . p r i n t l n ( ” Esperando c o n e x i o n d e l c l i e n t e . . . ” ) ;

void l o o p ( ) {
// s i e x i s t e algum d i s p o s i t i v o c o n e c t a d o
i f ( deviceConnected ) {

delay (1000);

c h a r a c t e r i s t i c T X 2 −>s e t V a l u e ( ” H e l l o ! ” ) ; // Enviamos un mensaje de p r u eb a


c h a r a c t e r i s t i c T X 2 −>n o t i f y ( ) ; // y l o enviamos a l a a p l i c a c i o n
}
delay (1000);

}
3.0.1. Server Linux y BLE
1. Conecte su dispositivo BLE al raspberry PI.
2. En una terminal inserte el comando hcitooldev.
3. Seguidamente sudohcitoollescan.
4. Utilice sudogatttool − b < BLEADDRESS > −Ipara acceder al disposi-
tivo.
5. Ahora use el comando connect para realizar la conexion.

6
6. Puede ejecutar el comando primary si dese ver el UUID primario.
7. El comando char − desc le mostrara todos los descriptores del BLE.
8. Para leer en el descriptor char − read − hnd < handle >.
9. Para escribir char − write − req < handle >< data >.

4. WIFI
La libreria WIFI es la encargada del ajuste y monitoreo de los procesos del
ESP-32 para WIFI,para ello observaremos dos tipos de conexion wifi que pueden
existir dentro de esta libreria.

4.0.1. AP

/∗
WiFiAccessPoint . i n o c r e a t e s a WiFi a c c e s s p o i n t and p r o v i d e s a web s e r v e r on i

Steps :
1 . Connect t o t h e a c c e s s p o i n t ”yourAp”
2 . P o i n t your web b r o w s e r t o h t t p : / / 1 9 2 . 1 6 8 . 4 . 1 /H t o t u r n t h e LED on or h t t p : /
OR
Run raw TCP ”GET /H” and ”GET /L” on PuTTY t e r m i n a l w i t h 1 9 2 . 1 6 8 . 4 . 1 as IP

Created f o r arduino−e sp 3 2 on 04 J ul y , 2018


by Elochukwu I f e d i o r a ( f e d y 0 )
∗/

#include <WiFi . h>


#include <W iF i C li e n t . h>
#include <WiFiAP . h>

#define LED BUILTIN 2 // S e t t h e GPIO p i n where you c o n n e c t e d your t e s t LED or

// S e t t h e s e t o your d e s i r e d c r e d e n t i a l s .
const char ∗ s s i d = ”yourAP” ;
const char ∗ password = ” yourPassword ” ;

WiFiServer s e r v e r ( 8 0 ) ;

void s e t u p ( ) {
pinMode (LED BUILTIN , OUTPUT) ;

S e r i a l . begin (115200);

7
Serial . println ();
S e r i a l . println (” Configuring access point . . . ” ) ;

// You can remove t h e password parameter i f you want t h e AP t o be open .


WiFi . softAP ( s s i d , password ) ;
IPAddress myIP = WiFi . softAPIP ( ) ;
S e r i a l . p r i n t ( ”AP IP a d d r e s s : ” ) ;
S e r i a l . p r i n t l n ( myIP ) ;
server . begin ( ) ;

S e r i a l . println (” Server started ” ) ;


}

void l o o p ( ) {
W i Fi C li e n t c l i e n t = s e r v e r . a v a i l a b l e ( ) ; // l i s t e n f o r incoming c l i e n t s

if ( client ) { // i f you g e t a c l i e n t ,
S e r i a l . p r i n t l n ( ”New C l i e n t . ” ) ; // p r i n t a message o u t t h e s e r i a l p
S t r i n g currentLine = ”” ; // make a S t r i n g t o h o l d incoming d a
while ( c l i e n t . c o n n e c t e d ( ) ) { // l o o p w h i l e t h e c l i e n t ’ s c o n n e c t e d
if ( client . available ()) { // i f t h e r e ’ s b y t e s t o rea d from t h e
char c = c l i e n t . r e a d ( ) ; // read a b y t e , t h e n
Serial . write ( c ) ; // p r i n t i t o u t t h e s e r i a l monitor
i f ( c == ’ \n ’ ) { // i f t h e b y t e i s a n e w l i n e c h a r a c t e

// i f t h e c u r r e n t l i n e i s b l a n k , you g o t two n e w l i n e c h a r a c t e r s i n a ro
// t h a t ’ s t h e end o f t h e c l i e n t HTTP r e q u e s t , so send a r e s p o n s e :
i f ( c u r r e n t L i n e . l e n g t h ( ) == 0 ) {
// HTTP h e a d e r s a l w a y s s t a r t w i t h a r e s p o n s e code ( e . g . HTTP/ 1 . 1 200
// and a c o n t e n t −t y p e so t h e c l i e n t knows what ’ s coming , t h e n a b l a n
c l i e n t . p r i n t l n ( ”HTTP/ 1 . 1 200 OK” ) ;
c l i e n t . p r i n t l n ( ” Content−type : t e x t / html ” ) ;
client . println ();

// t h e c o n t e n t o f t h e HTTP r e s p o n s e f o l l o w s t h e h e a d e r :
c l i e n t . p r i n t ( ” C l i c k <a h r e f =\”/H\”>here </a> t o t u r n ON t h e LED.<br>”
c l i e n t . p r i n t ( ” C l i c k <a h r e f =\”/L\”>here </a> t o t u r n OFF t h e LED.<br>

// The HTTP r e s p o n s e ends w i t h a n o t h e r b l a n k l i n e :


client . println ();
// b r e a k o u t o f t h e w h i l e l o o p :
break ;
} else { // i f you g o t a n e w l i n e , t h e n c l e a r c u r r e n t L i n e :
currentLine = ”” ;
}
} e l s e i f ( c != ’ \ r ’ ) { // i f you g o t a n y t h i n g e l s e b u t a c a r r i a g e r e t u r

8
c u r r e n t L i n e += c ; // add i t t o t h e end o f t h e c u r r e n t L i n e
}

// Check t o s e e i f t h e c l i e n t r e q u e s t was ”GET /H” or ”GET /L ” :


i f ( c u r r e n t L i n e . endsWith ( ”GET /H” ) ) {
d i g i t a l W r i t e (LED BUILTIN , HIGH ) ; // GET /H t u r n s t h e LED
}
i f ( c u r r e n t L i n e . endsWith ( ”GET /L” ) ) {
d i g i t a l W r i t e (LED BUILTIN , LOW) ; // GET /L t u r n s t h e LED
}
}
}
// c l o s e t h e c o n n e c t i o n :
c l i e n t . stop ( ) ;
S e r i a l . p r i n t l n ( ” Client Disconnected . ” ) ;
}
}
4.0.2. Modo estacion

I f t h e IP a d d r e s s o f your s h i e l d i s yourAddress :
h t t p : // yourAddress /H t u r n s t h e LED on
h t t p : // yourAddress /L t u r n s i t o f f

This example i s w r i t t e n f o r a network u s i n g WPA e n c r y p t i o n . For


WEP o r WPA, change t h e W i f i . b e g i n ( ) c a l l a c c o r d i n g l y .

Circuit :
∗ WiFi s h i e l d a t t a c h e d
∗ LED a t t a c h e d t o p i n 5

c r e a t e d f o r a r d u i n o 25 Nov 2012
by Tom I g o e

ported for sparkfun esp32


3 1 . 0 1 . 2 0 1 7 by Jan Hendrik B e r l i n

∗/

#include <WiFi . h>

const char∗ s s i d = ” yourssid ” ;


const char∗ password = ” yourpasswd ” ;

WiFiServer s e r v e r ( 8 0 ) ;

9
void s e t u p ( )
{
S e r i a l . begin (115200);
pinMode ( 5 , OUTPUT) ; // s e t t h e LED p i n mode

delay ( 1 0 ) ;

// We s t a r t by c o n n e c t i n g t o a WiFi network

Serial . println ();


Serial . println ();
Serial . p r i n t ( ” Connecting t o ” ) ;
Serial . println ( ssid );

WiFi . b e g i n ( s s i d , password ) ;

while ( WiFi . s t a t u s ( ) != WL CONNECTED) {


delay (50 0);
Serial . print (” . ” );
}

Serial . p r i n t l n ( ”” ) ;
Serial . p r i n t l n ( ”WiFi c o n n e c t e d . ” ) ;
Serial . p r i n t l n ( ” IP a d d r e s s : ” ) ;
Serial . p r i n t l n ( WiFi . l o c a l I P ( ) ) ;

server . begin ( ) ;

int v a l u e = 0 ;

void l o o p ( ) {
W iF i C li e n t c l i e n t = s e r v e r . a v a i l a b l e ( ) ; // l i s t e n f o r incoming c l i e n t s

if ( client ) { // i f you g e t a c l i e n t ,
S e r i a l . p r i n t l n ( ”New C l i e n t . ” ) ; // p r i n t a message o u t t h e s e r i a l p
S t r i n g currentLine = ”” ; // make a S t r i n g t o h o l d incoming d a
while ( c l i e n t . c o n n e c t e d ( ) ) { // l o o p w h i l e t h e c l i e n t ’ s c o n n e c t e d
if ( client . available ()) { // i f t h e r e ’ s b y t e s t o rea d from t h e
char c = c l i e n t . r e a d ( ) ; // read a b y t e , t h e n
Serial . write ( c ) ; // p r i n t i t o u t t h e s e r i a l monitor
i f ( c == ’ \n ’ ) { // i f t h e b y t e i s a n e w l i n e c h a r a c t e

// i f t h e c u r r e n t l i n e i s b l a n k , you g o t two n e w l i n e c h a r a c t e r s i n a ro
// t h a t ’ s t h e end o f t h e c l i e n t HTTP r e q u e s t , so send a r e s p o n s e :

10
i f ( c u r r e n t L i n e . l e n g t h ( ) == 0 ) {
// HTTP h e a d e r s a l w a y s s t a r t w i t h a r e s p o n s e code ( e . g . HTTP/ 1 . 1 200
// and a c o n t e n t −t y p e so t h e c l i e n t knows what ’ s coming , t h e n a b l a n
c l i e n t . p r i n t l n ( ”HTTP/ 1 . 1 200 OK” ) ;
c l i e n t . p r i n t l n ( ” Content−type : t e x t / html ” ) ;
client . println ();

// t h e c o n t e n t o f t h e HTTP r e s p o n s e f o l l o w s t h e h e a d e r :
c l i e n t . p r i n t ( ” C l i c k <a h r e f =\”/H\”>here </a> t o t u r n t h e LED on p i n 5
c l i e n t . p r i n t ( ” C l i c k <a h r e f =\”/L\”>here </a> t o t u r n t h e LED on p i n 5

// The HTTP r e s p o n s e ends w i t h a n o t h e r b l a n k l i n e :


client . println ();
// b r e a k o u t o f t h e w h i l e l o o p :
break ;
} else { // i f you g o t a n e w l i n e , t h e n c l e a r c u r r e n t L i n e :
currentLine = ”” ;
}
} e l s e i f ( c != ’ \ r ’ ) { // i f you g o t a n y t h i n g e l s e b u t a c a r r i a g e r e t u r
c u r r e n t L i n e += c ; // add i t t o t h e end o f t h e c u r r e n t L i n e
}

// Check t o s e e i f t h e c l i e n t r e q u e s t was ”GET /H” or ”GET /L ” :


i f ( c u r r e n t L i n e . endsWith ( ”GET /H” ) ) {
d i g i t a l W r i t e ( 5 , HIGH ) ; // GET /H t u r n s t h e LED on
}
i f ( c u r r e n t L i n e . endsWith ( ”GET /L” ) ) {
d i g i t a l W r i t e ( 5 , LOW) ; // GET /L t u r n s t h e LED o f f
}
}
}
// c l o s e t h e c o n n e c t i o n :
c l i e n t . stop ( ) ;
S e r i a l . p r i n t l n ( ” Client Disconnected . ” ) ;
}
}

Referencias
[1] https : //espressif.com/
[2] https : //en.wikipedia.org/wiki/ESP 32
[3] https : //www.bluetooth.com/specif ications/gatt/services/ v

[4] https : //www.arduino.cc/

11
[5] https : //www.jaredwolf f.com/get − started − with − bluetooth − low −
energy

12

Вам также может понравиться