UWP Can not use GattCharacteristic.WriteValueAsync send data

峰 郑 21 Reputation points
2022-10-09T08:03:13.873+00:00

Hello. I am making UWP windows app. I want to Bluetooth receive and send data, but GattCharacteristic.WriteValueAsync always failed.

public async void DebugConnect()  
        {  
            Debug.WriteLine($"DebugConnect");  
            MsgDevice msg;  
            if (msgDeviceDictionary.TryGetValue(targetDeviceID, out msg))  
            {  
                Debug.WriteLine($"Device ConnectStatus:{msg.Device.ConnectionStatus.ToString()}");  
                return;  
            }  
            try  
            {  
                MsgDevice msgDevice = new MsgDevice();  
                Debug.WriteLine($"DebugConnect get device start");  
                msgDevice.Device = await BluetoothLEDevice.FromIdAsync(targetDeviceID);  
                Debug.WriteLine($"DebugConnect get device end");  
                if (msgDevice.Device != null)  
                {  
                    Debug.WriteLine($"DebugConnect get service start");  
                    GattDeviceServicesResult serviceResult = await msgDevice.Device.GetGattServicesForUuidAsync(Guid.Parse(targetServiceID), BluetoothCacheMode.Cached);  
                    Debug.WriteLine($"DebugConnect get service end");  
                    if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count > 0)  
                    {  
  
                        msgDevice.Service = serviceResult.Services[0];  
  
                        Debug.WriteLine($"DebugConnect get SendCharacteristics start");  
                        GattCharacteristicsResult characteristicsResult = await msgDevice.Service.GetCharacteristicsForUuidAsync(Guid.Parse(targetSendCharacteristicID), BluetoothCacheMode.Cached);  
                        Debug.WriteLine($"DebugConnect get SendCharacteristics end");  
                        if (characteristicsResult.Status == GattCommunicationStatus.Success && characteristicsResult.Characteristics.Count > 0)  
                        {  
                            msgDevice.SendCharacteristic = characteristicsResult.Characteristics[0];  
                            Debug.WriteLine($"DebugConnect SendCharacteristic CharacteristicProperties: {msgDevice.SendCharacteristic.CharacteristicProperties}");  
                        }  
                        else  
                        {  
                            Debug.WriteLine($"DebugConnect SendCharacteristics no found.");  
                        }  
  
                        Debug.WriteLine($"DebugConnect get GetCharacteristics start");  
                        characteristicsResult = await msgDevice.Service.GetCharacteristicsForUuidAsync(Guid.Parse(targetGetCharacteristicID), BluetoothCacheMode.Cached);  
                        Debug.WriteLine($"DebugConnect get GetCharacteristics end");  
                        if (characteristicsResult.Status == GattCommunicationStatus.Success && characteristicsResult.Characteristics.Count > 0)  
                        {  
                            msgDevice.GetCharacteristic = characteristicsResult.Characteristics[0];  
                            Debug.WriteLine($"DebugConnect get 订阅 Start {msgDevice.GetCharacteristic.CharacteristicProperties}");  
                            GattCommunicationStatus scStatus = await msgDevice.GetCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);  
                            Debug.WriteLine($"DebugConnect get 订阅 end");  
                            if (scStatus != GattCommunicationStatus.Success)  
                            {  
                                Debug.WriteLine($"订阅失败");  
                                msgDevice.GetCharacteristic = null;  
                            }  
                            else  
                            {  
                                Debug.WriteLine($"订阅成功");  
                                msgDevice.GetCharacteristic.ValueChanged += DebugOnGetMessage;  
                            }  
  
                        }  
                        else  
                        {  
                            Debug.WriteLine($"DebugConnect GetCharacteristics no found.");  
                        }  
  
                        characteristicsResult = null;  
  
                        if (msgDevice.IsValid)  
                        {  
                            msgDevice.Device.ConnectionStatusChanged += DebugOnDeviceConnectChanged;  
                            msgDevice.Service.Session.MaintainConnection = true;  
                            msgDeviceDictionary.Add(msgDevice.Device.DeviceId, msgDevice);  
                        }  
                        else  
                        {  
                            Debug.WriteLine($"msgDevice is not Valid");  
                        }  
                    }  
                    else  
                    {  
                        Debug.WriteLine($"DebugConnect Service no found.");  
                    }  
                    serviceResult = null;  
                }  
                else  
                {  
                    Debug.WriteLine($"DebugConnect Device not found.");  
                }  
            }  
            catch (System.Runtime.InteropServices.COMException e)  
            {  
                Debug.WriteLine($"Exceprtion Message : {e.Message}");  
                Debug.WriteLine($"Exceprtion StackTrace : {e.StackTrace}");  
            }  
        }  
  
