Módulo 3.4

GATT: Intercambio de Datos

Perfil de Atributos Genéricos para comunicación BLE

Santi Scagliusi, PhD

Comenzar arrow_downward
sync_alt
Operaciones
Read, Write, Notify
folder_open
Servicios
Agrupación lógica
description
Características
Valores de datos
notifications
CCCD
Control de notificaciones

Arquitectura Cliente-Servidor

GATT define cómo se intercambian datos entre dispositivos BLE conectados.

smartphone
Cliente GATT
Inicia operaciones
(Típicamente: Central)
Read Write
Notify Indicate
memory
Servidor GATT
Contiene los datos
(Típicamente: Periférico)

upload Operaciones Iniciadas por Cliente

Read Lectura

El cliente solicita el valor actual de una característica. El servidor responde con los datos.

Write Escritura

El cliente envía datos al servidor. Requiere confirmación (ACK) del servidor.

Write w/o resp Escritura sin respuesta

El cliente envía datos sin esperar confirmación. Más rápido pero sin garantía de entrega.

download Operaciones Iniciadas por Servidor

Notify Notificación

El servidor envía datos al cliente sin esperar confirmación. Ideal para datos de sensor en tiempo real.

Indicate Indicación

El servidor envía datos y espera confirmación del cliente. Garantiza entrega pero más lento.

priority_high
Requiere CCCD: El cliente debe habilitar notificaciones/indicaciones escribiendo en el CCCD del servidor.

Notificaciones e Indicaciones

Cómo el servidor envía datos de forma proactiva al cliente.

notifications_active Flujo de Habilitación

  1. 1
    Cliente descubre CCCD

    El CCCD es un descriptor de la característica

  2. 2
    Cliente escribe en CCCD

    0x0001 para notificaciones, 0x0002 para indicaciones

  3. 3
    Servidor puede enviar

    El servidor ahora puede enviar datos cuando cambian

Notificaciones
Sin confirmación (rápido)
0x0001
Indicaciones
Con confirmación (fiable)
0x0002
Notify Notificación
  • check Sin esperar confirmación
  • check Múltiples notificaciones seguidas
  • check Ideal para datos de sensor
  • warning Puede perder datos si hay congestión
Indicate Indicación
  • check Cliente confirma recepción
  • check Entrega garantizada
  • check Ideal para datos críticos
  • warning Una indicación a la vez (más lento)

Estructura de Atributos

Todo en GATT son atributos con una estructura común.

table_rows Componentes de un Atributo

Handle
UUID
Permisos
Valor
0x0001 16-bit
0x2800 Tipo de atributo
R W
Acceso
Variable 0-512 bytes
tag

Handle (Identificador)

  • check Número único de 16 bits (0x0001 - 0xFFFF)
  • check Asignado por el servidor en orden creciente
  • check El cliente usa el handle para acceder al atributo
fingerprint

UUID (Tipo)

  • check Define el tipo/propósito del atributo
  • check 16-bit (SIG) o 128-bit (vendor)
  • check Ejemplos: 0x2800 (Service), 0x2803 (Characteristic)
lock

Permisos

  • check Control de acceso (Read, Write)
  • check Requisitos de seguridad (encriptación)
  • check Nivel de autenticación requerido
data_array

Valor

  • check Los datos reales del atributo
  • check Tamaño variable (0-512 bytes)
  • check Formato definido por el UUID

UUIDs: Identificadores Únicos

Los UUIDs identifican servicios, características y descriptores.

verified

UUID SIG (16-bit)

Definidos por Bluetooth SIG para servicios y características estándar.

0000XXXX-0000-1000-8000-00805F9B34FB

Los 16 bits se insertan en la base UUID de Bluetooth

0x2800 Primary Service
0x2803 Characteristic Declaration
0x2902 CCCD
0x180F Battery Service
extension

UUID Vendor (128-bit)

UUIDs personalizados para servicios propietarios. Generados aleatoriamente.

00001523-1212-EFDE-1523-785FEABCD123

128 bits completos - garantiza unicidad

lightbulb
Nordic LBS UUID:
00001523-1212-EFDE-1523-785FEABCD123

Usa un generador de UUIDs online para crear los tuyos. Asegúrate de que la base sea única para tu empresa/proyecto.

Servicios GATT

Los servicios agrupan características relacionadas funcionalmente.

folder_open Estructura de un Servicio

0x2800 Primary Service Declaration

El valor contiene el UUID del servicio (16 o 128 bits).

Valor del atributo:
UUID del servicio
0x2801 Secondary Service

Servicio auxiliar incluido por otro servicio. Raramente usado.

category Servicios Estándar Comunes

Battery Service 0x180F

Nivel de batería del dispositivo

Heart Rate Service 0x180D

Datos de frecuencia cardíaca

Device Information 0x180A

Información del fabricante, modelo, etc.

Nordic LBS 128-bit

LED Button Service - ejemplo de Nordic

Características y Descriptores

Las características contienen los valores de datos reales.

account_tree Estructura de una Característica

folder
Service Declaration
UUID: 0x2800 | Value: Service UUID
description
Characteristic Declaration
UUID: 0x2803 | Value: Properties + Handle + Char UUID
data_object
Characteristic Value
UUID: Char UUID | Value: Datos reales
tune
CCCD (Descriptor)
UUID: 0x2902 | Value: 0x0000/0x0001/0x0002
info
User Description (Opcional)
UUID: 0x2901 | Value: "Temperature"

