Example #1
0
        /// <summary>
        /// Returns list of paired devices
        /// </summary>
        /// <returns>List of paired devices</returns>
        public async Task <List <DeviceInfo> > GetPairedDevices()
        {
            List <DeviceInfo> devices = new List <DeviceInfo>();

            try
            {
                // find all the Paired devices
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
                var pairedDevices = await PeerFinder.FindAllPeersAsync();

                // Covert devices to ViewModel
                foreach (var device in pairedDevices)
                {
                    devices.Add(new DeviceInfo()
                    {
                        DisplayName = device.DisplayName,
                        HostName    = device.HostName.RawName
                    });
                }
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2147023729)
                {
                    throw new Exception("The Bluetooth settings is off. Please turn it on.");
                }

                throw;
            }

            return(devices);
        }
Example #2
0
        /// <summary>
        /// Asynchronous call to re-populate the ListBox of peers.
        /// </summary>
        private async void RefreshPeerAppList()
        {
            try
            {
                //StartProgress("finding peers ...");
                var peers = await PeerFinder.FindAllPeersAsync();

                // By clearing the backing data, we are effectively clearing the ListBox
                _peerApps.Clear();

                if (peers.Count == 0)
                {
                    tbPeerList.Text = AppResources.Msg_NoPeers;
                }
                else
                {
                    tbPeerList.Text = String.Format(AppResources.Msg_FoundPeers, peers.Count);
                    // Add peers to list
                    foreach (var peer in peers)
                    {
                        _peerApps.Add(new PeerAppInfo(peer));
                    }

                    // If there is only one peer, go ahead and select it
                    if (PeerList.Items.Count == 1)
                    {
                        PeerList.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public async Task <IEnumerable <PeerInformation> > FindPeersAsync()
        {
            _peerInformationList = null;

            if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Browse) ==
                PeerDiscoveryTypes.Browse)
            {
                if (PeerFinder.AllowWiFiDirect)
                {
                    // Find all discoverable peers with compatible roles
                    _peerInformationList = await PeerFinder.FindAllPeersAsync();

                    if (_peerInformationList == null)
                    {
                        Verbose("Found no peer");
                    }
                    else
                    {
                        Verbose(string.Format("I found {0} devices(s) executing this same app !", _peerInformationList.Count()));
                    }
                }
                else
                {
                    Verbose("WIFI direct not available");
                }
            }
            else
            {
                Verbose("Browse not available");
            }

            return(_peerInformationList);
        }
Example #4
0
    public async void list(string args)
    {
        Debug.WriteLine("Listing Paired Bluetooth Devices");

        PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
        try
        {
            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                Debug.WriteLine("No paired devices were found.");
            }

            // return serializable device info
            var pairedDeviceList = new List <PairedDeviceInfo>(pairedDevices.Select(x => new PairedDeviceInfo(x)));
            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, pairedDeviceList));
        }
        catch (Exception ex)
        {
            if ((uint)ex.HResult == 0x8007048F)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Bluetooth is disabled"));
            }
            else
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
            }
        }
    }
        private async void btnRefresh_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try {
                var peers = await PeerFinder.FindAllPeersAsync();

                PeerList.ItemsSource = (peers ?? new PeerInformation[] {}).Select(p => new PeerAppInfo(p));
            } catch (Exception ex) {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    var result = MessageBox.Show(AppResources.Err_BluetoothOff, AppResources.Err_BluetoothOffCaption, MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.OK)
                    {
                        var connectionSettingsTask = new ConnectionSettingsTask {
                            ConnectionSettingsType = ConnectionSettingsType.Bluetooth
                        };
                        connectionSettingsTask.Show();
                    }
                }
                else if ((uint)ex.HResult == 0x80070005)
                {
                    // You should remove this check before releasing.
                    MessageBox.Show(AppResources.Err_MissingCaps);
                }
                else if ((uint)ex.HResult == 0x8000000E)
                {
                    MessageBox.Show(AppResources.Err_NotAdvertising);
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Example #6
0
        private async void Connect(bool notify)
        {
            if (isConnecting)
            {
                return;
            }
            isConnecting = true;

            try
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
                var peers = await PeerFinder.FindAllPeersAsync();

                System.Diagnostics.Debug.WriteLine(string.Join("\n", peers.Select(d => d.DisplayName)));
                var peer = peers.FirstOrDefault(d => d.DisplayName == settings.BluetoothName) ?? peers.FirstOrDefault();
                System.Diagnostics.Debug.WriteLine("Connect: " + (peer?.DisplayName ?? "Null"));

                if (peer != null)
                {
                    await connection.Connect(peer);
                }
            }
            catch (Exception exc)
            {
                if (notify)
                {
                    await new MessageDialog(exc.Message).ShowAsync();
                }
            }

            isConnecting = false;
        }
