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"); } } }
private void CloseConnection(bool continueAdvertise) { if (_dataReader != null) { _dataReader.Dispose(); _dataReader = null; } if (_dataWriter != null) { _dataWriter.Dispose(); _dataWriter = null; } if (_socket != null) { _socket.Dispose(); _socket = null; } if (continueAdvertise) { // Since there is no connection, let's advertise ourselves again, so that peers can find us. PeerFinder.Start(); } else { PeerFinder.Stop(); } }
/// <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")); } }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> private async void LoadState(Object navigationParameter, Dictionary <String, Object> pageState) { // Set the app role - should be either client or singlepair string displayName = await UserInformation.GetDisplayNameAsync(); progressBar.Visibility = Visibility.Visible; if (!string.IsNullOrEmpty(displayName)) { PeerFinder.DisplayName = displayName; } //Checks whether the PC supports Wi-Fi Direct, NFC or both. //Depending on the hardware supported, different messages are displayed to the user. if (((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) == PeerDiscoveryTypes.Triggered) && ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Browse) == PeerDiscoveryTypes.Browse)) { PeerFinder.Role = PeerRole.Client; PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; PeerFinder.AllowBluetooth = false; PeerFinder.AllowInfrastructure = false; PeerFinder.AllowWiFiDirect = true; PeerFinder.Start(); } else if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Browse) == PeerDiscoveryTypes.Browse) { PeerFinder.Role = PeerRole.Client; PeerFinder.Start(); } else { proximityStatus.Text = "Neither Wi-Fi Direct nor NFC are supported :( Try on another PC"; } }
public override async Task <Connections> GetConnections() { if (isPrePairedDevice) { PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; } try { PeerFinder.AllowBluetooth = true; PeerFinder.AllowWiFiDirect = true; PeerFinder.DisplayName = "Virtual Shields"; PeerFinder.Role = PeerRole.Peer; if (!isPrePairedDevice) { PeerFinder.Start(); } var peers = await PeerFinder.FindAllPeersAsync(); var connections = new Connections(); foreach (var peer in peers) { connections.Add(new Connection(peer.DisplayName, peer)); } return(connections); } catch (Exception) { return(null); } }
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); } } }
//-------------------------------------------------------------------------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; } } }
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); } }
/// <summary> /// Closes existing Bluetooth connection. /// </summary> /// <param name="continueAdvertise">indicates whether the app should be discoverable to remote peers after closing connection. </param> private void CloseConnection(bool continueAdvertise) { PeerFinder.Stop(); this.isListeningEnabled = false; if (dataReader != null) { dataReader.Dispose(); dataReader = null; } if (dataWriter != null) { dataWriter.Dispose(); dataWriter = null; } if (connectionSocket != null) { connectionSocket.Dispose(); connectionSocket = null; } if (continueAdvertise) { PeerFinder.Start(); } }
private static StreamSocket RunAsServer(string localPeerDisplayName, string remotePeerDisplayName) { PeerFinder.DisplayName = localPeerDisplayName; PeerFinder.AllowInfrastructure = false; PeerFinder.AllowBluetooth = false; PeerFinder.AllowWiFiDirect = true; PeerFinder.ConnectionRequested += (sender, e) => { if (e.PeerInformation.DisplayName == remotePeerDisplayName) { SetRemotePeerInformation(e.PeerInformation); } }; PeerFinder.Start(); Task <StreamSocket> task = Task.Run(() => { return((MResetEvent.WaitOne(30000)) ? PeerFinder.ConnectAsync(RemotePeerInformation).AsTask().Result : throw new Exception("Listen Timeout")); }); EllipsisAnimation(task.Wait, "Listening"); PeerFinder.Stop(); return(task.Result); }
private static StreamSocket RunAsClient(string localPeerDisplayName, string remotePeerDisplayName) { PeerFinder.DisplayName = localPeerDisplayName; PeerFinder.AllowInfrastructure = false; PeerFinder.AllowBluetooth = false; PeerFinder.AllowWiFiDirect = true; PeerFinder.Start(); PeerWatcher watcher = PeerFinder.CreateWatcher(); watcher.Added += (sender, peerInfo) => { if (peerInfo.DisplayName == remotePeerDisplayName) { SetRemotePeerInformation(peerInfo); } }; watcher.Start(); Task <StreamSocket> task = Task.Run(() => { return((MResetEvent.WaitOne(30000)) ? PeerFinder.ConnectAsync(RemotePeerInformation).AsTask().Result : throw new Exception("Connect Timeout")); }); EllipsisAnimation(task.Wait, "Connecting"); PeerFinder.Stop(); return(task.Result); }
void PeerFinder_StartFindingPeers(object sender, RoutedEventArgs e) { rootPage.NotifyUser("", NotifyType.ErrorMessage); if (!_peerFinderStarted) { // attach the callback handler (there can only be one PeerConnectProgress handler). PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler); // attach the incoming connection request event handler PeerFinder.ConnectionRequested += new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested); // start listening for proximate peers PeerFinder.Start(); _peerFinderStarted = true; if (_browseConnectSupported && _triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer or click Browse for Peers button.", NotifyType.StatusMessage); PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible; } else if (_triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage); } else if (_browseConnectSupported) { rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage); PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible; } } }
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; } } } }
// Click event handler for "Advertise" button. private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e) { if (_started) { WriteMessageText("Sie warten bereits auf eine Verbindung !\r\n"); return; } PeerFinder.DisplayName = DisplayNameTextBox.Text; if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) == PeerDiscoveryTypes.Triggered) { PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; WriteMessageText("Tappen Sie ein Gerät an, das auch auf eine Verbindung wartet.\n"); } else { WriteMessageText("Antippen für eine Verbindung wird von Ihrem Gerät nicht unterstützt.\n"); } if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Browse) != PeerDiscoveryTypes.Browse) { WriteMessageText("Das Verbinden über W-Lan wird von Ihrem Gerät nicht unterstützt.\n"); } PeerFinder.Start(); _started = true; }
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"; } }
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); } }); } }
private void FindPeer() { LogMessage("Tap peer to start the game"); //Get informed when a peer is found PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; //Start advertising this app and waiting for peers PeerFinder.Start(); }
public void AdvertiseForPeers(MainPage.SongData songData) { //Init PeerFinder to make a connection from phone->phone PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; PeerFinder.Start(); WriteMessageText("You can now tap to connect a peer device that is also advertising for a connection.\n", true); }
// Constructor public MainPage() { InitializeComponent(); PeerFinder.Start(); // Sample code to localize the ApplicationBar // BuildLocalizedApplicationBar(); }
/// <summary> /// Start peer discovering /// </summary> public void StartPeerFinder(Visitor pInfo) { this.pInformation = pInfo; PeerFinder.AlternateIdentities.Add("Windows", "241465c5-9581-4a6c-aff1-7cd42ca293cd_833ns6bn3bbt0!App"); PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged; PeerFinder.ConnectionRequested += (d, e) => { }; PeerFinder.AllowInfrastructure = true; PeerFinder.AllowBluetooth = true; PeerFinder.Start(); }
// 'real' main function private async void MainPage_Loaded(object sender, RoutedEventArgs e) { //Geolocator locator = new Geolocator(); // init geolocator for GPS functionality locator = new Geolocator(); locator.MovementThreshold = 10; locator.StatusChanged += geolocator_StatusChanged; if (EmulatorMode == false) // Turn off all Bluetooth features if running on emulator { try // search and selection of all paired Bluetooth devices { PeerFinder.Start(); PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; // find / get All Paired BT Devices var peers = await PeerFinder.FindAllPeersAsync(); // make peers the container for all paired Bluetooth devices TextBox_StatusMessage.Text = "Finding Paired Devices..."; // update status message for (int i = 0; i < peers.Count; i++) // add all found Bluetooth devices to list box by adding the name { ListBox_PairedBluetoothDevices.Items.Add(peers[i].DisplayName); } if (peers.Count <= 2) // set / update status message incl. number of found Bluetooth devices { TextBox_StatusMessage.Text = "Found " + peers.Count + " devices, please select the BikeNav device"; } } catch (Exception ex) // if error { // in case of an error check if Bluetooth and location settings are correctly turned on if both 'modules' are deactivated show a message for both errors if ((uint)ex.HResult == 0x8007048F && locator.LocationStatus == PositionStatus.Disabled) { MessageBox.Show("You have to enable your Bluetooth and Location settings"); } else if ((uint)ex.HResult == 0x8007048F) // if Bluetooth deactivated but location is correctly turned on show message for Bluetooth only { MessageBox.Show("You have to enable your Bluetooth settings"); } else if (locator.LocationStatus == PositionStatus.Disabled) // if emulator mode enabled and location deactivated show message for Location { MessageBox.Show("You have to enable your Location settings"); } } } if (locator.LocationStatus == PositionStatus.Disabled && EmulatorMode) // if emulator mode enabled and location deactivated show message for Location { MessageBox.Show("You have to enable your Location settings"); } if (locator.LocationStatus != PositionStatus.Disabled) // if Bluetooth and Location settings are correct { GetCoordinate(); // search for current GPS position } }
/// <summary> /// Prepare the app to receive NFC y Bluetooth data. /// </summary> public void WaitForDataAsync() { PeerFinder.AlternateIdentities["WindowsPhone"] = WINDOWS8_APP_IDENTITY; PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged; PeerFinder.ConnectionRequested += (d, e) => { }; PeerFinder.AllowInfrastructure = true; PeerFinder.AllowBluetooth = true; PeerFinder.Start(); string famName = Windows.ApplicationModel.Package.Current.Id.FamilyName; }
public PeerDiscoveryTypes StartBluetooth() { PeerDiscoveryTypes type = PeerDiscoveryTypes.None; PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested; PeerFinder.DisplayName = (string)settingsService.Get("email"); PeerFinder.Start(); type = PeerFinder.SupportedDiscoveryTypes; return(type); }
/// <summary> /// Start advertising for a peer connection /// </summary> public void StartConnect() { if (_peerFinderStarted) { return; } // Advertise ourselves for peer app discovery PeerFinder.Start(); _peerFinderStarted = true; UpdateConnectionStatus(ConnectionStatus.ReadyForTap); }
/// <summary> /// Starts the process of finding a peer app and makes an app discoverable to remote peers. /// </summary> /// <param name="options"></param> public void startAdvertising(string options) { try { PeerFinder.ConnectionRequested += OnConnectionRequested; PeerFinder.Start(); this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } catch (Exception) { this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while starting advertising")); } }
void MainPage_Loaded(object sender, RoutedEventArgs e) { PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested; PeerFinder.DisplayName = "Peer " + Guid.NewGuid().ToString().Substring(0, 10); PeerFinder.AllowInfrastructure = true; PeerFinder.AllowBluetooth = true; PeerFinder.AllowWiFiDirect = false; PeerFinder.Start(); }
private async void RefreshPairedDevicesList() { try { // Search for all paired devices PeerFinder.Start(); lstBTPaired.Items.Clear(); PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; var peers = await PeerFinder.FindAllPeersAsync(); // By clearing the backing data, we are effectively clearing the ListBox if (peers.Count == 0) { MessageBox.Show("Bluetooth ist deaktiviert"); } else { // Found paired devices. for (int i = 0; i < peers.Count; i++) { lstBTPaired.Items.Add(peers[i].DisplayName); } //if (peers.Count <= 3) //{ txtBTStatus.Text = "Found " + peers.Count + " Devices"; //} } } catch (Exception ex) { if ((uint)ex.HResult == 0x8007048F) { var result = MessageBox.Show("Bluetooth off", "Bluetooth Off", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { ShowBluetoothcControlPanel(); } } else if ((uint)ex.HResult == 0x80070005) { MessageBox.Show("missing caps"); } else { MessageBox.Show(ex.Message); } } }
/// <summary> /// Send personal information to windows 8 application. /// </summary> /// <param name="pInfo"></param> /// <returns></returns> public async void SendInfo(Visitor pInfo) { this.pInformation = pInfo; var content = JsonConvert.SerializeObject(pInformation); if (writer != null) { writer.WriteInt32(content.Length); writer.WriteString(content); await writer.StoreAsync(); } PeerFinder.Stop(); PeerFinder.Start(); }
// Constructor public MainPage() { InitializeComponent(); PeerFinder.Start(); _connectionManager = new ConnectionManager(); _connectionManager.MessageReceived += message => Deployment.Current.Dispatcher.BeginInvoke(() => { tbResult.Text += string.Format("-> {0}\r\n", message); }); _connectionManager.PeerConnected += () => Deployment.Current.Dispatcher.BeginInvoke(() => ToggleUI(true)); }
/// <summary> /// Asynchronous call to re-populate the ListBox of peers. /// </summary> private async void RefreshPeerAppList() { // By clearing the backing data, we are effectively clearing the ListBox _peerApps.Clear(); try { PeerFinder.DisplayName = txtUserId.Text; // PeerFinder.Start() is used to advertise our presence so that peers can find us. // It must always be called before FindAllPeersAsync. PeerFinder.Start(); var peers = await PeerFinder.FindAllPeersAsync(); if (peers.Count == 0) { MessageBox.Show(AppResources.Msg_NoPeers); } else { MessageBox.Show(String.Format("Found {0} peers", peers.Count)); // Found paired devices. foreach (var peer in peers) { MessageBox.Show(peer.DisplayName); _peerApps.Add(new PeerAppInfo(peer)); } } } catch (Exception ex) { if ((uint)ex.HResult == 0x8007048F) { MessageBox.Show(AppResources.Msg_BluetoothOff); } else if ((uint)ex.HResult == 0x80070005) { // You should remove this check before releasing. MessageBox.Show(AppResources.Msg_MissingCaps); } else { MessageBox.Show(ex.Message); } } }