public void Reset() { NetworkConnectionStatus = NetworkConnectionState.NotSearching; PeerFinder.Stop(); StopInitBrowseWpToWin(); if (dataReader != null) { try { listening = false; if (dataReader != null) { dataReader.Dispose(); dataReader = null; } if (dataWriter != null) { dataWriter.Dispose(); dataWriter = null; } if (socket != null) { socket.Dispose(); socket = null; } } catch (Exception) { } } }
void StartPeerWatcher() { if (peerWatcher == null) { peerWatcher = PeerFinder.CreateWatcher(); // Hook up events, this should only be done once peerWatcher.Added += PeerWatcher_Added; peerWatcher.Removed += PeerWatcher_Removed; peerWatcher.Updated += PeerWatcher_Updated; peerWatcher.EnumerationCompleted += PeerWatcher_EnumerationCompleted; peerWatcher.Stopped += PeerWatcher_Stopped; } PeerWatcherStatus status = peerWatcher.Status; if (status == PeerWatcherStatus.Created || status == PeerWatcherStatus.Stopped || status == PeerWatcherStatus.Aborted) { try { foundPeers.SelectionChanged -= PeersSelectionChanged; availablePeers.Clear(); foundPeers.ItemsSource = availablePeers; noPeersFound.Visibility = Visibility.Collapsed; foundPeers.SelectionChanged += PeersSelectionChanged; peerWatcher.Start(); progressBar.Visibility = Visibility.Visible; } catch (Exception err) { proximityStatus.Text = "Error starting PeerWatcher: " + err.ToString(); } } }
public async Task ConnectAndSendFileAsync(PeerInformation selectedPeer, StorageFile selectedFile) { var socket = await PeerFinder.ConnectAsync(selectedPeer); Verbose(string.Format("Connected to {0}, now processing transfer ...please wait", selectedPeer.DisplayName)); await SendFileToPeerAsync(selectedPeer, socket, selectedFile); }
async void ConnectToPeer(PeerInformation peer) { try { _socket = await PeerFinder.ConnectAsync(peer); if (_dataReader == null) { _dataReader = new DataReader(_socket.InputStream); } // We can preserve battery by not advertising our presence. PeerFinder.Stop(); _peerName = peer.DisplayName; //UpdateChatBox(AppResources.Msg_ChatStarted, true); connected = true; // Listen for incoming messages. ListenForIncomingMessage(); } catch (Exception ex) { // In this sample, we handle each exception by displaying it and // closing any outstanding connection. An exception can occur here if, for example, // the connection was refused, the connection timeout etc. MessageBox.Show(ex.Message); } }
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; } } } }
/// <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"); } }
async void ConnectToPeer(PeerInformation peer) { try { _socket = await PeerFinder.ConnectAsync(peer); // We can preserve battery by not advertising our presence. PeerFinder.Stop(); _peerName = peer.DisplayName; UpdateChatBox(AppResources.Msg_ChatStarted, true); // Since this is a chat, messages can be incoming and outgoing. // Listen for incoming messages. ListenForIncomingMessage(); } catch (Exception ex) { // In this sample, we handle each exception by displaying it and // closing any outstanding connection. An exception can occur here if, for example, // the connection was refused, the connection timeout etc. MessageBox.Show(ex.Message); CloseConnection(false); } }
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); } }); } }
// Handles PeerFinder_ConnectButton click async void PeerFinder_Connect(object sender, RoutedEventArgs e) { rootPage.NotifyUser("", NotifyType.ErrorMessage); PeerInformation peerToConnect = null; if (PeerFinder_FoundPeersList.Items.Count == 0) { rootPage.NotifyUser("Cannot connect, there were no peers found!", NotifyType.ErrorMessage); } else { try { peerToConnect = (PeerInformation)((ComboBoxItem)PeerFinder_FoundPeersList.SelectedItem).Tag; if (peerToConnect == null) { peerToConnect = (PeerInformation)((ComboBoxItem)PeerFinder_FoundPeersList.Items[0]).Tag; } rootPage.NotifyUser("Connecting to " + peerToConnect.DisplayName + "....", NotifyType.StatusMessage); StreamSocket socket = await PeerFinder.ConnectAsync(peerToConnect); rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage); PeerFinder_StartSendReceive(socket, peerToConnect); } catch (Exception err) { rootPage.NotifyUser("Connection to " + peerToConnect.DisplayName + " failed: " + err.Message, NotifyType.ErrorMessage); } } }
private void DoConnect(StreamSocket receivedSocket) { socket = receivedSocket; StartListeningForMessages(); PeerFinder.Stop(); FireConnectionStatusChanged(TriggeredConnectState.Completed); }
public void Reset() { PeerFinder.Stop(); StopInitBrowseWpToWin(); if (dataReader != null) { try { listening = false; if (dataReader != null) { dataReader.Dispose(); dataReader = null; } if (dataWriter != null) { dataWriter.Dispose(); dataWriter = null; } if (socket != null) { socket.Dispose(); socket = null; } } catch (Exception) { } } }
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; }
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; }
// Invoked when the main page navigates to a different scenario protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { // If PeerFinder was started, stop it when navigating to a different page. if (_peerFinderStarted) { // detach the callback handler (there can only be one PeerConnectProgress handler). PeerFinder.TriggeredConnectionStateChanged -= new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler); // detach the incoming connection request event handler PeerFinder.ConnectionRequested -= new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested); PeerFinder.Stop(); _socketHelper.CloseSocket(); _peerFinderStarted = false; } if (_peerWatcher != null) { // unregister for events _peerWatcher.Added -= PeerWatcher_Added; _peerWatcher.Removed -= PeerWatcher_Removed; _peerWatcher.Updated -= PeerWatcher_Updated; _peerWatcher.EnumerationCompleted -= PeerWatcher_EnumerationCompleted; _peerWatcher.Stopped -= PeerWatcher_Stopped; _peerWatcher = null; } }
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); } } }
public async Task <StreamSocket> ConnectToDevice(PeerInformation peer) { return(await PeerFinder.ConnectAsync(peer)); //Peer myPeer = peers.First(s => s.Name == identity); //return await PeerFinder.ConnectAsync(myPeer.Information); }
/// <summary> /// Disconnect currently active connections and/or stop listening to tap events. /// </summary> public void Stop() { PeerFinder.Stop(); switch (_status) { case ConnectionStatusValue.Searching: case ConnectionStatusValue.Connecting: case ConnectionStatusValue.Listening: { PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged; PeerFinder.ConnectionRequested -= ConnectionRequested; } break; case ConnectionStatusValue.Connected: { if (_socket != null) { _socket.Dispose(); _socket = null; } } break; } _status = ConnectionStatusValue.Idle; }
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); } }
void TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs e) { switch (e.State) { case TriggeredConnectState.PeerFound: UpdateConnectionStatus(ConnectionStatus.PeerFound); break; case TriggeredConnectState.Canceled: UpdateConnectionStatus(ConnectionStatus.Canceled); break; case TriggeredConnectState.Failed: UpdateConnectionStatus(ConnectionStatus.Failed); break; case TriggeredConnectState.Completed: StartSendReceive(e.Socket); UpdateConnectionStatus(ConnectionStatus.Completed); // Stop advertising since we have connected PeerFinder.Stop(); _peerFinderStarted = false; break; } }
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 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(); } }
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)); } } }
/// <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); } }
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); }
private async Task ConnectToPeers(PeerInformation peer) { try { progressBar.Visibility = Visibility.Visible; UpdatePlayerStatus(peer, " - connecting..."); StreamSocket s = await PeerFinder.ConnectAsync(peer); ConnectedPeer temp = new ConnectedPeer(peer.DisplayName); connectedPeers[temp] = new SocketReaderWriter(s, this); connectedPeers[temp].ReadMessage(); UpdatePlayerStatus(peer, " - ready"); ConnectedPlayers.Items.Add(peer.DisplayName); startGameButton.Visibility = Visibility.Visible; } catch (Exception) { sendInvitationsText.Text = "Cannot connect to " + peer.DisplayName; } // PeerFinder.ConnectAsync aborts PeerWatcher // restart PeerWatcher whether connect failed or succeeded StartPeerWatcher(); }
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); }
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); }
} // 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()
public async Task <IReadOnlyList <IBluetoothDevice> > GetPairedDevices() { PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = ""; var devices = await PeerFinder.FindAllPeersAsync(); return(devices.Select(a => new BluetoothDevice(a)).ToList()); }
//-------------------------------------------------------------------------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; } } }