Example #7
0
            internal void Run()
            {
                PeerFinder.Role            = PeerRole.Client;
                PeerFinder.AllowWiFiDirect = true;
                PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged;

                if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                     Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                    Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
                {
                    Console.WriteLine("Peer discovery using Wi-Fi Direct is not supported.\n");
                    return;
                }

                PeerFinder.Start();

                var peerInfoCollection = PeerFinder.FindAllPeersAsync().AsTask().Result;

                if (peerInfoCollection.Count == 0)
                {
                    Console.WriteLine("No peers found");
                    return;
                }

                foreach (var info in peerInfoCollection)
                {
                    Console.WriteLine("Peer found: {0}", info.DisplayName);

                    Windows.Networking.Sockets.StreamSocket socket =
                        PeerFinder.ConnectAsync(info).AsTask().Result;

                    Sender(socket);
                }
            }
Example #8
0
 /// <summary>
 /// Detect all Pebble bluetooth connections that have been paired with this system.
 /// </summary>
 /// <returns></returns>
 public static async Task <IList <Flint.Core.Pebble> > DetectPebbles()
 {
     // Configure PeerFinder to search for all paired devices.
     PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
     return((await PeerFinder.FindAllPeersAsync()).Select(
                x => new Flint.Core.Pebble(new PebbleBluetoothConnection(x), x.DisplayName)).ToList());
 }
        async void PeerFinder_BrowsePeers(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("Finding Peers...", NotifyType.StatusMessage);
            try
            {
                _peerInformationList = await PeerFinder.FindAllPeersAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("FindAll throws exception" + ex.Message);
            }
            Debug.WriteLine("Async operation completed");
            rootPage.NotifyUser("No peers found", NotifyType.StatusMessage);

            if (_peerInformationList.Count > 0)
            {
                PeerFinder_FoundPeersList.Items.Clear();
                for (int i = 0; i < _peerInformationList.Count; i++)
                {
                    ListBoxItem item = new ListBoxItem();
                    item.Content = _peerInformationList[i].DisplayName;
                    PeerFinder_FoundPeersList.Items.Add(item);
                }
                PeerFinder_ConnectButton.Visibility  = Visibility.Visible;
                PeerFinder_FoundPeersList.Visibility = Visibility.Visible;
                rootPage.NotifyUser("Finding Peers Done", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("No peers found", NotifyType.StatusMessage);
                PeerFinder_ConnectButton.Visibility  = Visibility.Collapsed;
                PeerFinder_FoundPeersList.Visibility = Visibility.Collapsed;
            }
        }
Example #10
0
        private RadioState GetState()
        {
            RadioState state = RadioState.Unknown;

            var t = Task.Run(async() =>
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

                try
                {
                    var peers = await PeerFinder.FindAllPeersAsync();
                    state     = RadioState.On;
                }
                catch (Exception ex)
                {
                    if ((uint)ex.HResult == 0x8007048F)
                    {
                        state = RadioState.Off;
                    }
                }
            });

            t.Wait();

            return(state);
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            PeerFinder.AllowBluetooth  = true;
            PeerFinder.AllowWiFiDirect = true;

            PeerFinder.ConnectionRequested             += PeerFinder_ConnectionRequested;
            PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;

            PeerFinder.Start();

            _peerWatcher          = PeerFinder.CreateWatcher();
            _peerWatcher.Added   += _peerWatcher_Added;
            _peerWatcher.Removed += _peerWatcher_Removed;
            _peerWatcher.EnumerationCompleted += _peerWatcher_EnumerationCompleted;
            _peerWatcher.Updated += _peerWatcher_Updated;
            _peerWatcher.Start();

            try
            {
                var allpeer = await PeerFinder.FindAllPeersAsync();

                this.listviewAllDevice.ItemsSource = allpeer;
            }
            catch (Exception ex)
            {
                this.textboxDebug.Text += ex.Message + "\n";
            }
        }
