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;
        }
Exemple #2
0
        /// <summary>
        /// Called when custom pairing is initiated so that we can handle the custom ceremony
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void PairingRequestedHandler(
            DeviceInformationCustomPairing sender,
            DevicePairingRequestedEventArgs args)
        {
            // Save the args for use in ProvidePin case
            pairingRequestedHandlerArgs = args;

            // Save the deferral away and complete it where necessary.
            if (args.PairingKind != DevicePairingKinds.DisplayPin)
            {
                deferral = args.GetDeferral();
            }

            string confirmationMessage;

            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmOnly:
                // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
                // If this is an App for Athens where there is no Windows Consent UX, you may want to provide your own confirmation.
            {
                confirmationMessage = string.Format(bluetoothConfirmOnlyFormatString, args.DeviceInformation.Name, args.DeviceInformation.Id);
                DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
                // Accept the pairing which also completes the deferral
                AcceptPairing();
            }
            break;

            case DevicePairingKinds.DisplayPin:
                // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN
                // on the target device
            {
                confirmationMessage = string.Format(bluetoothDisplayPinFormatString, args.Pin);
                DisplayMessagePanelAsync(confirmationMessage, MessageType.OKMessage);
            }
            break;

            case DevicePairingKinds.ProvidePin:
                // A PIN may be shown on the target device and the user needs to enter the matching PIN on
                // this Windows device.
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // PIN Entry
                    inProgressPairButton.Flyout = savedPairButtonFlyout;
                    inProgressPairButton.Flyout.ShowAt(inProgressPairButton);
                });

                break;

            case DevicePairingKinds.ConfirmPinMatch:
                // We show the PIN here and the user responds with whether the PIN matches what they see
                // on the target device. Response comes back and we set it on the PinComparePairingRequestedData
                // then complete the deferral.
            {
                confirmationMessage = string.Format(bluetoothConfirmPinMatchFormatString, args.Pin);
                DisplayMessagePanelAsync(confirmationMessage, MessageType.YesNoMessage);
            }
            break;
            }
        }
Exemple #3
0
 private void CustomOnPairingRequested(
     DeviceInformationCustomPairing sender,
     DevicePairingRequestedEventArgs args)
 {
     Console.WriteLine("Done Pairing");
     args.Accept("0");
 }
Exemple #4
0
        private static void PairingRequestedHandler(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args, string pin)
        {
            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmOnly:
                Console.WriteLine("Pairing mode: ConfirmOnly");
                args.Accept();
                return;

            case DevicePairingKinds.ProvidePin:
                Console.WriteLine("Pairing mode: ProvidePin");
                Console.WriteLine($"Pin is requested by the device. Using '{pin}' as a pin code");
                args.Accept(pin);
                return;

            case DevicePairingKinds.ConfirmPinMatch:
                Console.WriteLine("Pairing mode: ConfirmPinMatch");
                Console.WriteLine($"The device's pin code: '{args.Pin}'");
                Console.WriteLine("Waiting for the target device to accept the pairing (you probably need to follow the instructions on the target device's screen)");
                args.Accept();
                return;
            }

            Console.WriteLine($"Unexpected pairing type: {args.PairingKind}");
            throw new Exception();
        }
Exemple #5
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();
                }
            }
        }
        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);
            }
        }
 private void OnCustomPairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
 {
     while (pin == null)
     {
         Thread.Sleep(500);
     }
     args.Accept(pin);
     pin = null;
 }
