public async Task <bool> DoInAppPairing()
        {
            Debug.WriteLine("Trying in app pairing");

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = await DeviceInfo.Pairing.PairAsync();

            CanPair  = DeviceInfo.Pairing.CanPair;
            IsPaired = DeviceInfo.Pairing.IsPaired;

            Debug.WriteLine($"Pairing result: {result.Status.ToString()}");

            if (result.Status == DevicePairingResultStatus.Paired ||
                result.Status == DevicePairingResultStatus.AlreadyPaired)
            {
                return(true);
            }
            else
            {
                MessageDialog d = new MessageDialog("Pairing error", result.Status.ToString());
                await d.ShowAsync();

                return(false);
            }
        }
Beispiel #2
0
        private async Task<int> pair_ganglion_async ()
        {
            if (ganglion_info == null)
            {
                return (int) CustomExitCodes.GANGLION_NOT_FOUND_ERROR;
            }
            if (ganglion_device == null)
            {
                return (int) CustomExitCodes.GANGLION_IS_NOT_OPEN_ERROR;
            }

            DevicePairingResult result = null;
            DeviceInformationPairing pairing_information = ganglion_device.DeviceInformation.Pairing;

            try
            {
                if ((pairing_information.CanPair) && (!pairing_information.IsPaired))
                {
                    result = await ganglion_device.DeviceInformation.Pairing.PairAsync (pairing_information.ProtectionLevel).AsTask ().TimeoutAfter (timeout);
                }
                else
                {
                    return (int) CustomExitCodes.GANGLION_ALREADY_PAIR_ERROR;
                }
            }
            catch (TimeoutException e)
            {
                return (int) CustomExitCodes.TIMEOUT_ERROR;
            }
            catch (Exception e)
            {
                return (int) CustomExitCodes.GENERAL_ERROR;
            }
            return (int) CustomExitCodes.STATUS_OK;
        }
        private async void PairDevice()
        {
            try
            {
                var bleDeviceDisplay = SelectedDevice as BLEDeviceInfo;
                if (bleDeviceDisplay == null)
                {
                    NotifyStatusMessage?.Invoke("Please select a device.");
                    return;
                }
                DevicePairingResult result = await bleDeviceDisplay.DeviceInfo.Pairing.PairAsync();

                if (result.Status == DevicePairingResultStatus.AlreadyPaired)
                {
                    NotifyStatusMessage?.Invoke("Device already paired.");
                }
                else if (result.Status == DevicePairingResultStatus.Paired)
                {
                    NotifyStatusMessage?.Invoke("Device already paired.");
                }
                else
                {
                    NotifyStatusMessage?.Invoke("Paired Result: " + result.ToString());
                }
            }catch (Exception ex)
            {
                NotifyStatusMessage?.Invoke("Exception: " + ex.Message);
            }
        }
        private async void PairButton_Click()
        {
            // Do not allow a new Pair operation to start if an existing one is in progress.
            if (isBusy)
            {
                return;
            }

            isBusy = true;

            rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage);

            // For more information about device pairing, including examples of
            // customizing the pairing process, see the DeviceEnumerationAndPairing sample.

            // Capture the current selected item in case the user changes it while we are pairing.
            var bleDeviceDisplay = ResultsListView.SelectedItem as BluetoothLEDeviceDisplay;

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = await bleDeviceDisplay.DeviceInformation.Pairing.PairAsync();

            rootPage.NotifyUser($"Pairing result = {result.Status}",
                                result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired
                    ? NotifyType.StatusMessage
                    : NotifyType.ErrorMessage);

            isBusy = false;
        }
    private async Task <DeviceInformation> PairWithDevice(BluetoothLEDevice _dev)
    {
        if (isPairing)
        {
            return(null);
        }

        isPairing = true;
        DeviceInformation   devInfo;
        DevicePairingResult result = await _dev.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);

        if (result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired)
        {
            devInfo = _dev.DeviceInformation;
        }
        else if (result.Status == DevicePairingResultStatus.AlreadyPaired)
        {
            devInfo = _dev.DeviceInformation;
        }
        else
        {
            devInfo = null;
        }

        isPairing = false;
        return(devInfo);
    }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Gray out the pair button and results view while pairing is in progress.
            resultsListView.IsEnabled = false;
            pairButton.IsEnabled      = false;
            rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage);

            // Get the device selected for pairing
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            // Get ceremony type and protection level selections
            DevicePairingKinds           ceremoniesSelected  = GetSelectedCeremonies();
            ProtectionLevelSelectorInfo  protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;
            DevicePairingProtectionLevel protectionLevel     = protectionLevelInfo.ProtectionLevel;

            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;

            rootPage.NotifyUser(
                "Pairing result = " + result.Status.ToString(),
                result.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);

            HidePairingPanel();
            UpdatePairingButtons();
            resultsListView.IsEnabled = true;
        }
