public void Disconnect() { State = BluetoothConnectionState.Disconnected; if (Reader != null) { Reader = null; } if (Writer != null) { Writer.DetachStream(); Writer = null; } if (Socket != null) { Socket.Dispose(); Socket = null; } if (BluetoothService != null) { BluetoothService = null; } if (BluetoothListener != null) { BluetoothListener = null; } }
private void OnStateChangedEvent(object sender, BluetoothConnectionState state) { if (StateChanged != null) { StateChanged(sender, state); } }
//react public void connectionManager_StateChanged(object sender, BluetoothConnectionState state) { //enable/disable according to the connection state //enumerateButton.IsEnabled = (state == BluetoothConnectionState.Disconnected); //cancelButton.IsEnabled = (state == BluetoothConnectionState.Connecting); // disconnectButton.IsEnabled = (state == BluetoothConnectionState.Connected); last_alive_time = DateTime.Now; }
public async Task ConnectToDevice(string deviceId, Guid sensorId) { //if (DeviceCollection == null) await ScanForDevices(); foreach (var item in DeviceCollection) { if (item.Id == deviceId) { SelectedDevice = item; break; } } if (SelectedDevice != null) { BluetoothService = await RfcommDeviceService.FromIdAsync(SelectedDevice.Id); if (BluetoothService != null) { try { if (Socket != null || Reader != null || BluetoothListener != null || Writer != null) { Disconnect(); } Socket = new StreamSocket(); timer.Start(); await Socket.ConnectAsync(BluetoothService.ConnectionHostName, BluetoothService.ConnectionServiceName); timer.Stop(); if (Socket != null) { Writer = new DataWriter(Socket.OutputStream); Reader = new DataReader(Socket.InputStream); State = BluetoothConnectionState.Connected; SensorId = sensorId; } } catch (Exception ex) { } } } }
//En esta metodo se muestran los dispositivos que sean del tipo SerialPort en un PopupMenu public async Task EnumerateDevicesAsync(Rect invokerRect) { this.State = BluetoothConnectionState.Enumerating; //seleccionamos todos los dispositivos disponibles var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); //Creamos el PopupMenu en el que se mostraran los dispositivos PopupMenu menu = new PopupMenu(); //Añadimos los dispositivos encontrados al PopupMenu foreach (var serviceInfo in serviceInfoCollection) menu.Commands.Add(new UICommand(serviceInfo.Name, new UICommandInvokedHandler(ConnectToServiceAsync), serviceInfo)); //Seleccionamos el dispositvo con el que nos queremos comunicar var result = await menu.ShowForSelectionAsync(invokerRect); //Si no se pudo conectar al dispositivo se cambia el estado de la conexion a desconectado if (result == null) this.State = BluetoothConnectionState.Disconnected; }
/// <summary> /// Displays a PopupMenu for selection of the other Bluetooth device. /// Continues by establishing a connection to the selected device. /// </summary> /// <param name="invokerRect">for example: connectButton.GetElementRect();</param> public async Task EnumerateDevicesAsync(Rect invokerRect) { this.State = BluetoothConnectionState.Enumerating; var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); PopupMenu menu = new PopupMenu(); foreach (var serviceInfo in serviceInfoCollection) { menu.Commands.Add(new UICommand(serviceInfo.Name, new UICommandInvokedHandler(delegate(IUICommand command) { Task connect = ConnectToServiceAsync(command); }), serviceInfo)); } var result = await menu.ShowForSelectionAsync(invokerRect); if (result == 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); } }
/// <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; }
//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); } }
//En esta metodo se muestran los dispositivos que sean del tipo SerialPort en un PopupMenu public async Task EnumerateDevicesAsync(Rect invokerRect) { this.State = BluetoothConnectionState.Enumerating; //seleccionamos todos los dispositivos disponibles var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); //Creamos el PopupMenu en el que se mostraran los dispositivos PopupMenu menu = new PopupMenu(); //Añadimos los dispositivos encontrados al PopupMenu foreach (var serviceInfo in serviceInfoCollection) { menu.Commands.Add(new UICommand(serviceInfo.Name, new UICommandInvokedHandler(ConnectToServiceAsync), serviceInfo)); } //Seleccionamos el dispositvo con el que nos queremos comunicar var result = await menu.ShowForSelectionAsync(invokerRect); //Si no se pudo conectar al dispositivo se cambia el estado de la conexion a desconectado if (result == null) { this.State = BluetoothConnectionState.Disconnected; } }
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); } }
//Evento para habilitar o desahbilitar los botones segun la conexion private void connectionManager_StateChanged(object sender, BluetoothConnectionState state) { progress.IsIndeterminate = (state == BluetoothConnectionState.Connecting); btncancelar.IsEnabled = (state == BluetoothConnectionState.Connecting); btndesconectar.IsEnabled = (state == BluetoothConnectionState.Connected); }
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); } }
private void OnStateChangedEvent(object sender, BluetoothConnectionState state) { if (StateChanged != null) StateChanged(sender, state); }
//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; }
public async Task EnumerateDevicesAsync(object sender) { //this.State = BluetoothConnectionState.Enumerating; var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); MenuFlyout mf = new MenuFlyout(); foreach (var serviceInfo in serviceInfoCollection) { MenuFlyoutItem mi = new MenuFlyoutItem(); mi.Text = serviceInfo.Name; //selected_device_global = (DeviceInformation)serviceInfo; mi.Name = serviceInfo.Id; mi.Click += ConnectToServiceAsync; mf.Items.Add(mi); //menu.Commands.Add(new UICommand(serviceInfo.Name, new UICommandInvokedHandler(ConnectToServiceAsync), serviceInfo)); } if (serviceInfoCollection.Count == 0) { MenuFlyoutItem mi = new MenuFlyoutItem(); mi.Text = "No device found..."; this.State = BluetoothConnectionState.Disconnected; mf.Items.Add(mi); } mf.ShowAt(sender as FrameworkElement); }
private async Task ListenForMessagesAsync() { while (reader != null) { try { // Read first byte (length of the subsequent message, 255 or less). uint sizeFieldCount = await reader.LoadAsync(1); if (sizeFieldCount != 1) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the message. uint messageLength = reader.ReadByte(); uint actualMessageLength = await reader.LoadAsync(messageLength); if (messageLength != actualMessageLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the message and process it. string message = reader.ReadString(actualMessageLength); OnMessageReceivedEvent(this, message); } catch (Exception ex) { if (reader != null) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } } } }
/// <summary> /// Send a string message. /// </summary> /// <param name="message">The string to send.</param> /// <returns></returns> public async Task<uint> SendMessageAsync(string message) { uint sentMessageSize = 0; try { if (writer != null) { uint messageSize = writer.MeasureString(message); writer.WriteByte((byte)messageSize); sentMessageSize = writer.WriteString(message); await writer.StoreAsync(); if (sentMessageSize <= 0) { Disconnect(); } } } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; } return sentMessageSize; }