Exemple #9
0
 /// <summary>
 /// ペアリング要求時のハンドラ
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private static void PairingRequestedHandler(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
 {
     switch (args.PairingKind)
     {
     case DevicePairingKinds.ConfirmOnly:
         args.Accept();
         break;
     }
 }
Exemple #10
0
 private void handlerPairingReq(DeviceInformationCustomPairing CP, DevicePairingRequestedEventArgs DPR)
 {
     //so we get here for custom pairing request.
     //this is the magic place where your pin goes.
     //my device actually does not require a pin but
     //windows requires at least a "0".  So this solved
     //it.  This does not pull up the Windows UI either.
     DPR.Accept("0");
 }
Exemple #11
0
        private async void CustomPairInfo_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            Deferral PairDeferral = args.GetDeferral();

            try
            {
                PairConfirmaion = new TaskCompletionSource <bool>();

                switch (args.PairingKind)
                {
                case DevicePairingKinds.ConfirmPinMatch:
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Tips.Text             = $"{Globalization.GetString("BluetoothUI_Tips_Text_5")}{Environment.NewLine}{args.Pin}";
                            Tips.Visibility       = Visibility.Visible;
                            PinConfirm.Visibility = Visibility.Visible;
                            PinRefuse.Visibility  = Visibility.Visible;
                        });

                    if (await PairConfirmaion.Task)
                    {
                        args.Accept(args.Pin);
                    }

                    break;
                }

                case DevicePairingKinds.ConfirmOnly:
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Tips.Text             = Globalization.GetString("BluetoothUI_Tips_Text_6");
                            Tips.Visibility       = Visibility.Visible;
                            PinConfirm.Visibility = Visibility.Visible;
                            PinRefuse.Visibility  = Visibility.Visible;
                        });

                    if (await PairConfirmaion.Task)
                    {
                        args.Accept();
                    }

                    break;
                }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(CustomPairInfo_PairingRequested)}, pair with bluetooth failed");
            }
            finally
            {
                PairDeferral.Complete();
            }
        }
        /// <summary>
        /// Called when a custom pairing is initiated so that we can handle its custom ceremony
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public async void PairingRequestedHandlerAsync(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            LogService.Write((Enum.GetName(typeof(DevicePairingKinds), args.PairingKind)), LoggingLevel.Information);

            BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(args.DeviceInformation);

            // Save the args for use in ProvidePin case
            _pairingRequestedArgs = args;

            // Save the deferral away and complete it where necessary.
            if (args.PairingKind != DevicePairingKinds.DisplayPin)
            {
                _deferral = args.GetDeferral();
            }

            switch (args.PairingKind)
            {
            // Windows itself will pop the confirmation dialog as part of "consent" depending on which operating OS is running
            case DevicePairingKinds.ConfirmOnly:
            {
                var confirmationMessage = string.Format(BluetoothConfirmOnlyText, args.DeviceInformation.Name, args.DeviceInformation.Id);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage))
                {
                    AcceptPairing();
                }
            }
            break;

            // We only show the PIN on this side. The ceremony is actually completed when the user enters the PIN on the target device.
            case DevicePairingKinds.DisplayPin:
            {
                var confirmationMessage = string.Format(BluetoothDisplayPINText, args.Pin);
                await DisplayMessagePanel(confirmationMessage, MessageType.OKMessage);
            }
            break;

            // A PIN may be shown on the target device and the user needs to enter the matching PIN on the originating device.
            case DevicePairingKinds.ProvidePin:
            {
                _inProgressPairButton.Flyout = _savedPairButtonFlyout;
                _inProgressPairButton.Flyout.ShowAt(_inProgressPairButton);
            }
            break;

            // We show the PIN here and the user responds with whether the PIN matches what is displayed on the target device.
            case DevicePairingKinds.ConfirmPinMatch:
            {
                var confirmationMessage = string.Format(BluetoothConfirmPINMatchText, args.Pin);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.YesNoMessage))
                {
                    AcceptPairing();
                }
            }
            break;
            }
        }
        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;
             * }*/
        }
        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 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);
        }
Exemple #17
0
        private async void OnPairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmOnly:
                // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
                // If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation.
                args.Accept();
                break;

            case DevicePairingKinds.DisplayPin:
                // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN
                // on the target device. We automatically except here since we can't really "cancel" the operation
                // from this side.
                args.Accept();

                // No need for a deferral since we don't need any decision from the user
                Debug.WriteLine("Please enter this PIN on the device you are pairing with: {0}", args.Pin);
                break;

            case DevicePairingKinds.ProvidePin:
                // A PIN may be shown on the target device and the user needs to enter the matching PIN on
                // this Windows device. Get a deferral so we can perform the async request to the user.
                var collectPinDeferral = args.GetDeferral();

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // NOT IMPLEMENTED - Make ASYNC
                    // GET PIN FROM USER

                    collectPinDeferral.Complete();
                });

                break;

            case DevicePairingKinds.ConfirmPinMatch:
                // We show the PIN here and the user responds with whether the PIN matches what they see
                // on the target device. Response comes back and we set it on the PinComparePairingRequestedData
                // then complete the deferral.
                var displayMessageDeferral = args.GetDeferral();

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // NOT IMPLEMENTED - Make ASYNC
                    // CONFIRM PIN MATCH

                    displayMessageDeferral.Complete();
                });

                break;
            }
        }
        private void OnPairRequestedAsyncCallback(
            DeviceInformationCustomPairing sender,
            DevicePairingRequestedEventArgs args)
        {
            this.log.Info("OnPairRequested", () => string.Format("Paring kind {0}", args.PairingKind.ToString()));

            BT_PairInfoRequest pairInfo = new BT_PairInfoRequest();

            pairInfo.DeviceName = args.DeviceInformation.Name;

            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmOnly:
                // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
                // If this is an App for 'Windows IoT Core' or a Desktop and Console application
                // where there is no Windows Consent UX, you may want to provide your own confirmation.
                args.Accept();
                break;

            case DevicePairingKinds.ProvidePin:
                // A PIN may be shown on the target device and the user needs to enter the matching PIN on
                // this Windows device. Get a deferral so we can perform the async request to the user.
                using (Windows.Foundation.Deferral collectPinDeferral = args.GetDeferral()) {
                    pairInfo.PinRequested = true;
                    if (this.BT_PairInfoRequested != null)
                    {
                        this.BT_PairInfoRequested(this, pairInfo);
                    }
                    else
                    {
                        this.log.Error(9999, "No subscriber to pin request");
                    }

                    this.log.Info("OnPairRequested",
                                  () => string.Format("Pin '{0}' Response:{1}",
                                                      pairInfo.Pin, pairInfo.Response));

                    if (pairInfo.Response)
                    {
                        // TODO Check for the result to see if you go ahead
                    }

                    if (!string.IsNullOrEmpty(pairInfo.Pin))
                    {
                        args.Accept(pairInfo.Pin);
                    }
                    // TODO - needs to be disposed
                    collectPinDeferral.Complete();
                };
                break;
            }
        }
