首页 > 解决方案 > UWP 如何检查来自 BLE 设备的传入请求?

问题描述

如何检查从配对 BLE 设备到当前设备的所有传入请求?

我认为事件是可能的,也许 UWP 有针事件,或者我必须实现自定义事件,但是正确的方法在哪里?

微软有关于GATT Server的解释,我认为这不是我需要的,因为我不需要具有服务和特性的服务器,我只需要检查传入的请求并解析我的应用程序中传递的数据。

标签: bluetoothuwpbluetooth-lowenergygattbluetooth-gatt

解决方案


我没有找到检查传入请求的确定方法,但我做了一些技巧。应用程序可以订阅来自设备的通知(在我的情况下是 Mi Band 2),并通过 ValueChanged 从该设备接收一些数据。有一次我在连接和配对设备后调用 App.xaml.cs 中的 ValueChanged 处理程序,这适用于所有应用程序,我不需要一次又一次地调用它。

这是 App.xaml.cs 代码的一部分。

    protected async override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        MiBand2SDK.MiBand2 band = new MiBand2SDK.MiBand2();
        var page = typeof(Views.AuthPage);

        // Checking for device availability and current session
        if (_LocalSettings.Values["isAuthorized"] != null 
            && await band.ConnectAsync())
        {
            if (e.PreviousExecutionState == ApplicationExecutionState.NotRunning && await band.Auth.AuthenticateAsync())
                page = typeof(Views.MainPage);
            else if (band.Auth.IsAuthenticated())
                page = typeof(Views.MainPage);

            // Here we are, this notification handler of responses from the band.
            band.HeartRate.SetNotificationHandler();
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Not Authenticated...");
        }
       // other part of code...

这是 HeartRate.SetNotificationHandler() 代码:

    public async void SetNotificationHandler()
    {
        _heartRateMeasurementCharacteristic = await Gatt.GetCharacteristicByServiceUuid(HEART_RATE_SERVICE, HEART_RATE_MEASUREMENT_CHARACTERISTIC);

        Debug.WriteLine("Subscribe for HeartRate notifications from band...");
        if (await _heartRateMeasurementCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify) == GattCommunicationStatus.Success)
            // Just subscribe for notifications and set ValueChanged. It's all.
            _heartRateMeasurementCharacteristic.ValueChanged += HeartRateMeasurementCharacteristicValueChanged;
    }

希望它可以帮助某人...


推荐阅读