private async Task Connect(DeviceInformation serviceInfo) { try { // 指定されたデバイス情報で接続を行う //if (DeviceService == null) //{ var DeviceService = await RfcommDeviceService.FromIdAsync(serviceInfo.Id); var BtSocket = new StreamSocket(); await BtSocket.ConnectAsync( DeviceService.ConnectionHostName, DeviceService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); var Writer = new DataWriter(BtSocket.OutputStream); var Message = "Connected " + DeviceService.ConnectionHostName.DisplayName; //} // 接続されたBluetoothデバイスにデータを送信する //SetPower(this.Power); byte[] byteArray = Encoding.UTF8.GetBytes("hello, home-pc"); while (true) { Writer.WriteBytes(byteArray); var sendResult = await Writer.StoreAsync(); Thread.Sleep(1000); } } catch (Exception ex) { _logger.Error(ex); } }
public async void Initialize() { // Enumerate devices with the object push service var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.ObexObjectPush)); if (services.Count > 0) { // Initialize the target Bluetooth BR device var service = await RfcommDeviceService.FromIdAsync(services[0].Id); // Check that the service meets this App's minimum requirement if (SupportsProtection(service) && IsCompatibleVersion(service)) { _service = service; // Create a socket and connect to the target _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel .BluetoothEncryptionAllowNullAuthentication); // The socket is connected. At this point the App can wait for // the user to take some action, e.g. click a button to send a // file to the device, which could invoke the Picker and then // send the picked file. The transfer itself would use the // Sockets API and not the Rfcomm API, and so is omitted here for // brevity. } } }
private async void LoadBluetoothGPS() { //Ensure the bluetooth capability is enabled by opening package.appxmanifest in a text editor, // and add the following to the <Capabilities> section: // <m2:DeviceCapability Name="bluetooth.rfcomm"> // <m2:Device Id="any"> // <m2:Function Type="name:serialPort" /> // </m2:Device> // </m2:DeviceCapability> //Get list of devices string serialDeviceType = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); var devices = await DeviceInformation.FindAllAsync(serialDeviceType); string GpsDeviceName = "HOLUX GPSlim236"; //Change name to your device or build UI for user to select from list of 'devices' //Select device by name var bluetoothDevice = devices.Where(t => t.Name == GpsDeviceName).FirstOrDefault(); //Get service RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(bluetoothDevice.Id); if (rfcommService != null) { var device = new NmeaParser.BluetoothDevice(rfcommService); device.MessageReceived += device_MessageReceived; await device.OpenAsync(); } }
/// <summary> /// Opens a bluetooth connnection to a MindWave Mobile headset. /// Please specify a Bluetooth name (Usually "MindWave Mobile") in the first parameter. /// </summary> public async void ConnectBluetooth(String BTname) { if (!connected) { RaiseConnecting(); try { connected = true; var BluetoothZarizeni = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); var MindWaveHeadset = BluetoothZarizeni.SingleOrDefault(d => d.Name == BTname); var serviceRfcomm = await RfcommDeviceService.FromIdAsync(MindWaveHeadset.Id); socket = new StreamSocket(); await socket.ConnectAsync(serviceRfcomm.ConnectionHostName, serviceRfcomm.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); reader = new DataReader(socket.InputStream); RaiseConnected(); ParseHeadsetPackets(); } catch { RaiseNoHeadset(); connected = false; this.Dispose(); } } else { throw new AlreadyConnected(); } }
async void Polacz_Click(object sender, RoutedEventArgs e) { try { urzadzenie_bt_do_polaczenia = urzadzenia_bt.Single(x => x.Name == Do_polaczenia.SelectedValue.ToString()); _service = await RfcommDeviceService.FromIdAsync(urzadzenie_bt_do_polaczenia.Id); _socket = new StreamSocket(); Polacz.IsEnabled = false; Odswiez.IsEnabled = false; Do_polaczenia.IsEnabled = false; Polacz.Content = "Łączenie"; await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); blokuj_przyciski(false); Polacz.Content = "Połączono"; Do_polaczenia.IsEnabled = false; Polacz.IsEnabled = false; Odswiez.IsEnabled = false; wypisz("Połączenie zostało nawiązane,\nteraz można rozpocząć pomiary z"); WriterData = new DataWriter(_socket.OutputStream); ReaderData = new DataReader(_socket.InputStream); polaczono = true; } catch (Exception) { Odswiez.IsEnabled = true; Do_polaczenia.IsEnabled = true; Polacz.Content = "Połącz"; Polacz.IsEnabled = true; wypisz("Sprawdź wybrane urządzenie i czy jest ono dostępne"); } }
public async Task <Boolean> establishConnection(String deviceId) { try { _chatService = await RfcommDeviceService.FromIdAsync(deviceId); lock (this) { _chatSocket = new StreamSocket(); } await _chatSocket.ConnectAsync(_chatService.ConnectionHostName, _chatService.ConnectionServiceName); _writer = new DataWriter(_chatSocket.OutputStream); _reader = new DataReader(_chatSocket.InputStream); _reader.InputStreamOptions = InputStreamOptions.Partial; var version = await initAdapter(); ApplicationData.Current.LocalSettings.Values["obd"] = deviceId; return(true); } catch (Exception) { return(false); } }
public async void Connect() { try { var devices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.SerialPort)); var device = devices.Single(x => x.Name == "HMSoft"); _service = await RfcommDeviceService.FromIdAsync( device.Id); _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel. BluetoothEncryptionAllowNullAuthentication); } catch (Exception ex) { //tbError.Text = ex.Message; } }
public async void Connect(string deviceName) { try { var devices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.SerialPort)); foreach (var dev in devices) { Debug.Print("{0} {1}\n", dev.Name, dev.Kind.ToString()); } var device = devices.Single(x => x.Name == deviceName); _service = await RfcommDeviceService.FromIdAsync( device.Id); _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel. BluetoothEncryptionAllowNullAuthentication); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private async void Connect_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(App.ChatServiceID)); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect()); if (dev != null) { remoteService = await RfcommDeviceService.FromIdAsync(dev.Id); if (remoteService != null) { InputText.IsEnabled = true; } } }
private async Task SetupConnections() { string device1 = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1); await AddCommandLog(string.Format("Connecting to : {0}", device1)); await AddCommandLog(string.Format("Devices found : {0}", deviceCollection.Count)); selectedDevice = deviceCollection[0]; deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id); if (deviceService != null) { await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName); await LogStatus("Connection Established!"); await SendInitializationCommands(); await SetupOptions(true); await LogStatus("Ready for command"); } else { await SetupOptions(false); throw new Exception("Didn't find the specified bluetooth device"); } }
private async void Button_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect(200, 20, 50, 50)); if (dev != null) { // if a device is selected create a BluetoothDevice instance to get more information RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id); if (service != null) { foreach (KeyValuePair <uint, IBuffer> attrib in await service.GetSdpRawAttributesAsync()) { SdpDataElement de = SdpDataElement.FromByteArray(attrib.Value.ToArray()); System.Diagnostics.Debug.WriteLine(attrib.Key.ToString("X") + " " + de.ToString()); } // set data-binding so that device properties are displayed DeviceInformationPanel.DataContext = service; } } }
private async Task <StreamSocket> DeviceList_Connect() { // btnListPrinters.IsEnabled = false; //DeviceList.Visibility = Windows.UI.Xaml.Visibility.Collapsed; if (DeviceList.SelectedIndex == -1) { return(null); } var dataServiceDevice = dataServiceDeviceCollection[DeviceList.SelectedIndex]; dataService = await RfcommDeviceService.FromIdAsync(dataServiceDevice.Id); if (dataService == null) { NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return(null); } // txtDeviceName.Text = dataServiceDevice.Name; lock (this) { dataSocket = new StreamSocket(); } try { await dataSocket.ConnectAsync(dataService.ConnectionHostName, dataService.ConnectionServiceName); dataWriter = new DataWriter(dataSocket.OutputStream); //Panel_SelectPrinter.Visibility = Visibility.Collapsed; //PanelSelectFile.Visibility = Visibility.Visible; //panelDisconnect.Visibility = Visibility.Visible; DataReader dataReader = new DataReader(dataSocket.InputStream); // ReceiveStringLoop(dataReader); NotifyUser("connected using SPP.", NotifyType.StatusMessage); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND NotifyUser("Please verify that the device is using SPP.", NotifyType.ErrorMessage); // btnListPrinters.IsEnabled = true; break; case (0x80070103): //not connected, possibly switched off NotifyUser("Please verify that the device is switched ON.", NotifyType.ErrorMessage); // btnListPrinters.IsEnabled = true; break; default: throw; } } return(dataSocket); }
private async void DeviceSelectionListView_ItemClick(object sender, ItemClickEventArgs e) { DeviceViewModel selectedDevice = (DeviceViewModel)e.ClickedItem; if (selectedDevice == null) { ShowErrorDialog("No device selected", "Device selection error"); return; } System.Diagnostics.Debug.WriteLine("Device " + selectedDevice.Name); RfcommDeviceService BtDevice = await RfcommDeviceService.FromIdAsync(selectedDevice.Id); if (BtDevice == null) { ShowErrorDialog("Didn't find the specified bluetooth device", "Device selection error"); return; } string nameAttribute = await BTEngine.Instance.GetNameAttribute(BtDevice); if (nameAttribute.Length <= 0) { ShowErrorDialog("The specified bluetooth device is not having right version for our communications", "Device selection error"); } System.Diagnostics.Debug.WriteLine("Bt attribute : " + nameAttribute); BTEngine.Instance.SelectedDevice = BtDevice; BTEngine.Instance.ConnectToDevice(BTEngine.Instance.SelectedDevice); }
private async void ConnectButton_Click(object sender, EventArgs e) { if (deviceList.SelectedIndex == -1) { return; } try { ComboboxItem <string> item = (ComboboxItem <string>)deviceList.SelectedItem; RfcommDeviceService rfcommDeviceService = await RfcommDeviceService.FromIdAsync(item.Value); socket = new StreamSocket(); await socket.ConnectAsync(rfcommDeviceService.ConnectionHostName, rfcommDeviceService.ConnectionServiceName); } catch (Exception ex) { MessageBox.Show(this, ex.Message, this.Text); return; } deviceList.Enabled = false; refreshButton.Enabled = false; connectButton.Enabled = false; closeButton.Enabled = true; sendButton.Enabled = true; await ReadAsync(socket).ConfigureAwait(true); }
private async void FindDeviceRfc() { try { classBluetoothDevices.Clear(); var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(); for (int i = 0; i < services.Count; i++) { //if (services[i].Id.Contains("Bluetooth") && (service.ProtectionLevel== SocketProtectionLevel.BluetoothEncryptionWithAuthentication || service.ProtectionLevel == SocketProtectionLevel.BluetoothEncryptionWithAuthentication || SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication)) if (services[i].Id.Contains("Bluetooth")) { var service = await RfcommDeviceService.FromIdAsync(services[0].Id); BluetoothLEDevice bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(services[0].Id); // MessageDialog messageDialog = new MessageDialog(services[i].Properties.ElementAt(2).Key + "\t" + services[i].Properties.ElementAt(2).Value.ToString() +"\n"+ service.ToString()); // await messageDialog.ShowAsync(); if (service != null) { classBluetoothDevices.Add(new ClassBluetoothDevice() { namea = services[i].Name, rfcommDeviceService = service }); } } } listV.ItemsSource = classBluetoothDevices; } catch (Exception) { } }
private async void connect_Click(object sender, RoutedEventArgs e) { if (this.deviceSelector.SelectedValue is DeviceListItem) { var deviceInfo = ((DeviceListItem)this.deviceSelector.SelectedValue).deviceInfo; var deviceService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id); if (deviceService == null) { errorBox.Text = "Device not found!"; } else { try { connect.Content = "Connecting..."; if (((App)Application.Current).streamSocket != null) { ((App)Application.Current).streamSocket.Dispose(); } ((App)Application.Current).streamSocket = new StreamSocket(); await((App)Application.Current).streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName); this.Frame.Navigate(typeof(DriveControlPage)); } catch (Exception ex) { connect.Content = "Connect"; errorBox.Text = "Cannot connect bluetooth device:" + ex.Message; } } } }
public async Task <string> Connect() { try { var devices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.SerialPort)); var device = devices.Single(x => x.Name == connectionName); service = await RfcommDeviceService.FromIdAsync(device.Id); socket = new StreamSocket(); await socket.ConnectAsync( service.ConnectionHostName, service.ConnectionServiceName); dataReader = new DataReader(socket.InputStream); dataWriter = new DataWriter(socket.OutputStream); return("connected"); } catch (Exception ex) { Debug.WriteLine(ex.Message); socket.Dispose(); socket = null; service.Dispose(); service = null; return("error occured"); } }
public async Task LoadAsync() { //AddToChart("Control.CycleCount"); AddToChart("control.sensors.Temperature"); // Enumerate devices with the object push service DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); var device = devices.Single(); var _srv = await RfcommDeviceService.FromIdAsync(device.Id); await _stream.ConnectAsync(_srv.ConnectionHostName, _srv.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //var s = _stream.OutputStream.AsStreamForWrite(); //Start listener Task.Run(ListenAsync); //DevicePicker //Paired bluetooth devices //DeviceInformationCollection PairedBluetoothDevices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); //DeviceInformation device = PairedBluetoothDevices.Single(i => i.Name == "HC-06"); IsLoaded = true; }
private void Open(DeviceInformation serviceInfo) { try { //指定されたデバイス情報で接続を行う if (DeviceService == null) { DeviceService = RfcommDeviceService.FromIdAsync(serviceInfo.Id).GetResults(); BtSocket = new StreamSocket(); BtSocket.ConnectAsync( this.DeviceService.ConnectionHostName, this.DeviceService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); Writer = new DataWriter(BtSocket.OutputStream); Reader = new DataReader(BtSocket.InputStream); this.Message = "Connected " + DeviceService.ConnectionHostName.DisplayName; IsOpen = true; } } catch (Exception ex) { this.Message = ex.Message; DeviceService = null; IsOpen = false; } }
public async void Connect(DeviceInformation serviceInfo) { if (socket != null) { try { connectService = RfcommDeviceService.FromIdAsync(serviceInfo.Id); rfcommService = await connectService; if (rfcommService != null) { await socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); dataReader = new StreamReader(socket.InputStream.AsStreamForRead()); dataWriter = new StreamWriter(socket.OutputStream.AsStreamForWrite()); dataReadWorker.RunWorkerAsync(); } else { MessageBox.Show("Connection failed"); } //await socket.ConnectAsync(serviceInfo., rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //dataReader = new DataReader(socket.InputStream); //dataReadWorker.RunWorkerAsync(); //dataWriter = new DataWriter(socket.OutputStream); } catch (Exception) { throw; } } }
public async override Task ConnectToDeviceAsync(DeviceInformation deviceInformation) { var device = deviceInformation.PlatformDeviceObject as Windows.Devices.Enumeration.DeviceInformation; if (device == null) { throw new NotSupportedException("Unknown platform device object in device information."); } lastConnectedDeviceName = device.Name; var connectService = RfcommDeviceService.FromIdAsync(device.Id); RfcommDeviceService rfcommService = await connectService; if (rfcommService != null) { socket = new StreamSocket(); await socket.ConnectAsync( rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); reader = new DataReader(socket.InputStream); // Wait for one cycle before continue. await Task.Delay(200); } }
private async Task ConnectAsyncInternal() { _tokenSource = new CancellationTokenSource(); string selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector); DeviceInformation device = (from d in devices where d.Name == _deviceName select d).FirstOrDefault(); if (device == null) { throw new Exception("LEGO EV3 brick named '" + _deviceName + "' not found."); } RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(device.Id); if (service == null) { throw new Exception("Unable to connect to LEGO EV3 brick...is the manifest set properly?"); } _socket = new StreamSocket(); await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); _reader = new DataReader(_socket.InputStream); _reader.ByteOrder = ByteOrder.LittleEndian; await ThreadPool.RunAsync(PollInput); }
public async void Connect(Action <bool> action) { string DeviceName = ""; try { //получаем все сопряжённые устройства RFCOMM (Dev B) var device = DeviceList.FirstOrDefault(x => x.Name == DeviceName); //BT_Device = await BluetoothDevice.FromIdAsync(device.Id); var _service = await RfcommDeviceService.FromIdAsync(device.Id); _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); conectionStatus = true; } catch (Exception e) { conectionStatus = false; } }
public async Task Connect() { try { lock (this) { _socket = new StreamSocket(); } _service = await RfcommDeviceService.FromIdAsync(BluetoothDevice.Id); await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName); dataReader = new DataReader(_socket.InputStream); dataWriter = new DataWriter(_socket.OutputStream); IsConnected = true; } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND IsConnected = false; throw new Exception("Please verify that you are running the BluetoothRfcommChat server."); break; default: IsConnected = false; throw; } } }
public async Task <bool> ConnectAsync(DeviceInformation device) { //RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(device.Id); RfcommDeviceService rfcommService; try { rfcommService = await RfcommDeviceService.FromIdAsync(device.Id); if (rfcommService == null) { return(false); } Stream = new StreamSocket(); try { await Stream.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName); } catch { return(false); } IsConnected = true; _btReader = new DataReader(Stream.InputStream); _btWriter = new DataWriter(Stream.OutputStream); _btWriter.UnicodeEncoding = UnicodeEncoding.Utf8; } catch (Exception ex) { } return(true); }
private async Task Connect(DeviceInformation serviceInfo) { try { //指定されたデバイス情報で接続を行う if (DeviceService == null) { DeviceService = await RfcommDeviceService.FromIdAsync(serviceInfo.Id); BtSocket = new StreamSocket(); await BtSocket.ConnectAsync( this.DeviceService.ConnectionHostName, this.DeviceService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); Writer = new DataWriter(BtSocket.OutputStream); this.Message = "Connected " + DeviceService.ConnectionHostName.DisplayName; } //接続されたBluetoothデバイスにデータを送信する SetPower(this.Power); } catch (Exception ex) { this.Message = ex.Message; DeviceService = null; } }
public static async Task <StreamSocketConnection> ConnectAsync(Guid serviceUuid, IObjectSerializer serializer) { // Find all paired instances of the Rfcomm service var serviceId = RfcommServiceId.FromUuid(serviceUuid); var deviceSelector = RfcommDeviceService.GetDeviceSelector(serviceId); var devices = await DeviceInformation.FindAllAsync(deviceSelector); if (devices.Count > 0) { var device = devices.First(); // TODO var deviceService = await RfcommDeviceService.FromIdAsync(device.Id); if (deviceService == null) { // Access to the device is denied because the application was not granted access return(null); } var attributes = await deviceService.GetSdpRawAttributesAsync(); IBuffer serviceNameAttributeBuffer; if (!attributes.TryGetValue(SdpServiceNameAttributeId, out serviceNameAttributeBuffer)) { // The service is not advertising the Service Name attribute (attribute id = 0x100). // Please verify that you are running a BluetoothConnectionListener. return(null); } using (var attributeReader = DataReader.FromBuffer(serviceNameAttributeBuffer)) { var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { // The service is using an unexpected format for the Service Name attribute. // Please verify that you are running a BluetoothConnectionListener. return(null); } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; var serviceName = attributeReader.ReadString(serviceNameLength); var socket = new StreamSocket(); await socket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName); var connection = await StreamSocketConnection.ConnectAsync(socket, serializer); return(connection); } } // No devices found return(null); }
async private void ConnectDevice_Click(object sender, RoutedEventArgs e) { DeviceInformation DeviceInfo = ((PairedDeviceInfo)ConnectDevices.SelectedItem).DeviceInfo;// await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text); bool success = true; try { _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id); if (_socket != null) { // Disposing the socket with close it and release all resources associated with the socket _socket.Dispose(); } _socket = new StreamSocket(); try { // Note: If either parameter is null or empty, the call will throw an exception await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName); } catch (Exception ex) { success = false; System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message); } // If the connection was successful, the RemoteAddress field will be populated if (success) { _Mode = Mode.JustConnected; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.buttonDisconnect.IsEnabled = true; this.buttonSend.IsEnabled = true; this.buttonStartRecv.IsEnabled = true; this.buttonStopRecv.IsEnabled = false; status.Text = "Connected now starting Listen"; }); Listen(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.buttonStartRecv.IsEnabled = false; this.buttonStopRecv.IsEnabled = true; status.Text = "Listening for config info."; }); System.Diagnostics.Debug.WriteLine("Just Connected"); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message); _socket.Dispose(); _socket = null; } }
private async void DeviceList_Tapped(object sender, TappedRoutedEventArgs e) { btnListPrinters.IsEnabled = false; DeviceList.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var dataServiceDevice = dataServiceDeviceCollection[DeviceList.SelectedIndex]; App.dataServiceDevice = dataServiceDevice; dataService = await RfcommDeviceService.FromIdAsync(dataServiceDevice.Id); Debug.WriteLine("After FromIdAsync"); if (dataService == null) { NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } App.Stream = new StreamSocket(); try { await App.Stream.ConnectAsync(dataService.ConnectionHostName, dataService.ConnectionServiceName); } catch { //return false; } //IsConnected = true; App._btReader = new DataReader(App.Stream.InputStream); App._btWriter = new DataWriter(App.Stream.OutputStream); App._btWriter.UnicodeEncoding = UnicodeEncoding.Utf8; App._btReader.UnicodeEncoding = UnicodeEncoding.Utf8; //App._btReader.InputStreamOptions = InputStreamOptions.Partial; Debug.WriteLine("Finished"); var n = App._btWriter.WriteString("b\n"); await App._btWriter.StoreAsync(); n = App._btWriter.WriteString("b\n"); await App._btWriter.StoreAsync(); n = App._btWriter.WriteString("b\n"); await App._btWriter.StoreAsync(); n = App._btWriter.WriteString("b\n"); await App._btWriter.StoreAsync(); //this.Frame.Navigate(typeof(ControllerPage)); this.Frame.Navigate(typeof(ServerMenuPage)); Debug.WriteLine("After Frame.Navigate"); }
private async void Button_Click(object sender, RoutedEventArgs e) { var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush)); var service = await RfcommDeviceService.FromIdAsync(services[0].Id); // Create a socket and connect to the target StreamSocket socket = new StreamSocket(); await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); }