public void GetDataFromAccelero() { Task task = Task.Run(async() => { GattDeviceServicesResult sensorServiceResult = await bluetoothDevice.GetGattServicesForUuidAsync(SensorSRVID); GattDeviceServicesResult heartrateService = await bluetoothDevice.GetGattServicesForUuidAsync(HeartrateSRVID); GattCharacteristicsResult characteristicsResult1 = await sensorServiceResult.Services[0].GetCharacteristicsForUuidAsync(SensorCHARMES); GattCharacteristicsResult characteristicsResult2 = await sensorServiceResult.Services[0].GetCharacteristicsForUuidAsync(SensorCHARID); GattCharacteristicsResult characteristicsResult3 = await sensorServiceResult.Services[0].GetCharacteristicsForUuidAsync(new Guid("000000070000351221180009af100700")); GattCharacteristicsResult heartrateNotifyCharacteristic = await heartrateService.Services[0].GetCharacteristicsForUuidAsync(HeartrateNOTIFYID); if (characteristicsResult1.Status == GattCommunicationStatus.Success && heartrateNotifyCharacteristic.Characteristics.Count > 0) { GattCommunicationStatus notify = await heartrateNotifyCharacteristic.Characteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (notify == GattCommunicationStatus.Success) { sensorNCharacteristic = heartrateNotifyCharacteristic.Characteristics[0]; sensorNCharacteristic.ValueChanged += OnAccelData; } } WriteToDevice(characteristicsResult2.Characteristics[0], new byte[] { 0x01, 0x03, 0x19 }); GattDescriptorsResult descriptor = await heartrateNotifyCharacteristic.Characteristics[0].GetDescriptorsForUuidAsync(new Guid("0000" + "2902" + "-0000-1000-8000-00805f9b34fb")); DataWriter dataWriter = new DataWriter(); dataWriter.WriteBytes(new byte[] { 1, 0 }); await descriptor.Descriptors[0].WriteValueAsync(dataWriter.DetachBuffer()); WriteToDevice(characteristicsResult2.Characteristics[0], new byte[] { 0x02 }); HeartrateKeepAliveThread = new Task(RunHeartrateKeepAlive2, TaskCreationOptions.LongRunning); HeartrateKeepAliveThread.Start(); while (true) { ; } }); }
/// <summary> /// Add a service (and it's included services, characteristics, and descriptors) to the lists /// </summary> /// <param name="service">The service to add</param> private async Task AddService(GattDeviceService service) { if (!serviceObjects.Contains(service)) { GattDeviceServicesResult res = await service.GetIncludedServicesAsync(); if (res.Status == GattCommunicationStatus.Success) { foreach (GattDeviceService s in res.Services) { await AddService(s); } } GattCharacteristicsResult charRes = await service.GetCharacteristicsAsync(); if (charRes.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in charRes.Characteristics) { GattDescriptorsResult descRes = await c.GetDescriptorsAsync(); if (descRes.Status == GattCommunicationStatus.Success) { foreach (GattDescriptor d in descRes.Descriptors) { descriptorObjects.Add(d); } } characteristicObjects.Add(c); } } serviceObjects.Add(service); } }
private async Task BuildDescriptors(GattCharacteristic ch, BLE_CharacteristicDataModel dataModel) { try { // TODO - change to an awaitable with result this.log.InfoEntry("BuildDescriptors"); dataModel.Descriptors = new List <BLE_DescriptorDataModel>(); GattDescriptorsResult descriptors = await ch.GetDescriptorsAsync(); if (descriptors.Status == GattCommunicationStatus.Success) { if (descriptors.Descriptors.Count > 0) { foreach (GattDescriptor desc in descriptors.Descriptors) { GattReadResult r = await desc.ReadValueAsync(); if (r.Status == GattCommunicationStatus.Success) { // New characteristic data model to add to service IDescParser parser = this.descParserfactory.GetParser(desc.Uuid, desc.AttributeHandle); BLE_DescriptorDataModel descDataModel = new BLE_DescriptorDataModel() { Uuid = desc.Uuid, AttributeHandle = desc.AttributeHandle, ProtectionLevel = (BLE_ProtectionLevel)desc.ProtectionLevel, DisplayName = parser.Parse(r.Value.FromBufferToBytes()), Parser = parser, }; dataModel.Descriptors.Add(descDataModel); this.log.Info("ConnectToDevice", () => string.Format(" Descriptor:{0} Uid:{1} Value:{2}", BLE_DisplayHelpers.GetDescriptorName(desc), desc.Uuid.ToString(), descDataModel.DisplayName)); } ; } } } else { this.log.Error(9999, "BuildDescriptors", () => string.Format("Get Descriptors result:{0}", descriptors.Status.ToString())); } } catch (Exception e) { this.log.Exception(9999, " BuildDescriptors", "", e); } }
/// <summary> /// Get the list of the GATT descriptors included in a specific GATT characteristic /// </summary> /// <returns>List of the included GATT descriptors</returns> public async Task <IList <BleGattDescriptor> > GetDescriptorsAsync(BleGattCharacteristic characteristic) { List <BleGattDescriptor> descriptors = new List <BleGattDescriptor>(); GattCharacteristic gatt_characteristic = characteristic.Context as GattCharacteristic; GattDescriptorsResult result = await gatt_characteristic.GetDescriptorsAsync(BluetoothCacheMode.Uncached); foreach (GattDescriptor descriptor in result.Descriptors) { BleGattDescriptor ble_descriptor = new BleGattDescriptor(); ble_descriptor.Name = ""; ble_descriptor.Guid = descriptor.Uuid; ble_descriptor.Context = descriptor; descriptors.Add(ble_descriptor); } return(descriptors); }
private async Task GetAllDescriptors() { StringBuilder sb = new StringBuilder(); sb.Append("ObservableGattCharacteristics::getAllDescriptors: "); sb.Append(Name); try { GattDescriptorsResult result = await characteristic.GetDescriptorsAsync(Services.SettingsServices.SettingsService.Instance.UseCaching?BluetoothCacheMode.Cached : BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { sb.Append(" - found "); sb.Append(result.Descriptors.Count); sb.Append(" descriptors"); Debug.WriteLine(sb); foreach (GattDescriptor descriptor in result.Descriptors) { ObservableGattDescriptors temp = new ObservableGattDescriptors(descriptor, this); await temp.Initialize(); Descriptors.Add(temp); } } else if (result.Status == GattCommunicationStatus.Unreachable) { sb.Append(" - failed with Unreachable"); Debug.WriteLine(sb.ToString()); } else if (result.Status == GattCommunicationStatus.ProtocolError) { sb.Append(" - failed with ProtocolError"); Debug.WriteLine(sb.ToString()); } } catch (Exception ex) { Debug.WriteLine(" - Exception: {0}" + ex.Message); Value = "Unknown (exception: " + ex.Message + ")"; } }
private async void GetAllDescriptors() { StringBuilder sb = new StringBuilder(); sb.Append("ObservableGattCharacteristics::getAllDescriptors: "); sb.Append(Name); try { GattDescriptorsResult result = await Characteristic.GetDescriptorsAsync(Parent.CacheMode); if (result.Status == GattCommunicationStatus.Success) { sb.Append(" - found "); sb.Append(result.Descriptors.Count); sb.Append(" descriptors"); Debug.WriteLine(sb); foreach (GattDescriptor descriptor in result.Descriptors) { Descriptors.Add(new ObservableGattDescriptors(descriptor, this)); } } else if (result.Status == GattCommunicationStatus.Unreachable) { sb.Append(" - failed with Unreachable"); Debug.WriteLine(sb.ToString()); } else if (result.Status == GattCommunicationStatus.ProtocolError) { sb.Append(" - failed with ProtocolError"); Debug.WriteLine(sb.ToString()); } } catch (Exception ex) { Debug.WriteLine(" - Exception: {0}" + ex.Message); throw; } }
private async Task BuildDescriptors(GattCharacteristic ch, BLE_CharacteristicDataModel dataModel) { dataModel.Descriptors = new Dictionary <string, BLE_DescriptorDataModel>(); GattDescriptorsResult descriptors = await ch.GetDescriptorsAsync(); if (descriptors.Status == GattCommunicationStatus.Success) { if (descriptors.Descriptors.Count > 0) { foreach (GattDescriptor desc in descriptors.Descriptors) { GattReadResult r = await desc.ReadValueAsync(); if (r.Status == GattCommunicationStatus.Success) { // New characteristic data model to add to service BLE_DescriptorDataModel descDataModel = new BLE_DescriptorDataModel() { Uuid = desc.Uuid, AttributeHandle = desc.AttributeHandle, ProtectionLevel = (BLE_ProtectionLevel)desc.ProtectionLevel, DisplayName = BLE_ParseHelpers.GetDescriptorValueAsString(desc.Uuid, r.Value.FromBufferToBytes()) }; dataModel.Descriptors.Add(descDataModel.Uuid.ToString(), descDataModel); this.log.Info("ConnectToDevice", () => string.Format(" Descriptor:{0} Uid:{1} Value:{2}", BLE_DisplayHelpers.GetDescriptorName(desc), desc.Uuid.ToString(), descDataModel.DisplayName)); } ; } } } else { this.log.Error(9999, "BuildDescriptors", () => string.Format("Get Descriptors result:{0}", descriptors.Status.ToString())); } }
public async Task <Tuple <GattCommunicationStatus, byte[]> > ReadDescriptorValueAsync(GattCharacteristic characteristic) { GattDescriptorsResult result = await characteristic.GetDescriptorsAsync(); byte[] output = null; if (result.Status == GattCommunicationStatus.Success) { IReadOnlyList <GattDescriptor> descriptors = result.Descriptors; foreach (GattDescriptor d in descriptors) { var value = await d.ReadValueAsync(); var reader = DataReader.FromBuffer(value.Value); output = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(output); } } else { output = new byte[0]; } return(new Tuple <GattCommunicationStatus, byte[]>(result.Status, output)); }
public bool GetFeatures() { foreach (var service in services.Services) { string servUuid = service.Uuid.ToString().Substring(4, 4); if (!servUuid.Equals("ffe0")) { continue; } var t = Task.Run(async() => await service.GetCharacteristicsAsync()); ueiCharacteristics = WaitTask(t, 10) == t ? t.Result : null; break; } services = null; stage = 4; if (ueiCharacteristics == null) { return(false); } foreach (var characteristic in ueiCharacteristics.Characteristics) { String chUuid = characteristic.Uuid.ToString().Substring(4, 4); var t = Task.Run(async() => await characteristic.GetDescriptorsAsync()); ueiDescriptors = WaitTask(t, 10) == t ? t.Result : null; stage = 5; if (ueiDescriptors == null) { return(false); } foreach (var descriptor in ueiDescriptors.Descriptors) { String s = descriptor.Uuid.ToString().Substring(4, 4); if (chUuid.Equals("ffe2") && s.Equals("2902")) { hasCCCD = true; } else if (chUuid.Equals("ffe2") && s.Equals("2901")) { readChUserDesc = descriptor; } else if (chUuid.Equals("ffe1") && s.Equals("2901")) { writeChUserDesc = descriptor; } } if (chUuid.Equals("ffe1")) { writeCh = characteristic; } else if (chUuid.Equals("ffe2")) { readCh = characteristic; } } ueiCharacteristics = null; stage = 6; if (hasCCCD) { Subscribe(GattClientCharacteristicConfigurationDescriptorValue.Notify); readCh.ValueChanged += DataCharacteristic_ValueChanged; } stage = 7; ReadSubscription(); stage = 8; if (subscription == null) { return(false); } return(true); }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { BluetoothLEAdvertisement advertisement = args.Advertisement; if (tryConnecting || connected || btAddresses.Contains(args.BluetoothAddress)) { return; } btAddresses.Add(args.BluetoothAddress); Log($"New advertisement from address {args.BluetoothAddress:x} with name {advertisement.LocalName}"); tryConnecting = true; device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); if (device != null) { connected = true; tryConnecting = false; Log($" BluetoothLEDevice Name={device.Name}"); Log("-- Enumerating all BLE services, characteristics, and descriptors"); GattDeviceServicesResult getGattServices = await device.GetGattServicesAsync(); if (GattCommunicationStatus.Success == getGattServices.Status) { foreach (GattDeviceService service in getGattServices.Services) { Log($" Service {service.Uuid}"); GattCharacteristicsResult getCharacteristics = await service.GetCharacteristicsAsync(); if (GattCommunicationStatus.Success == getCharacteristics.Status) { foreach (GattCharacteristic characteristic in getCharacteristics.Characteristics) { Log($" Characteristic {characteristic.Uuid} property {characteristic.CharacteristicProperties}"); if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read)) { GattReadResult readResult = await characteristic.ReadValueAsync(); if (GattCommunicationStatus.Success == readResult.Status) { LogBuffer($" Read value 0x", readResult.Value); } else { Log($" Failed to read from readable characteristic"); } } GattDescriptorsResult getDescriptors = await characteristic.GetDescriptorsAsync(); if (GattCommunicationStatus.Success == getDescriptors.Status) { foreach (GattDescriptor descriptor in getDescriptors.Descriptors) { GattReadResult readResult = await descriptor.ReadValueAsync(); if (GattCommunicationStatus.Success == readResult.Status) { LogBuffer($" Descriptor {descriptor.Uuid} value 0x", readResult.Value); } } } else { Log($"Getting GATT descriptors failed with status {getDescriptors.Status}"); } } } else { Log($"Getting GATT characteristics failed with status {getCharacteristics.Status}"); } } foreach (GattDeviceService service in getGattServices.Services) { service.Session.Dispose(); service.Dispose(); } } else { Log($"Getting GATT services failed with status {getGattServices.Status}"); } // Dump complete, release device. device.Dispose(); device = null; connected = false; } else { tryConnecting = false; Log($" Failed to obtain BluetoothLEDevice from that advertisement"); } }
public async Task <GattDescriptorsResult> GetDescriptorsAsync(GattCharacteristic characteristic) { GattDescriptorsResult results = await characteristic.GetDescriptorsAsync(); return(results); }
private async Task ConnectToDevice(BluetoothLEDeviceInfo deviceInfo) { this.log.Info("ConnectToDevice", () => string.Format("Attempting connection to {0}: FromIdAsync({1})", deviceInfo.Name, deviceInfo.Id)); try { // https://github.com/microsoft/Windows-universal-samples/blob/master/Samples/BluetoothLE/cs/Scenario2_Client.xaml.cs this.log.Info("ConnectToDevice", () => string.Format("--------------------------------------------------------------------")); this.log.Info("ConnectToDevice", () => string.Format(" Param Device Info ID {0}", deviceInfo.Id)); this.currentDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); if (this.currentDevice == null) { this.log.Info("ConnectToDevice", "Connection failed"); } else { this.log.Info("ConnectToDevice", "Connection ** OK **"); this.currentDevice.NameChanged += CurrentDevice_NameChanged; } // This just does the easy serial communications - this is using a regular HC-05 Classic (RFCOMM) board //RfcommDeviceService s = await RfcommDeviceService.FromIdAsync(this.id); //BluetoothDevice.GetRfcommServicesAsync(); this.log.Info("ConnectToDevice", () => string.Format("Device:{0} Connection status {1}", this.currentDevice.Name, this.currentDevice.ConnectionStatus.ToString())); GattDeviceServicesResult services = await this.currentDevice.GetGattServicesAsync(); if (services.Status == GattCommunicationStatus.Success) { if (services.Services != null) { if (services.Services.Count > 0) { foreach (GattDeviceService serv in services.Services) { // Service this.log.Info("ConnectToDevice", () => string.Format("Gatt Service:{0} Uid:{1}", BLE_DisplayHelpers.GetServiceName(serv), serv.Uuid.ToString())); GattCharacteristicsResult characteristics = await serv.GetCharacteristicsAsync(); if (characteristics.Status == GattCommunicationStatus.Success) { if (characteristics.Characteristics != null) { if (characteristics.Characteristics.Count > 0) { foreach (GattCharacteristic ch in characteristics.Characteristics) { await this.DumpCharacteristic(ch); GattDescriptorsResult descriptors = await ch.GetDescriptorsAsync(); if (descriptors.Status == GattCommunicationStatus.Success) { if (descriptors.Descriptors.Count > 0) { foreach (GattDescriptor desc in descriptors.Descriptors) { GattReadResult r = await desc.ReadValueAsync(); string descName = "N/A"; if (r.Status == GattCommunicationStatus.Success) { //descName = Encoding.ASCII.GetString(r.Value.FromBufferToBytes()); descName = BLE_ParseHelpers.GetDescriptorValueAsString(desc.Uuid, r.Value.FromBufferToBytes()); } // descriptors have read and write this.log.Info("ConnectToDevice", () => string.Format(" Descriptor:{0} Uid:{1} Value:{2}", BLE_DisplayHelpers.GetDescriptorName(desc), desc.Uuid.ToString(), descName)); } } } else { this.log.Info("ConnectToDevice", () => string.Format(" Get Descriptors result:{0}", descriptors.Status.ToString())); } } } else { this.log.Info("ConnectToDevice", () => string.Format("No characteristics")); } } } else { this.log.Info("ConnectToDevice", () => string.Format(" Characteristics result {0}", characteristics.Status.ToString())); } } } else { this.log.Info("ConnectToDevice", "No services exposed"); } } else { this.log.Error(9999, "Null services"); } } else { this.log.Info("ConnectToDevice", () => string.Format(" Get Services result {0}", services.Status.ToString())); } this.log.Info("ConnectToDevice", () => string.Format("--------------------------------------------------------------------")); } catch (Exception e) { this.log.Exception(9999, "BLE Connect Exception", e); } try { if (this.currentDevice == null) { // report error this.log.Info("ConnectToDevice", () => string.Format("NULL device returned for {0}", deviceInfo.Id)); return; } else { // 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 this.currentDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); ////GattDeviceServicesResult result = await BluetoothLEDevice.FromIdAsync(this.currentDevice.DeviceId); //System.Diagnostics.Debug.WriteLine("Device Connected {0}", this.currentDevice.BluetoothAddress); this.log.Info("ConnectToDevice", () => string.Format("Device Connected {0}", this.currentDevice.BluetoothAddress)); } } catch (Exception ex) { this.log.Exception(9999, "on main task", ex); } }
private IEnumerable <GattDescriptor> ParseResult(GattDescriptorsResult result) { Platform.AssertStatus(result.Status, result.ProtocolError); return(result.Descriptors.Select(x => new GattDescriptor(x, this))); }
/// <summary> /// Connect to the device, check if there's the DFU Service and start the firmware update /// </summary> /// <param name="device">The device discovered</param> /// <returns></returns> public async void connectToDeviceAsync(DeviceInformation device) { try { var deviceAddress = "N/A"; if (device.Id.Contains("-")) { deviceAddress = device.Id.Split('-')[1]; } Console.WriteLine("Connecting to:" + deviceAddress + "..."); BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id); Console.WriteLine("Name:" + bluetoothLeDevice); //Perform the connection to the device var result = await bluetoothLeDevice.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { Console.WriteLine("Device " + deviceAddress + " connected. Updating firmware..."); //Scan the available services var services = result.Services; foreach (var service_ in services) { Console.WriteLine("Service " + service_.Uuid); //If DFUService found... if (service_.Uuid == new Guid(UARTService.UARTService_UUID)) { //NRF52 DFU Service Console.WriteLine("UART Service found"); service = service_; //Scan the available characteristics GattCharacteristicsResult result_ = await service.GetCharacteristicsAsync(); if (result_.Status == GattCommunicationStatus.Success) { var characteristics = result_.Characteristics; foreach (var characteristic in characteristics) { Console.WriteLine("Char " + characteristic.Uuid + "-"); Console.WriteLine("Handle " + characteristic.AttributeHandle + "-"); Console.WriteLine("Handle " + characteristic.UserDescription + "-"); if (characteristic.Uuid.ToString() == UARTCharacteristics_UUID_RX) { Console.WriteLine("UARTService_UUID_RX found " + characteristic.UserDescription); this.rxCharacteristic = characteristic; } if (characteristic.Uuid.ToString() == UARTCharacteristics_UUID_TX) { Console.WriteLine("UARTService_UUID_TX found " + characteristic.UserDescription); this.txCharacteristic = characteristic; } GattDescriptorsResult result2_ = await characteristic.GetDescriptorsAsync(); var descriptors = result2_.Descriptors; foreach (var descriptor in descriptors) { Console.WriteLine("Descr " + descriptor.Uuid + "-"); Console.WriteLine("Handle " + descriptor.AttributeHandle + "-"); if (descriptor.Uuid.ToString() == CCCD) { Console.WriteLine("CCC found " + characteristic.UserDescription); this.cccd = descriptor; } } } } this.startReaderAsync(this.txCharacteristic); this.startReaderAsync(this.rxCharacteristic); break; } } } else { Console.WriteLine("Status error: " + result.Status.ToString() + " need to restarte the device"); } } catch (Exception e) { Console.WriteLine("ERROR: Accessing2 your device failed." + Environment.NewLine + e.Message + "\n" + e.StackTrace); } }
public static void ThrowIfError(this GattDescriptorsResult result, [CallerMemberName] string tag = null) => result.Status.ThrowIfError(tag, result.ProtocolError);