Exemple #1
0
        /// <summary>
        /// Registers characteristic handlers for the device driver module service.
        /// </summary>
        /// <param name="service"></param>
        private async Task RegisterDeviceModuleDriverServiceCharacteristicsAsync(GattDeviceService service)
        {
            //Getting the characteristics of the service.
            GattCharacteristicsResult results = await service.GetCharacteristicsAsync();

            if (results.Status == GattCommunicationStatus.Success)
            {
                foreach (GattCharacteristic characteristic in results.Characteristics)
                {
                    if (characteristic.Uuid == DEVICE_BATTERY_WRITE_CHARACTERISTIC_UUID)
                    {
                        //Caching the device module driver
                        deviceModuleDriverReadWriteCharacteristic = characteristic;

                        //Registering block state changed indicator.
                        GattCommunicationStatus commStatus = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        if (commStatus == GattCommunicationStatus.Success)
                        {
                            characteristic.ValueChanged += OnDeviceBatteryInfoUpdated;
                            Console.WriteLine("Successfully registered notify for battery read.");
                        }
                        else
                        {
                            OnConnectionError(commStatus);
                        }
                    }
                }
            }
            else
            {
                OnConnectionError(results.Status);
            }
        }
        /// <summary>
        /// Retrieves the characteristics of the given service.
        /// The error logging is handled in the function.
        /// </summary>
        /// <param name="service"></param>
        /// <returns>The list of characteristic if it succeed, null otherwise</returns>
        public static async Task <IReadOnlyList <GattCharacteristic> > GetCharacteristics(GattDeviceService service)
        {
            try
            {
                DeviceAccessStatus status = await service.RequestAccessAsync();

                if (status == DeviceAccessStatus.Allowed)
                {
                    GattCharacteristicsResult result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        return(result.Characteristics);
                    }
                    else
                    {
                        LogHelper.Error("Error accessing device");
                        return(null);
                    }
                }
                else
                {
                    LogHelper.Error("Error accessing device: access not granted");
                    return(null);
                }
            }
            catch (Exception e)
            {
                LogHelper.Error("Restricted service. Can't read characteristics: " + e.Message);
                return(null);
            }
        }
Exemple #3
0
        /// <summary>
        /// Get the list of the GATT characteristics included in a specific GATT service
        /// </summary>
        /// <returns>List of the included GATT characteristics</returns>
        public async Task <IList <BleGattCharacteristic> > GetCharacteristicsAsync(BleGattService service)
        {
            List <BleGattCharacteristic> characteristics = new List <BleGattCharacteristic>();

            GattDeviceService         gatt_service = service.Context as GattDeviceService;
            GattCharacteristicsResult result       = await gatt_service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

            foreach (GattCharacteristic characteristic in result.Characteristics)
            {
                BleGattCharacteristic ble_characteristic = new BleGattCharacteristic();
                ble_characteristic.Name     = "";
                ble_characteristic.Guid     = characteristic.Uuid;
                ble_characteristic.Context  = characteristic;
                ble_characteristic.CanRead  = characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read);
                ble_characteristic.CanWrite = ((characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) ||
                                               (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse)));
                ble_characteristic.CanNotify = ((characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) ||
                                                (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate)));

                characteristics.Add(ble_characteristic);
                _ble_characteristics.Add(characteristic, ble_characteristic);
            }

            return(characteristics);
        }
        /// <summary>
        /// Registers characteristic handlers for the device data service.
        /// </summary>
        /// <param name="service"></param>
        private async Task RegisterDataServiceCharacteristicsAsync(GattDeviceService service)
        {
            //Getting the characteristics of the service.
            GattCharacteristicsResult results = await service.GetCharacteristicsAsync();

            if (results.Status == GattCommunicationStatus.Success)
            {
                foreach (GattCharacteristic characteristic in results.Characteristics)
                {
                    if (characteristic.Uuid == DEVICE_DATA_READ_CHARACTERISTIC_UUID)
                    {
                        //Registering block state changed indicator.
                        GattCommunicationStatus commStatus = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        if (commStatus == GattCommunicationStatus.Success)
                        {
                            characteristic.ValueChanged += OnBlockStateInfoUpdate;
                            Console.WriteLine("Successfully registered notify for data read.");
                        }
                        else
                        {
                            OnConnectionError(commStatus);
                        }
                    }
                }
            }
            else
            {
                OnConnectionError(results.Status);
            }
        }