Example #12
0
        public async Task <bool> LoadBluetoothDevices()
        {
            BluetoothDevices.Clear();
            //PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805f9b34fb}";
            if (PeerFinder.AlternateIdentities.ContainsKey("Bluetooth:Paired"))
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = string.Empty;
            }
            IReadOnlyList <PeerInformation> availableDevices;

            try
            {
                availableDevices = await PeerFinder.FindAllPeersAsync();
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    BluetoothIsEnabled = false;
                    return(false);
                }
                throw;
            }
            BluetoothIsEnabled = true;
            foreach (var device in availableDevices)
            {
                BluetoothDevices.Add(new BluetoothDeviceViewModel
                {
                    DisplayName   = device.DisplayName,
                    CanonicalName = device.HostName.CanonicalName
                });
            }
            return(true);
        }
Example #13
0
        /// <summary>
        /// Searches for Bluetooth peers
        /// </summary>
        /// <param name="options"></param>
        public async void discoverDevices(string options)
        {
            try
            {
                PeerFinder.Start();
                discoveredPeers = await PeerFinder.FindAllPeersAsync();

                PeerInfo[] peerInfo = new PeerInfo[discoveredPeers.Count];

                for (int i = 0; i < discoveredPeers.Count; i++)
                {
                    var peer = discoveredPeers[i];

                    //TODO It seems PeerInformation.HostName property sometimes returns null. Check what is the cause.
                    string hostName = peer.HostName == null ? "Unknown host" : peer.HostName.DisplayName;
                    peerInfo[i] = new PeerInfo(peer.DisplayName, hostName);
                }

                this.DispatchCommandResult(discoveredPeers.Count > 0
                                               ? new PluginResult(PluginResult.Status.OK, JsonHelper.Serialize(peerInfo))
                                               : new PluginResult(PluginResult.Status.ERROR, "No devices were found"));
            }
            catch (Exception)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while discovering devices"));
            }
        }
        private async Task <bool> SetupDeviceConn()
        {
            //Connect to your paired NXTCar using BT + StreamSocket (over RFCOMM)
            PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";

            var devices = await PeerFinder.FindAllPeersAsync();

            if (devices.Count == 0)
            {
                MessageBox.Show("No bluetooth devices are paired, please pair your i-Racer (DaguCar)");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));

                return(false);
            }

            PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("Car"));

            if (peerInfo == null)
            {
                MessageBox.Show("No paired  i-Racer (DaguCar) was found, please pair your i-Racer (DaguCar)");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));

                return(false);
            }

            StreamSocket s = new StreamSocket();
            await s.ConnectAsync(peerInfo.HostName, "1");

            cc = new CarControl(s);

            return(true);
        }
