예제 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObservableGattDeviceService" /> class.
 /// </summary>
 /// <param name="service">The service this class wraps</param>
 public ObservableGattDeviceService(GattDeviceService service)
 {
     Service = service;
     Name    = GattServiceUuidHelper.ConvertUuidToName(service.Uuid);
     UUID    = Service.Uuid.ToString();
     GetAllCharacteristics();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ObservableGattDeviceService" /> class.
 /// </summary>
 /// <param name="service">The service this class wraps</param>
 public ObservableGattDeviceService(GattDeviceService service, BluetoothCacheMode cacheMode)
 {
     CacheMode = cacheMode;
     Service   = service;
     Name      = GattServiceUuidHelper.ConvertUuidToName(service.Uuid);
     UUID      = Service.Uuid.ToString();
     GetAllCharacteristics();
 }
        private async Task <bool> GetAllPrimaryServices(BluetoothCacheMode cacheMode)
        {
            var    succeeded = false;
            string debugMsg  = String.Format("GetAllPrimaryServices: ");

            Debug.WriteLine(debugMsg + "Entering");

            // Get all the services for this device
            var result = await BluetoothLEDevice.GetGattServicesAsync(cacheMode);

            if (result.Status == GattCommunicationStatus.Success)
            {
                System.Diagnostics.Debug.WriteLine(debugMsg + "GetGattServiceAsync SUCCESS");

                lock (Services)
                {
                    foreach (var serv in result.Services)
                    {
                        if (!GattServiceUuidHelper.IsReserved(serv.Uuid))
                        {
                            var temp = new ObservableGattDeviceService(serv);
                            // This isn't awaited so that the user can disconnect while the services are still being enumerated
                            temp.Initialize();
                            Services.Add(temp);
                        }
                        else
                        {
                            serv.Dispose();
                        }
                    }
                    ServiceCount = Services.Count();
                }

                succeeded = true;
            }
            else if (result.Status == GattCommunicationStatus.ProtocolError)
            {
                ErrorText = debugMsg + "GetGattServiceAsync Error: Protocol Error - " + result.ProtocolError.Value;
                System.Diagnostics.Debug.WriteLine(ErrorText);
                string msg           = "Connection protocol error: " + result.ProtocolError.Value.ToString();
                var    messageDialog = new MessageDialog(msg, "Connection failures");
                await messageDialog.ShowAsync();
            }
            else if (result.Status == GattCommunicationStatus.Unreachable)
            {
                ErrorText = debugMsg + "GetGattServiceAsync Error: Unreachable";
                System.Diagnostics.Debug.WriteLine(ErrorText);
                string msg           = "Device unreachable";
                var    messageDialog = new MessageDialog(msg, "Connection failures");
                await messageDialog.ShowAsync();
            }

            return(succeeded);
        }
예제 #4
0
        /// <summary>
        /// Navigate to page
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="mode"></param>
        /// <param name="suspensionState"></param>
        /// <returns>Navigate to task</returns>
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> suspensionState)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal,
                () =>
            {
                if (Services.SettingsServices.SettingsService.Instance.SettingsDictionary.Keys.Contains(Characteristic.UUID + "-UseWindowsNotification"))
                {
                    UseWindowsNotifications = (bool)Services.SettingsServices.SettingsService.Instance.SettingsDictionary[Characteristic.UUID + "-UseWindowsNotification"];
                }
            });

            if (Characteristic.Characteristic.CharacteristicProperties != GattCharacteristicProperties.None)
            {
                StringBuilder sb    = new StringBuilder();
                bool          first = true;

                foreach (GattCharacteristicProperties p in Enum.GetValues(typeof(GattCharacteristicProperties)))
                {
                    if (p == GattCharacteristicProperties.None)
                    {
                        continue;
                    }

                    if (GattServiceUuidHelper.IsReadOnly(Characteristic.Characteristic.Service.Uuid) &&
                        (p == GattCharacteristicProperties.Write || p == GattCharacteristicProperties.WriteWithoutResponse))
                    {
                        continue;
                    }

                    if (Characteristic.Characteristic.CharacteristicProperties.HasFlag(p))
                    {
                        if (!first)
                        {
                            sb.Append(", ");
                        }
                        else
                        {
                            first = false;
                        }

                        sb.Append(Enum.GetName(typeof(GattCharacteristicProperties), p));
                    }
                }

                Properties = sb.ToString();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ObservableGattDeviceService" /> class.
 /// </summary>
 /// <param name="service">The service this class wraps</param>
 public ObservableGattDeviceService(GattDeviceService service)
 {
     Service = service;
     Name    = GattServiceUuidHelper.ConvertUuidToName(service.Uuid);
     UUID    = service.Uuid.ToString();
 }
        /// <summary>
        /// Connect to this bluetooth device
        /// </summary>
        /// <returns>Connection task</returns>
        public async Task <bool> Connect()
        {
            bool   ret      = false;
            string debugMsg = String.Format("Connect: ");

            Debug.WriteLine(debugMsg + "Entering");

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(async() =>
            {
                Debug.WriteLine(debugMsg + "In UI thread");
                try
                {
                    if (bluetoothLEDevice == null)
                    {
                        Debug.WriteLine(debugMsg + "Calling BluetoothLEDevice.FromIdAsync");
                        BluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(DeviceInfo.Id);

                        if (bluetoothLEDevice == null)
                        {
                            ret = false;
                            Debug.WriteLine(debugMsg + "BluetoothLEDevice is null");

                            MessageDialog dialog = new MessageDialog("No permission to access device", "Connection error");
                            await dialog.ShowAsync();
                            return;
                        }
                        else
                        {
                            // Setup our event handlers and view model properties
                            BluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged;
                            BluetoothLEDevice.NameChanged             += BluetoothLEDevice_NameChanged;
                        }
                    }
                    else
                    {
                        Debug.WriteLine(debugMsg + "Previously connected, not calling BluetoothLEDevice.FromIdAsync");
                    }

                    Debug.WriteLine(debugMsg + "BluetoothLEDevice is " + BluetoothLEDevice.Name);

                    Name        = bluetoothLEDevice.Name;
                    CanPair     = DeviceInfo.Pairing.CanPair;
                    IsPaired    = DeviceInfo.Pairing.IsPaired;
                    IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected;

                    UpdateSecureConnectionStatus();

                    // Get all the services for this device
                    CancellationTokenSource GetGattServicesAsyncTokenSource = new CancellationTokenSource(5000);

                    BluetoothCacheMode cacheMode = BluetoothLEExplorer.Services.SettingsServices.SettingsService.Instance.UseCaching ? BluetoothCacheMode.Cached : BluetoothCacheMode.Uncached;

                    // In case we connected before, clear the service list and recreate it
                    Services.Clear();

                    var GetGattServicesAsyncTask = Task.Run(() => BluetoothLEDevice.GetGattServicesAsync(cacheMode), GetGattServicesAsyncTokenSource.Token);

                    result = await GetGattServicesAsyncTask.Result;

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        System.Diagnostics.Debug.WriteLine(debugMsg + "GetGattServiceAsync SUCCESS");
                        foreach (var serv in result.Services)
                        {
                            if (!GattServiceUuidHelper.IsReserved(serv.Uuid))
                            {
                                ObservableGattDeviceService temp = new ObservableGattDeviceService(serv);
                                // This isn't awaited so that the user can disconnect while the services are still being enumerated
                                temp.Initialize();
                                Services.Add(temp);
                            }
                            else
                            {
                                serv.Dispose();
                            }
                        }

                        ServiceCount = Services.Count();
                        ret          = true;
                    }
                    else if (result.Status == GattCommunicationStatus.ProtocolError)
                    {
                        ErrorText = debugMsg + "GetGattServiceAsync Error: Protocol Error - " + result.ProtocolError.Value;
                        System.Diagnostics.Debug.WriteLine(ErrorText);
                        string msg        = "Connection protocol error: " + result.ProtocolError.Value.ToString();
                        var messageDialog = new MessageDialog(msg, "Connection failures");
                        await messageDialog.ShowAsync();
                    }
                    else if (result.Status == GattCommunicationStatus.Unreachable)
                    {
                        ErrorText = debugMsg + "GetGattServiceAsync Error: Unreachable";
                        System.Diagnostics.Debug.WriteLine(ErrorText);
                        string msg        = "Device unreachable";
                        var messageDialog = new MessageDialog(msg, "Connection failures");
                        await messageDialog.ShowAsync();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(debugMsg + "Exception - " + ex.Message);
                    string msg = String.Format("Message:\n{0}\n\nInnerException:\n{1}\n\nStack:\n{2}", ex.Message, ex.InnerException, ex.StackTrace);

                    var messageDialog = new MessageDialog(msg, "Exception");
                    await messageDialog.ShowAsync();

                    // Debugger break here so we can catch unknown exceptions
                    Debugger.Break();
                }
            });

            if (ret)
            {
                Debug.WriteLine(debugMsg + "Exiting (0)");
            }
            else
            {
                Debug.WriteLine(debugMsg + "Exiting (-1)");
            }

            return(ret);
        }