Exemple #5
0
        public async Task FindAllServices(GattDeviceService service)
        {
            try
            {
                IReadOnlyList <GattCharacteristic> characteristics = null;
                var accessStatus = await service.RequestAccessAsync();

                if (accessStatus == DeviceAccessStatus.Allowed)
                {
                    var result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        characteristics = result.Characteristics;
                    }
                    else
                    {
                        // On error, act as if there are no characteristics.
                        characteristics = new List <GattCharacteristic>();
                    }
                    foreach (GattCharacteristic c in characteristics)
                    {
                        // add to a list
                    }
                }
            }
            catch
            {
            }
        }
Exemple #6
0
        private async Task DiscoverControlCharacteristics()
        {
            if (_controlService != null)
            {
                var characteristicsResult = await _controlService.GetCharacteristicsAsync();

                foreach (var characteristic in characteristicsResult.Characteristics)
                {
                    if (characteristic.Uuid == MyoInfoCharacteristicUUID)
                    {
                        _myoInfoCharacteristic = characteristic;
                    }
                    else if (characteristic.Uuid == FirmwareVersionCharacteristicUUID)
                    {
                        _firmwareVersionCharacteristic = characteristic;
                    }
                    else if (characteristic.Uuid == CommandCharacteristicUUID)
                    {
                        _commandCharacteristic = characteristic;
                    }
                }
            }
            else
            {
                Debug.LogError("Control Service is missing!");
            }
        }
Exemple #7
0
        private async Task DiscoverEmgDataCharacteristics()
        {
            if (_emgDataService != null)
            {
                var characteristicsResult = await _emgDataService.GetCharacteristicsAsync();

                foreach (var characteristic in characteristicsResult.Characteristics)
                {
                    if (characteristic.Uuid == EmgData0CharacteristicUUID)
                    {
                        _emgData0Characteristic = characteristic;
                    }
                    else if (characteristic.Uuid == EmgData1CharacteristicUUID)
                    {
                        _emgData1Characteristic = characteristic;
                    }
                    else if (characteristic.Uuid == EmgData2CharacteristicUUID)
                    {
                        _emgData2Characteristic = characteristic;
                    }
                    else if (characteristic.Uuid == EmgData3CharacteristicUUID)
                    {
                        _emgData3Characteristic = characteristic;
                    }
                }
            }
            else
            {
                Debug.LogError("EMG Data Service is missing!");
            }
        }
Exemple #8
0
        /// <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);
            }
        }
Exemple #9
0
 private void GetCharacteristics()
 {
     _Service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached)
     .AsTask()
     .ContinueWith(async r3 =>
     {
         _Characteristics = r3.Result.Characteristics.ToList();
         if (_Characteristics?.Count != 4)
         {
             Thread.Sleep(300);
             GetCharacteristics();
         }
         else
         {
             _WriteChar                = _Characteristics.First(c => c.Uuid == WriteCharUUID);
             _ReadChar                 = _Characteristics.First(c => c.Uuid == ReadCharUUID);
             _NotifyChar               = _Characteristics.First(c => c.Uuid == NotifyCharUUID);
             _ReadChar.ValueChanged   += _Read;
             _NotifyChar.ValueChanged += _Read;
             await _ReadChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
             await _NotifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
         }
     })
     .Wait();
 }
Exemple #10
0
        /// <summary>
        /// Get GATT characteristic by service UUID.
        /// Returns <see cref="GattCharacteristic"/>'s default in case of "Access denied" or "Service not found".
        /// </summary>
        /// <param name="service">GATT Service</param>
        /// <param name="characteristicUuid">GATT Characteristic UUID</param>
        /// <returns>GattCharacteristic object if characteristic is exists, else returns null</returns>
        public static async Task <GattCharacteristic> GetCharacteristicFromUuid(GattDeviceService service,
                                                                                Guid characteristicUuid)
        {
            GattCharacteristicsResult currentResult = await service.GetCharacteristicsAsync();

            return(currentResult.Characteristics.FirstOrDefault(characteristic =>
                                                                characteristic.Uuid == characteristicUuid));
        }
        public async Task <GattCharacteristic> GetCharacteristic(GattDeviceService service)
        {
            var characteristics = await service.GetCharacteristicsAsync();

            var characteristic = characteristics.Characteristics.Single(c => c.Uuid == new Guid("00001624-1212-efde-1623-785feabcd123"));

            return(characteristic);
        }
