Пример #1
0
////////////////////////////////////////////////////////////////////////////////////////////


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bluetoothLeDevice != null)
            {
                bluetoothLeDevice.Dispose();
                bluetoothLeDevice = null;
            }
            btDevice.StopDiscovery();
        }
Пример #2
0
        public void Dispose()
        {
            //lock (_lock)
            //{

            Close();

            if (_Device == null)
            {
                return;
            }

            if (BluetoothRadio != null)
            {
                BluetoothRadio.StateChanged -= _BluetoothRadio_StateChanged;
                BluetoothRadio = null;
            }

            if (_Characteristics != null)
            {
                if (_ReadChar != null && _NotifyChar != null)
                {
                    _ReadChar.ValueChanged   -= _Read;
                    _NotifyChar.ValueChanged -= _Read;
                }
                _Characteristics = null;
            }

            if (_Service != null)
            {
                _Service.Dispose();
                _Service = null;
            }

            if (_Device != null)
            {
                _Device.ConnectionStatusChanged -= _Device_ConnectionStatusChanged;
                _Device.GattServicesChanged     -= _Device_GattServicesChanged;
                _Device.Dispose();
                _Device = null;
            }

            //}
            GC.Collect();

            Monitor.Enter(_ReadLock);

            Monitor.Pulse(_ReadLock);

            Monitor.Exit(_ReadLock);
        }
Пример #3
0
        public string DisconnectUEI()
        {
            if (hasCCCD)
            {
                Subscribe(GattClientCharacteristicConfigurationDescriptorValue.None);
            }
            ;

            if (readCh != null)
            {
                readCh = null;
                writeCh.Service.Dispose();
                writeCh = null;
            }
            if (bleDevice.ConnectionStatus == BluetoothConnectionStatus.Disconnected)
            {
                return("Already disconnected");
            }

            bleDevice.Dispose();
            DateTime waitStart = DateTime.Now;
            TimeSpan delay;

            while (bleDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                delay = DateTime.Now - waitStart;
                if (delay.TotalSeconds > 10)
                {
                    return("Disconnection failed");
                }
            }
            delay = DateTime.Now - waitStart;
            return("Disconnection succeeded after " + delay.TotalMilliseconds + "ms");
        }
Пример #4
0
 public partial ValueTask DisposeAsync()
 {
     session.Dispose();
     device.Dispose();
     // TODO: wait for disconnect
     return(ValueTask.CompletedTask);
 }
Пример #5
0
 public void disconnect()
 {
     if (_isConnected)
     {
         // Don't need to watch value changes anymore
         foreach (GattCharacteristic c in characteristicObjects)
         {
             c.ValueChanged -= CharacteristicValueChanged;
         }
         var task = Task.Run(async() => {
             // Unsubscribe from characteristics
             foreach (GattCharacteristic c in subscribeCharacteristics)
             {
                 await _subscribeToCharacteristic(c.Uuid.ToString().ToUpper(), false);
             }
         });
         task.Wait();
         int i = devices.IndexOf(connectedDevice);
         connectedDevice.Dispose();
         connectedDevice = null;
         // Make sure the disposed object will not be used again
         // Force it to get a new device id
         devices.RemoveAt(i);
         deviceAddresses.RemoveAt(i);
         serviceObjects.Clear();
         characteristicObjects.Clear();
         descriptorObjects.Clear();
         subscribeCharacteristics.Clear();
         _isConnected = false;
     }
 }
Пример #6
0
 public void Disconnect()
 {
     if (connectedDevice != null)
     {
         connectedDevice.Dispose(); connectedDevice = null;
     }
 }
Пример #7
0
        public async ValueTask DisposeAsync()
        {
            if (Interlocked.Increment(ref _disposeCount) != 1)
            {
                return;
            }

            _connectionTimer.Change(Timeout.Infinite, Timeout.Infinite);
            await _deviceSemaphore.WaitAsync();

            try
            {
                try
                {
                    if (_characteristic != null)
                    {
                        await UnsubscribeFromDevice();
                    }

                    _device?.Dispose();
                    _connectionTimer.Dispose();
                }
                catch
                {
                }
            }
            finally
            {
                _deviceSemaphore.Release();
            }
            _deviceSemaphore.Dispose();
        }
        public async Task <bool> DisconnectAsync()
        {
            //if (Status != READERSTATE.IDLE)
            //    return false;

            BARCODEPowerOff();

            // Need to clear the CCCD from the remote device so we stop receiving notifications

            //var result = await notificationCharacteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
            var result = await notificationCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

            if (result != GattCommunicationStatus.Success)
            {
                return(false);
            }

            notificationCharacteristic.ValueChanged -= BLE_Recv;

            foreach (var ser in services)
            {
                ser?.Dispose();
            }

            bluetoothLeDevice?.Dispose();
            bluetoothLeDevice = null;

            return(true);
        }