settings Propiedades de Característica

Definen qué operaciones soporta la característica.

0x02 Read Cliente puede leer
0x08 Write Cliente puede escribir
0x04 Write w/o Sin respuesta
0x10 Notify Servidor puede notificar
0x20 Indicate Servidor puede indicar

label Descriptores Comunes

CCCD 0x2902

Client Characteristic Configuration Descriptor. Habilita notificaciones/indicaciones.

User Description 0x2901

Descripción legible de la característica. Útil para debugging.

Presentation Format 0x2904

Formato del valor (uint8, float, etc.), unidades y exponente.

CCCD en Detalle

El descriptor más importante para comunicación bidireccional.

notifications Client Characteristic Configuration Descriptor

El CCCD es un valor de 16 bits que el cliente escribe para controlar si el servidor puede enviar notificaciones o indicaciones.

Deshabilitado 0x0000

El servidor no puede enviar datos

Notificaciones 0x0001

Habilita notificaciones (bit 0)

Indicaciones 0x0002

Habilita indicaciones (bit 1)

group CCCD por Cliente

Cada cliente conectado tiene su propio valor de CCCD. El servidor mantiene un valor separado para cada conexión.

smartphone Cliente A 0x0001
tablet Cliente B 0x0000
laptop Cliente C 0x0002
tips_and_updates
Persistencia: El valor del CCCD se puede almacenar en flash (bonding) para que persista entre reconexiones. Usa CONFIG_BT_SETTINGS=y.

Tabla de Atributos: my_lbs

Ejemplo completo del servicio LED Button Service de Nordic.

table_chart Attribute Table - Nordic LBS

Handle UUID Tipo Permisos Valor
0x0010 0x2800 Service Declaration R LBS UUID (128-bit)
0x0011 0x2803 Char Declaration (Button) R Props: Read+Notify
0x0012 Button UUID Char Value (Button) R N 0x00 / 0x01
0x0013 0x2902 CCCD R W 0x0000
0x0014 0x2803 Char Declaration (LED) R Props: Write
0x0015 LED UUID Char Value (LED) W 0x00 / 0x01

touch_app Button Characteristic

  • check Lectura del estado actual del botón
  • check Notificaciones cuando cambia el estado
  • check Valor: 0x00 (no presionado) / 0x01 (presionado)

lightbulb LED Characteristic

  • check Escritura para controlar el LED
  • check Solo escritura (sin lectura ni notificaciones)
  • check Valor: 0x00 (apagado) / 0x01 (encendido)

APIs de Zephyr para GATT

Macros y funciones para definir servicios GATT.

Definición de servicio GATT
/* Definir servicio con macros */ BT_GATT_SERVICE_DEFINE(my_svc, /* Primary Service */ BT_GATT_PRIMARY_SERVICE(&my_uuid), /* Característica con Read + Notify */ BT_GATT_CHARACTERISTIC(&button_uuid, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ, read_button, NULL, NULL), /* CCCD para notificaciones */ BT_GATT_CCC(button_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), /* Característica con Write */ BT_GATT_CHARACTERISTIC(&led_uuid, BT_GATT_CHRC_WRITE, BT_GATT_PERM_WRITE, NULL, write_led, NULL), );
Callbacks de lectura/escritura
/* Callback de lectura */ static ssize_t read_button( struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) { return bt_gatt_attr_read(conn, attr, buf, len, offset, &button_state, sizeof(button_state)); } /* Callback de escritura */ static ssize_t write_led( struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, uint16_t len, uint16_t offset, uint8_t flags) { if (len != 1) return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); uint8_t val = *((uint8_t *)buf); set_led_state(val ? 1 : 0); return len; }

Envío de Notificaciones

Cómo enviar datos de forma proactiva desde el servidor.

Enviar notificaciones
/* Enviar notificación del estado del botón */ int send_button_notification(uint8_t button_state) { return bt_gatt_notify( NULL, // NULL = todas las conexiones &my_svc.attrs[2], // Atributo del valor de característica &button_state, // Datos a enviar sizeof(button_state) // Tamaño de los datos ); } /* Callback cuando cambia el CCCD */ static void button_ccc_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value) { bool notify_enabled = (value == BT_GATT_CCC_NOTIFY); printk("Button notifications %s\n", notify_enabled ? "enabled" : "disabled"); }
BT_GATT_SERVICE_DEFINE()

Macro para definir un servicio GATT completo en tiempo de compilación.

bt_gatt_notify()

Envía una notificación a uno o todos los clientes conectados.

bt_gatt_indicate()

Envía una indicación con callback de confirmación.

bt_gatt_attr_read()

Helper para implementar callbacks de lectura.

BT_GATT_CCC()

Macro para añadir un CCCD a una característica.

bt_gatt_exchange_mtu()

Negocia el MTU con el peer para datos más grandes.

Resumen del Módulo

sync_alt
Cliente-Servidor
Read, Write, Notify, Indicate
folder_open
Servicios
Agrupan características
description
Características
Declaration + Value + Descriptors
notifications
CCCD
Habilita notificaciones
arrow_forward Siguiente módulo

3.5 Seguridad en BLE

Pairing, bonding, encriptación y niveles de seguridad.