internal PeerAppInfo(PeerInformation peerInformation) { this.PeerInfo = peerInformation; this.DisplayName = this.PeerInfo.DisplayName; //this.HostName = this.PeerInfo.HostName.DisplayName; //this.ServiceName = this.PeerInfo.ServiceName; }
private void DoConnect(PeerInformation peerInformation) { if (IsWindowsPhone) { var hostName = (HostName)peerInformation.GetType().GetRuntimeProperty("HostName").GetMethod.Invoke(peerInformation, null); if (hostName != null) { var serviceName = (string)peerInformation.GetType().GetRuntimeProperty("ServiceName").GetMethod.Invoke(peerInformation, null); DoConnect(hostName, "{" + rfcommServiceUuid.ToString().ToUpperInvariant() + "}"); return; } } PeerFinder.ConnectAsync(peerInformation).AsTask().ContinueWith(p => { if (!p.IsFaulted) { DoConnect(p.Result); } else { Debug.WriteLine("connection fault"); FireConnectionStatusChanged(TriggeredConnectState.Failed); } }); }
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 NXTCar"); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:")); return(false); } PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("NXT")); if (peerInfo == null) { MessageBox.Show("No paired NXTCar was found, please pair your NXTCar"); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:")); return(false); } StreamSocket s = new StreamSocket(); await s.ConnectAsync(peerInfo.HostName, "1"); //This would ask winsock to do an SPP lookup for us; i.e. to resolve the port the //device is listening on //await s.ConnectAsync(peerInfo.HostName, "{00001101-0000-1000-8000-00805F9B34FB}"); _cc = new CarControl(s); return(_cc.IsConnected); }
public async void Connect() { listen = true; PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; var pairedDevices = await PeerFinder.FindAllPeersAsync(); if (pairedDevices.Count == 0) { } else { PeerInformation selectedDevice = pairedDevices[0]; // pick the first paired device try // 'try' used in the case the socket has already been connected { await socket.ConnectAsync(selectedDevice.HostName, "1"); writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()); reader = new StreamReader(socket.InputStream.AsStreamForRead()); isConnected = true; doListen(); } catch (Exception) { isConnected = false; } } }
public async Task ConnectAsync() { _tokenSource = new CancellationTokenSource(); PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; IReadOnlyList <PeerInformation> peers = await PeerFinder.FindAllPeersAsync(); PeerInformation peer = (from p in peers where p.DisplayName == _deviceName select p).FirstOrDefault(); if (peer == null) { throw new Exception(_deviceName + " Brick not found"); } _socket = new StreamSocket(); await _socket.ConnectAsync(peer.HostName, "1"); _reader = new DataReader(_socket.InputStream); _reader.ByteOrder = ByteOrder.LittleEndian; //¿qué hacía esto en wp 8.0? //ThreadPool.QueueUserWorkItem(PollInput); await ThreadPool.RunAsync(PollInput); }
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); }
// Start the send receive operations void PeerFinder_StartSendReceive(StreamSocket socket, PeerInformation peerInformation) { ConnectedPeer connectedPeer = new ConnectedPeer(socket, false, new Windows.Storage.Streams.DataWriter(socket.OutputStream)); _socketHelper.Add(connectedPeer); if (!_peerFinderStarted) { _socketHelper.CloseSocket(); return; } PeerFinder_ConnectionGrid.Visibility = Visibility.Visible; PeerFinder_SendButton.Visibility = Visibility.Visible; PeerFinder_MessageBox.Visibility = Visibility.Visible; PeerFinder_SendToPeerList.Visibility = Visibility.Visible; if (peerInformation != null) { // Add a new peer to the list of peers. ComboBoxItem item = new ComboBoxItem(); item.Content = peerInformation.DisplayName; PeerFinder_SendToPeerList.Items.Add(item); PeerFinder_SendToPeerList.SelectedIndex = 0; } // Hide the controls related to setting up a connection PeerFinder_AcceptButton.Visibility = Visibility.Collapsed; PeerFinder_BrowseGrid.Visibility = Visibility.Collapsed; PeerFinder_AdvertiseGrid.Visibility = Visibility.Collapsed; _socketHelper.StartReader(connectedPeer); }
/// <summary> /// Creates the protocol - encapsulates the socket creation /// </summary> /// <param name="peer">The peer.</param> /// <returns>A protocol object</returns> public static async Task<Protocol> CreateProtocolAsync(PeerInformation peer) { //#if WINDOWS_PHONE || WINDOWS_PHONE_APP // {00001101-0000-1000-8000-00805f9b34fb} specifies we want a Serial Port - see http://developer.nokia.com/Community/Wiki/Bluetooth_Services_for_Windows_Phone // {00000000-deca-fade-deca-deafdecacaff} Fix ServiceID for WP8.1 Update 2 try { StreamSocket socket = new StreamSocket(); await socket.ConnectAsync(peer.HostName, Guid.Parse(Pebble_Time_Manager.Common.Constants.PebbleGuid).ToString("B")); return new Protocol(socket); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } // await socket.ConnectAsync(peer.HostName, Guid.Parse("0000180a-0000-1000-8000-00805f9b34fb").ToString("B")); return null; //await socket.ConnectAsync(peer.HostName, Guid.Parse("00001101-0000-1000-8000-00805f9b34fb").ToString("B")); //#endif //throw new NotImplementedException(); }
} // ExecuteConnectCommand() #endif /// <summary> /// Connects to the specified peer. /// </summary> /// <param name="peerInformation">The peer information.</param> /// <returns>An async Task.</returns> private async Task Connect(PeerInformation peerInformation) { var socket = await this.bluetoothManager.ConnectToDevice(peerInformation); if (socket == null) { // stop any running operation this.Stop(); this.ShowToast("Connection to OBD Interface failed"); return; } // if this.OutputText("Connected."); this.ConnectedHint = "Connected"; this.socketConnection = new ObdStreamSocketDeviceConnection(socket); this.socketConnection.ConnectionClosed += this.OnConnectionClosed; this.socketConnection.ErrorEncountered += this.OnErrorEncountered; this.obdManager = new ObdManager(this.socketConnection); this.obdManager.ErrorEncountered += this.OnErrorEncountered; if (this.wasRunning) { this.Start(); } // if } // Connect()
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); }
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(); }
public async Task Connect(PeerInformation peer) { StreamSocket socket = null; BinaryWriter writer = null; Disconnect(); try { socket = new StreamSocket(); await socket.ConnectAsync(peer.HostName, "{00001101-0000-1000-8000-00805f9b34fb}"); writer = new BinaryWriter(socket.OutputStream.AsStreamForWrite()); Socket = socket; Writer = writer; Peer = peer; } catch (Exception e) { writer?.Dispose(); writer = null; socket?.Dispose(); socket = null; throw; } }
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); } }
internal PairedDeviceInfo(PeerInformation peerInformation) { this.PeerInfo = peerInformation; this.DisplayName = this.PeerInfo.DisplayName; this.HostName = this.PeerInfo.HostName.DisplayName; this.ServiceName = this.PeerInfo.ServiceName; }
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); } }
/// <summary> /// Having a list of block heights of the blocks that needs to be downloaded and having a list of available /// peer nodes that can be asked to provide the blocks, this method selects which peer is asked to provide /// which block. /// <para> /// Past experience with the node is considered when assigning the task to a peer. /// Peers with better quality score tend to get more work than others. /// </para> /// </summary> /// <param name="requestedBlockHeights">List of block heights that needs to be downloaded.</param> /// <param name="availablePeersInformation">List of peers that are available including information about lengths of their chains.</param> /// <returns>List of block heights that each peer is assigned, mapped by information about peers.</returns> public static Dictionary <PeerInformation, List <int> > AssignBlocksToPeers(List <int> requestedBlockHeights, List <PeerInformation> availablePeersInformation) { Dictionary <PeerInformation, List <int> > res = new Dictionary <PeerInformation, List <int> >(); foreach (PeerInformation peerInformation in availablePeersInformation) { res.Add(peerInformation, new List <int>()); } foreach (int blockHeight in requestedBlockHeights) { // Only consider peers that have the chain long enough to be able to provide block at blockHeight height. List <PeerInformation> filteredPeers = availablePeersInformation.Where(p => p.ChainHeight >= blockHeight).ToList(); int[] scores = filteredPeers.Select(n => n.QualityScore == BlockPuller.MaxQualityScore ? BlockPuller.MaxQualityScore * 2 : n.QualityScore).ToArray(); int totalScore = scores.Sum(); // Randomly choose a peer to assign the task to with respect to scores of all filtered peers. int index = GetNodeIndex(scores, totalScore); PeerInformation selectedPeer = filteredPeers[index]; // Assign the task to download block with height blockHeight to the selected peer. res[selectedPeer].Add(blockHeight); } return(res); }
private async void ConnectToDevice(PeerInformation peer) { if (_socket != null) { // Disposing the socket with close it and release all resources associated with the socket _socket.Dispose(); } try { _socket = new StreamSocket(); string serviceName = (String.IsNullOrWhiteSpace(peer.ServiceName)) ? tbServiceName.Text : peer.ServiceName; // Note: If either parameter is null or empty, the call will throw an exception await _socket.ConnectAsync(peer.HostName, serviceName); // If the connection was successful, the RemoteAddress field will be populated MessageBox.Show(String.Format(AppResources.Msg_ConnectedTo, _socket.Information.RemoteAddress.DisplayName)); } catch (Exception ex) { // In a real app, you would want to take action dependent on the type of // exception that occurred. MessageBox.Show(ex.Message); _socket.Dispose(); _socket = null; } }
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); }
private async Task SendFileToPeerAsync(PeerInformation selectedPeer, StreamSocket socket, StorageFile selectedFile) { byte[] buff = new byte[BLOCK_SIZE]; var prop = await selectedFile.GetBasicPropertiesAsync(); using (var dw = new DataWriter(socket.OutputStream)) { // 1. Send the filename length dw.WriteInt32(selectedFile.Name.Length); // filename length is fixed // 2. Send the filename dw.WriteString(selectedFile.Name); // 3. Send the file length dw.WriteUInt64(prop.Size); // 4. Send the file var fileStream = await selectedFile.OpenStreamForReadAsync(); while (fileStream.Position < (long)prop.Size) { var rlen = await fileStream.ReadAsync(buff, 0, buff.Length); dw.WriteBytes(buff); } await dw.FlushAsync(); await dw.StoreAsync(); await socket.OutputStream.FlushAsync(); } }
public void HandleLinkFailureCallback(object state) { PeerInformation peer = (PeerInformation)state; peer.isActive = false; Log.WriteLine("[LRM] Network discovery: {0} disconnected", peer.remoteRouterId); }
// 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 WaitForHost(PeerInformation peer) { if (peer != null) { try { WaitingForHostParameters parameters = new WaitingForHostParameters() { ConnectionType = Connection.BrowseAndConnect, Peer = peer, Socket = null, }; PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged; ReceivedInvitations.SelectionChanged -= InvitationSelected; ReceivedInvitations.SelectedItem = null; Frame.Navigate(typeof(WaitingForHost), parameters); } catch (Exception err) { acceptInvitation.FontSize = Constants.FontSizeNormal; acceptInvitation.LineHeight = Constants.FontSizeNormal; AcceptInvitation += err.ToString(); } } }
// Start the send receive operations void PeerFinder_StartSendReceive(StreamSocket socket, PeerInformation peerInformation) { ConnectedPeer connectedPeer = new ConnectedPeer(socket, false, new Windows.Storage.Streams.DataWriter(socket.OutputStream)); _socketHelper.Add(connectedPeer); if (!_peerFinderStarted) { _socketHelper.CloseSocket(); return; } HideAllControls(); ToggleConnectedControls(true); if (peerInformation != null) { // Add a new peer to the list of peers. ComboBoxItem item = new ComboBoxItem(); item.Content = peerInformation.DisplayName; PeerFinder_SendToPeerList.Items.Add(item); PeerFinder_SendToPeerList.SelectedIndex = 0; } _socketHelper.StartReader(connectedPeer); }
async void PeerFinder_Connect(object sender, RoutedEventArgs e) { rootPage.NotifyUser("", NotifyType.ErrorMessage); PeerInformation peerToConnect = null; try { // If nothing is selected, select the first peer if (PeerFinder_FoundPeersList.SelectedIndex == -1) { peerToConnect = _peerInformationList[0]; } else { peerToConnect = _peerInformationList[PeerFinder_FoundPeersList.SelectedIndex]; } rootPage.NotifyUser("Connecting to " + peerToConnect.DisplayName + "....", NotifyType.StatusMessage); StreamSocket socket = await PeerFinder.ConnectAsync(peerToConnect); rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage); PeerFinder_StartSendReceive(socket); } catch (Exception err) { rootPage.NotifyUser("Connection to " + peerToConnect.DisplayName + " failed: " + err.Message, NotifyType.ErrorMessage); } }
private void UpdatePlayerStatus(PeerInformation peer, string status) { try { for (int i = 0; i < availablePeers.Count; i++) { if (availablePeers[i].Peer.Id == peer.Id) { if (status.Equals(" - connecting...")) { availablePeers[i].Status = status; } else if (status.Equals(" - ready")) { foundPeers.SelectionChanged -= PeersSelectionChanged; availablePeers.RemoveAt(i); foundPeers.SelectionChanged += PeersSelectionChanged; } } } } catch (Exception err) { sendInvitationsText.Text = err.ToString(); } }
// This method sends the status of all it's links (SNPPs) as a message to // a UDP port specified during construction as "rcPort". public void SendRCUpdateCallback(object state) { BatchUpdate batchUpdate = new BatchUpdate(); batchUpdate.senderID = routerId; batchUpdate.senderPort = localMgmtPort; int linkCounter = 0; foreach (KeyValuePair <byte, uint> ifaceDef in interfaceDefinitions) { if (peers[ifaceDef.Key] != null && peers[ifaceDef.Key].isActive) { PeerInformation peer = peers[ifaceDef.Key]; int capacity = (int)BWMgmt.AvailableBandwidthAt(ifaceDef.Key); //SendRCUpdateSingle(ifaceDef.Key); // Execute a more general method for given SNPP batchUpdate.linkList.Add(new Link( routerId, asId, snId, ifaceDef.Key, peer.remoteRouterId, peer.remoteAsId, peer.remoteSnId, peer.remoteSNPP, capacity )); linkCounter++; } } sendMgmtMessage(rcPort, batchUpdate); //Log.WriteLine("[LRM] Sent RC update ({0} links)", linkCounter); }
private async void _peerWatcher_Added(PeerWatcher sender, PeerInformation args) { await this.textboxDebug.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.textboxDebug.Text += "Added\n"; }); }
public PebbleBluetoothConnection(PeerInformation peerInformation) { if (peerInformation == null) { throw new ArgumentNullException("peerInformation"); } _PeerInformation = peerInformation; }
public ConnectedSphero(PeerInformation peerInformation, StreamSocket spheroSocket) : base(peerInformation) { _spheroSocketWrapper = new StreamSocketWrapper(spheroSocket); _runner = new AwaitingConnectedSpheroRunner(_spheroSocketWrapper); _runner.Disconnected += (sender, args) => RaiseDisconnected(); _runner.Start(); }
/// <summary> /// Connects to a phone or a device /// </summary> /// <param name="options"></param> public async void connect(string options) { ConnectionOptions connectionOptions; try { string[] args = JsonHelper.Deserialize <string[]>(options); connectionOptions = JsonHelper.Deserialize <ConnectionOptions>(args[0]); } catch (Exception) { this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } if (string.IsNullOrEmpty(connectionOptions.Address)) { this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { PeerInformation peer = null; foreach (var discoveredDevice in discoveredPeers) { //TODO It seems PeerInformation.HostName property sometimes returns null. So we connect to a phone/device by name instead of host address if (discoveredDevice.DisplayName == connectionOptions.Address) { peer = discoveredDevice; } } if (peer != null) { if (connectionOptions.Type == ConnectionType.PhoneToPhone) { connectionSocket = await PeerFinder.ConnectAsync(peer); } else { //TODO this kind of connection has not been tested yet connectionSocket = new StreamSocket(); await connectionSocket.ConnectAsync(peer.HostName, peer.ServiceName); } this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } else { this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Unable to find a peer with the following address: " + connectionOptions.Address)); } } catch (Exception) { this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while connecting to the peer")); } }