Exemple #19
0
 private void Custom_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
 {
     if (args.PairingKind == DevicePairingKinds.ProvidePin)
     {
         // add reference: Microsoft.VisualBasic.dll
         string result = Microsoft.VisualBasic.Interaction.InputBox("Pin?", "Pairing...", "");
         if (string.IsNullOrEmpty(result) == false)
         {
             args.Accept(result);
         }
     }
     else
     {
         args.Accept();
     }
 }
Exemple #20
0
        private void PairingRequestedHandler(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs arguments)
        {
            switch (arguments.PairingKind)
            {
            case DevicePairingKinds.ConfirmOnly:
                arguments.Accept();
                break;

            case DevicePairingKinds.ProvidePin:
                var    collectPinDeferral = arguments.GetDeferral();
                string pin = "000000";
                arguments.Accept(pin);
                collectPinDeferral.Complete();
                break;
            }
        }
        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;
            }
        }
        private async void CustomPairInfo_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            Deferral PairDeferral = args.GetDeferral();

            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmPinMatch:
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Tips.Text             = "请确认PIN码与配对设备一致\r" + args.Pin;
                        Tips.Visibility       = Visibility.Visible;
                        PinConfirm.Visibility = Visibility.Visible;
                        PinRefuse.Visibility  = Visibility.Visible;
                    });

                break;
            }

            case DevicePairingKinds.ConfirmOnly:
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Tips.Text             = "请确认是否与配对设备配对";
                        Tips.Visibility       = Visibility.Visible;
                        PinConfirm.Visibility = Visibility.Visible;
                        PinRefuse.Visibility  = Visibility.Visible;
                    });

                break;
            }
            }
            await Task.Run(() =>
            {
                PinLock.WaitOne();

                if (IsPinConfirm)
                {
                    args.Accept();
                }
            });

            PairDeferral.Complete();
        }
Exemple #23
0
        private async void CustomPairInfo_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            Deferral PairDeferral = args.GetDeferral();

            switch (args.PairingKind)
            {
            case DevicePairingKinds.ConfirmPinMatch:
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Tips.Text             = $"{Globalization.GetString("BluetoothUI_Tips_Text_5")}{Environment.NewLine}{args.Pin}";
                        Tips.Visibility       = Visibility.Visible;
                        PinConfirm.Visibility = Visibility.Visible;
                        PinRefuse.Visibility  = Visibility.Visible;
                    });

                break;
            }

            case DevicePairingKinds.ConfirmOnly:
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Tips.Text             = Globalization.GetString("BluetoothUI_Tips_Text_6");
                        Tips.Visibility       = Visibility.Visible;
                        PinConfirm.Visibility = Visibility.Visible;
                        PinRefuse.Visibility  = Visibility.Visible;
                    });

                break;
            }
            }
            await Task.Run(() =>
            {
                PinLock.WaitOne();

                if (IsPinConfirm)
                {
                    args.Accept();
                }
            }).ConfigureAwait(false);

            PairDeferral.Complete();
        }
        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);
        }
        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);
        }