Exemple #12
0
        //public IAsyncOperation<GattCharacteristicsResult> GetCharacteristicsAsync(BluetoothCacheMode cacheMode);
        public async Task Init(GattDeviceService service)
        {
            var characteristics = await service.GetCharacteristicsAsync(); //NOTE: cache mode?

            foreach (var characteristic in characteristics.Characteristics)
            {
            }
        }
        /// <summary>
        /// Gets all the characteristics of this service
        /// </summary>
        private async Task GetAllCharacteristics()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("ObservableGattDeviceService::getAllCharacteristics: ");
            sb.Append(name);

            try
            {
                // Request the necessary access permissions for the service and abort
                // if permissions are denied.
                GattOpenStatus status = await service.OpenAsync(GattSharingMode.SharedReadAndWrite);

                if (status != GattOpenStatus.Success && status != GattOpenStatus.AlreadyOpened)
                {
                    string error = " - Error: " + status.ToString();
                    Name += error;
                    sb.Append(error);
                    Debug.WriteLine(sb.ToString());

                    return;
                }

                GattCharacteristicsResult result = await service.GetCharacteristicsAsync(Services.SettingsServices.SettingsService.Instance.UseCaching?BluetoothCacheMode.Cached : BluetoothCacheMode.Uncached);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    sb.Append(" - getAllCharacteristics found ");
                    sb.Append(result.Characteristics.Count());
                    sb.Append(" characteristics");
                    Debug.WriteLine(sb);
                    foreach (GattCharacteristic gattchar in result.Characteristics)
                    {
                        ObservableGattCharacteristics temp = new ObservableGattCharacteristics(gattchar, this);
                        await temp.Initialize();

                        Characteristics.Add(temp);
                    }
                }
                else if (result.Status == GattCommunicationStatus.Unreachable)
                {
                    sb.Append(" - getAllCharacteristics failed with Unreachable");
                    Debug.WriteLine(sb.ToString());
                }
                else if (result.Status == GattCommunicationStatus.ProtocolError)
                {
                    sb.Append(" - getAllCharacteristics failed with Unreachable");
                    Debug.WriteLine(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("getAllCharacteristics: Exception - {0}" + ex.Message);
                Name += " - Exception: " + ex.Message;
            }
        }
        //Get all the characteristics of this service
        private async void GetAllCharacteristics()
        {
            Console.WriteLine("ObservableGattDeviceService::getAllCharacteristics: ");

            try
            {
                //Request the necessary access permission for the service and abort if permissions are denied
                GattOpenStatus status = await service.OpenAsync(GattSharingMode.SharedReadAndWrite);

                if (status != GattOpenStatus.Success && status != GattOpenStatus.AlreadyOpened)
                {
                    Console.WriteLine("Error: " + status.ToString());
                    return;
                }

                CancellationTokenSource tokenSource = new CancellationTokenSource(5000);
                var task = Task.Run(() => service.GetCharacteristicsAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached), tokenSource.Token);

                GattCharacteristicsResult result = null;
                result = await task.Result;

                if (result.Status == GattCommunicationStatus.Success)
                {
                    Console.WriteLine("getAllCharacteristics found " + result.Characteristics.Count() + " characteristics");

                    foreach (GattCharacteristic gattChar in result.Characteristics)
                    {
                        characteristics.Add(new ObservableGattCharacteristics(gattChar, this));
                    }
                }
                else if (result.Status == GattCommunicationStatus.Unreachable)
                {
                    Console.WriteLine("getAllCharacteristics failed with Unreachable");
                }
                else if (result.Status == GattCommunicationStatus.ProtocolError)
                {
                    Console.WriteLine("getAllCharacteristics failed with Unreachable");
                }
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    if (ex is TaskCanceledException)
                    {
                        Console.WriteLine("Getting characteristics took too long. Timed out.");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("getAllCharacteristics: Exception: " + ex.Message);
                throw;
            }
        }
Exemple #15
0
 async void Build(ChangeEvent pEvent)
 {
     mCharacteristics = null;
     mCharacteristics = new List <ICharacteristicBLE>();
     await mService.GetCharacteristicsAsync().AsTask().ContinueWith((arg) =>
     {
         Debug.WriteLine("Found Characteristics.");
         CharacteristicsAquired(arg.Result, pEvent);
     });
 }
        public static async Task <IReadOnlyList <GattCharacteristic> > GetCharacteristics2Async(this GattDeviceService service)
        {
            var result = await service.GetCharacteristicsAsync();

            if (result.Status != GattCommunicationStatus.Success)
            {
                throw new Exception("Could not get characteristics from service");
            }
            return(result.Characteristics);
        }
Exemple #17
0
        //MOSTRA LE CARATTERISTICHE DEL SERVIZIO HR
        private async void servizi()
        {
            GattDeviceService         HRservice         = BluetoothDevice.GetGattService(HRserviceGuid);
            GattCharacteristicsResult HRcharacteristics = await HRservice.GetCharacteristicsAsync();

            foreach (GattCharacteristic caratteristica in HRcharacteristics.Characteristics.Where(caratteristica => caratteristica.AttributeHandle == 36)) //13
            {
                HRreader = caratteristica;
                OutputList.Items.Insert(0, "Servizio HR trovato in" + HRreader.CharacteristicProperties.ToString());
            }
        }
Exemple #18
0
        protected async override Task <IList <ICharacteristic> > GetCharacteristicsNativeAsync()
        {
            var nativeChars = (await _nativeService.GetCharacteristicsAsync()).Characteristics;
            var charList    = new List <ICharacteristic>();

            foreach (var nativeChar in nativeChars)
            {
                var characteristic = new Characteristic(nativeChar, this);
                charList.Add(characteristic);
            }
            return(charList);
        }
Exemple #19
0
        /// <summary>Build the GATT service data model</summary>
        /// <param name="service">The OS GATT service object</param>
        /// <param name="deviceDataModel">The portable GATT session data model</param>
        /// <returns>The async task</returns>
        public async Task BuildServiceDataModel(GattDeviceService service, BluetoothLEDeviceInfo deviceDataModel)
        {
            this.log.Info("BuildServiceDataModel", () => string.Format("Gatt Service:{0}  Uid:{1}",
                                                                       BLE_DisplayHelpers.GetServiceName(service), service.Uuid.ToString()));

            // New service data model to add to device info
            BLE_ServiceDataModel serviceDataModel = new BLE_ServiceDataModel()
            {
                Characteristics = new Dictionary <string, BLE_CharacteristicDataModel>(),
                AttributeHandle = service.AttributeHandle,
                DeviceId        = deviceDataModel.Id,
                DisplayName     = BLE_DisplayHelpers.GetServiceName(service),
                Uuid            = service.Uuid,
                SharingMode     = (BLE_SharingMode)service.SharingMode,
            };

            if (service.DeviceAccessInformation != null)
            {
                serviceDataModel.DeviceAccess = (BLE_DeviceAccessStatus)service.DeviceAccessInformation.CurrentStatus;
            }
            this.BuildSessionDataModel(service.Session, serviceDataModel.Session);

            // TODO
            //service.ParentServices

            // Get the characteristics for the service
            GattCharacteristicsResult characteristics = await service.GetCharacteristicsAsync();

            if (characteristics.Status == GattCommunicationStatus.Success)
            {
                if (characteristics.Characteristics != null)
                {
                    if (characteristics.Characteristics.Count > 0)
                    {
                        foreach (GattCharacteristic ch in characteristics.Characteristics)
                        {
                            await this.BuildCharacteristicDataModel(ch, serviceDataModel);
                        }
                    }
                    else
                    {
                        this.log.Info("ConnectToDevice", () => string.Format("No characteristics"));
                    }
                }
            }
            else
            {
                this.log.Error(9999, "HarvestDeviceInfo", () => string.Format("Failed to get Characteristics result {0}", characteristics.Status.ToString()));
            }

            // Add the service data model to the device info data model
            deviceDataModel.Services.Add(serviceDataModel.Uuid.ToString(), serviceDataModel);
        }
Exemple #20
0
        private static async Task <BleGattService> ExtractDomainModel(GattDeviceService gattDeviceService)
        {
            var srvChars = await gattDeviceService.GetCharacteristicsAsync(BluetoothCacheMode.Cached);

            return(new BleGattService
            {
                Uuid = gattDeviceService.Uuid,
                DeviceId = gattDeviceService.Session?.DeviceId?.Id ?? string.Empty,
                Characteristics = srvChars.Characteristics.AsEnumerable()
                                  .Select(sc => new BleGattCharacteristic(sc.Uuid, sc.UserDescription)).ToArray()
            });
        }
        private async void Get_Characteriisics(GattDeviceService myService)
        {
            var CharResult = await myService.GetCharacteristicsAsync();

            if (CharResult.Status == GattCommunicationStatus.Success)
            {
                foreach (GattCharacteristic c in CharResult.Characteristics)
                {
                    if (c.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        selectedCharacteristic = c;
                        break;
                    }
                }
                try
                {
                    // Write the ClientCharacteristicConfigurationDescriptor in order for server to send notifications.
                    var result = await selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                        GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    if (result == GattCommunicationStatus.Success)
                    {
                        var dialogNotifications = new MessageDialog("Successfully registered for notifications");
                        await dialogNotifications.ShowAsync();

                        selectedCharacteristic.ValueChanged += SelectedCharacteristic_ValueChanged;
                    }
                    else
                    {
                        var dialogNotifications = new MessageDialog($"Error registering for notifications: {result}");
                        await dialogNotifications.ShowAsync();
                    }
                }
                catch (Exception ex)
                {
                    // This usually happens when not all characteristics are found
                    // or selected characteristic has no Notify.
                    var dialogNotifications = new MessageDialog(ex.Message);
                    await dialogNotifications.ShowAsync();

                    await Task.Delay(100);

                    Get_Characteriisics(myService); //try again
                    //!!! Add a max try counter to prevent infinite loop!!!!!!!
                }
            }
            else
            {
                var dialogNotifications = new MessageDialog("Restricted service. Can't read characteristics");
                await dialogNotifications.ShowAsync();
            }
        }
Exemple #22
0
        private async Task <IReadOnlyList <GattCharacteristic> > GetCharacteristics(GattDeviceService service)
        {
            if (service != null)
            {
                var characteristicsResult = await service.GetCharacteristicsAsync();

                if (characteristicsResult.Status == GattCommunicationStatus.Success)
                {
                    return(characteristicsResult.Characteristics);
                }
            }

            return(null);
        }
Exemple #23
0
        private async void AchieveCharateristic(GattDeviceService service)
        {
            var result = await service.GetCharacteristicsAsync();

            var characteristics = result.Characteristics;

            _ListCharacteristics = new ObservableCollection <GattCharacteristicModel>();
            foreach (var characteristic in characteristics)
            {
                Debug.WriteLine(characteristic.Service.Uuid + ": " + characteristic.Uuid);
                _ListCharacteristics.Add(new GattCharacteristicModel(characteristic));
            }
            lvBTDevice.ItemsSource = _ListCharacteristics;
        }
        private async void ListCharactericsButton_Click(object sender, RoutedEventArgs e)
        {
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => listView.Items.Clear());

            service = ((GattDeviceServiceListItem)selectedListItem).service;
            var characteristics = await service.GetCharacteristicsAsync();

            foreach (GattCharacteristic characteristic in characteristics.Characteristics)
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => listView.Items.Add(new GattCharacteristicListItem(characteristic)));

                Debug.WriteLine($"Characteristic UUID: {characteristic.Uuid}");
            }
        }
Exemple #25
0
        private static async void GetCharacteristics(GattDeviceService service)
        {
            IReadOnlyList <GattCharacteristic> characteristics = null;
            string device = service.Device.DeviceInformation.Id.Substring(41);

            try
            {
                DeviceAccessStatus accessStatus = await service.RequestAccessAsync();

                if (accessStatus == DeviceAccessStatus.Allowed)
                {
                    GattCharacteristicsResult result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        characteristics = result.Characteristics;
                        Console.WriteLine("Found Characteristics");
                    }
                    else
                    {
                        blePowermates[device].isSubscribing = false;
                        Console.WriteLine("Error accessing service.");
                        characteristics = new List <GattCharacteristic>();
                    }
                }
                else
                {
                    blePowermates[device].isSubscribing = false;
                    Console.WriteLine("Error accessing service.");
                }
            } catch (Exception ex)
            {
                blePowermates[device].isSubscribing = false;
                Console.WriteLine("Error: Restricted service. Can't read characteristics: " + ex.ToString());
            }

            if (characteristics != null)
            {
                foreach (GattCharacteristic characteristic in characteristics)
                {
                    Console.WriteLine("└Characteristic uuid: " + characteristic.Uuid.ToString());
                    if (UuidEquals(uuidRead, characteristic.Uuid))
                    {
                        SubscribeToValueChange(characteristic);
                        Console.WriteLine(" └Subscribing to Read Characteristic");
                    }
                }
            }
        }
        /// <summary>
        /// Helper function, enumerates a service searching for a specific characteristic.
        /// </summary>
        /// <param name="service">Service to enumerate.</param>
        /// <param name="characteristicAssignedNumber">Characteristic to find.</param>
        /// <returns><see cref="GattCharacteristic"/> of found characteristic, or null.</returns>
        private async Task <GattCharacteristic> FindCharacteristicInService(GattDeviceService service, ushort characteristicAssignedNumber)
        {
            var characteristics = await service.GetCharacteristicsAsync();

            foreach (var characteristic in characteristics.Characteristics)
            {
                var can = Bluetooth.Utility.UuidToAssignedNumber(characteristic.Uuid);
                if (can == characteristicAssignedNumber)
                {
                    return(characteristic);
                }
            }

            return(null);
        }
        private async void EnumeratingChara(GattDeviceService service)
        {
            string charaName;

            characteristics = null;
            try
            {
                var accessStatus = await service.RequestAccessAsync();

                if (accessStatus == DeviceAccessStatus.Allowed)
                {
                    var result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        characteristics = result.Characteristics;
                    }
                    else
                    {
                        NotifyUser("Error accessing service.", NotifyType.ErrorMessage);
                        characteristics = new List <GattCharacteristic>();
                    }
                }
                else
                {
                    NotifyUser("Error accessing service.", NotifyType.ErrorMessage);
                    characteristics = new List <GattCharacteristic>();
                }
            }
            catch (Exception ex)
            {
                NotifyUser("Restricted service. Can't read charcteristics:" + ex.Message, NotifyType.ErrorMessage);
                characteristics = new List <GattCharacteristic>();
            }
            var chara = characteristics[0];

            charaName                      = DisplayHelpers.GetCharacteristicName(chara);
            CharaReadUUID.Text             = charaName;
            CharaReadUUIDBorder.Visibility = Visibility.Visible;
            EnumerationReadDescriptor(chara);

            chara                           = characteristics[1];
            charaName                       = DisplayHelpers.GetCharacteristicName(chara);
            CharaWriteUUID.Text             = charaName;
            CharaWriteUUIDBorder.Visibility = Visibility.Visible;
            EnumerationWriteDescriptor(chara);
            CharaReadUUIDBorder.Visibility = Visibility.Visible;
        }
        async Task <IReadOnlyList <GattCharacteristic> > DoGetCharacteristics()
        {
            List <GattCharacteristic> characteristics = new List <GattCharacteristic>();

            var result = await _service.GetCharacteristicsAsync();

            if (result.Status == GattCommunicationStatus.Success)
            {
                foreach (var c in result.Characteristics)
                {
                    characteristics.Add(new GattCharacteristic(this, c));
                }
            }

            return(characteristics.AsReadOnly());
        }
Exemple #29
0
        private async void ListServices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (connected)
            {
                ListCharacteristics.Items.Clear();
                selectedService = ListServices.SelectedItem as GattDeviceService;
                var characteristics = await selectedService.GetCharacteristicsAsync();

                foreach (var charact in characteristics.Characteristics)
                {
                    ListCharacteristics.Items.Add(charact);

                    connectedDeviceCharacteristics.Add(charact);
                }
            }
        }
        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.
                                }
                            }
                        }
                    }
                }
            }
        }