Beispiel #7
0
        private async void DeviceDiscovered(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs advertisement)
        {
            var isNew = false;

            lock (this)
            {
                if (false == advertisedDevices.Contains(advertisement.BluetoothAddress))
                {
                    this.advertisedDevices.Add(advertisement.BluetoothAddress);
                    isNew = true;
                }
            }

            if (true == isNew)
            {
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(advertisement.BluetoothAddress);

                DevicePairingKinds             ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
                DevicePairingProtectionLevel   protectionLevel    = DevicePairingProtectionLevel.None;
                DeviceInformationCustomPairing customPairing      = device.DeviceInformation.Pairing.Custom;

                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                customPairing.PairingRequested -= PairingRequestedHandler;

                if ((result.Status == DevicePairingResultStatus.AlreadyPaired) || (result.Status == DevicePairingResultStatus.Paired))
                {
                    sender.Stop();
                }
            }
        }
Beispiel #8
0
        private static async Task <bool> Pair(DeviceInformation device, string pin)
        {
            device.Pairing.Custom.PairingRequested += (s, a) => PairingRequestedHandler(s, a, pin);

            // DeviceInformation.Pairing.PairAsync function doesn't work for non UWP applications. Thus, DeviceInformation.Pairing.Custom.PairAsync is used.
            // https://stackoverflow.com/questions/45191412/deviceinformation-pairasync-not-working-in-wpf

            // DevicePairingKinds.DisplayPin option conflicts with DevicePairingKinds.ProvidePin: I used "Bluetooth Module HC 05" to test pairing with PIN code.
            // This device requires pin code "1234" to be paired. When both DevicePairingKinds.DisplayPin and DevicePairingKinds.ProvidePin flags were used in PairAsync function,
            // the PairingRequestedHandler was called with PairingKind equal to DevicePairingKinds.DisplayPin instead of DevicePairingKinds.ProvidePin, which made pairing fail.
            // Therefore, I decided not to use DevicePairingKinds.DisplayPin flag.

            // DevicePairingResult res = await device.Pairing.PairAsync();
            DevicePairingResult res = await device.Pairing.PairAsync();

            if (res.Status != DevicePairingResultStatus.Paired)

            /*
             * DevicePairingResult res = await device.Pairing.Custom
             *  .PairAsync(DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch, DevicePairingProtectionLevel.None)
             *  ;
             * if (res.Status != DevicePairingResultStatus.Paired)
             */
            {
                Debug.WriteLine($"Failed to pair device. Status = {res.Status}");
                // throw new Exception($"Failed to pair device. Status = {res.Status}");
                return(false);
            }

            return(true);
        }
        public async Task <bool> ConnectWithPin()
        {
            ulong address = this.Address;

            DeviceInformation deviceInformation = bluetoothLEDevice.DeviceInformation;

            if (deviceInformation.Pairing.CanPair)
            {
                DeviceInformationCustomPairing customPairing = deviceInformation.Pairing.Custom;
                customPairing.PairingRequested += OnCustomPairingRequested;
                DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ProvidePin);

                customPairing.PairingRequested -= OnCustomPairingRequested;
                if ((result.Status == DevicePairingResultStatus.Paired) || (result.Status == DevicePairingResultStatus.AlreadyPaired))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Called to pair a targeted device
        /// </summary>
        /// <param name="pairButton">Pair button</param>
        /// <param name="currentDevice">Displayable information for the targeted device</param>
        public async Task PairingRequestedAsync(Button pairButton, BluetoothDeviceInfo currentDevice)
        {
            try
            {
                _deviceInfo           = currentDevice;
                _inProgressPairButton = pairButton;

                // Display confirmation message panel
                string deviceIdentifier    = _deviceInfo.Name != BluetoothDeviceNameUnknownText ? _deviceInfo.Name : _deviceInfo.IdWithoutProtocolPrefix;
                string confirmationMessage = string.Format(BluetoothAttemptingToPairFormat, _deviceInfo.Name, _deviceInfo.IdWithoutProtocolPrefix);

                await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);

                // Save the flyout and set to null so it doesn't appear without explicitly being called
                _savedPairButtonFlyout       = pairButton.Flyout;
                _inProgressPairButton.Flyout = null;
                pairButton.IsEnabled         = false;

                // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                DevicePairingKinds           ceremoniesSelected = GetSelectedCeremonies();
                DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                // Setup a custom pairing and handler, then get the results of the request
                DeviceInformationCustomPairing customPairing = _deviceInfo.DeviceInformation.Pairing.Custom;
                customPairing.PairingRequested += PairingRequestedHandlerAsync;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                if (result.Status == DevicePairingResultStatus.Paired)
                {
                    confirmationMessage = string.Format(BluetoothPairingSuccessFormat, deviceIdentifier, result.Status.ToString());
                }
                else
                {
                    confirmationMessage = string.Format(BluetoothPairingFailureFormat, deviceIdentifier, result.Status.ToString());
                }

                // Display the result of the pairing attempt
                await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);

                // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure their current state is reflected
                if (BluetoothWatcherEnabled)
                {
                    BluetoothDeviceCollection.Clear();
                    StopWatcher();
                    StartWatcherAsync();
                }
                else
                {
                    // If the watcher is off, this is an inbound request so we only need to clear the list
                    BluetoothDeviceCollection.Clear();
                }

                _inProgressPairButton = null;
                pairButton.IsEnabled  = true;
            }
            catch (Exception ex)
            {
                LogService.Write(ex.ToString(), LoggingLevel.Error);
            }
        }
