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

                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;
            }
        }
Пример #3
0
 public bool Open(IDeviceInfo dev)
 {
     lock (_lock)
     {
         if (_Device != null && _Characteristics != null && _ReadChar != null && _NotifyChar != null && _WriteChar != null)
         {
             return(false); //TODO: check connection
         }
         BluetoothLEDevice.FromIdAsync(dev.Path)
         .AsTask()
         .ContinueWith(r1 =>
         {
             _Device = r1.Result;
             if (_Device != null)
             {
                 BluetoothRadio.StateChanged     -= _BluetoothRadio_StateChanged;
                 BluetoothRadio.StateChanged     += _BluetoothRadio_StateChanged;
                 _Device.ConnectionStatusChanged += _Device_ConnectionStatusChanged;
                 _Device.GattServicesChanged     += _Device_GattServicesChanged;
                 _Device.GetGattServicesForUuidAsync(HIOServiceUuid)
                 .AsTask()
                 .ContinueWith(r2 =>
                 {
                     _Service = r2.Result.Services.First();
                     _Service.OpenAsync(GattSharingMode.SharedReadAndWrite).AsTask().Wait();
                     if (_Characteristics == null)
                     {
                         _Characteristics = new List <GattCharacteristic>();
                     }
                     lock (_Characteristics)
                     {
                         GetCharacteristics();
                         Trace.WriteLine($"Number of chars: {_Characteristics?.Count ?? -1}");
                     }
                 })
                 .Wait();
             }
         })
         .Wait();
         return(true);
     }
 }
Пример #4
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();
                }
            }
        }