Exemple #26
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}] すでにペアリング済み");
            }
        }
Exemple #27
0
        private async void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            resultsListView.IsEnabled = false;


            string val = resultsListView.SelectedValue.ToString();

            deviceInfoDisp = ResultCollection.Where(r => r.Id == val).FirstOrDefault();

            this.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage);

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

            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            Debug.WriteLine("Is Paired -- " + deviceInfoDisp.IsPaired);
            customPairing.PairingRequested += PairingRequestedHandler;

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

            customPairing.PairingRequested -= PairingRequestedHandler;

            if (result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired)
            {
                Debug.WriteLine("Paired..");
            }
            deviceInfoDisp = ResultCollection.Where(r => r.Id == val).FirstOrDefault();
            Debug.WriteLine("Is Paired -- " + deviceInfoDisp.IsPaired);
            //this.NotifyUser(
            //    "Unpairing result = " + result.Status.ToString(),
            //    result.Status == DeviceUnpairingResultStatus.Unpaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);

            UpdateButtons(deviceInfoDisp);
            resultsListView.IsEnabled = true;
        }
        /// <summary>
        /// 异步启动蓝牙的配对过程
        /// </summary>
        /// <param name="DeviceInfo"></param>
        /// <returns></returns>
        private async Task PairAsync(DeviceInformation DeviceInfo)
        {
            DevicePairingKinds PairKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch;

            DeviceInformationCustomPairing CustomPairing = DeviceInfo.Pairing.Custom;

            CustomPairing.PairingRequested += CustomPairInfo_PairingRequested;

            DevicePairingResult PairResult = await CustomPairing.PairAsync(PairKinds, DevicePairingProtectionLevel.EncryptionAndAuthentication);

            CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested;

            if (PairResult.Status == DevicePairingResultStatus.Paired)
            {
                BluetoothWatcher.Stop();
                BluetoothDeviceCollection.Clear();
                BluetoothWatcher.Start();
            }
            else
            {
                Tips.Text = "配对失败";
            }
        }
Exemple #29
0
        /// <summary>
        /// 异步启动蓝牙的配对过程
        /// </summary>
        /// <param name="DeviceInfo"></param>
        /// <returns></returns>
        private async Task PairAsync(BluetoothDeivceData Device)
        {
            try
            {
                if (Device.DeviceInfo.Pairing.CanPair)
                {
                    DeviceInformationCustomPairing CustomPairing = Device.DeviceInfo.Pairing.Custom;

                    CustomPairing.PairingRequested += CustomPairInfo_PairingRequested;

                    DevicePairingResult PairResult = await CustomPairing.PairAsync(DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch, DevicePairingProtectionLevel.EncryptionAndAuthentication);

                    CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested;

                    if (PairResult.Status == DevicePairingResultStatus.Paired)
                    {
                        Device.Update();
                    }
                    else
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Tips.Text       = Globalization.GetString("BluetoothUI_Tips_Text_4");
                            Tips.Visibility = Visibility.Visible;
                        });
                    }
                }
                else
                {
                    LogTracer.Log($"Unable pair with Bluetooth device: \"{Device.Name}\", reason: CanPair property return false");
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"Unable pair with Bluetooth device: \"{Device.Name}\"");
            }
        }