Beispiel #11
0
        private async void BtPair()
        {
            rootPage.StatusBar("Paring Started Please Wait...", BarStatus.Warnning);

            Btdevice            deviceInfoDisp = resultListView.SelectedItem as Btdevice;
            DevicePairingResult dpr            = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync();

            rootPage.StatusBar("Paring Result" + dpr.Status.ToString(), dpr.Status == DevicePairingResultStatus.Paired ? BarStatus.Sucess : BarStatus.Error);
        }
        public async void Connect()
        {
            // Repair the device if needed
            if (!devInfo.Pairing.IsPaired)
            {
                Debug.WriteLine("Pairing...");

                DeviceInformationCustomPairing customPairing = devInfo.Pairing.Custom;
                customPairing.PairingRequested += PairingRequested;
                DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None);

                customPairing.PairingRequested -= PairingRequested;

                Debug.WriteLine("Pair status: " + result.Status);
            }
            else
            {
                Debug.WriteLine("Already Paired");
            }

            // Get the actual device
            try {
                device = await BluetoothDevice.FromIdAsync(devInfo.Id);

                device.ConnectionStatusChanged += ConnectionStatusChanged;
            } catch (Exception ex) {
                Debug.WriteLine("Bluetooth Not Available");
                return;
            }

            //try {
            var services = await device.GetRfcommServicesAsync();

            if (services.Services.Count > 0)
            {
                var service = services.Services[0];
                stream = new StreamSocket();
                //try {
                await stream.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);

                //} catch (Exception ex) {
                //Debug.WriteLine("Could not connect to device");
                //}
                Debug.WriteLine("Stream Connected");
                rx = new DataReader(stream.InputStream);
                rx.InputStreamOptions = InputStreamOptions.Partial;
                tx = new DataWriter(stream.OutputStream);

                OnConnected();
            }

            /*} catch (Exception ex) {
             *  Debug.WriteLine("Failed to get services");
             *  return;
             * }*/
        }