Example #15
0
        //-------------------------------------------------------------------------wyszukiwanie urzadzenia
        async private void findDevice()
        {
            try
            {
                PeerFinder.Start();
                PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805f9b34fb}";
                var foundDevices = await PeerFinder.FindAllPeersAsync();

                foreach (var device in foundDevices)
                {
                    if (device.DisplayName.Equals(deviceName))
                    {
                        found = true;
                        await receiveFile(device);

                        break;
                    }
                }
                if (!found)
                {
                    popupDialog("Nie znaleziono urządzenia!\nUpewnij się że urządzenia są sparowane\nPowrót");
                }
            }
            catch (Exception e)
            {
                if ((uint)e.HResult == 0x8007048F)
                {
                    disconnect();
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                    popupDialog("Bluetooth jest wyłączone!\nPowrót");
                    return;
                }
            }
        }
        public async Task <List <IBluetoothDevice> > GetPairedDevices()
        {
            var devices = new List <IBluetoothDevice>();

            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

            var pairedDevices = (await PeerFinder.FindAllPeersAsync()).ToList();

            if (pairedDevices.Count > 0)
            {
                foreach (var paireddevice in pairedDevices)
                {
                    var device = new WP80BluetoothDevice()
                    {
                        Name = paireddevice.DisplayName, Address = paireddevice.HostName.CanonicalName
                    };

                    device.BluetoothDevice = paireddevice;

                    var id = paireddevice.GetPropertyValue <string>("Id");

                    if (!String.IsNullOrEmpty(id))
                    {
                        var guid = Guid.Parse(id);
                        device.UniqueIdentifiers.Add(guid);
                    }


                    devices.Add(device);
                }
            }


            return(devices);
        }
        private async Task InitializeBtComponentAsync()
        {
            deviceNames.Items.Clear();
            try
            {
                // find all the Paired devices
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
                var pairedDevices = await PeerFinder.FindAllPeersAsync();

                // Covert devices to ViewModel
                foreach (var device in pairedDevices)
                {
                    devices.Add(new DeviceInfo()
                    {
                        DisplayName = device.DisplayName,
                        HostName    = device.HostName.RawName
                    });
                }
                deviceNames.ItemsSource = devices;
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2147023729)
                {
                    ErrorMessage.Text = "BT KAPALI";
                }
                throw;
            }
            return;
        }
        /*
         * public void StartDiscovery()
         * {
         *
         * }
         *
         * public void EndDiscovery()
         * {
         *
         * }
         *
         * public event EventHandler DeviceDiscoveryStarted;
         * public event EventHandler DeviceDiscoverEnded;
         * public event EventHandler<DeviceFoundEventArgs> DeviceDiscovered;
         */
        public async Task <List <IBluetoothDevice> > FindDevicesWithIdentifier(string identifier)
        {
            PeerFinder.AlternateIdentities["Bluetooth:SDP"] = identifier;

            var result = new List <IBluetoothDevice>();

            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                Debug.WriteLine("No paired devices were found.");
            }
            else
            {
                foreach (var pairedDevice in pairedDevices)
                {
                    var device = new WP80BluetoothDevice()
                    {
                        Name = pairedDevice.DisplayName, Address = pairedDevice.HostName.CanonicalName
                    };

                    device.BluetoothDevice = pairedDevice;
                    var id = pairedDevice.GetPropertyValue <string>("Id");

                    if (!String.IsNullOrEmpty(id))
                    {
                        var guid = Guid.Parse(id);
                        device.UniqueIdentifiers.Add(guid);
                    }
                    result.Add(device);
                }
            }

            return(result);
        }
        public async Task Start(ConnectMethod connectMethod = ConnectMethod.Tap, string displayAdvertiseName = null)
        {
            Reset();
            connectMode = connectMethod;
            if (!string.IsNullOrEmpty(displayAdvertiseName))
            {
                PeerFinder.DisplayName = displayAdvertiseName;
            }

            try
            {
                PeerFinder.Start();
            }
            catch (Exception)
            {
                Debug.WriteLine("Peerfinder error");
            }

            // Enable browse
            if (connectMode == ConnectMethod.Browse)
            {
                if (ConnectCrossPlatform)
                {
                    await InitBrowseWpToWin();
                }

                await PeerFinder.FindAllPeersAsync().AsTask().ContinueWith(p =>
                {
                    if (!p.IsFaulted)
                    {
                        FirePeersFound(p.Result);
                    }
                });
            }
        }
Example #20
0
        private async void AppToApp()
        {
            PeerFinder.Start();
            ConnectAppToAppButton.Content = "Connecting...";
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                MessageBox.Show("No paired devices were found.");
            }
            else
            {
                foreach (var pairedDevice in pairedDevices)
                {
                    if (pairedDevice.DisplayName == WindowsPhoneName.Text)
                    {
                        controllerManager.Connect(pairedDevice.HostName);
                        //PeerInformation[] peers = pairedDevices.ToArray();
                        //PeerInformation peerInfo = pairedDevices.FirstOrDefault(c => c.DisplayName.Contains(WindowsPhoneName.Text));

                        //await s.ConnectAsync(peerInfo.HostName, "1");
                        ConnectAppToAppButton.Content   = "Connected";
                        WindowsPhoneName.IsReadOnly     = true;
                        ConnectAppToAppButton.IsEnabled = false;

                        //input = new DataReader(s.InputStream);
                        connected = true;
                        continue;
                    }
                }
            }
        }
