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; }
public async void Connect() { ClearBluetoothLEDevice(); try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(BluetoothLEDeviceId); bluetoothLeDevice.ConnectionStatusChanged += BluetoothLeDevice_ConnectionStatusChanged; } catch (Exception ex) when((uint)ex.HResult == 0x800710df) { // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on. } if (bluetoothLeDevice != null) { Guid ancsUuid = new Guid("7905F431-B5CE-4E99-A40F-4B1E122D00D0"); try { GattService = bluetoothLeDevice.GetGattService(ancsUuid); } catch (Exception ex) { throw new Exception("Apple Notification Center Service not found."); } if (GattService == null) { throw new Exception("Apple Notification Center Service not found."); } else { Guid notificationSourceUuid = new Guid("9FBF120D-6301-42D9-8C58-25E699A21DBD"); Guid controlPointUuid = new Guid("69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9"); Guid dataSourceUuid = new Guid("22EAC6E9-24D6-4BB5-BE44-B36ACE7C7BFB"); try { ControlPoint = new ControlPoint(GattService.GetCharacteristics(controlPointUuid).First()); DataSource = new DataSource(GattService.GetCharacteristics(dataSourceUuid).First()); NotificationSource = new NotificationSource(GattService.GetCharacteristics(notificationSourceUuid).First()); } catch (Exception ex) { throw new Exception(ex.Message); } } } else { ClearBluetoothLEDevice(); throw new Exception("Failed to connect to device."); } }