Beispiel #13
0
        private async Task <bool> TryToPairDevice(DeviceInformation deviceInfo)
        {
            bool paired = false;

            if (deviceInfo != null)
            {
                if (deviceInfo.Pairing.IsPaired != true)
                {
                    paired = false;

                    DevicePairingKinds           ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                    DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                    // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                    DeviceInformationCustomPairing customPairing = deviceInfo.Pairing.Custom;

                    customPairing.PairingRequested += PairingRequestedHandler;
                    DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                    customPairing.PairingRequested -= PairingRequestedHandler;

                    if (result.Status == DevicePairingResultStatus.Paired)
                    {
                        paired = true;
                    }
                    else
                    {
                        StatusText.Text = "Pairing Failed " + result.Status.ToString();
                        EnableRetry();
                    }
                }
                else
                {
                    paired = true;
                }

                if (paired)
                {
                    // device is paired, set up the sensor Tag
                    StatusText.Text = "Verbunden, pairing versuch...";

                    DeviceInfoConnected = deviceInfo;

                    //Start watcher for Bluetooth LE Services
                    StartBLEWatcher();
                }
                else
                {
                }
            }
            else
            {
            }        //Null device
            return(paired);
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            pairButton.IsEnabled = false;
            DevicePairingResult dpr = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync();

            rootPage.NotifyUser(
                "Pairing result = " + dpr.Status.ToString(),
                dpr.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);
        }
Beispiel #15
0
        public async Task <bool> PairingDeviceAsync(string deviceId)
        {
            var device = FindKnownBluetoothDevice(deviceId);
            // do pairing
            DevicePairingResult pairingResult = await device.DeviceInformation.Pairing.PairAsync();

            if (pairingResult.Status == DevicePairingResultStatus.Paired)
            {
                return(true);
            }
            return(false);
        }
Beispiel #16
0
        static async void PairBluetooth(string param)
        {
            DevicePairingResult      result             = null;
            DeviceInformationPairing pairingInformation = _selectedDevice.DeviceInformation.Pairing;

            await _selectedDevice.DeviceInformation.Pairing.UnpairAsync();

            if (pairingInformation.CanPair)
            {
                result = await _selectedDevice.DeviceInformation.Pairing.PairAsync(pairingInformation.ProtectionLevel);
            }
        }
Beispiel #17
0
        private async void TryPair(string val)
        {
            DeviceInformationDisplay _deviceInformationDisplayConnect = ResultCollection.Where(r => r.Id == val).FirstOrDefault();

            DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
            //  ProtectionLevelSelectorInfo protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;

            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            DeviceInformationCustomPairing customPairing = _deviceInformationDisplayConnect.DeviceInformation.Pairing.Custom;


            customPairing.PairingRequested += PairingRequestedHandler;

            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;


            StopWatcher();

            var bleDevice = await BluetoothLEDevice.FromIdAsync(_deviceInformationDisplayConnect.Id);



            var accService = await GattDeviceService.FromIdAsync(_deviceInformationDisplayConnect.Id);

            //Get the accelerometer data characteristic
            var accData = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            //Subcribe value changed

            //accData.ValueChanged += AccData_ValueChanged;
            accData.ValueChanged += test;

            //Set configuration to notify
            await accData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            //Get the accelerometer configuration characteristic
            var accConfig = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            GattReadResult Resultat = await accConfig.ReadValueAsync();

            var Output = Resultat.Value.ToArray();

            Debug.WriteLine("Acc: " + Output.Count());
            Debug.WriteLine("Registre 0:" + Output[0].ToString());
            Debug.WriteLine("Registre 1:" + Output[1].ToString());

            Output[0] = 0x7F;

            await accConfig.WriteValueAsync(Output.AsBuffer());
        }
        static async Task <bool> Pair(AnkiBLE.anki_vehicle vehicle)
        {
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address);

            DeviceInformationCustomPairing customPairing = device.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ConfirmOnly, DevicePairingProtectionLevel.None);

            customPairing.PairingRequested -= PairingRequestedHandler;
            return(result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired);
        }
        public static async Task <GattDeviceService> GetServiceAsync(string deviceId)
        {
            BluetoothLEDevice device = null;

            try
            {
                Debug.WriteLine("Connecting to Bluetooth LE device.");
                device = await BluetoothLEDevice.FromIdAsync(deviceId);
            }
            catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
            {
                throw new InvalidOperationException("Bluetooth radio is not on.", ex);
            }

            if (device == null)
            {
                throw new InvalidOperationException("Failed to connect to device.");
            }

            if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired)
            {
                DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.EncryptionAndAuthentication);

                if (dpr == null)
                {
                    throw new InvalidOperationException("Failed to pair with device");
                }
                if (!(dpr.Status == DevicePairingResultStatus.Paired || dpr.Status == DevicePairingResultStatus.AlreadyPaired))
                {
                    throw new InvalidOperationException($"Failed to pair with device with result: '{dpr.Status}'");
                }
            }

            Debug.WriteLine("Requesting 'Wi-Fi config message protocol' service for device.");
            GattDeviceServicesResult result = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached);

            if (result.Status != GattCommunicationStatus.Success)
            {
                throw new InvalidOperationException("Device unreachable.");
            }

            GattDeviceService service = result.Services.FirstOrDefault(s => s.Uuid == MessageProtocolServiceId);

            if (service == null)
            {
                throw new InvalidOperationException("This device does not support the Message Protocol.");
            }

            Debug.WriteLine("Connected to Bluetooth LE device.");
            return(service);
        }