private async void DebugSendData(byte[] data)  
        {  
            try  
            {  
                MsgDevice msg;  
                if (msgDeviceDictionary.TryGetValue(targetDeviceID, out msg))  
                {  
                    if (msg.Device.ConnectionStatus == BluetoothConnectionStatus.Disconnected)  
                    {  
                        Debug.WriteLine($"DebugSendData Disconnected");  
                        return;  
                    }  
                    DataWriter writer = new DataWriter();  
                    writer.WriteBytes(data);  
                    IBuffer buffer = writer.DetachBuffer();  
                    GattCommunicationStatus status = await msg.SendCharacteristic.WriteValueAsync(buffer, GattWriteOption.WriteWithoutResponse);  
                    if (status != GattCommunicationStatus.Success)  
                    {  
                        Debug.WriteLine($"send error");  
                    }  
                    else  
                    {  
                        Debug.WriteLine($"send success");  
                    }  
                    //writer.Dispose();  
                    buffer = null;  
  
                }  
                else  
                {  
                    Debug.WriteLine($"Dont connect");  
                }  
            }  
            catch (System.Exception e)  
            {  
                Debug.WriteLine($"Exceprtion Message : {e.Message}");  
                Debug.WriteLine($"Exceprtion StackTrace : {e.StackTrace}");  
            }  
        }  