Пример #9
0
        public static async Task <CancellationToken> Subscribe(BluetoothLEDevice mi_device, IProgress <MiDeviceData> progress)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            using (var service = await GetService(mi_device))
            {
                var characteristic = await GetCharacteristic(service);

                await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                characteristic.ValueChanged += async(sender, evt) =>
                {
                    var deviceDatas = ReadDatas(evt.CharacteristicValue);
                    progress.Report(deviceDatas);
                    if (cts.Token.IsCancellationRequested)
                    {
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

                        mi_device.Dispose();
                    }
                };
            }

            return(cts.Token);
        }
Пример #10
0
 public async Task Disconnect()
 {
     try
     {
         if (_uartService != null)
         {
             await _uartService.Stop();
         }
         if (_gattDeviceService != null)
         {
             _gattDeviceService.Dispose();
         }
         if (_bleDevice != null)
         {
             _bleDevice.Dispose();
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("BLE_Device::Disconnect EXCEPTION " + ex.ToString());
     }
     finally
     {
         _uartService       = null;
         _gattDeviceService = null;
         _bleDevice         = null;
         _sbResponse.Clear();
     }
 }
Пример #11
0
        private async Task <Spell> Connect(DeviceInformation args, BluetoothLEDevice device)
        {
            string          spellName = device.Name.Split(new string[] { ": " }, StringSplitOptions.None)[1];
            Spell           result;
            Action <string> markBadDevice = (msg) =>
            {
                Console.WriteLine(msg);
                badDeviceIds.Add(args.Id);
                device.Dispose();
                return;
            };

            if (!Enum.TryParse <Spell>(spellName, out result))
            {
                markBadDevice("Spell device: " + device.Name + " has an invalid spell name!");
            }
            var serviceResult = await device.GetGattServicesForUuidAsync(SERVICE_UUID);

            if (serviceResult.Services.Count != 1)
            {
                markBadDevice("Spell device" + device.Name + " does not have a spell service!");
            }
            var characteristicsResult = await serviceResult.Services[0].GetCharacteristicsForUuidAsync(CHARACTERISTIC_UUID);

            if (characteristicsResult.Characteristics.Count != 1)
            {
                markBadDevice("Spell device " + device.Name + " has an invalid number of trigger characteristics!");
            }
            spellDevices[result]  = device;
            spellTriggers[result] = characteristicsResult.Characteristics[0];
            return(result);
        }
Пример #12
0
        private void ClearBluetoothLEDevice()
        {
            GattService?.Dispose();
            GattService = null;


            if (ControlPoint != null)
            {
                ControlPoint = null;
            }

            if (NotificationSource != null)
            {
                NotificationSource.ValueChanged -= NotificationSource_ValueChanged;
                NotificationSource = null;
            }

            if (DataSource != null)
            {
                DataSource.NotificationAttributesReceived -= DataSource_NotificationAttributesReceived;
                DataSource = null;
            }

            try
            {
                bluetoothLeDevice.ConnectionStatusChanged -= BluetoothLeDevice_ConnectionStatusChanged;
            }
            catch (Exception ex)
            {
                // Do nothing
            }

            bluetoothLeDevice?.Dispose();
            bluetoothLeDevice = null;
        }
Пример #13
0
        private void CleanupConnection()
        {
            if (mConnectionCancelTokenSource != null)
            {
                mConnectionCancelTokenSource.Dispose();
                mConnectionCancelTokenSource = null;
            }

            mUploadCharacteristic   = null;
            mDownloadCharacteristic = null;

            if (mService != null)
            {
                mService.Dispose();
                mService = null;
            }

            if (mDevice != null)
            {
                mDevice.Dispose();
                mDevice = null;
            }

            mSendBufferWriter.BaseStream.SetLength(0);
            mReceiveBufferReader.BaseStream.SetLength(0);
            mReceiveMessageSize    = -1;
            mReceiveMessageAddress = -1;
            mValueWriting          = false;
        }
Пример #14
0
        private void btnDevDisConn_Click(object sender, EventArgs e)
        {
            btnDevConnect.BackColor = btnDevDisConn.BackColor;

            bluetoothLeDevice?.Dispose();
            bluetoothLeDevice = null;
        }
Пример #15
0
        private async void cbDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bleDevice?.Dispose();
            bleDevice = null;

            var bleDeviceDisp = cbDevices.SelectedItem as BluetoothLEDeviceDisplay;

            if (bleDeviceDisp == null)
            {
                return;
            }

            services.Clear();
            try
            {
                bleDevice = await BluetoothLEDevice.FromIdAsync(bleDeviceDisp.Id);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x800710df)
            {
                // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
            }

            if (bleDevice != null)
            {
                foreach (var service in bleDevice.GattServices)
                {
                    services.Add(new BluetoothLEAttributeDisplay(service));
                }
            }
        }
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskInstance = taskInstance;

            // Get the details of the trigger
            var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;

            if (details != null)
            {
                // If the background watcher stopped unexpectedly, an error will be available here.
                var error = details.Error;

                if (error == BluetoothError.Success)
                {
                    // The Advertisements property is a list of all advertisement events received
                    // since the last task triggered. The list of advertisements here might be valid even if
                    // the Error status is not Success since advertisements are stored until this task is triggered
                    IReadOnlyList <BluetoothLEAdvertisementReceivedEventArgs> advertisements = details.Advertisements;

                    // The signal strength filter configuration of the trigger is returned such that further
                    // processing can be performed here using these values if necessary. They are read-only here.
                    var rssiFilter = details.SignalStrengthFilter;

                    // Make sure we have advertisements to work with
                    if (advertisements.Count == 0)
                    {
                        return;
                    }

                    // Grab the first advertisement
                    var eventArg = advertisements[0];

                    if (eventArg.RawSignalStrengthInDBm > WriteCharacteristicMinRSSI)
                    {
                        // Get a deferral so we can use the await operator without the background task returning and closing the thread
                        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

                        // Get a connection to the device and get the service that we're looking for
                        BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArg.BluetoothAddress);

                        // Get the service and characteristic we're looking for
                        var service        = device.GetGattService(IoServiceUuid);
                        var characteristic = service.GetCharacteristics(OutputCommandCharacteristicGuid)[0];

                        // Write to the motor characteristic telling it to spin
                        GattCommunicationStatus status = await this.writeToCharacteristic(characteristic);

                        // Wait a couple seconds before we disconnect so we can see the motor spin
                        await Task.Delay(TimeSpan.FromSeconds(MotorSpinSeconds));

                        // Disconnect from the device so the motor stops
                        device.Dispose();

                        // Let the system know that we've finished the background task
                        deferral.Complete();
                    }
                }
            }
        }