Beispiel #20
0
 private async void PairAsync()
 {
     // We must update the collection on the UI thread
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
     {
         if (this.CanPair && !this.Pairing)
         {
             DevicePairingResult res = await information.Pairing.PairAsync();
             if (res.Status == DevicePairingResultStatus.Paired)
             {
                 OnDevicePaired?.Invoke(this);
             }
         }
     });
 }
Beispiel #21
0
        private async void Initialize()
        {
            Console.WriteLine(tag, "Connecting...");
            this.Device = await BluetoothLEDevice.FromBluetoothAddressAsync(this.DeviceAddress);

            DevicePairingResult result = await this.Device.DeviceInformation.Pairing.PairAsync();

            if (result.Status != DevicePairingResultStatus.AlreadyPaired && result.Status != DevicePairingResultStatus.Paired)
            {
                Console.WriteLine(tag, "Failed to pair:" + result.Status);
                this.Device.Dispose();
                return;
            }
            EnableUpgradeMode();
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            if (deviceInfoDisp != null)
            {
                PairButton.IsEnabled = false;
                bool paired = true;
                //if (deviceInfoDisp.IsPaired != true)
                //{
                paired = false;
                DevicePairingKinds           ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                customPairing.PairingRequested -= PairingRequestedHandler;

                if (result.Status == DevicePairingResultStatus.Paired)
                {
                    paired = true;
                }
                else
                {
                    //UserOut.Text = "Pairing Failed " + result.Status.ToString();
                }
                //UpdatePairingButtons();
                //}

                if (paired)
                {
                    // device is paired, set up the sensor Tag
                    //UserOut.Text = "Setting up SensorTag";

                    //DeviceInfoConnected = deviceInfoDisp;

                    //Start watcher for Bluetooth LE Services
                    //StartBLEWatcher();
                }
                PairButton.IsEnabled = true;
            }
        }
Beispiel #23
0
        public bool DoInAppPairing(DevicePairingProtectionLevel minProtectionLevel, IDevicePairingSettings devicePairingSettings)
        {
            Debug.WriteLine("Trying in app pairing");

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = DeviceInfo.Pairing.PairAsync(minProtectionLevel, devicePairingSettings).GetAwaiter().GetResult();

            Debug.WriteLine($"Pairing result: {result.Status}");

            if (result.Status != DevicePairingResultStatus.Paired ||
                result.Status != DevicePairingResultStatus.AlreadyPaired)
            {
                Debug.WriteLine("Pairing error: " + result.Status.ToString());
                return(false);
            }
            return(true);
        }
        public async Task pairlingFirstAsync()
        {
            if (DeviceMap.Count == 0)
            {
                return;
            }
            var deviceMap              = DeviceMap.First();
            var deviceInfo             = deviceMap.Value;
            DevicePairingResult result = await deviceInfo.Pairing.PairAsync();

            if (result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired)
            {
            }
            else
            {
                // fail
            }
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Gray out the pair button and results view while pairing is in progress.
            resultsListView.IsEnabled = false;
            pairButton.IsEnabled      = false;
            rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage);

            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            DevicePairingResult dpr = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync();

            rootPage.NotifyUser(
                "Pairing result = " + dpr.Status.ToString(),
                dpr.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);

            UpdatePairingButtons();
            resultsListView.IsEnabled = true;
        }
