设备断开连接并清除所有内容后,BLE IGattCharacteristic通知将触发

时间:2019-02-15 16:33:09

标签: c# xamarin.ios

我正在xamarin.IOS中开发一个应用程序。此应用程序连接到BLE条形码扫描仪(通过Plugin.BluetoothLE),并在扫描条形码时获得通知。当我断开BLE并重新连接(离开UIView并返回),重新订阅扫描通知时,就会出现问题。扫描条形码后,我收到两次通知。或者,如果我断开10x的重新连接,那么我会收到10x的通知。断开设备的连接后,似乎无法摆脱通知订阅。

我一起尝试过: 取消IGattCharacteristic的通知 -取消每个BLE连接 -再次获取所有连接的设备,以确保它们已断开连接 -停止BLE适配器 -处理包含我的BLE东西的整个类 完成所有这些操作后,当我重新连接到设备时,仍会触发以前的通知。

显然,这不是全部代码,它显示了主要内容

UIView:

    private ScannerHelper ble;

    public override void ViewDidAppear(bool animated)
    {
        if (ble == null) ble = new ScannerHelper();
        ScannerHelper.GetDevice();
    }

    public override void ViewDidDisappear(bool animated)
    {
        ble.StopDevice();
        ble=null;
    }       


    ---------------------------------------------------------
    The ScannerHelper class :

    using Plugin.BluetoothLE;

    private IDevice BLEScanner;
    private Characteristic;

    public void GetDevice()
    {
        CrossBleAdapter.AdapterScanner.FindAdapters();

        var scanner = CrossBleAdapter.Current.Scan().Subscribe(scanResult =>
        {
            if ((scanResult.Device.Name != null) && (scanResult.Device.Name.Length > 0))
            {

                scanResult.Device.Connect();

                scanResult.Device.WhenAnyCharacteristicDiscovered().Subscribe(characteristic =>
                {
                    if (characteristic.Service.Uuid == ScannerServiceUUID)
                    {
                        if (characteristic.CanNotify()) { 

                            Characteristic=characteristic;
                            CrossBleAdapter.Current.StopScan();
                            BLEScanner=scanResult.Device;

                            characteristic.EnableNotifications();
                            characteristic.WhenNotificationReceived().Subscribe(result => {     
                                BarcodeScanned();
                            });                     

                        }
                    }
                });
            }
        });
    }

    public void StopDevice()
    {
        Characteristic.DisableNotifications();
        BLEScanner.CancelConnection();
        Characteristic=null;
        BLEScanner=null;

        var devices = CrossBleAdapter.Current.GetConnectedDevices();
        devices.Subscribe(deviceResult => { if (deviceResult.Count() > 0) foreach (var device in deviceResult) { device.CancelConnection(); } });           
    }

当UIView消失时,我应该与扫描仪完全断开连接,并取消所有通知...所有内容。当我重新打开UIView时,应该重新连接到扫描仪,就像我刚启动该应用程序一样。

0 个答案:

没有答案