This is script, DebugConnect ran successfully,but DebugSendData always failed or wait. I have enabled Bluetooth.

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Roy Li - MSFT 32,486 Reputation points Microsoft Vendor
    2022-10-27T02:23:49.757+00:00

    Hello,

    Welcome to Microsoft Q&A!

    I've got some information from the Bluetooth team about this. After checking the log, our engineer found that the peripheral device is not responding to one of our ATT read requests. This request in particular gets no response:

    254541-bluetooth.png

    Generally speaking, the Bluetooth connection will be disconnected due to timeout if no response is received. The write request from your app is blocked during that time since we need to finish the pending read first. Since the read fails and causes the app to disconnect from the device, the write request also gets failed after the timeout. As a result, the write attempt never even gets sent in this case; it fails due to a previous command’s timeout.

    In the trace which is reported to be succeed. the same issue happens. A read request timeout for the same characteristic followed by a disconnection which causes the pended write from the app to fail. However, it seems like in this case our API did not correctly report that the write failed back to the app. Regardless, no write request was attempted over the air to the peripheral device for the same reason as above.

    So the real culprit seems to be that the peripheral device is not responding to ATT_READ_REQ for the Peripheral Preferred Connection Parameters (a.k.a. PPCP). From what our engineer can see in the logs it is not acting as a compliant Bluetooth device should.

    You could make use of the Bluetooth Virtual Sniffer tool we provide to better diagnose these kinds of issues: Microsoft Bluetooth Test Platform - BTVS - Windows drivers | Microsoft Learn.
    With that tool you would be able to see in real time that the device is not responding to that ATT read request.

    Another suggestion is that you could try to use other kind of Bluetooth device to test for your app.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 峰 郑 21 Reputation points
    2022-10-11T04:23:50.617+00:00

    And WriteValueWithResultAsync Error Message:
    DebugLightOn
    device connect status:Connected。 DeviceAccessInformation:Allowed. WasSecureConnectionUsedForPairing:False. device id:BluetoothLE#BluetoothLE00:e0:4c:2c:80:67-a8:31:02:90:b2:8a. device isEnable:False
    DeviceAccessInformation Allowed
    SessionStatus Active, CanMaintainConnection:True. MaintainConnection:True
    RequestAccessAsync start
    RequestAccessAsync end deviceAccessStatus:Allowed
    The thread 0x40c8 has exited with code 0 (0x0).
    The thread 0x2ff0 has exited with code 0 (0x0).
    The thread 0x3900 has exited with code 0 (0x0).
    The thread 0x1218 has exited with code 0 (0x0).
    onecore\internal\sdk\inc\wil\opensource/wil/winrt.h(1594)\Windows.Devices.Bluetooth.dll!00007FFFC299A0D8: (caller: 00007FFFC29C0C7B) Exception(1) tid(19a8) 8000FFFF Catastrophic failure
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: wil::ResultException at memory location 0x000000725C3FD910.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    onecoreuap\drivers\wdm\bluetooth\user\winrt\gatt\gattcharacteristic.cpp(1166)\Windows.Devices.Bluetooth.dll!00007FFFC2A7A66F: (caller: 00007FFFC29C789A) ReturnHr(3) tid(19a8) 8000FFFF Catastrophic failure
    onecoreuap\drivers\wdm\bluetooth\user\winrt\gatt\gattcharacteristic.cpp(749)\Windows.Devices.Bluetooth.dll!00007FFFC29C78B9: (caller: 00007FFFC29C8FF0) ReturnHr(4) tid(19a8) 8000FFFF Catastrophic failure
    Exception thrown at 0x00007FFFDE204FD9 (KernelBase.dll) in BluetoothUWP.exe: 0xE0434352 (parameters: 0xFFFFFFFF8000FFFF, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x00007FFF2B8F0000).
    Exceprtion Message : Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
    'BluetoothUWP.exe' (Win32): Loaded 'C:\Windows\System32\mscoree.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dll'.
    'BluetoothUWP.exe' (Win32): Unloaded 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dll'
    'BluetoothUWP.exe' (Win32): Unloaded 'C:\Windows\System32\mscoree.dll'
    'BluetoothUWP.exe' (Win32): Loaded 'C:\Windows\System32\mscoree.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dll'.
    'BluetoothUWP.exe' (Win32): Unloaded 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dll'
    'BluetoothUWP.exe' (Win32): Unloaded 'C:\Windows\System32\mscoree.dll'
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Diagnostics.StackTrace.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Reflection.Metadata.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.IO.FileSystem.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.IO.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Collections.Immutable.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.IO.FileSystem.Primitives.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Runtime.Extensions.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Runtime.Handles.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Threading.Overlapped.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Reflection.dll'. Module was built without symbols.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Core.dll'. Module was built without symbols.
    'BluetoothUWP.exe' (Win32): Unloaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Core.dll'
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 (KernelBase.dll) in BluetoothUWP.exe: 0xE0434352 (parameters: 0xFFFFFFFF80131040, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x00007FFF2B8F0000).
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
    Exception thrown at 0x00007FFFDE204FD9 in BluetoothUWP.exe: Microsoft C++ exception: EEFileLoadException at memory location 0x000000725C3F8928.
    Exception thrown at 0x00007FFFDE204FD9 (KernelBase.dll) in BluetoothUWP.exe: 0xE0434352 (parameters: 0xFFFFFFFF80131040, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x00007FFF2B8F0000).
    DebugOnDeviceConnectChanged Device id:BluetoothLE#BluetoothLE00:e0:4c:2c:80:67-a8:31:02:90:b2:8a. connectStatuc:Disconnected
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Text.Encoding.dll'.
    'BluetoothUWP.exe' (Win32): Loaded 'E:\VSProject\BluetoothUWP\bin\x64\Debug\AppX\System.Reflection.Extensions.dll'. Module was built without symbols.
    Exceprtion StackTrace : at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at BluetoothUWP.Bluetooth.<DebugSendDataAsync>d__32.MoveNext()