Exemple #30
0
        /// <summary>
        /// User wants to use custom pairing with the selected ceremony types and Default protection level
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Use the pair button on the bluetoothDeviceListView.SelectedItem to get the data context
            BluetoothDeviceInformationDisplay deviceInfoDisp =
                ((Button)sender).DataContext as BluetoothDeviceInformationDisplay;
            string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothAttemptingToPairFormat");
            string confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);

            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);

            // Save the pair button
            Button pairButton = sender as Button;

            inProgressPairButton = pairButton;

            // Save the flyout and set to null so it doesn't pop up unless we want it
            savedPairButtonFlyout       = pairButton.Flyout;
            inProgressPairButton.Flyout = null;

            // Disable the pair button until we are done
            pairButton.IsEnabled = false;

            // Get ceremony type and protection level selections
            DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();
            // Get protection level
            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);

            if (result.Status == DevicePairingResultStatus.Paired)
            {
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothPairingSuccessFormat");
                confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);
            }
            else
            {
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothPairingFailureFormat");
                confirmationMessage = string.Format(formatString, result.Status.ToString(), deviceInfoDisp.Name,
                                                    deviceInfoDisp.Id);
            }
            // Display the result of the pairing attempt
            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);

            // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure state is reflected in list
            if (BluetoothToggle.IsOn)
            {
                bluetoothDeviceObservableCollection.Clear();
                StopWatcher();
                StartWatcher();
            }
            else
            {
                // If the watcher is off this is an inbound request so just clear the list
                bluetoothDeviceObservableCollection.Clear();
            }

            // Re-enable the pair button
            inProgressPairButton = null;
            pairButton.IsEnabled = true;
        }
 private static void OnPairingRequested(DeviceInformationCustomPairing pairing, DevicePairingRequestedEventArgs args)
 {
     args.Accept("0");
 }
        private async void PairingRequestedHandler(
            DeviceInformationCustomPairing sender,
            DevicePairingRequestedEventArgs args)
        {
            switch (args.PairingKind)
            {
                case DevicePairingKinds.ConfirmOnly:
                    // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
                    // If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation.
                    args.Accept();
                    break;

                case DevicePairingKinds.DisplayPin:
                    // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN
                    // on the target device. We automatically except here since we can't really "cancel" the operation
                    // from this side.
                    args.Accept();

                    // No need for a deferral since we don't need any decision from the user
                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        ShowPairingPanel(
                            "Please enter this PIN on the device you are pairing with: " + args.Pin,
                            args.PairingKind);

                    });
                    break;

                case DevicePairingKinds.ProvidePin:
                    // A PIN may be shown on the target device and the user needs to enter the matching PIN on 
                    // this Windows device. Get a deferral so we can perform the async request to the user.
                    var collectPinDeferral = args.GetDeferral();

                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                    {
                        string pin = await GetPinFromUserAsync();
                        if (!string.IsNullOrEmpty(pin))
                        {
                            args.Accept(pin);
                        }

                        collectPinDeferral.Complete();
                    });
                    break;

                case DevicePairingKinds.ConfirmPinMatch:
                    // We show the PIN here and the user responds with whether the PIN matches what they see
                    // on the target device. Response comes back and we set it on the PinComparePairingRequestedData
                    // then complete the deferral.
                    var displayMessageDeferral = args.GetDeferral();

                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                    {
                        bool accept = await GetUserConfirmationAsync(args.Pin);
                        if (accept)
                        {
                            args.Accept();
                        }

                        displayMessageDeferral.Complete();
                    });
                    break;
            }
        }
 private void OnPairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
 {
     Utils.HandlePairing(Dispatcher, args);
 }
        /// <summary>
        /// Called when custom pairing is initiated so that we can handle the custom ceremony
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void PairingRequestedHandler(
            DeviceInformationCustomPairing sender,
            DevicePairingRequestedEventArgs args)
        {
            // Save the args for use in ProvidePin case
            pairingRequestedHandlerArgs = args;

            // Save the deferral away and complete it where necessary.
            if (args.PairingKind != DevicePairingKinds.DisplayPin)
            {
                deferral = args.GetDeferral();
            }

            string confirmationMessage;

            switch (args.PairingKind)
            {
                case DevicePairingKinds.ConfirmOnly:
                    // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
                    // If this is an App for Athens where there is no Windows Consent UX, you may want to provide your own confirmation.
                    {
                        confirmationMessage = string.Format(bluetoothConfirmOnlyFormatString, args.DeviceInformation.Name, args.DeviceInformation.Id);
                        DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
                        // Accept the pairing which also completes the deferral
                        AcceptPairing();
                    }
                    break;

                case DevicePairingKinds.DisplayPin:
                    // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN
                    // on the target device
                    {
                        confirmationMessage = string.Format(bluetoothDisplayPinFormatString, args.Pin);
                        DisplayMessagePanel(confirmationMessage, MessageType.OKMessage);
                    }
                    break;

                case DevicePairingKinds.ProvidePin:
                    // A PIN may be shown on the target device and the user needs to enter the matching PIN on 
                    // this Windows device.
                    await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                    {
                        // PIN Entry
                        inProgressPairButton.Flyout = savedPairButtonFlyout;
                        inProgressPairButton.Flyout.ShowAt(inProgressPairButton);
                    });
                    break;

                case DevicePairingKinds.ConfirmPinMatch:
                    // We show the PIN here and the user responds with whether the PIN matches what they see
                    // on the target device. Response comes back and we set it on the PinComparePairingRequestedData
                    // then complete the deferral.
                    {
                        confirmationMessage = string.Format(bluetoothConfirmPinMatchFormatString, args.Pin);
                        DisplayMessagePanel(confirmationMessage, MessageType.YesNoMessage);
                    }
                    break;
            }
        }