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 RegisterBand() { bool backgroundRegistered = false; var bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault(); var consentGranted = await GetConsentForHeartRate(bandInfo); if (consentGranted.HasValue && consentGranted.Value) { // The Guid used for the RfcommServiceId is from the Package.appxmanifest. var device = (await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.FromUuid(new Guid("A502CA9A-2BA5-413C-A4E0-13804E47B38F"))))) .FirstOrDefault(x => x.Name == bandInfo.Name); backgroundRegistered = device != null && await BackgroundTaskProvider.RegisterBandDataTask( typeof(BandDataTask).FullName, device.Id); } if (backgroundRegistered) { var success = new MessageDialog( "The BandDataTask has been registered successfully and the app can be closed.", "Background task registered"); success.Commands.Add(new UICommand("Ok", command => { this.IsBandRegistered = true; })); await success.ShowAsync(); } else { MessageDialog error; if (consentGranted.HasValue && !consentGranted.Value) { error = new MessageDialog( "The BandDataTask was not registered as you have rejected consent to access the heart rate sensor. Please try again.", "Background task not registered"); } else { error = new MessageDialog( "The BandDataTask was not registered successfully. Check your Microsoft Band is connected and try again.", "Background task not registered"); } error.Commands.Add(new UICommand("Ok", command => { })); await error.ShowAsync(); } }
private async System.Threading.Tasks.Task MakeDiscoverable() { // Make the system discoverable. Don'd repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists" if (!App.IsBluetoothDiscoverable) { Guid BluetoothServiceUuid = new Guid("17890000-0068-0069-1532-1992D79BE4D8"); try { provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid)); Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindServiceNameAsync(provider.ServiceId.AsString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket); // SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Don't bother setting SPD attributes provider.StartAdvertising(listener, true); App.IsBluetoothDiscoverable = true; } catch (Exception e) { string formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat"); string confirmationMessage = string.Format(formatString, e.Message); DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage); } } }
//-----------------private functions----------------------------// private async void loadBluetoothPeers() { _rfcommDevices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (_rfcommDevices.Count > 0) { List <string> peerNames = new List <string>(); foreach (var chatServiceInfo in _rfcommDevices) { peerNames.Add(chatServiceInfo.Name); } _selectBluetoothPeerBox.ItemsSource = peerNames; if (ApplicationData.Current.LocalSettings.Values.ContainsKey("obd")) { String obdPeerId = ApplicationData.Current.LocalSettings.Values["obd"].ToString(); int i = 0; foreach (var chatServiceInfo in _rfcommDevices) { if (chatServiceInfo.Id == obdPeerId) { _selectBluetoothPeerBox.SelectedIndex = i; } i++; } } _connectButton.IsEnabled = true; } }
private async void RunButton_Click(object sender, RoutedEventArgs e) { // Clear any previous messages MainPage.Current.NotifyUser("", NotifyType.StatusMessage); // Find all paired instances of the Rfcomm chat service chatServiceInfoCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (chatServiceInfoCollection.Count > 0) { List <string> items = new List <string>(); foreach (var chatServiceInfo in chatServiceInfoCollection) { items.Add(chatServiceInfo.Name); } cvs.Source = items; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { MainPage.Current.NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } }
/// <summary> /// Initialize a server socket listening for incoming Bluetooth Rfcomm connections /// </summary> async void InitializeRfcommServer() { try { ListenButton.IsEnabled = false; DisconnectButton.IsEnabled = true; rfcommProvider = await RfcommServiceProvider.CreateAsync( RfcommServiceId.FromUuid(RfcommChatServiceUuid)); // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); rfcommProvider.StartAdvertising(socketListener); NotifyStatus("Listening for incoming connections"); } catch (Exception e) { NotifyError(e); } }
/// <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); } }
public static async Task <string> RegisterBackgroundTask(Guid uuid, string serviceName, string serviceDescriptor) { System.Diagnostics.Debug.WriteLine("RegisterBackgroundTask"); try { // Applications registering for background trigger must request for permission. BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); BackgroundTaskBuilder backgroundTaskBuilder = new BackgroundTaskBuilder(); backgroundTaskBuilder.Name = BackgroundTaskName; backgroundTaskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint; RfcommConnectionTrigger trigger = new RfcommConnectionTrigger(); trigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(uuid); // TODO: helper function to create sdpRecordBlob trigger.InboundConnection.SdpRecord = getsdpRecordBlob(serviceName, serviceDescriptor); //backgroundTaskBuilder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false)); backgroundTaskBuilder.SetTrigger(trigger); BackgroundTaskRegistration backgroundTaskRegistration = backgroundTaskBuilder.Register(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("ERROR: Accessing your device failed." + Environment.NewLine + e.Message); return("ERROR: Accessing your device failed." + Environment.NewLine + e.Message); } return(null); }
/// <summary> /// RfcommServerの初期化 /// </summary> private async void InitializeRfcommServer() { //UUIDを定義 Guid RfcommChatServiceUuid = Guid.Parse("17fcf242-f86d-4e35-805e-546ee3040b84"); //UUIDからRfcommProviderをイニシャライズ rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommChatServiceUuid)); // SocketListenerを生成,OnConnectionReceivedをコールバックとして登録 socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; // Listeningをスタート // //awaitはasyncキーワードによって変更された非同期メソッドでのみ使用でる. //中断ポイントを挿入することで,メソッドの実行を,待機中のタスクが完了するまで中断する //async修飾子を使用して定義され,通常1つ以上のawait式を含むメソッドが,"非同期メソッド"と呼る await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //SDP属性を設定し,そのSDPレコードを他のデバイスが検索できるようにアドバタイズする // //SDP(Session Description Protcol): //セッションの告知・招待などを必要とするマルチメディアセッションを開始するため //必要な情報を記述するためのプレゼンテーション層に属するプロトコル InitializeServiceSdpAttributes(rfcommProvider); rfcommProvider.StartAdvertising(socketListener, true); }
public override async void Initialize() { System.Diagnostics.Debug.WriteLine("Initializing the Server."); try { rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid)); } // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE). catch (Exception ex) when((uint)ex.HResult == 0x800710DF) // The Bluetooth radio may be off. { System.Diagnostics.Debug.WriteLine("Could not initialize RfcommServiceProvider"); return; } // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); try { rfcommProvider.StartAdvertising(socketListener, true); } catch (Exception e) { // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why. Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices. System.Diagnostics.Debug.WriteLine("Could not start advertising"); return; } System.Diagnostics.Debug.WriteLine("Server Succesfully Initialized."); }
/// <summary> /// Initializes the server using RfcommServiceProvider to advertise the Chat Service UUID and start listening /// for incoming connections. /// </summary> private async void InitializeServer() { try { rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommChatServiceUuid)); } // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE). catch (Exception ex) when((uint)ex.HResult == 0x800710DF) { // The Bluetooth radio may be off. throw new InvalidOperationException("Make sure your Bluetooth Radio is on: " + ex.Message, ex); } // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; var rfcomm = rfcommProvider.ServiceId.AsString(); await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); try { rfcommProvider.StartAdvertising(socketListener, true); } catch (Exception e) { // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why. Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices. throw new Exception(e.Message); } }
public async void InitializeRfCommServer() { try { Console.WriteLine("Starting Serwer.."); rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommServiceUuid)); // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; await socketListener.BindServiceNameAsync( rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.PlainSocket ); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); rfcommProvider.StartAdvertising(socketListener); ServerInitiated = true; Console.WriteLine("Server initialized.."); } catch (Exception e) { Console.WriteLine(e.Message); ServerInitiated = false; } }
async void InitializeBluetooth() { try { var service_id = RfcommServiceId.FromUuid(Guid.Parse("ff1477c2-7265-4d55-bb08-c3c32c6d635c")); provider = await RfcommServiceProvider.CreateAsync(service_id); StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindServiceNameAsync( provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // InitializeServiceSdpAttributes var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); writer.WriteUInt32(SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); provider.StartAdvertising(listener, true); } catch (Exception error) { Debug.WriteLine(error.ToString()); } }
/// <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> private async void RunButton_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 rootPage.NotifyUser("", NotifyType.StatusMessage); // 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); } DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { rootPage.NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } button.IsEnabled = true; }
public async void StartBroadcast(NetworkController netctl) { this.netctl = netctl; try { commServiceProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.Constants.broadcastGuid)); listener = new StreamSocketListener(); listener.ConnectionReceived += RecieveConnection; var rfcomm = commServiceProvider.ServiceId.AsString(); await listener.BindServiceNameAsync(commServiceProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); Logging.Log.Trace("Initializing Session Description Protocal (SDP) Attributes"); SetupBroadcastAttributes(commServiceProvider); Logging.Log.Trace("SDP Attributes Initialized"); commServiceProvider.StartAdvertising(listener, true); } catch (Exception ex) { Logging.Log.Error("An error occured advertising the bluetooth connection"); Logging.Log.Error(ex.Message); return; } Console.WriteLine("Broadcasting Connections."); }
public static async Task <StreamSocket> Connect(BluetoothDevice bluetoothDevice) { Check.IsNull(bluetoothDevice); var serviceGuid = Guid.Parse("34B1CF4D-1069-4AD6-89B6-E161D79BE4D8"); var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(serviceGuid), BluetoothCacheMode.Uncached); var rfcommService = bluetoothDevice.RfcommServices.FirstOrDefault(); for (int i = 0; i < bluetoothDevice.RfcommServices.Count; i++) { rfcommService = bluetoothDevice.RfcommServices.ElementAt(i); if (rfcommService.ServiceId.Uuid.Equals(serviceGuid)) { break; } } if (rfcommService != null) { return(await ConnectToStreamSocket(bluetoothDevice, rfcommService.ConnectionServiceName)); } else { throw new Exception( "Selected bluetooth device does not advertise any RFCOMM service"); } }
//-------------------------------------------------------------------------uruchamianie serwera async private void startServer() { try { rfcommProvider = await RfcommServiceProvider.CreateAsync( RfcommServiceId.FromUuid(serviceUuid)); } catch (Exception e) { if ((uint)e.HResult == 0x9000000F) { disconnect(); System.Diagnostics.Debug.WriteLine(e.StackTrace); showPopupDialog("Bluetooth jest wyłączone!\nPowrót"); return; } } socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString()); var sdpWriter = new DataWriter(); sdpWriter.WriteByte(SdpServiceNameAttributeType); sdpWriter.WriteByte((byte)SdpServiceName.Length); sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; sdpWriter.WriteString(SdpServiceName); rfcommProvider.SdpRawAttributes.Add(SdpServiceNameAttributeId, sdpWriter.DetachBuffer()); rfcommProvider.StartAdvertising(socketListener); }
/// <summary> /// Make this device discoverable to other Bluetooth devices within range /// </summary> /// <returns></returns> private async Task <bool> MakeDiscoverable() { // Make the system discoverable. Don't repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists." if (!_isBluetoothDiscoverable) { try { Guid BluetoothServiceUuid = new Guid(Constants.BluetoothServiceUuid); _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid)); StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.PlainSocket); // No need to set SPD attributes _provider.StartAdvertising(listener, true); _isBluetoothDiscoverable = true; } catch (Exception ex) { string confirmationMessage = string.Format(BluetoothNoDeviceAvailableFormat, ex.Message); await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); } } return(_isBluetoothDiscoverable); }
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); }
public Scenario3_BgChatServer() { this.InitializeComponent(); trigger = new RfcommConnectionTrigger(); trigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid); // TODO: helper function to create sdpRecordBlob trigger.InboundConnection.SdpRecord = sdpRecordBlob.AsBuffer(); }
public static IAsyncOperation <DeviceInformationCollection> getDeviceInfo(Guid guid) { return(AsyncInfo.Run((token) => { return Task.Run(async() => { var dev = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(guid)); return await DeviceInformation.FindAllAsync(dev); }); })); }
GetRfcommDeviceServiceForHostFromUuid(HostName host, Guid uuid) { RfcommServiceId id; BluetoothDevice device; id = RfcommServiceId.FromUuid(uuid); device = await BluetoothDevice.FromHostNameAsync(host); return((await device.GetRfcommServicesForIdAsync(id)).Services[0]); }
public static IAsyncOperation <TetheringState> SendBluetooth(DeviceInformation dev, TetheringState state) { return(AsyncInfo.Run(async(cancel) => { for (var tryout = 10; tryout > 0; tryout--) { try { var selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(ServiceUuid)); var devices = await DeviceInformation.FindAllAsync(selector); var service = devices.SingleOrDefault(d => d.Id.StartsWith(dev.Id, StringComparison.OrdinalIgnoreCase)); if (service == null) { throw new Exception("Tethermote Service not found"); } using (var socket = await ConnectDevice(service)) { using (var outstream = socket.OutputStream) { await outstream.WriteAsync(new byte[] { (byte)state }.AsBuffer()); } using (var instream = socket.InputStream) { var buf = new Windows.Storage.Streams.Buffer(1); var red = (await instream.ReadAsync(buf, 1, Windows.Storage.Streams.InputStreamOptions.Partial)).Length; if (red == 1) { return (TetheringState)buf.ToArray()[0]; } Debug.WriteLine("No data"); } } } catch (Exception ex) { Debug.WriteLine(ex); try { await PingDevice(dev.Id); } catch (Exception e2) { Debug.WriteLine(e2); } if (tryout != 1) { await Task.Delay(100); } } } return TetheringState.Error; })); }
public Scenario3_BgChatServer() { this.InitializeComponent(); trigger = new RfcommConnectionTrigger(); // Local service Id is the only mandatory field that should be used to filter a known service UUID. trigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid); // The SDP record is nice in order to populate optional name and description fields trigger.InboundConnection.SdpRecord = sdpRecordBlob.AsBuffer(); }
public RfcommDeviceServicesResult GetRfcommServices(BluetoothCacheMode cacheMode) { BluetoothError error = BluetoothError.Success; List <RfcommDeviceService> services = new List <RfcommDeviceService>(); foreach (Guid g in GetRfcommServices(ref _info)) { services.Add(new Rfcomm.RfcommDeviceService(this, RfcommServiceId.FromUuid(g))); } return(new RfcommDeviceServicesResult(error, services.AsReadOnly())); }
/// <summary> /// Initializes the server using RfcommServiceProvider to advertise the Service UUID and start listening /// for incoming connections. /// </summary> public async Task <bool> InitializeRfcommServer() { App.LogService.Write("Initializing RFCOMM server..."); if (_isInitialized) { App.LogService.Write("RFCOMM server already initialized!"); return(true); } try { _rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothConstants.RfcommServiceUuid)); } // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE). catch (Exception ex) when((uint)ex.HResult == 0x800710DF) { // The Bluetooth radio may be off. App.LogService.Write("Make sure your Bluetooth Radio is on: " + ex.Message); return(false); } // Create a listener for this service and start listening App.LogService.Write("Creating socket listener..."); _socketListener = new StreamSocketListener(); _socketListener.ConnectionReceived += OnConnectionReceived; var rfcomm = _rfcommProvider.ServiceId.AsString(); await _socketListener.BindServiceNameAsync(_rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(_rfcommProvider); try { App.LogService.Write("Starting BT advertisement..."); _rfcommProvider.StartAdvertising(_socketListener, true); } catch (Exception e) { // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why. // Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices. App.LogService.Write(e.Message, LoggingLevel.Error); return(false); } App.LogService.Write("Listening for incoming connections"); _isInitialized = true; return(true); }
protected override async Task StartCoreAsync() { var serviceId = RfcommServiceId.FromUuid(_serviceUuid); _serviceProvider = await RfcommServiceProvider.CreateAsync(serviceId); _listener.ConnectionReceived += OnConnectionReceived; await _listener.BindServiceNameAsync(serviceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); InitializeServiceSdpAttributes(_serviceProvider); _serviceProvider.StartAdvertising(_listener, true); }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { AvatarDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as AvatarDeviceDisplay; var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id);; var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(avatarServiceUUID), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { Status.Text = "Could not discover the avatar service on the remote device"; return; } deviceWatcher.Stop(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); EnableActivityDetectionAsync(); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND Status.Text = "Please verify that you are running the Avatar server."; RunButton.IsEnabled = true; break; default: throw; } } }
public async Task InitializeAsync() { // Initialize the provider for the hosted RFCOMM service _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.SERVICE_UUID)); // Create a listener for this service and start listening _listener = new StreamSocketListener(); _listener.ConnectionReceived += OnConnectionReceivedAsync; await _listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start advertising InitializeServiceSdpAttributes(_provider); _provider.StartAdvertising(_listener, true); }