Пример #17
0
 public void destroy()
 {
     // Destroy EVERYTHING.
     device.ConnectionStatusChanged -= Device_ConnectionStatusChanged;
     try { controller.Disconnect(); } catch (Exception) { }
     device.Dispose();
     isDisconnected = true;
 }
 /// <summary>
 /// Disconnect from the ble device and close open characteristics
 /// </summary>
 public void Disconnect()
 {
     if (Characteristic != null)
     {
         Characteristic.Service.Dispose();
     }
     mBluetoothLEDevice?.Dispose();
 }
        public override void Disconnect()
        {
            InvokeDeviceRemoved();
            _indexedChars.Clear();

            _bleDevice.Dispose();
            _bleDevice = null;
        }
Пример #20
0
 public override void Close()
 {
     if (device.ConnectionStatus == BluetoothConnectionStatus.Disconnected)
     {
         throw new PortClosedException();
     }
     device.Dispose();
 }
Пример #21
0
 private void DisconnectDevice()
 {
     bluetoothLeDevice.Dispose();
     midiSignals = null;
     midiDevices = null;
     System.GC.Collect();
     devices.Text = "Disconnected, Scan Again";
 }
Пример #22
0
 private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
 {
     if (bleDevice != null)
     {
         bleDevice.ConnectionStatusChanged -= ConnectionStatusChanged;
         characteristic.ValueChanged       -= ValueChanged;
         bleDevice.Dispose();
     }
 }
Пример #23
0
        private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            int connectionStatus = (int)bluetoothLEDevice.ConnectionStatus;

            if (connectionStatus == 0)
            {
                bluetoothLEDevice.Dispose(); //Dispose if connection is lost
            }
        }
Пример #24
0
 public void Dispose()
 {
     DeviceInfo.Dispose();
     Battery.Dispose();
     Sensors.Dispose();
     Config.Dispose();
     BLEDevice.Dispose();
     GC.SuppressFinalize(this);
 }