Example #21
0
    public async void isEnabled(string args)
    {
        string callbackId = JsonHelper.Deserialize <string[]>(args)[0];

        // This is a bad way to do this, improve later
        // See if we can determine in the Connection Manager
        // https://msdn.microsoft.com/library/windows/apps/jj207007(v=vs.105).aspx
        PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

        try
        {
            var peers = await PeerFinder.FindAllPeersAsync();

            // Handle the result of the FindAllPeersAsync call
        }
        catch (Exception ex)
        {
            if ((uint)ex.HResult == 0x8007048F)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId);
            }
            else
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message), callbackId);
            }
        }

        DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
    }
        private async void lstBTPaired_Tap_1(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                if (lstBTPaired.SelectedItem == null)                      // To prevent errors, make sure something is Selected
                {
                    txtBTStatus.Text = "No Device Selected! Try again..."; // Set UI Output
                    return;
                }
                else
                if (lstBTPaired.SelectedItem != null)                                                // Just making sure something was Selected
                {
                    PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";                         // Grab Paired Devices
                    var PF = await PeerFinder.FindAllPeersAsync();                                   // Store Paired Devices

                    bluetoothSocket = new StreamSocket();                                            // Create a new Socket Connection
                    await bluetoothSocket.ConnectAsync(PF[lstBTPaired.SelectedIndex].HostName, "1"); // Connect using Socket to Selected Item

                    // Once Connected, let's give Arduino a HELLO
                    var datab = GetBufferFromByteArray(Encoding.UTF8.GetBytes("1")); // Create Buffer/Packet for Sending
                    await bluetoothSocket.OutputStream.WriteAsync(datab);            // Send Arduino Buffer/Packet Message

                    btnSendCommand.IsEnabled = true;                                 // Allow commands to be sent via Command Button (Enabled)
                }
            }
            catch (Exception ex)
            {
                txtBTStatus.Text = "Faild to connect: retrying";
                lstBTPaired_Tap_1(sender, e);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.HResult);
            }
        }
Example #23
0
        } // CheckForBluetooth()

        /// <summary>
        /// Finds available bluetooth devices.
        /// </summary>
        /// <returns>A list of bluetooth devices.</returns>
        public async Task <List <PeerInformation> > FindBluetoothDevices()
        {
            this.CheckForBluetooth();

            var retDevices = new List <PeerInformation>();

            try
            {
                var devices = await PeerFinder.FindAllPeersAsync();

                if (devices == null)
                {
                    this.ShowMessageBox("No bluetooth devices are found, please pair OBD Interface");
                    return(retDevices);
                } // if

                if (devices.Count == 0)
                {
                    this.ShowMessageBox("No bluetooth devices are paired, please pair OBD Interface");
                    return(retDevices);
                } // if

                retDevices.AddRange(devices);
            }
            catch (Exception ex)
            {
                this.OutputText("Error finding devices: " + ex.Message);
            } // if

            return(retDevices);
        } // FindBluetoothDevices()
Example #24
0
        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Register for incoming connection requests
                PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;

                // Start advertising ourselves so that our peers can find us
                txtPeerName.Text = PeerFinder.DisplayName = "Peer " + Guid.NewGuid().ToString().Substring(0, 10);

                PeerFinder.Start();

                var available_peers = await PeerFinder.FindAllPeersAsync();

                var list = available_peers.ToList();

                PeerList.ItemsSource = new ObservableCollection <PeerInformation>(list);
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    MessageBox.Show("Bluetooth is turned off");
                }
            }
        }
Example #25
0
        /// <summary>
        /// Search for nearby devices running NFC Talk. Uses Bluetooth.
        ///
        /// Searching action will be invoked when search is started.
        /// SearchFinished action will be invoked when search has finished. Found peers can be accessed via the Peers property.
        /// ConnectivityProblem action will be invoked if search fails.
        /// </summary>
        public async void Search()
        {
            if (_status != ConnectionStatusValue.Idle)
            {
                Peers = null;

                try
                {
                    if (Searching != null)
                    {
                        Searching();
                    }

                    Peers = await PeerFinder.FindAllPeersAsync();

                    if (SearchFinished != null)
                    {
                        SearchFinished();
                    }
                }
                catch (Exception ex)
                {
                    if (ConnectivityProblem != null)
                    {
                        ConnectivityProblem();
                    }
                }
            }
            else
            {
                throw new Exception("Bad state, please start first");
            }
        }
