Buscar..


Observaciones

Documentación

Notas

  • Windows 10 solo puede actuar en modo central, por lo que solo puede conectarse a dispositivos que admiten el modo periférico. Debido a esto, dos dispositivos con Windows 10 no pueden conectarse a través de Bluetooth LE.
  • Windows 10 debe estar emparejado con un dispositivo Bluetooth LE para poder conectarse a él.

Configuración inicial

Para usar cualquier funcionalidad de Bluetooth en una aplicación de la Plataforma Universal de Windows, debe verificar la capacidad de Bluetooth en el Package.appxmanifest .

  1. Abrir Package.appxmanifest
  2. Ir a la pestaña de Capabilities
  3. Encuentre Bluetooth a la izquierda y marque la casilla junto a él.

Crear un anuncio de Bluetooth LE

Este ejemplo muestra cómo anunciar una carga útil personalizada desde un dispositivo Windows 10 en primer plano. La carga útil utiliza una empresa inventada (identificada como 0xFFFE) y anuncia la cadena Hello World en el anuncio.

BluetoothLEAdvertisementPublisher publisher = new BluetoothLEAdvertisementPublisher();

// Add custom data to the advertisement
var manufacturerData = new BluetoothLEManufacturerData();
manufacturerData.CompanyId = 0xFFFE;

var writer = new DataWriter();
writer.WriteString("Hello World");

// Make sure that the buffer length can fit within an advertisement payload (~20 bytes). 
// Otherwise you will get an exception.
manufacturerData.Data = writer.DetachBuffer();

// Add the manufacturer data to the advertisement publisher:
publisher.Advertisement.ManufacturerData.Add(manufacturerData);

publisher.Start();

Nota: Esto es solo para publicidad en primer plano (mientras la aplicación está abierta).

Escuche un anuncio de Bluetooth LE

Escucha general

Este ejemplo muestra cómo escuchar un anuncio específico.

BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();

// Use active listening if you want to receive Scan Response packets as well
// this will have a greater power cost.
watcher.ScanningMode = BluetoothLEScanningMode.Active;

// Register a listener, this will be called whenever the watcher sees an advertisement. 
watcher.Received += OnAdvertisementReceived;

watcher.Start();

Filtro de publicidad: escucha de un anuncio específico

A veces quieres escuchar un anuncio específico. En este caso, escuche un anuncio que contenga una carga útil con una compañía inventada (identificada como 0xFFFE) y que contenga la cadena Hello World en el anuncio. Esto se puede combinar con el ejemplo de Crear un anuncio de Bluetooth LE para que una máquina con Windows publique y otra escuche.

Nota: ¡Asegúrese de configurar este filtro de publicidad antes de iniciar su observador!

var manufacturerData = new BluetoothLEManufacturerData();
manufacturerData.CompanyId = 0xFFFE;

// Make sure that the buffer length can fit within an advertisement payload (~20 bytes). 
// Otherwise you will get an exception.
var writer = new DataWriter();
writer.WriteString("Hello World");
manufacturerData.Data = writer.DetachBuffer();

watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);

Filtro de señal: escucha para anuncios de proximidad

A veces, solo desea activar su observador cuando la publicidad del dispositivo está dentro del alcance. Puede definir su propio rango, solo tenga en cuenta que los valores normales están entre 0 y -128.

// Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm 
// will start to be considered "in-range" (callbacks will start in this range).
watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70;

// Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction 
// with OutOfRangeTimeout to determine when an advertisement is no longer 
// considered "in-range".
watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75;

// Set the out-of-range timeout to be 2 seconds. Used in conjunction with 
// OutOfRangeThresholdInDBm to determine when an advertisement is no longer 
// considered "in-range"
watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000);

Devoluciones de llamada

watcher.Received += OnAdvertisementReceived;
watcher.Stopped += OnAdvertisementWatcherStopped;

private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    // Do whatever you want with the advertisement

    // The received signal strength indicator (RSSI)
    Int16 rssi = eventArgs.RawSignalStrengthInDBm;
}


private async void OnAdvertisementWatcherStopped(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs)
{
    // Watcher was stopped
}

Nota: Esto es solo para escuchar en primer plano.

Juzgar la distancia según el RSSI de un anuncio de Bluetooth LE

Cuando se activa la devolución de llamada de su Bluetooth LE Watcher, eventArgs incluye un valor RSSI que le indica la intensidad de la señal recibida (qué tan fuerte es la respuesta).

private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    // The received signal strength indicator (RSSI)
    Int16 rssi = eventArgs.RawSignalStrengthInDBm;
}

Esto puede traducirse aproximadamente a la distancia, pero no debe usarse para medir distancias reales ya que cada radio individual es diferente. Diferentes factores ambientales pueden hacer que la distancia sea difícil de medir (como paredes, cajas alrededor de la radio o incluso humedad del aire).

Una alternativa para juzgar la distancia pura es definir "cubos". Las radios tienden a reportar de 0 a -50 DBm cuando están muy cerca, de -50 a -90 cuando están a una distancia media, y por debajo de -90 cuando están lejos. La prueba y el error son los mejores para determinar qué desea que sean estos depósitos para su aplicación.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow