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); }
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 <DeviceInformationCollection> FindPairedDevicesAsync() { var aqsDevices = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(aqsDevices); return(devices); }
public override async Task <Connections> GetConnections() { if (this.isPrePairedDevice) { PeerFinder.AlternateIdentities["Bluetooth:Paired"] = string.Empty; } try { var devices = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); var peers = await DeviceInformation.FindAllAsync(devices); var connections = new Connections(); foreach (var peer in peers) { connections.Add(new Connection(peer.Name, peer)); } return(connections); } catch (Exception e) { Debug.WriteLine("GetConnections: pairing failed: " + e); return(null); } }
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. } } }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage); ResetUI(); }
// This App requires a connection that is encrypted but does not care about // whether its authenticated. bool SupportsProtection(RfcommDeviceService service) { switch (service.ProtectionLevel) { case SocketProtectionLevel.PlainSocket: if ((service.MaxProtectionLevel == SocketProtectionLevel.BluetoothEncryptionWithAuthentication) || (service.MaxProtectionLevel == SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication)) { // The connection can be upgraded when opening the socket so the // App may offer UI here to notify the user that Windows may // prompt for a PIN exchange. return(true); } else { // The connection cannot be upgraded so an App may offer UI here // to explain why a connection won't be made. return(false); } case SocketProtectionLevel.BluetoothEncryptionWithAuthentication: return(true); case SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication: return(true); } return(false); }
/// <summary> /// 连接到指定的蓝牙设备的RFComm服务 /// </summary> /// <param name="BL">要连接到的设备</param> /// <returns>主机对象的规范名称</returns> public async Task <string> ConnectToRfcommServiceAsync(BluetoothList BL) { if (BL == null) { throw new ArgumentNullException(nameof(BL), "Parameter could not be null"); } try { var Device = await Windows.Devices.Bluetooth.BluetoothDevice.FromIdAsync(BL.Id); var Services = await Device.GetRfcommServicesForIdAsync(RfcommServiceId.ObexObjectPush); if (Services.Services.Count == 0) { throw new Exception(Globalization.GetString("BluetoothUI_Tips_Text_3")); } RfcommDeviceService RfcService = Services.Services[0]; return(RfcService.ConnectionHostName.CanonicalName); } catch { throw new Exception(Globalization.GetString("BluetoothUI_Tips_Text_2")); } }
/// <summary> /// Sends a contact request to the specified Bluetooth device. /// </summary> /// <param name="device">The device to send the request to.</param> /// <param name="myAddress">The local address to send to the device.</param> /// <returns>The Erebus address of the device if the request was accepted; otherwise null.</returns> public static ErebusAddress?RequestAddContact(RfcommDeviceService device, ErebusAddress myAddress) { Log.RecordEvent(typeof(BluetoothUtils), $"Attempting to add Bluetooth device '{device.ConnectionHostName.CanonicalName}' as a contact.", LogEntrySeverity.Info); try { var socket = new StreamSocket(); new Func <Task>(async() => { await socket.ConnectAsync(device.ConnectionHostName, RfcommAddContactService.AsString(), SocketProtectionLevel.BluetoothEncryptionWithAuthentication); })().Wait(); using (var r = new BinaryReader(socket.InputStream.AsStreamForRead())) using (var w = new BinaryWriter(socket.OutputStream.AsStreamForWrite())) { w.Write(myAddress); var addr = r.ReadErebusAddress(); var vkp = PlatformServiceProvider.Create("VerificationKeyProvider"); var local = vkp.CreatePrivateKey(); w.Write(local.Item2.Length); w.Write(local.Item2); vkp.AddKeyPair(addr, local.Item1, r.ReadBytes(r.ReadInt32())); Log.RecordEvent(typeof(BluetoothUtils), $"Successfully negotiated contact with {addr} via Bluetooth RFCOMM.", LogEntrySeverity.Info); return(addr); } } catch (Exception e) { Log.RecordEvent(typeof(BluetoothUtils), $"Exception adding contact: {e.Message}; assuming other user rejected request.", LogEntrySeverity.Error); return(null); } }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } NotifyUser(disconnectReason); Acceleration.Clear(); Acceleration.Add(new XYZ(0.0, 0.0, 0.0)); ResetMainUI(); }
/// <summary> /// When the user presses the "Start" button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list. /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private async void StartButton_Click(object sender, RoutedEventArgs e) { StartButton.IsEnabled = false; // Find all paired instances of the Rfcomm chat service and display them in a list chatServiceDeviceCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid))); if (chatServiceDeviceCollection.Count > 0) { DeviceList.Items.Clear(); foreach (var chatServiceDevice in chatServiceDeviceCollection) { DeviceList.Items.Add(chatServiceDevice.Name); } NotifyUser("Select a device.", NotifyType.StatusMessage); } else { NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } StartButton.IsEnabled = true; }
/// <summary> /// When the user presses the run button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list. /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> public async void Run() { // Find all paired instances of the Rfcomm chat service and display them in a list RfcommServiceId serid = RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid); string stsel = RfcommDeviceService.GetDeviceSelector(serid); string stsel1 = "System.Devices.InterfaceClassGuid:=\"{B142FC3E-FA4E-460B-8ABC-072B628B3C70}\" AND System.DeviceInterface.Bluetooth.ServiceGuid:=\"{34B1CF4D-1069-4AD6-89B6-E161D79BE4D8}\""; string stsel2 = "System.Devices.InterfaceClassGuid:=\"{B142FC3E-FA4E-460B-8ABC-072B628B3C70}\""; string stsel3 = ""; chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(stsel); int i = 0; if (chatServiceDeviceCollection.Count > 0) { //DeviceList.Items.Clear(); foreach (var chatServiceDevice in chatServiceDeviceCollection) { //if (chatServiceDevice.Name == "BAKULEV-X240") { //DeviceList.Items.Add(chatServiceDevice.Name + " " + chatServiceDevice.Id); i++; } } //DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible; SelectDevice(0); //bakulev } else { //rootPage.NotifyUser( // "No chat services were found. Please pair with a device that is advertising the chat service.", // NotifyType.ErrorMessage); } }
private async void btnListPrinters_Click(object sender, RoutedEventArgs e) { var button = sender as Button; // Disable the button while we do async operations so the user can't Run twice. button.IsEnabled = false; // Clear any previous messages NotifyUser("", NotifyType.StatusMessage); // Find all paired instances of the Rfcomm service and display them in a list dataServiceDeviceCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); if (dataServiceDeviceCollection.Count > 0) { DeviceList.Items.Clear(); foreach (var dataServiceDevice in dataServiceDeviceCollection) { DeviceList.Items.Add(dataServiceDevice.Name); } DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { NotifyUser( "No SPP services were found. Please pair with a device that is advertising the SPP service.", NotifyType.ErrorMessage); } button.IsEnabled = true; }
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; } } }
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 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 void DisconnectSpp(string disconnectReason = "CloseRequested") { Log(disconnectReason); if (SppServiceReader != null) { SppServiceReader.DetachStream(); SppServiceReader = null; } if (SppServiceWriter != null) { SppServiceWriter.DetachStream(); SppServiceWriter = null; } if (SppService != null) { SppService.Dispose(); SppService = null; } lock (this) { if (SppServiceSocket != null) { SppServiceSocket.Dispose(); SppServiceSocket = null; } } }
private async Task Connect(DeviceInformation deviceInformation) { // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. var accessStatus = DeviceAccessInformation.CreateFromId(deviceInformation.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { throw new UnauthorizedAccessException("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); } var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInformation.Id); // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call) var rfcommServices = await bluetoothDevice.GetRfcommServicesAsync(); RfcommDeviceService bluetoothService = null; foreach (var service in rfcommServices.Services) { System.Diagnostics.Debug.WriteLine("Service {0}: {1}", service.ConnectionHostName, service.ConnectionServiceName); if (service.ServiceId.Uuid == RfcommServiceId.SerialPort.Uuid) { bluetoothService = service; break; } } if (bluetoothService != null) { bluetoothDevice.ConnectionStatusChanged += BluetoothDevice_ConnectionStatusChanged; var device = new UwpRfcommDevice(deviceInformation, bluetoothService); connectedDevices.Add(device.deviceInfo.Id, device); DeviceConnected?.Invoke(device); } }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (dataWriter != null) { dataWriter.DetachStream(); dataWriter = null; } if (dataService != null) { dataService.Dispose(); dataService = null; } lock (this) { if (dataSocket != null) { dataSocket.Dispose(); dataSocket = null; } } NotifyUser(disconnectReason, NotifyType.StatusMessage); }
public override void Disconnect() { if (_writer != null) { _writer.DetachStream(); _writer = null; } if (_deviceService != null) { _deviceService.Dispose(); _deviceService = null; } lock (this) { if (_socket != null) { _socket.Dispose(); _socket = null; } } ConnectCommand.Enabled = true; }
public async Task<bool> Connect(string deviceName) { try { if (this.Devices.Count > 0) { // getting selected Device this.device = await RfcommDeviceService.FromIdAsync( Devices.Where(x => x.Name == deviceName).FirstOrDefault().Id); // Oppening Socket this.socket = new StreamSocket(); await this.socket.ConnectAsync(device.ConnectionHostName, device.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Writer this.writer = new DataWriter(this.socket.OutputStream); this.IsConnected = true; return true; } return false; } catch (Exception) { this.IsConnected = false; return false; } }
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 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 void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } Debug.Log(disconnectReason); }
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"); } }
private void Disconnect() { if (reader != null) { reader.DetachStream(); reader.Dispose(); reader = null; } if (writer != null) { writer.DetachStream(); writer.Dispose(); writer = null; } if (socket != null) { lock (this) { socket.Dispose(); } socket = null; } BTService = null; BTDevice = null; DeviceInfoCollection = null; }
//-------------------------------------------------------------------------zamykanie polaczenia private void disconnect() { if (reader != null) { reader.Dispose(); reader = null; } if (writer != null) { writer.Dispose(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } if (service != null) { service = null; } if (stream != null) { stream.Dispose(); stream = null; } if (buffer != null) { buffer = null; } }
public void start() { dataService = null; dataServiceDeviceCollection = null; panelDisconnect.Visibility = Visibility.Collapsed; StatusPanel.Visibility = Visibility.Collapsed; }
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); } }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } ConversationListBox.Items.Add("========== Session Disconnected =========="); NotifyUser(disconnectReason, NotifyType.StatusMessage); StartButton.IsEnabled = true; DisconnectButton.IsEnabled = false; NetworkListComboBox.IsEnabled = false; ConnectButton.IsEnabled = false; RefreshButton.IsEnabled = false; }
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); }
/// <summary> /// Connect to the device /// </summary> /// <param name="portName">the name of the device to connect.</param> public override async void Connect(string portName = null) { if (this.Connected) return; try { this._currentDevice = (await this.AvailableDevicesAsync()).SingleOrDefault(d => d.Name == portName); this._socket = new StreamSocket(); this._rfcommService = await RfcommDeviceService.FromIdAsync(this._currentDevice.Id); await this._socket.ConnectAsync(this._rfcommService.ConnectionHostName, this._rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); this._writer = new DataWriter(this._socket.OutputStream); this._reader = new DataReader(this._socket.InputStream); this._connected = true; this.DataReceivedAsync(); } catch { this._connected = false; } }
private async Task SendMessage(string id) { chatService = await RfcommDeviceService.FromIdAsync(id); if (chatService == null) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "Access to the device is denied because the application was not granted access"; deferral.Complete(); } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."; deferral.Complete(); //RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."; deferral.Complete(); //RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. //attributeReader.UnicodeEncoding = System.Text.UnicodeEncoding.Utf8; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); await SendMessageAsync(); // Receive Message //DataReader chatReader = new DataReader(chatSocket.InputStream); //ReceiveStringLoop(chatReader); } catch (Exception ex) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = ex.ToString(); deferral.Complete(); } }
public async Task<String> GetNameAttribute(RfcommDeviceService service) { try { var attributes = await service.GetSdpRawAttributesAsync(BluetoothCacheMode.Uncached); if (!attributes.ContainsKey(SERVICE_NAME_ATTRIBUTE_ID)) { System.Diagnostics.Debug.WriteLine("Name attribute not found"); return ""; } var attributeReader = DataReader.FromBuffer(attributes[SERVICE_NAME_ATTRIBUTE_ID]); var attributeType = attributeReader.ReadByte(); if (attributeType != SERVICE_NAME_ATTRIBUTE_TYPE) { System.Diagnostics.Debug.WriteLine("Name attribute type not right :" + attributeType + " , expecting : " + SERVICE_NAME_ATTRIBUTE_TYPE); return ""; } var nameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; return attributeReader.ReadString(nameLength); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("GetNameAttribute - Exception " + ex.Message); } return ""; }
public async void ConnectToDevice(RfcommDeviceService device) { //connect the socket try { _streamSocket = new StreamSocket(); await _streamSocket.ConnectAsync( device.ConnectionHostName, device.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); if (ObexConnectionStatusChanged != null) { ObexConnectionStatusChanged(true, null); } ReceiveData(); } catch (Exception ex) { if (ObexConnectionStatusChanged != null) { ObexConnectionStatusChanged(false, "Cannot connect bluetooth device:" + ex.Message); } } }
public async void ConnectToServiceAsync(object sender, RoutedEventArgs e) { StorageFolder local_folder = App.appData.LocalFolder; StorageFolder devices_folder = await local_folder.CreateFolderAsync("devices_folder", CreationCollisionOption.OpenIfExists); StorageFile bluetooth_file = (StorageFile)await devices_folder.TryGetItemAsync("bluetooth_file.txt"); MenuFlyoutItem command = sender as MenuFlyoutItem; string bluetooth_file_line=null; //if file doesn't exist, return and wanting to connect at initialization, return if(bluetooth_file == null && command == null) { return; } //read from bluetooth file if (bluetooth_file != null) { bluetooth_file_line = await FileIO.ReadTextAsync(bluetooth_file); System.Diagnostics.Debug.WriteLine(bluetooth_file_line); } string serviceIDString; string serviceNameString; if (command == null) { string[] parse_bluetooth_file_line = bluetooth_file_line.Split(','); serviceNameString = parse_bluetooth_file_line[0]; serviceIDString = parse_bluetooth_file_line[1]; } else { DeviceInformation serviceInfo = (DeviceInformation)selected_device_global; serviceIDString = command.Name; serviceNameString = command.Text; } //this.State = BluetoothConnectionState.Connecting; this.Disconnect(); try { // Initialize the target Bluetooth RFCOMM device service connectService = RfcommDeviceService.FromIdAsync(serviceIDString); rfcommService = await connectService; if (rfcommService != null) { // Create a socket and connect to the target socket = new StreamSocket(); connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); await connectAction;//to make it cancellable writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); Task listen = ListenForMessagesAsync(); this.State = BluetoothConnectionState.Connected; //write device information if (command != null) { StorageFile device_info = await devices_folder.CreateFileAsync("bluetooth_file.txt", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(device_info, serviceNameString+ ','+ serviceIDString); } connectedBluetoothDeviceName = serviceNameString; if(changedName != null) changedName.Invoke(this, EventArgs.Empty); } else { OnExceptionOccuredEvent(this, new Exception("Unable to create service.\nMake sure that the 'bluetooth.rfcomm' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.")); } } catch (TaskCanceledException) { this.State = BluetoothConnectionState.Disconnected; } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } }
/// <summary> /// Terminate an connection. /// </summary> public void Disconnect() { if (reader != null) { reader = null; } if (writer != null) { writer.DetachStream(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } if (rfcommService != null) { rfcommService = null; } this.State = BluetoothConnectionState.Disconnected; }
private async Task<bool> ConnectToDevice() { foreach (var item in deviceCollection) { if (item.Name == deviceName) { selectedDevice = item; break; } } if (selectedDevice == null) { //errorStatus.Visibility = Visibility.Visible; errorStatusText = "Cannot find the device specified; Please check the device name"; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); return false; } deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id); if (deviceService != null) { //connect the socket try { await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName); } catch (Exception ex) { //errorStatus.Visibility = Visibility.Visible; errorStatusText = "Cannot connect bluetooth device:" + ex.Message; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); return false; } } else { //errorStatus.Visibility = Visibility.Visible; errorStatusText = "Didn't find the specified bluetooth device named " + deviceName; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); return false; } Debug.WriteLine("OK: connected to bluetooth device named " + deviceName); return true; }
private static async Task<int> ValidateConnection(RfcommDeviceService messageService) { if (messageService == null) { //statusTextBlock.Text = "Access to the device is denied because the application was not granted access"; return -1; } //Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await messageService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { //statusTextBlock.Text = // @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + // "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return -1; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { //statusTextBlock.Text = // "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + // "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return -1; } return 0; //var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. //attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; }
/// <summary> /// Disconnect /// </summary> public override void Disconnect() { if (this._reader != null) this._reader = null; if (this._writer != null) { this._writer.DetachStream(); this._writer = null; } if (this._socket != null) { this._socket.Dispose(); this._socket = null; } if (this._rfcommService != null) this._rfcommService = null; this._connected = false; }
private async Task ConnectToServiceAsync(IUICommand command) { DeviceInformation serviceInfo = (DeviceInformation)command.Id; this.State = BluetoothConnectionState.Connecting; try { // Initialize the target Bluetooth RFCOMM device service connectService = RfcommDeviceService.FromIdAsync(serviceInfo.Id); rfcommService = await connectService; if (rfcommService != null) { // Create a socket and connect to the target socket = new StreamSocket(); connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); await connectAction;//to make it cancellable writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); Task listen = ListenForMessagesAsync(); this.State = BluetoothConnectionState.Connected; } else OnExceptionOccuredEvent(this, new Exception("Unable to create service.\nMake sure that the 'bluetooth.rfcomm' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.")); } catch (TaskCanceledException) { this.State = BluetoothConnectionState.Disconnected; } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } }
private async Task SendMessage(string id) { //await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => //{ chatService = await RfcommDeviceService.FromIdAsync(id); if (chatService == null) { statusTextBlock.Text = "Access to the device is denied because the application was not granted access"; return; } //Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { statusTextBlock.Text = @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { statusTextBlock.Text = "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; //ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); await SendMessageAsync(); // Receive Message //DataReader chatReader = new DataReader(chatSocket.InputStream); //ReceiveStringLoop(chatReader); } catch (Exception) { throw; } //}); }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage); ResetUI(); }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ConnectButton_Click(object sender, RoutedEventArgs e) { // Make sure user has selected a device first if (resultsListView.SelectedItem != null) { rootPage.NotifyUser("Connecting to remote device. Please wait...", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please select an item to connect to", NotifyType.ErrorMessage); return; } RfcommChatDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as RfcommChatDeviceDisplay; // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { rootPage.NotifyUser("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices", NotifyType.ErrorMessage); return; } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { rootPage.NotifyUser("Bluetooth Device returned null. Access Status = " + accessStatus.ToString(), NotifyType.ErrorMessage); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { rootPage.NotifyUser( "Could not discover the chat service on the remote device", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; deviceWatcher.Stop(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; break; default: throw; } } }
private async void ConnectToDevice() { foreach(var item in deviceCollection) { if (item.Name == deviceName) { selectedDevice = item; break; } } if (selectedDevice == null) { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = "Cannot find the device specified; Please check the device name"; return; } else { deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id); if (deviceService != null) { //connect the socket try { await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName); } catch (Exception ex) { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = "Cannot connect bluetooth device:" + ex.Message; } } else { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = "Didn't find the specified bluetooth device"; } } }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { ServerButton.IsEnabled = false; ClientButton.IsEnabled = false; DisconnectButton.IsEnabled = true; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; DeviceInformation deviceInfo = await DeviceInformation.CreateFromIdAsync(chatServiceInfo.Id); chatService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id); if (chatService == null) { NotifyStatus("Access to the device is denied because the application was not granted access"); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { NotifyStatus("The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { NotifyStatus("The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Visibility = Visibility.Visible; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { socket = new StreamSocket(); } await socket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); writer = new DataWriter(socket.OutputStream); DataReader chatReader = new DataReader(socket.InputStream); while (true) { try { uint size = await chatReader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data break; } uint stringLength = chatReader.ReadUInt32(); uint actualStringLength = await chatReader.LoadAsync(stringLength); if (actualStringLength != stringLength) { // The underlying socket was closed before we were able to read the whole data break; } ConversationListBox.Items.Add("Received: \"" + chatReader.ReadString(stringLength) + "\""); } catch (Exception ex) { lock (this) { if (socket == null) { // Do not print anything here - the user closed the socket. } else { NotifyStatus("Read stream failed with error: " + ex.Message); Disconnect(); } } } } } catch (Exception ex) { ServerButton.IsEnabled = true; ClientButton.IsEnabled = true; DisconnectButton.IsEnabled = false; NotifyStatus("Error: " + ex.HResult.ToString() + " - " + ex.Message); } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void DeviceList_Tapped(object sender, TappedRoutedEventArgs e) { RunButton.IsEnabled = false; DeviceList.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceDevice = chatServiceDeviceCollection[DeviceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceDevice.Id); if (chatService == null) { rootPage.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; break; default: throw; } } }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { RunButton.IsEnabled = false; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id); if (chatService == null) { MainPage.Current.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { MainPage.Current.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { MainPage.Current.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { RunButton.IsEnabled = true; MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.ErrorMessage); } }
/// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage); RunButton.IsEnabled = true; DeviceList.Visibility = Windows.UI.Xaml.Visibility.Collapsed; ChatBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed; ConversationList.Items.Clear(); }
public async Task<bool> Init(bool simulatormode = false) { running = true; //initialize _data data = new Dictionary<string, string> {{"vin", DefValue}}; //VIN piDs = ObdShare.ObdUtil.GetPIDs(); foreach (var v in piDs.Values) { data.Add(v, DefValue); } this.simulatormode = simulatormode; if (simulatormode) { PollObd(); return true; } DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); var numDevices = deviceInfoCollection.Count(); DeviceInformation device = null; foreach (DeviceInformation info in deviceInfoCollection) { if (info.Name.ToLower().Contains("obd")) { device = info; } } if (device == null) return false; try { service = await RfcommDeviceService.FromIdAsync(device.Id); // 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); connected = true; } catch (Exception ex) { connected = false; System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message); } // If the connection was successful, the RemoteAddress field will be populated if (connected) { string msg = String.Format("Connected to {0}!", socket.Information.RemoteAddress.DisplayName); System.Diagnostics.Debug.WriteLine(msg); dataWriterObject = new DataWriter(socket.OutputStream); dataReaderObject = new DataReader(socket.InputStream); //initialize the device string s; s = await SendAndReceive("ATZ\r"); s = await SendAndReceive("ATE0\r"); s = await SendAndReceive("ATL1\r"); s = await SendAndReceive("ATSP00\r"); PollObd(); return true; } else return false; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message); if (dataReaderObject != null) { dataReaderObject.Dispose(); dataReaderObject = null; } if (dataWriterObject != null) { dataWriterObject.Dispose(); dataWriterObject = null; } if (socket != null) { socket.Dispose(); socket = null; } return false; } }
//Terminar la conexion con el dispositivo public void Disconnect() { //dejamos variables en null if (reader != null) reader = null; if (writer != null) { writer.DetachStream(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } if (rfcommService != null) rfcommService = null; this.State = BluetoothConnectionState.Disconnected; }
//Metodo que nos dara la conexion al dispositivo seleccionado private async void ConnectToServiceAsync(IUICommand command) { //Se obtiene el Id del dispositivo seleccionado DeviceInformation serviceInfo = (DeviceInformation)command.Id; //el estado de la conexion se pondra conectando this.State = BluetoothConnectionState.Connecting; try { //Inicializa el servicio del dispositivo RFCOMM de Bluetooth de destino connectService = RfcommDeviceService.FromIdAsync(serviceInfo.Id); rfcommService = await connectService; if (rfcommService != null) { //Se inicializa el socket socket = new StreamSocket(); connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //Puedes Cancelar la conexion await connectAction; //Se inicializan las variables que envian y reciben los mensajes writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); Task listen = ListenForMessagesAsync(); //se cambia el estado de conexion del bluetooth a conectado this.State = BluetoothConnectionState.Connected; } else OnExceptionOccuredEvent(this, new Exception("No se pudo connectar al servicio.\n Verifca que 'bluetooth.rfcomm' capabilityes es declarado con la funcion de tipo 'name:serialPort' en Package.appxmanifest.")); } catch (TaskCanceledException) { this.State = BluetoothConnectionState.Disconnected; } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } }
public Scenario1_ChatClient() { this.InitializeComponent(); chatSocket = null; chatWriter = null; chatService = null; chatServiceInfoCollection = null; App.Current.Suspending += App_Suspending; }