简体   繁体   English

C#Windows 10蓝牙LE无法连接到服务器

[英]C# Windows 10 Bluetooth LE can't connect to server

I'm developing ac# desktop api with forms where I want to receive ACC data from a BLE server und display them in a chart. 我正在开发带有表单的ac#桌面api,我想从BLE服务器接收ACC数据并在图表中显示它们。 So I'm running in a connection problem and I can't find any solution. 所以我遇到了连接问题,找不到任何解决方案。 I can find my LE server Device with the watcher. 我可以通过观察程序找到我的LE服务器设备。

DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);

returns me "AlreadyPaired" 返回我“已经配对”

But when I do 但是当我这样做

device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
mGattService = device.GetGattService(MotionService_GUID);
mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];

and then 接着

var con = device.ConnectionStatus;

I receive "Disconnected" in con. 我收到了“已断开连接”的提示。

I am bound with de device on windows( I searched for it in Windows and entered the Code) but I am not connected(based on the Status in the windows info center). 我与Windows上的设备绑定(我在Windows中搜索它并输入代码),但未连接(基于Windows信息中心的状态)。 I've read in another Thread in the windows c# developer page that it should not be necessary anymore to pair the device manually. 我在Windows c#开发人员页面的另一个线程中读到,不再需要手动配对设备。

I'm pretty shure that the rest of my code works because sometimes I can get a connection( pretty confusing for me) and see the right Data in my chart. 我很确定我的其余代码可以正常工作,因为有时我可以建立连接(这对我来说很混乱),并在图表中看到正确的数据。 Right now I just want to reach a stable connection before changing other part of my code. 现在,我只想在更改代码的其他部分之前建立稳定的连接。 Anyone any idea how to solve this? 有人知道如何解决这个问题吗? Thx medTech Thx医疗技术

Edit: Here is part of the Code: 编辑:这是代码的一部分:

Scanning for BLE 扫描BLE

private void button1_Click(object sender, EventArgs e)
        {

            // Create Bluetooth Listener
            var watcher = new BluetoothLEAdvertisementWatcher();

            watcher.ScanningMode = BluetoothLEScanningMode.Active;

            // Register callback for when we see an advertisements
            watcher.Received += OnAdvertisementReceivedAsync;

            // Wait 5 seconds to make sure the device is really out of range
            watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
            watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);

            // Starting watching for advertisements
            watcher.Start();
        }

Connect to Server: 连接到服务器:

private async void OnAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {

            // Filter for specific Device
            if (eventArgs.Advertisement.LocalName == "MYDEVICE")
            {
                watcher.Stop();

                var MotionService_GUID = new Guid("00002000-0000-1000-8000-00805F9B34FB");
                var ACC_Characteristic_GUID = new Guid("00002001-0000-1000-8000-00805F9B34FB");


                    device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
                    DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);
                    mGattService = device.GetGattService(MotionService_GUID);


                    mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];

                    GattDeviceServicesResult result = await device.GetGattServicesAsync();


                    GattCommunicationStatus status1 = await ReadFromCharacteristicAsync(mCharacteristic);

                    var con = device.ConnectionStatus;
                    while (status1 == GattCommunicationStatus.Success)
                    {
                        try
                        {
                            status1 = await ReadFromCharacteristicAsync(mCharacteristic);
                        }
                        catch
                        {
                            Console.WriteLine("ERROR");
                            status1 = GattCommunicationStatus.Unreachable;

                        }
                    }

            }
            }

Read from Characteristic: 从特性中读取:

async Task ReadFromCharacteristicAsync(GattCharacteristic mCharacteristic) { 异步任务ReadFromCharacteristicAsync(GattCharacteristic mCharacteristic){

        GattReadResult readResult = await mCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);

        if (readResult.Status == GattCommunicationStatus.Success)
        {
            byte[] data = new byte[readResult.Value.Length];
            DataReader.FromBuffer(readResult.Value).ReadBytes(data);
            if (chart1.IsHandleCreated)
            {
                this.Invoke((MethodInvoker)delegate { updateChart(data); });
            }

            return readResult.Status;
        }
        return readResult.Status;
    }

Terminate Connection 终止连接

 private async Task<bool> ClearBluetoothLEDeviceAsync()
        {

            mCharacteristic.Service.Dispose();
            mGattService.Dispose();
            await device.DeviceInformation.Pairing.UnpairAsync();
            device?.Dispose();
            device = null;
            GC.Collect();
            return true;
        }

SO now when I connect the first time to the Server, I only receive zeros which shows me that the there might be a authentication Error. 所以现在当我第一次连接到服务器时,我只收到零,这表明可能存在身份验证错误。 After that I always receive this Error: "System.ArgumentException" in mscorlib.dll with a notification that there is noch executable Code left because all Threads are doing some asynchronous stuff. 之后,我总是在mscorlib.dll中收到以下错误消息: “ System.ArgumentException”,并通知所有可执行线程都在做一些异步的工作,因此没有可用的可执行代码。 This Error gets thrown when I try to read from the Characteristic. 当我尝试从特征中读取时,会抛出此错误。 I never coded in c# before so I am not shure if there is an error in my asynchronous part oder the communication part. 我以前从来没有用c#编码过,所以我不确定在异步部分或通信部分是否有错误。 Thanks you 谢谢

Pairing is not the same as connecting! 配对与连接不同! I really advise using the BLE-advertisementWatcher to select and connect to your device. 我真的建议您使用BLE-advertisementWatcher选择并连接到您的设备。 The reason is that many BLE-devices don't save their pairing status. 原因是许多BLE设备无法保存其配对状态。 In windows device-watcher once paired, the device stays paired even if it is switched off or out of reach. 在Windows device-watcher中,一旦配对,即使设备关闭或无法访问,设备仍保持配对状态。 Also many times the connection status is kept, unless the device is unpaired and disposed in code or removed in windows settings. 同样,保持连接状态很多次,除非设备未配对并且以代码放置或在Windows设置中删除。

All BLE-devices that I know of start advertising as soon as there is no connection for some time. 我知道的所有BLE设备都会在一段时间没有连接后立即开始发布广告。 This time depends on the device, but most of the time within seconds. 此时间取决于设备,但是大多数时间在几秒钟内。

So don't pair but just connect if the device is advertising. 因此,如果设备正在做广告,则不要配对,而只需连接即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM