/// <summary>
        /// Gets all the characteristics of this service
        /// </summary>
        private async void 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)
                    {
                        if (gattchar.Uuid.ToString() == "49535343-1e4d-4bd9-ba61-23c647249616")
                        {
                            Characteristics.Clear();

                            Characteristics.Add(new ObservableGattCharacteristics(gattchar, this));
                        }
                    }
                }
                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);
                throw;
            }
        }
        //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;
            }
        }
        /// <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;
                }

                var 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;
            }
        }
        private async Task GetAllServiceAttributes()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("ObservableGattDeviceService::GetAllServiceAttributes: ");
            sb.Append(Name);

            // 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;
            }

            await GetAllIncludedServices();
            await GetAllCharacteristics();
        }
Exemple #5
0
        /// <summary>
        /// Gets all the characteristics of this service
        /// </summary>
        public async Task <bool> 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);
                    Log.WriteLine(sb.ToString());

                    return(false);
                }

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

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

                if (result.Status == GattCommunicationStatus.Success)
                {
                    sb.Append(" - getAllCharacteristics found ");
                    sb.Append(result.Characteristics.Count());
                    sb.Append(" characteristics");
                    Log.WriteLine(sb.ToString());
                    foreach (GattCharacteristic gattchar in result.Characteristics)
                    {
                        Characteristics.Add(new ObservableGattCharacteristics(gattchar, this));
                    }
                }
                else if (result.Status == GattCommunicationStatus.Unreachable)
                {
                    sb.Append(" - getAllCharacteristics failed with Unreachable");
                    Log.WriteLine(sb.ToString());
                }
                else if (result.Status == GattCommunicationStatus.ProtocolError)
                {
                    sb.Append(" - getAllCharacteristics failed with Unreachable");
                    Log.WriteLine(sb.ToString());
                }
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    if (ex is TaskCanceledException)
                    {
                        Log.WriteLine("!!!Getting characteristics took too long.");
                        Name += " - Timed out getting some characteristics";
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("!!!getAllCharacteristics: Exception - {0}" + ex.Message);
                throw;
            }
            return(true);
        }
Exemple #6
0
        public async Task <bool> TryToConnect(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                this.logger.Error($"'{nameof(deviceId)}' argument is null or empty");
                return(false);
            }

            bool success = false;

            try
            {
                GattDeviceService  service = null;
                GattCharacteristic responseCharacteristic = null;
                BluetoothLEDevice  bluetoothLeDevice      = await BluetoothLEDevice.FromIdAsync(deviceId)
                                                            .AsTask()
                                                            .ConfigureAwait(false);

                if (bluetoothLeDevice == null)
                {
                    this.logger.Error($"failed to create BLE device with id = '{deviceId}'");
                    return(false);
                }

                this.bluetoothLeDevice = bluetoothLeDevice;
                bluetoothLeDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                DeviceAccessStatus deviceStatus = await bluetoothLeDevice.RequestAccessAsync()
                                                  .AsTask()
                                                  .ConfigureAwait(false);

                if (deviceStatus != DeviceAccessStatus.Allowed)
                {
                    this.logger.Error($"failed to get access to BLE device with id = '{deviceId}'");
                    return(false);
                }

                // the following method connects to BLE device (and will call OnConnectionStatusChanged)

                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached)
                                                  .AsTask()
                                                  .ConfigureAwait(false);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    service = result.Services.Where(s => s.Uuid == SERVICE_GUID)
                              .FirstOrDefault();

                    if (service == null)
                    {
                        this.logger.Error($"BLE device with id = '{deviceId}' doesn't have '{SERVICE_GUID}' service");
                        return(false);
                    }

                    GattOpenStatus status = await service.OpenAsync(GattSharingMode.Exclusive)
                                            .AsTask()
                                            .ConfigureAwait(false);

                    if (status != GattOpenStatus.Success)
                    {
                        this.logger.Error($"failed to open '{SERVICE_GUID}' service on BLE device with id = '{deviceId}', result = '{status}'");
                        return(false);
                    }

                    GattCharacteristicsResult characteristicsResult = characteristicsResult = await service.GetCharacteristicsForUuidAsync(RESPONSE_CHARACTERISTICS_GUID)
                                                                                              .AsTask()
                                                                                              .ConfigureAwait(false);

                    if (characteristicsResult.Status != GattCommunicationStatus.Success)
                    {
                        this.logger.Error($"failed to get '{RESPONSE_CHARACTERISTICS_GUID}' characteristic from '{SERVICE_GUID}' " +
                                          $"service on BLE device with id = '{deviceId}', result = '{characteristicsResult.Status}', protocol error = {characteristicsResult.ProtocolError}");
                        return(false);
                    }

                    responseCharacteristic = characteristicsResult.Characteristics.FirstOrDefault();

                    if (responseCharacteristic == null)
                    {
                        this.logger.Error($"'{RESPONSE_CHARACTERISTICS_GUID}' characteristic doesn't seem to have any characteristics in '{SERVICE_GUID}' service on BLE device with id = '{deviceId}'");
                        return(false);
                    }
                }
                else
                {
                    this.logger.Error($"failed to retreive services provided by BLE device with id = '{deviceId}', result = '{result.Status}', protocol error = '{result.ProtocolError}'");
                    return(false);
                }

                this.service = service;
                this.responseCharacteristic = responseCharacteristic;
                this.responseCharacteristic.ValueChanged += OnCharacteristicValueChanged;

                success = true;

                return(true);
            }
            catch (Exception e)
            {
                this.logger.Error(e, "unexpected exception while connecting to BLE device");
                return(false);
            }
            finally
            {
                if (!success)
                {
                    Disconnect();
                }
            }
        }