Пример #25
0
        private async void deviceListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                TimerConnectToSensor.Stop();

                //I have to do 7 rows of code below if I choose another sensor in the list, to avoid the fact that the measurement character string continues to subscribe and therefore gets the value rotations of this but also from the previous sensor
                if (cadence != null && characteristic2 != null)
                {
                    //unsubscribe measurements characterstic2, is necessary to disconnect the existing measurement from the sensor, otherwise when re-opening the app or you choose another sensor we get an unstable measurement
                    await characteristic2.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

                    characteristic2.Service.Dispose();
                    cadence.Dispose();
                    cadence = null;
                }
                ErrorTextBlock.Text               = "Sensor: Searching...";
                ErrorTextBlock.Foreground         = new SolidColorBrush(Colors.DarkGreen);
                connectionStatusTextBlock.Text    = "";
                DeviceNameTextBlock.Text          = "";
                BTAddresTextBlock.Text            = "";
                FirmwareTextBlock.Text            = "";
                HardwareTextBlock.Text            = "";
                readingsTextBlock.Text            = "";
                subscriptionStatusTextBlock.Text  = "";
                subscriptionResultTextBlock.Text  = "";
                subscriptionResultTextBlock2.Text = "";
                NoError = true;
                SubscribeMeasurement      = false;
                selectedDeviceInfoWrapper = (BluetoothInformationWrapper)e.ClickedItem;
                cadence = await BluetoothLEDevice.FromIdAsync(selectedDeviceInfoWrapper.DeviceInformation.Id);

                if (selectedDeviceInfoWrapper != null)
                {
                    GetAllInfoSensor();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                ErrorTextBlock.Text       = "Sensor: Error!";
                ErrorTextBlock.Foreground = new SolidColorBrush(Colors.Red);
            }
        }
Пример #26
0
        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            BluetoothLEDevice device = null;

            try
            {
                watcher.Stop();

                device = await ConnectToDevice(eventArgs);

                GattDeviceService service = GetServiceData(device, wantedServiceUuidString);

                GattCharacteristic characteristic = GetCharacteristicData(service, wantedCharacteristicUuidString);

                BLEPort blePort = new BLEPort(device, characteristic);

                device.ConnectionStatusChanged += async(BluetoothLEDevice dev, object o) =>
                {
                    try
                    {
                        if (dev.ConnectionStatus == BluetoothConnectionStatus.Connected)
                        {
                            GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                                GattClientCharacteristicConfigurationDescriptorValue.Notify);

                            PortRequestedEventArgs portEventArgs = new PortRequestedEventArgs(blePort);
                            OnPortRequested(portEventArgs);
                        }
                    }
                    catch (Exception e)
                    {
                        if (dev != null)
                        {
                            dev.Dispose();
                        }

                        ExceptionOccuredEventArgs exceptionEventArgs = new ExceptionOccuredEventArgs(e);
                        OnWaitForPortConnectionsExceptionOccured(exceptionEventArgs);
                    }
                };
            }
            catch (Exception e)
            {
                if (device != null)
                {
                    device.Dispose();
                }

                ExceptionOccuredEventArgs exceptionEventArgs = new ExceptionOccuredEventArgs(e);
                OnWaitForPortConnectionsExceptionOccured(exceptionEventArgs);
            }
            finally
            {
                watcher.Start();
            }
        }
Пример #27
0
 void ExecuteDisconnectCommand()
 {
     _notifyCharacteristic = null;
     _writeCharacteristic  = null;
     _communicationService.Dispose();
     _communicationService = null;
     _device.Dispose();
     _device   = null;
     Connected = false;
 }
Пример #28
0
 public void Dispose()
 {
     if (Device != null)
     {
         Device.Dispose();
         Device = null;
         CharRX = null;
         CharTX = null;
     }
 }
        public void Disconnect()
        {
            DeviceRemoved?.Invoke(this, new EventArgs());
            _txChar = null;
            _rxChar = null;
            _indexedChars.Clear();

            _bleDevice.Dispose();
            _bleDevice = null;
        }
Пример #30
0
 internal void ReleaseBleDevice()
 {
     if (BleDevice != null)
     {
         BleDevice.ConnectionStatusChanged -= BleConnectionStatusChanged;
         BleDevice.NameChanged             -= BleNameChanged;
         BleDevice.GattServicesChanged     -= BleServiceChanged;
         BleDevice.Dispose();
         BleDevice = null;
     }
 }