Example #26
0
        //
        private async void ButtonConnectBikeNav_Click(object sender, RoutedEventArgs e)
        {
            if (ListBox_PairedBluetoothDevices.SelectedItem != null)
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";                                            // Grab Paired Devices
                var PF = await PeerFinder.FindAllPeersAsync();                                                      // Store Paired Devices

                BluetoothSocket = new StreamSocket();                                                               // Create a new Socket Connection
                await BluetoothSocket.ConnectAsync(PF[ListBox_PairedBluetoothDevices.SelectedIndex].HostName, "1"); // Connect using Socket to Selected Item

                var DataBuffer = GetBufferFromByteArray(Encoding.UTF8.GetBytes(""));                                // Create Buffer/Packet for Sending
                await BluetoothSocket.OutputStream.WriteAsync(DataBuffer);                                          // Send Arduino Buffer/Packet Message

                TextBox_StatusMessage.Text = "Connection successfully established";                                 // success message for Bluetooth connection

                ListBox_PairedBluetoothDevices.Visibility = Visibility.Collapsed;                                   // Quick and Dirty UI change between Bluetooth connect and already connected 'screen'

                TextBox_Latitude.Visibility  = Visibility.Visible;
                TextBox_Longitude.Visibility = Visibility.Visible;
                TextBox_Angle.Visibility     = Visibility.Visible;
                TextBox_Direction.Visibility = Visibility.Visible;
                TextBox_Speed.Visibility     = Visibility.Visible;
                TextBox_Distance.Visibility  = Visibility.Visible;
                TextBox_WPLong.Visibility    = Visibility.Visible;
                TextBox_NoWPs.Visibility     = Visibility.Visible;
                ListBox_WayPoints.Visibility = Visibility.Visible;

                Button_ConnectToBikeNav.Visibility = Visibility.Collapsed;
                Button_SendData.Visibility         = Visibility.Visible;        // end of UI change
            }
        }
Example #27
0
        private async void AppToDevice()
        {
            ConnectAppToDeviceButton.Content = "Connecting...";
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                MessageBox.Show("No paired devices were found.");
            }
            else
            {
                foreach (var pairedDevice in pairedDevices)
                {
                    if (pairedDevice.DisplayName == DeviceName.Text)
                    {
                        mConManager.Connect(pairedDevice.HostName);
                        ConnectAppToDeviceButton.Content   = "Connected";
                        DeviceName.IsReadOnly              = true;
                        ConnectAppToDeviceButton.IsEnabled = false;
                        continue;
                    }
                }
            }
        }
Example #28
0
        private async void SearchForPeers()
        {
            try
            {
                SystemTray.ProgressIndicator.IsVisible = true;

                // PeerFinder starten, um nach Peers suchen zu können
                PeerFinder.Start();

                // Nur nach verbundene Geräte suchen
                // PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

                // Peers suchen und Ergebnis anzeigen
                IReadOnlyList <PeerInformation> foundPeers = await PeerFinder.FindAllPeersAsync();

                PeersList.ItemsSource = foundPeers;

                SystemTray.ProgressIndicator.IsVisible = false;
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == BluetoothOff)
                {
                    // Bluetooth ist deaktiviert - Nutzer zu den Einstellungen navigieren zum Einschalten
                    Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Example #29
0
        public async Task <IReadOnlyList <IBluetoothDevice> > GetPairedDevices()
        {
            PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
            var devices = await PeerFinder.FindAllPeersAsync();

            return(devices.Select(a => new BluetoothDevice(a)).ToList());
        }
Example #30
0
        private async Task BrowseCommand()
        {
            this.IsBrowsing   = true;
            this.ErrorMessage = string.Empty;

            this.SelectedPeer = null;
            this.Peers.Clear();

            try
            {
                var peers = await PeerFinder.FindAllPeersAsync();

                if (peers != null && peers.Count > 0)
                {
                    foreach (var peer in peers)
                    {
                        this.Peers.Add(new FoundPeer(peer));
                    }
                }
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
            }

            this.IsBrowsing = false;
        }