コード例 #1
0
        private async System.Threading.Tasks.Task MakeDiscoverable()
        {
            // Make the system discoverable. Don'd repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists"
            if (!App.IsBluetoothDiscoverable)
            {
                Guid BluetoothServiceUuid = new Guid("17890000-0068-0069-1532-1992D79BE4D8");
                try
                {
                    provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid));

                    Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener();
                    listener.ConnectionReceived += OnConnectionReceived;
                    await listener.BindServiceNameAsync(provider.ServiceId.AsString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket);

                    //     SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
                    // Don't bother setting SPD attributes
                    provider.StartAdvertising(listener, true);
                    App.IsBluetoothDiscoverable = true;
                }
                catch (Exception e)
                {
                    string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat");
                    string confirmationMessage = string.Format(formatString, e.Message);
                    DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
                }
            }
        }
コード例 #2
0
        private async void App_InboundPairingRequested(object sender, InboundPairingEventArgs inboundArgs)
        {
            // Ignore the inbound if pairing is already in progress
            if (inProgressPairButton == null)
            {
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    // Make sure the Bluetooth grid is showing
                    await SwitchToSelectedSettingsAsync("BluetoothListViewItem");

                    // Restore the ceremonies we registered with
                    var localSettings            = Windows.Storage.ApplicationData.Current.LocalSettings;
                    Object supportedPairingKinds = localSettings.Values["supportedPairingKinds"];
                    int iSelectedCeremonies      = (int)DevicePairingKinds.ConfirmOnly;
                    if (supportedPairingKinds != null)
                    {
                        iSelectedCeremonies = (int)supportedPairingKinds;
                    }
                    SetSelectedCeremonies(iSelectedCeremonies);

                    // Clear any previous devices
                    bluetoothDeviceObservableCollection.Clear();

                    // Add latest
                    BluetoothDeviceInformationDisplay deviceInfoDisp = new BluetoothDeviceInformationDisplay(inboundArgs.DeviceInfo);
                    bluetoothDeviceObservableCollection.Add(deviceInfoDisp);

                    // Display a message about the inbound request
                    string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundPairingRequestFormat");
                    string confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);
                    DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
                });
            }
        }
コード例 #3
0
        private async Task ToggleBluetoothAsync(bool bluetoothState)
        {
            try
            {
                var access = await Radio.RequestAccessAsync();

                if (access != RadioAccessStatus.Allowed)
                {
                    return;
                }
                BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();

                if (null != adapter)
                {
                    var btRadio = await adapter.GetRadioAsync();

                    if (bluetoothState)
                    {
                        await btRadio.SetStateAsync(RadioState.On);
                    }
                    else
                    {
                        await btRadio.SetStateAsync(RadioState.Off);
                    }
                }
            }
            catch (Exception e)
            {
                string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat");
                string confirmationMessage = string.Format(formatString, e.Message);
                DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
            }
        }
コード例 #4
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Resource loading has to happen on the UI thread
            bluetoothConfirmOnlyFormatString     = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothConfirmOnlyFormat");
            bluetoothDisplayPinFormatString      = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothDisplayPinFormat");
            bluetoothConfirmPinMatchFormatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothConfirmPinMatchFormat");
            // Handle inbound pairing requests
            App.InboundPairingRequested += App_InboundPairingRequested;

            object oToggleSwitch = this.FindName("BluetoothToggle");

            if (oToggleSwitch != null)
            {
                var watcherToggle = oToggleSwitch as ToggleSwitch;
                if (watcherToggle.IsOn)
                {
                    if (deviceWatcher == null || (DeviceWatcherStatus.Stopped == deviceWatcher.Status))
                    {
                        StartWatchingAndDisplayConfirmationMessage();
                    }
                }
            }

            //Direct Jumping to Specific ListView from Outside
            if (null == e || null == e.Parameter)
            {
                await SwitchToSelectedSettingsAsync("PreferencesListViewItem");

                PreferencesListView.IsSelected = true;
            }
            else
            {
                await SwitchToSelectedSettingsAsync(e.Parameter.ToString());
            }
        }
コード例 #5
0
        private void StartWatchingAndDisplayConfirmationMessage()
        {
            // Clear the current collection
            bluetoothDeviceObservableCollection.Clear();
            // Start the watcher
            StartWatcher();
            // Display a message
            string confirmationMessage = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothOn");

            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
        }
コード例 #6
0
        private void StopWatchingAndDisplayConfirmationMessage()
        {
            // Clear any devices in the list
            bluetoothDeviceObservableCollection.Clear();
            // Stop the watcher
            StopWatcher();
            // Display a message
            string confirmationMessage = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothStoppedWatching");

            DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
        }