Beispiel #26
0
        public bool DoInAppPairing()
        {
            Debug.WriteLine("Trying in app pairing");

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = DeviceInfo.Pairing.PairAsync().GetAwaiter().GetResult();
            bool returnResult          = true;

            Debug.WriteLine($"Pairing result: {result.Status}");

            if (result.Status != DevicePairingResultStatus.Paired ||
                result.Status != DevicePairingResultStatus.AlreadyPaired)
            {
                Debug.WriteLine("Pairing error " + result.Status.ToString());
                returnResult = false;
            }
            return(returnResult);
        }
        public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing)
        {
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            short?groupOwnerIntent = 1;

            if (groupOwnerIntent.HasValue)
            {
                connectionParams.GroupOwnerIntent = groupOwnerIntent.Value;
            }

            DevicePairingKinds devicePairingKinds = DevicePairingKinds.None;

            //if (_supportedConfigMethods.Count > 0)
            //{
            //    // If specific configuration methods were added, then use them.
            //    foreach (var configMethod in _supportedConfigMethods)
            //    {
            //        connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod);
            //        devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod);
            //    }
            //}
            //else
            {
                // If specific configuration methods were not added, then we'll use these pairing kinds.
                devicePairingKinds = DevicePairingKinds.ConfirmOnly;// | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin;
            }

            connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
            DeviceInformationCustomPairing customPairing = pairing.Custom;

            customPairing.PairingRequested += OnPairingRequested;

            DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams);

            if (result.Status != DevicePairingResultStatus.Paired)
            {
                StatusBlock.Text = $"PairAsync failed, Status: {result.Status}";
                return(false);
            }
            return(true);
        }
        public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing)
        {
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            short?groupOwnerIntent = Utils.GetSelectedItemTag <short?>(cmbGOIntent);

            if (groupOwnerIntent.HasValue)
            {
                connectionParams.GroupOwnerIntent = groupOwnerIntent.Value;
            }

            DevicePairingKinds devicePairingKinds = DevicePairingKinds.None;

            if (_supportedConfigMethods.Count > 0)
            {
                // If specific configuration methods were added, then use them.
                foreach (var configMethod in _supportedConfigMethods)
                {
                    connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod);
                    devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod);
                }
            }
            else
            {
                // If specific configuration methods were not added, then we'll use these pairing kinds.
                devicePairingKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin;
            }

            connectionParams.PreferredPairingProcedure = Utils.GetSelectedItemTag <WiFiDirectPairingProcedure>(cmbPreferredPairingProcedure);
            DeviceInformationCustomPairing customPairing = pairing.Custom;

            customPairing.PairingRequested += OnPairingRequested;

            DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams);

            if (result.Status != DevicePairingResultStatus.Paired)
            {
                //rootPage.NotifyUser($"PairAsync failed, Status: {result.Status}", NotifyType.ErrorMessage);
                return(false);
            }
            return(true);
        }
Beispiel #29
0
        private async Task <bool> Pair()
        {
            Console.WriteLine("Pairing started. Please wait...");

            // For more information about device pairing, including examples of
            // customizing the pairing process, see the DeviceEnumerationAndPairing sample.

            // Capture the current selected item in case the user changes it while we are pairing.
            Debug.Assert(KnownDevices.Count == 1, "We shouldn't have more than one known device.");
            var bleDeviceDisplay = KnownDevices[0];

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = await bleDeviceDisplay.DeviceInformation.Pairing.PairAsync();

            //Debug.Assert(result.Status == DevicePairingResultStatus.AlreadyPaired ||
            //             result.Status == DevicePairingResultStatus.Paired);
            Console.WriteLine($"Pairing result = {result.Status}");
            return(result.Status == DevicePairingResultStatus.AlreadyPaired ||
                   result.Status == DevicePairingResultStatus.Paired);
        }
Beispiel #30
0
        /// <summary>
        /// ペアリング実施
        /// </summary>
        /// <param name="devInfo"></param>
        private async void DoPairing(DeviceInformation devInfo)
        {
            if (devInfo == null)
            {
                return;
            }

            if (devInfo.Pairing.IsPaired == false)
            {
                DeviceInformationCustomPairing customPairing = devInfo.Pairing.Custom;
                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ConfirmOnly, DevicePairingProtectionLevel.Default);

                customPairing.PairingRequested -= PairingRequestedHandler;
                Console.WriteLine("result is : " + result.Status);
                Debug.WriteLine($"[{/*MethodBase.GetCurrentMethod().Name*/0}] ペアリング結果:{result.Status}");
            }
            else
            {
                Debug.WriteLine($"[{/*MethodBase.GetCurrentMethod().Name*/0}] すでにペアリング済み");
            }
        }