C#UWP“订阅价值变化”

时间:2018-05-26 09:44:13

标签: c# uwp bluetooth-lowenergy

private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {

            // BT_Code: An Indicate or Notify reported that the value has changed.
            // Display the new value with a timestamp.
            var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat);
            var message = $"Value at {DateTime.Now:hh:mm:ss}: {newValue}";
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => CharacteristicLatestValue.Text = message);
        }

这是来自github的示例。通用BluetoothLE样本。我现在面临一个问题,如果我点击“阅读”按钮,它会显示我的rfduino阅读。但是因为我希望它在值发生变化时自动更新,我需要订阅值更改。

然而,当我点击“订阅价值变化”时,我收到的只是“未知格式”。任何专家都可以帮我解决这个问题吗?如果可能,我们可以使用Teamviewer。

private async void CharacteristicReadButton_Click()
        {
             // BT_Code: Read the actual value from the device by using Uncached.
            GattReadResult result = await selectedCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
            if (result.Status == GattCommunicationStatus.Success)
            {
                string formattedResult = FormatValueByPresentation(result.Value, presentationFormat);

                rootPage.NotifyUser($"Read result: {formattedResult}", NotifyType.StatusMessage);  
            }
            else
            {
                rootPage.NotifyUser($"Read failed: {result.Status}", NotifyType.ErrorMessage);
            }     
        }

2 个答案:

答案 0 :(得分:1)

首先,如果特征具有可指示或可通知的属性,您可以订阅特征值更改通知。它与你的阅读并不总是一样的。它可能是其他特征。

找到特征后,您必须编写该特征的ClientConfigurationDescriptor,并将Indicatable或Notifiable属性设置为True。它通知GATT服务器客户端对此特性的更改事件感兴趣。

只有您可以订阅并收到通知。此外,一旦通知到达,您不需要从特征原因中读取通知事件包括新的特征值。

答案 1 :(得分:0)

你的编码技巧不足以理解发生了什么 打破你在Rfuino和你的uwp app之间交换价值的愿望。
要发送值,您必须制定一些协议以了解有效消息何时到达 如果Rfuino允许你发送一个字节数组,那么就像发送一个起始字节一样 您的值为字节和结束字节。如STX,值X,值Y,值Z,ETX。(2,255,255,255,3) 如果在接收端你读了一条消息,如2,148,250,180,3,那么你就知道有一条有效的消息已经到了 我对Rfuino不太了解,但大多数装置都可以发出这样的信息 UWP的例子也很复杂,你要理解 在您的UWP应用程序中,您可以检查您的消息是否长度为5个字节,以2开头,以3结尾。 看看我在GitHub上的简单Ble示例:https://github.com/GrooverFromHolland/SimpleBleExample_by_Devicename
如果您对该示例有疑问或想要扩展它,请在GitHub上启动问题。 在Stackoverflow上停止询问有关此主题的问题,您将获得一些答案,但我们不会教您如何编码。