コード例 #7
0
        /// <summary>
        /// Turn off Bluetooth Radio and stops watching for Bluetooth devices
        /// </summary>
        private async void TurnOffBluetooth()
        {
            // Clear any devices in the list
            bluetoothDeviceObservableCollection.Clear();
            // Stop the watcher
            StopWatcher();
            // Display a message
            string confirmationMessage = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothOff");

            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
            await ToggleBluetoothAsync(false);
        }
コード例 #8
0
        private async void RegisterForInboundPairingRequests()
        {
            // Make the system discoverable for Bluetooth
            await MakeDiscoverable();

            // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present
            // so leave the diagnositic message put uot by the call to MakeDiscoverable()
            if (App.IsBluetoothDiscoverable)
            {
                string formatString;
                string confirmationMessage;

                // Get state of ceremony checkboxes
                DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();
                int iCurrentSelectedCeremonies        = (int)ceremoniesSelected;

                // Find out if we changed the ceremonies we orginally registered with - if we have registered before these will be saved
                var    localSettings            = Windows.Storage.ApplicationData.Current.LocalSettings;
                Object supportedPairingKinds    = localSettings.Values["supportedPairingKinds"];
                int    iSavedSelectedCeremonies = -1; // Deliberate impossible value
                if (supportedPairingKinds != null)
                {
                    iSavedSelectedCeremonies = (int)supportedPairingKinds;
                }

                if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected))
                {
                    confirmationMessage = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundRegistrationFailed");
                }
                else
                {
                    // Save off the ceremonies we registered with
                    localSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies;
                    formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundRegistrationSucceededFormat");
                    confirmationMessage = string.Format(formatString, ceremoniesSelected.ToString());
                }

                DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);

                // Enable the watcher switch
                BluetoothWatcherToggle.IsEnabled = true;
            }
            else
            {
                // Disable the watcher switch
                BluetoothWatcherToggle.IsEnabled = false;
            }
        }
コード例 #9
0
        /// <summary>
        /// User wants to unpair from the selected device
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UnpairButton_Click(object sender, RoutedEventArgs e)
        {
            // Use the unpair button on the bluetoothDeviceListView.SelectedItem to get the data context
            BluetoothDeviceInformationDisplay deviceInfoDisp = ((Button)sender).DataContext as BluetoothDeviceInformationDisplay;
            string formatString;
            string confirmationMessage;

            Button unpairButton = sender as Button;

            // Disable the unpair button until we are done
            unpairButton.IsEnabled = false;

            DeviceUnpairingResult unpairingResult = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync();

            if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired)
            {
                // Device is unpaired
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothUnpairingSuccessFormat");
                confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);
            }
            else
            {
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothUnpairingFailureFormat");
                confirmationMessage = string.Format(formatString, unpairingResult.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 unpair button
            unpairButton.IsEnabled = true;
        }
コード例 #10
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Resource loading has to happen on the UI thread
            bluetoothConfirmOnlyFormatString     = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothConfirmOnlyFormat");
            bluetoothDisplayPinFormatString      = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothDisplayPinFormat");
            bluetoothConfirmPinMatchFormatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothConfirmPinMatchFormat");
            // Handle inbound pairing requests
            App.InboundPairingRequested += App_InboundPairingRequested;

            object oToggleSwitch = this.FindName("BluetoothWatcherToggle");

            if (oToggleSwitch != null)
            {
                var watcherToggle = oToggleSwitch as ToggleSwitch;
                if (watcherToggle.IsOn)
                {
                    if (deviceWatcher == null || (DeviceWatcherStatus.Stopped == deviceWatcher.Status))
                    {
                        StartWatchingAndDisplayConfirmationMessage();
                    }
                }
            }
        }
コード例 #11
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;
        }
コード例 #12
0
        private async void App_InboundPairingRequested(object sender, InboundPairingEventArgs inboundArgs)
        {
            // Ignore the inbound if pairing is already in progress
            if (inProgressPairButton == null)
            {
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                // Make sure the Bluetooth grid is showing
                SwitchToSelectedSettings("BluetoothListViewItem");

                // Restore the ceremonies we registered with
                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    Object supportedPairingKinds = localSettings.Values["supportedPairingKinds"];
                    int iSelectedCeremonies = (int)DevicePairingKinds.ConfirmOnly;
                    if (supportedPairingKinds != null)
                    {
                        iSelectedCeremonies = (int)supportedPairingKinds;
                    }
                    SetSelectedCeremonies(iSelectedCeremonies);

                // Clear any previous devices
                bluetoothDeviceObservableCollection.Clear();

                // Add latest
                BluetoothDeviceInformationDisplay deviceInfoDisp = new BluetoothDeviceInformationDisplay(inboundArgs.DeviceInfo);
                    bluetoothDeviceObservableCollection.Add(deviceInfoDisp);

                // Display a message about the inbound request
                string formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundPairingRequestFormat");
                    string confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);
                    DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
                });
            }
        }