/// <summary> /// ConnectAsync to this bluetooth device /// </summary> /// <returns>Connection task</returns> /// <exception cref="Exception">Thorws Exception when no permission to access device</exception> public async Task ConnectAsync() { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { if (BluetoothLEDevice == null) { BluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(DeviceInfo.Id); if (BluetoothLEDevice == null) { throw new Exception("Connection error, no permission to access device"); } } BluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged; BluetoothLEDevice.NameChanged += BluetoothLEDevice_NameChanged; IsPaired = DeviceInfo.Pairing.IsPaired; IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected; Name = BluetoothLEDevice.Name; // Get all the services for this device var getGattServicesAsyncTokenSource = new CancellationTokenSource(5000); var getGattServicesAsyncTask = await Task.Run( () => BluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached), getGattServicesAsyncTokenSource.Token); _result = await getGattServicesAsyncTask; if (_result.Status == GattCommunicationStatus.Success) { // In case we connected before, clear the service list and recreate it Services.Clear(); foreach (var serv in _result.Services) { Services.Add(new ObservableGattDeviceService(serv)); } ServiceCount = Services.Count; } else { if (_result.ProtocolError != null) { throw new Exception(_result.ProtocolError.GetErrorString()); } } }); }
public static async Task <GattDeviceService> GetServiceAsync(string deviceId) { BluetoothLEDevice device = null; try { Debug.WriteLine("Connecting to Bluetooth LE device."); device = await BluetoothLEDevice.FromIdAsync(deviceId); } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { throw new InvalidOperationException("Bluetooth radio is not on.", ex); } if (device == null) { throw new InvalidOperationException("Failed to connect to device."); } if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired) { DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.EncryptionAndAuthentication); if (dpr == null) { throw new InvalidOperationException("Failed to pair with device"); } if (!(dpr.Status == DevicePairingResultStatus.Paired || dpr.Status == DevicePairingResultStatus.AlreadyPaired)) { throw new InvalidOperationException($"Failed to pair with device with result: '{dpr.Status}'"); } } Debug.WriteLine("Requesting 'Wi-Fi config message protocol' service for device."); GattDeviceServicesResult result = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status != GattCommunicationStatus.Success) { throw new InvalidOperationException("Device unreachable."); } GattDeviceService service = result.Services.FirstOrDefault(s => s.Uuid == MessageProtocolServiceId); if (service == null) { throw new InvalidOperationException("This device does not support the Message Protocol."); } Debug.WriteLine("Connected to Bluetooth LE device."); return(service); }
private async void ConnectButton_Click() { ConnectButton.IsEnabled = false; if (!await ClearBluetoothLEDeviceAsync()) { rootPage.NotifyUser("Error: Unable to reset state, try again.", NotifyType.ErrorMessage); ConnectButton.IsEnabled = false; return; } try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId); if (bluetoothLeDevice == null) { rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage); } } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { rootPage.NotifyUser("Bluetooth radio is not on.", NotifyType.ErrorMessage); } if (bluetoothLeDevice != null) { // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method. // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system). // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event. GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; rootPage.NotifyUser(String.Format("Found {0} services", services.Count), NotifyType.StatusMessage); foreach (var service in services) { ServiceCollection.Add(new BluetoothLEAttributeDisplay(service)); } ConnectButton.Visibility = Visibility.Collapsed; ServiceList.Visibility = Visibility.Visible; } else { rootPage.NotifyUser("Device unreachable", NotifyType.ErrorMessage); } } ConnectButton.IsEnabled = true; }
private async void OHbtnConn_Click(object sender, RoutedEventArgs e) { OHbtnConn.IsEnabled = false; if (OHbtnConn.Content.ToString() == "Connect") { if (lstDevices.SelectedItem != null) { device = lstDevices.SelectedItem as DeviceInformation; OHtxtStat.Text = "Initializing device..."; //HeartRateService.Instance.DeviceConnectionUpdated += OnDeviceConnectionUpdated; //await HeartRateService.Instance.InitializeServiceAsync(device); try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id); if (bluetoothLeDevice == null) { var dialog = new MessageDialog("Failed to connect to device."); await dialog.ShowAsync(); } else { GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; OHtxtStat.Text = String.Format("Connected & Found {0} services", services.Count); } } } catch (Exception ex) { var dialog = new MessageDialog("Retrieving device properties failed with message: " + ex.Message); await dialog.ShowAsync(); } } } else//Disconnect { characteristics.ValueChanged -= Characteristic_ValueChanged; service.Dispose(); bluetoothLeDevice = null; GC.Collect(); } OHbtnConn.Content = OHbtnConn.Content.ToString() == "Disconnect" ? "Connect" : "Disconnect"; OHbtnConn.IsEnabled = true; }
public async void Connect(string id) { try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id); if (bluetoothLeDevice == null) { Log.d("Failed to connect to device.", NotifyType.ErrorMessage); return; } bluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChangedHandler; mBluetoothGatt = await GattSession.FromDeviceIdAsync(bluetoothLeDevice.BluetoothDeviceId); mBluetoothGatt.MaintainConnection = true; } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { Log.d("Bluetooth radio is not on.", NotifyType.ErrorMessage); return; } if (bluetoothLeDevice != null) { // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method. // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system). // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event. GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(RX_SERVICE_UUID); if (result.Status == GattCommunicationStatus.Success) { _services.Clear(); _services.AddRange(result.Services); Log.d(String.Format("Found {0} services", _services.Count), NotifyType.StatusMessage); foreach (var service in _services) { Log.d("SERVICE: " + DisplayHelpers.GetServiceName(service)); GetCharachteristics(service); } } else { Log.d("Device unreachable", NotifyType.ErrorMessage); } } }
private async void ConnectDevice() { //This works only if your device is already paired! foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); // Display BLE device name var dialogBleDeviceName = new MessageDialog("BLE Device Name " + bleDevice.Name); await dialogBleDeviceName.ShowAsync(); myDevice = bleDevice; } if (myDevice != null) { int servicesCount = 3;//Fill in the amount of services from your device!!!!! int tryCount = 0; bool connected = false; while (!connected)//This is to make sure all services are found. { tryCount++; serviceResult = await myDevice.GetGattServicesAsync(); if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount) { connected = true; Debug.WriteLine("Connected in " + tryCount + " tries"); } if (tryCount > 5)//make this larger if faild { Debug.WriteLine("Failed to connect to device "); return; } } if (connected) { for (int i = 0; i < serviceResult.Services.Count; i++) { var service = serviceResult.Services[i]; //This must be the service that contains the Gatt-Characteristic you want to read from or write to !!!!!!!. string myServiceUuid = "0000ffe0-0000-1000-8000-00805f9b34fb"; if (service.Uuid.ToString() == myServiceUuid) { Get_Characteriisics(service); break; } } } } }
/** * \fn disconnectDeviceAsync * \brief disconnect from bluetooth device */ public uint disconnectDeviceAsync() { try { if (null != this.txNordicCharacteristic) { this.txNordicCharacteristic = null; } if (null != this.rxNordicCharacteristic) { this.rxNordicCharacteristic.ValueChanged -= AssociatedCharacteristic_ValueChanged; this.rxNordicCharacteristic = null; } // dispose service dictionnary if (null != this.gatt) { foreach (GattDeviceService service in this.gatt.Services) { try { service.Dispose(); } catch { } GC.Collect(); } } GC.SuppressFinalize(this.gatt); this.gatt = null; // disconnect device try { if (null != this.connectedDevice) { this.connectedDevice.Dispose(); // according to docs, this one line should be enough to disconnect GC.SuppressFinalize(this.connectedDevice); GC.Collect(); } } catch { } //Following two lines are undocumented but necessary this.connectedDevice = null; GC.SuppressFinalize(this); GC.Collect(); // default connect this.bIsConnected = false; } catch (Exception ex) { throw new ElaBleException("An exception occurs while tryig to disconnect from device.", ex); } return(ErrorHandler.ERR_OK); }
async void ConnectDevice(DeviceInformation deviceInfo) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); // ... GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; // ... } }
/// <summary> /// Obtain a new Characteristic /// </summary> /// <param name="device"></param> /// <returns></returns> internal virtual async System.Threading.Tasks.Task RenewCharacteristic() { if (Device != null) { Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress); Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached); AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("00001623-1212-efde-1623-785feabcd123")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached); Characteristic = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("00001624-1212-efde-1623-785feabcd123")); MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green); } }
/// <summary> /// Starts a new Task and tries to load all characteristics. /// Can only be called once! /// </summary> internal void RequestCharacteristics() { if (characteristicsLoaded) { Logger.Warn("Requesting characteristics failed - already loaded!"); return; } characteristicsLoaded = true; Logger.Debug("Requesting characteristics for: " + BOARD.DeviceId); Task.Run(async() => { try { // Get all services: GattDeviceServicesResult sResult = await BOARD.GetGattServicesAsync(); if (sResult.Status == GattCommunicationStatus.Success) { ONEWHEEL_CHARACTERISTICS.Clear(); foreach (GattDeviceService s in sResult.Services) { // Get all characteristics: GattCharacteristicsResult cResult = await s.GetCharacteristicsAsync(); if (cResult.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in cResult.Characteristics) { ONEWHEEL_CHARACTERISTICS.Add(c.Uuid, c); } } } Logger.Debug("Finished requesting characteristics for: " + BOARD.DeviceId); // Run unlock: UNLOCK_HELPER.Start(); } else { Logger.Warn("Failed to request GetGattServicesAsync() for " + BOARD.DeviceId + " - " + sResult.Status.ToString()); } } catch (Exception e) { Logger.Error("Error during requesting characteristics for: " + BOARD.DeviceId, e); } Logger.Debug("Finished requesting characteristics for: " + BOARD.DeviceId); }, REQUEST_SUBS_CANCEL_TOKEN.Token); }
private async void UpdateGattService() { GattDeviceServicesResult gattDeviceServicesResult = await BluetoothLEDevice.GetGattServicesAsync(); if (gattDeviceServicesResult.Status == GattCommunicationStatus.Success) { GattServiceList = ""; foreach (GattDeviceService gattService in gattDeviceServicesResult.Services) { GattServiceList += "\n" + gattService.Uuid; } } OnPropertyChanged("GattServiceList"); }
public void GetSteps() { Task task = Task.Run(async() => { GattDeviceServicesResult sensorServiceResult = await bluetoothDevice.GetGattServicesForUuidAsync(SensorSRVID); GattCharacteristicsResult characteristicsResult = await sensorServiceResult.Services[0].GetCharacteristicsForUuidAsync(new Guid("00000007-0000-3512-2118-0009af100700")); GattReadResult readResult = await characteristicsResult.Characteristics[0].ReadValueAsync(); using DataReader reader = DataReader.FromBuffer(readResult.Value); byte[] vs = new byte[10]; reader.ReadBytes(vs); uint steps = reader.ReadUInt32(); Console.WriteLine(steps.ToString().Substring(1, 3)); Console.WriteLine(steps); Console.WriteLine(steps.ToString().Substring(2, 4)); }); }
public GattDeviceServicesResultWrapper( [JetBrains.Annotations.NotNull] IGattCharacteristicsResultWrapperFactory characteristicsFactory, [JetBrains.Annotations.NotNull] GattDeviceServicesResult service) { Guard.ArgumentNotNull(characteristicsFactory, nameof(characteristicsFactory)); Guard.ArgumentNotNull(service, nameof(service)); _service = service; _services = _service.Services .Select(s => new GattDeviceServiceWrapper(characteristicsFactory, s)) .ToArray( ); }
/// <summary> /// 按GUID 查找主服务 /// </summary> /// <param name="characteristic">GUID 字符串</param> /// <returns></returns> public async Task SelectDeviceService() { Guid guid = new Guid(ServiceGuid); //foreach (var CurrentService in rr.GetResults().Services) //{ Debug.WriteLine(CurrentService.Uuid.ToString()); } CurrentDevice.GetGattServicesForUuidAsync(guid).Completed = (asyncInfo, asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { try { GattDeviceServicesResult result = asyncInfo.GetResults(); string msg = "主服务=" + CurrentDevice.ConnectionStatus; ValueChanged(MsgType.NotifyTxt, msg, CurrentDevice == null ? null : CurrentDevice.DeviceId); if (result.Services.Count > 0) { //Debug.WriteLine(result.Services[0].Uuid.ToString()); CurrentService = result.Services[CHARACTERISTIC_INDEX]; if (CurrentService != null) { asyncLock = true; //GetCurrentWriteCharacteristic(); GetCurrentNotifyCharacteristic(); } } else { msg = "没有发现服务,自动重试中"; ValueChanged(MsgType.NotifyTxt, msg, CurrentDevice == null ? null : CurrentDevice.DeviceId); SelectDeviceService(); } } catch (Exception e) { ValueChanged(MsgType.NotifyTxt, "没有发现服务,自动重试中", CurrentDevice == null ? null : CurrentDevice.DeviceId); SelectDeviceService(); } } }; }
public async Task ConnectDevice(string id) { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id); if (bluetoothLeDevice != null) { GattDeviceServicesResult gattDeviceServicesResult = await bluetoothLeDevice.GetGattServicesAsync(); Log.Debug($"{bluetoothLeDevice.Name} Services: {gattDeviceServicesResult.Services.Count}, {gattDeviceServicesResult.Status}, {gattDeviceServicesResult.ProtocolError}"); if (gattDeviceServicesResult.Status == GattCommunicationStatus.Success) { _selectedDeviceServices = gattDeviceServicesResult.Services.FirstOrDefault(x => x.Uuid.ToString() == ServiceUUID); foreach (var service in gattDeviceServicesResult.Services) { Log.Debug("service: " + service.Uuid); } if (_selectedDeviceServices != null) { GattCharacteristicsResult gattCharacteristicsResult = await _selectedDeviceServices.GetCharacteristicsAsync(); if (gattCharacteristicsResult.Status == GattCommunicationStatus.Success) { var characteristics = gattCharacteristicsResult.Characteristics.Where(x => x.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)); _commandCharacteristic = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == CommandUUID); _serialCharacteristic = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == SerialPortUUID); GattCharacteristicProperties properties = _serialCharacteristic.CharacteristicProperties; if (_serialCharacteristic != null) { if (properties.HasFlag(GattCharacteristicProperties.Read)) { ReadBLESerial(); } if (properties.HasFlag(GattCharacteristicProperties.Write)) { WriteBlunoSettings(); } if (properties.HasFlag(GattCharacteristicProperties.Notify)) { // This characteristic supports subscribing to notifications. } } } } } } }
private async Task <bool> GetDeviceServicesAsync() { // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method. // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system). // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event. GattDeviceServicesResult result = await _heartRateDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { _serviceCollection.AddRange(result.Services.Select(a => new BluetoothAttribute(a))); return(true); } else { return(false); } }
/// <summary> /// Try to connect with the pen. /// </summary> /// <param name="penInformation">PenInformation instance that holds the pen's information</param> /// <returns>True or false if the connection is successful</returns> public async Task <bool> Connect(PenInformation penInformation) { try { if (penInformation.Protocol != Protocols.V2) { throw new NotSupportedException("Not supported protocol version"); } await semaphreSlime.WaitAsync(); Debug.WriteLine(""); bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(penInformation.Id); var status = await bluetoothLEDevice.RequestAccessAsync(); Debug.WriteLine("RequestAccessAsync result is " + status.ToString()); if (status != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed) { throw new Exception(); } GattDeviceServicesResult result = await bluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status != GattCommunicationStatus.Success || await Bind(result.Services) == false) { Debug.WriteLine("GetGattServicesAsync status is " + result.Status.ToString()); throw new Exception(); } bluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged; return(true); } catch { DisposeBluetoothResource(); return(false); } finally { semaphreSlime.Release(); } }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { lock (lockObj) { if (toioList.Count(t => t.Address == args.BluetoothAddress) > 0) { return; } } var bleServiceUUIDs = args.Advertisement.ServiceUuids; foreach (var uuid in bleServiceUUIDs) { if (uuid == Toio.ServiceUUID) { Task task = Task.Run(async() => { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(Toio.ServiceUUID); if (result.Status == GattCommunicationStatus.Success) { var service = result.Services[0]; Toio toio = new Toio(args.BluetoothAddress, service); // Test byte battery = toio.ReadBatteryLife(); lock (lockObj) { toioList.Add(toio); } if (newlyFound != null) { newlyFound(toio); } } }); task.Wait(); } } }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { string localName = args.Advertisement.LocalName; if (localName != "heart rate sensor") { return; } if (!lockO && (BluetoothLEDevice == null || BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Disconnected)) { lockO = true; BluetoothLEDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); GattDeviceServicesResult service = await BluetoothLEDevice.GetGattServicesAsync(); foreach (GattDeviceService s in service.Services.Where(x => x.Uuid.ToString().StartsWith("0000180d"))) { var car = await s.GetCharacteristicsAsync(); foreach (var c in car.Characteristics.Where(x => x.Uuid.ToString().StartsWith("00002a37"))) { Characteristic = c; Characteristic.ValueChanged += C_ValueChanged; var value_result = await c.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (value_result != GattCommunicationStatus.Success) { Characteristic.ValueChanged -= C_ValueChanged; Console.WriteLine($"ERROR: Gatt Subscription hat failed: {value_result}"); Console.WriteLine($"{c.Uuid}"); } else { Console.WriteLine("Subscription was successfull"); Console.WriteLine($"{c.Uuid}"); } } } lockO = false; } return; }
private async Task MapServices() { Services.Clear(); GattDeviceServicesResult result = await BluetoothLeDevice.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { Services.Add( new BleService { Service = service }); } } }
private async Task <GattDeviceService> GetServiceAsync(Guid guid) { GattDeviceServicesResult result = await Device.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { if (service.Uuid.Equals(guid)) { openServices.Add(service); return(service); } } } throw (new Exception("GetService: Couldnt find Service " + guid + " Result:" + result.Status)); }
/// <summary> /// Get the list of the primary GATT services /// </summary> /// <returns>List of the primary GATT services</returns> public async Task <IList <BleGattService> > GetServicesAsync() { List <BleGattService> services = new List <BleGattService>(); GattDeviceServicesResult result = await _ble_device.GetGattServicesAsync(BluetoothCacheMode.Uncached); foreach (GattDeviceService gatt_service in result.Services) { BleGattService service = new BleGattService(); service.Name = ""; service.Guid = gatt_service.Uuid; service.Context = gatt_service; services.Add(service); } return(services); }
private async Task <BLEGetInfoStatus> GetBLEDeviceInfo(BluetoothLEDeviceInfo deviceDataModel) { this.log.InfoEntry("GetBLEDeviceInfo"); BLEGetInfoStatus result = await this.GetDevice(deviceDataModel); if (result.Status != BLEOperationStatus.Success) { return(result); } try { deviceDataModel.Services.Clear(); GattDeviceServicesResult services = await this.currentDevice.GetGattServicesAsync(BluetoothCacheMode.Cached); if (services.Status != GattCommunicationStatus.Success) { return(this.BuildConnectFailure(BLEOperationStatus.GetServicesFailed, services.Status.ToString())); } if (services.Services == null) { return(this.BuildConnectFailure(BLEOperationStatus.GetServicesFailed, "Null Services")); } if (services.Services.Count == 0) { return(this.BuildConnectFailure(BLEOperationStatus.NoServices, "No services exposed")); } result.Status = BLEOperationStatus.Success; result.DeviceInfo = deviceDataModel; foreach (GattDeviceService service in services.Services) { // TODO make sure status is set in functions await this.BuildServiceDataModel(service, result); } return(result); } catch (Exception e) { this.log.Exception(9999, "HarvestDeviceInfo", "Failure", e); return(this.BuildConnectFailure(BLEOperationStatus.GetServicesFailed, "Exception on getting services")); } }
private bool BluetoothSetup() { BluetoothLEDevice device = this.Waitfor( "connection to Bluetooth device", BluetoothLEDevice.FromBluetoothAddressAsync(System.Convert.ToUInt64("001580912553", 16))); if (device == null) { this.logEol("Device wasn't found"); return(false); } GattDeviceServicesResult deviceServices = this.Waitfor( "device services", device.GetGattServicesAsync()); DeviceAccessStatus deviceAccessStatus = this.Waitfor( "device access", device.RequestAccessAsync()); this.logEol($"Device access status: {deviceAccessStatus}"); System.Guid gyroServiceGuid = System.Guid.Parse("0000ffe0-0000-1000-8000-00805f9b34fb"); GattDeviceService gyroService = deviceServices.Services.Single(x => x.Uuid.Equals(gyroServiceGuid)); var gyroServiceAccessStatus = this.Waitfor( "gro data service access", gyroService.RequestAccessAsync()); this.logEol($"Gyro service access status: {gyroServiceAccessStatus}"); GattCharacteristicsResult characteristics = this.Waitfor( "gyro data service", gyroService.GetCharacteristicsAsync()); this.txRxChannel = characteristics .Characteristics .SingleOrDefault(x => x.UserDescription.Replace(" ", "") == "TX&RX"); if (this.txRxChannel == default(GattCharacteristic)) { this.logEol("Couldn't find TXRX channel...disconnected?"); return(false); } this.txRxChannel.ValueChanged += this.TxRx_ValueChanged; return(true); }
public async Task <ResourceEnumerationResult> EnumerateResourcesAsync(string deviceId) { using (var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceId)) { if (bleDevice == null) { return(new ResourceEnumerationResult(ResourceEnumerationResult.EnumerationStatus.ProtocolError)); } var discoveredCharacteristics = new List <ICharacteristicInfo>(); var device = bleDevice.ToDeviceInfo(discoveredCharacteristics); // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. // For all uses we recommend using the GetGattServicesAsync method. // BT_Code: GetGattServicesAsync returns a list of all the supported services of // the device (even if it's not paired to the system). // If the services supported by the device are expected to change during BT usage, // subscribe to the GattServicesChanged event. GattDeviceServicesResult result = await bleDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status != GattCommunicationStatus.Success) { var status = result.Status.ToEnumerationStatus(); return(new ResourceEnumerationResult(device, status)); } foreach (var service in result.Services) { var gattCharacteristicsResult = await service.GetCharacteristicsAsync(); if (result.Status != GattCommunicationStatus.Success) { var status = gattCharacteristicsResult.Status.ToEnumerationStatus(); return(new ResourceEnumerationResult(device, status)); } var servicChars = gattCharacteristicsResult.Characteristics.Select(ch => ch.ToCharacteristicInfo()); discoveredCharacteristics.AddRange(servicChars); } return(new ResourceEnumerationResult(device, ResourceEnumerationResult.EnumerationStatus.Success)); } }
// Not used but can be usefull for debugging public async void EnumeratingUsages() { if (!HasDeviceConnected()) { return; } GattDeviceServicesResult services = await connectedDevice.GetGattServicesAsync(); if (services.Status == GattCommunicationStatus.Success) { foreach (GattDeviceService s in services.Services) { await s.RequestAccessAsync(); GattCharacteristicsResult characteristicsResult = await s.GetCharacteristicsAsync(); Console.WriteLine("Service : " + s.Uuid); if (characteristicsResult.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in characteristicsResult.Characteristics) { GattCharacteristicProperties props = c.CharacteristicProperties; Console.WriteLine("\t characteristics : " + c.Uuid + " / " + c.UserDescription); if (props.HasFlag(GattCharacteristicProperties.Read)) { Console.WriteLine("\t\tRead"); } if (props.HasFlag(GattCharacteristicProperties.Write)) { Console.WriteLine("\t\tWrite"); } if (props.HasFlag(GattCharacteristicProperties.Notify)) { Console.WriteLine("\t\tNotify"); } } } s.Dispose(); } } }
public void Dispose() { Disconnect(); Gatt = null; AllCharacteristic = null; Characteristic = null; if (Device != null) { Device.Dispose(); } Device = null; IsConnected = false; // Finally, we clear this device to welcome new Advertisements MainBoard.registeredBluetoothDevices.RemoveAll(s => s == BluetoothAddress); }
private async void ConnDevice_Button_Click(object sender, RoutedEventArgs e) { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ConnDevice_Id.Text); if (bluetoothLeDevice == null) { FindDevice_List.Text += String.Format("{0} : Failed to connect to device.\r\n", ConnDevice_Id.Text); return; } GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); int control_a = 0; if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { FindDevice_List.Text += String.Format("{0} : {1} \r\n", bluetoothLeDevice.Name, service.Uuid); var characteristics = await service.GetCharacteristicsAsync(); var characterCount = 0; foreach (var characteristic in characteristics.Characteristics) { if (control_a == 5) { character_now = characteristic; } control_a++; if (characteristic.CharacteristicProperties.Equals(GattCharacteristicProperties.Notify)) { ConnService_Id.Text = service.Uuid.ToString(); } FindDevice_List.Text += String.Format("\t {0} : {1} : {2}\r\n", characterCount++, characteristic.UserDescription, characteristic.CharacteristicProperties); } } } else { FindDevice_List.Text += String.Format("{0} : {1}\r\n", bluetoothLeDevice.Name, "NOT FOUND ANY SERVICE"); } }
/// <summary> /// Gets characteristic for uuid /// </summary> /// <param name="uuid">Uuid for characteristic</param> /// <returns></returns> private async Task <GattCharacteristic> GetCharacteristic(Guid uuid) { GattCharacteristic characteristic = null; GattDeviceServicesResult servicesResult = await mBluetoothLEDevice.GetGattServicesForUuidAsync(uuid); if (servicesResult.Status == GattCommunicationStatus.Success) { GattCharacteristicsResult characteristicsResult = await servicesResult.Services[0].GetCharacteristicsForUuidAsync(uuid); if (characteristicsResult.Status == GattCommunicationStatus.Success) { if (characteristicsResult.Characteristics.Count == 1) { characteristic = characteristicsResult.Characteristics[0]; } } } return(characteristic); }
/// <summary> /// Get the list of the GATT services included in a specific GATT service /// </summary> /// <returns>List of the included GATT services</returns> public async Task <IList <BleGattService> > GetServicesAsync(BleGattService service) { List <BleGattService> services = new List <BleGattService>(); GattDeviceService gatt_service = service.Context as GattDeviceService; GattDeviceServicesResult result = await gatt_service.GetIncludedServicesAsync(BluetoothCacheMode.Uncached); foreach (GattDeviceService included_service in result.Services) { BleGattService ble_service = new BleGattService(); ble_service.Name = ""; ble_service.Guid = gatt_service.Uuid; ble_service.Context = included_service; services.Add(ble_service); } return(services); }