public async Task <bool> HasService(RfcommServiceId serviceId, ushort sdpServiceNameAttributeId)
        {
            var rfcommServices = await m_btDevice.GetRfcommServicesForIdAsync(
                serviceId,
                BluetoothCacheMode.Uncached);

            if (rfcommServices.Services.Count == 0)
            {
                // Could not discover the service on the remote device
                return(false);
            }

            var m_frCommService = rfcommServices.Services[0];
            var attributes      = await m_frCommService.GetSdpRawAttributesAsync();

            if (!attributes.ContainsKey(sdpServiceNameAttributeId))
            {
                // The service is using an unexpected format for the Service Name attribute.
                return(false);
            }

            var attributeReader = DataReader.FromBuffer(attributes[sdpServiceNameAttributeId]);

            attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

            var serviceNameLength = attributeReader.ReadByte();
            var serviceName       = attributeReader.ReadString(serviceNameLength);

            return(serviceName == BluetoothMessageOrchestrator.SdpServiceName);
        }
Esempio n. 2
0
        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;
                }
            }
        }
Esempio n. 3
0
        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 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);
            }
        }
Esempio n. 5
0
        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);
                }
            }
        }
Esempio n. 6
0
        /// <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);
            }
        }
        //-----------------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;
            }
        }
Esempio n. 8
0
    /// <summary>
    /// Bluetooth device picker를 열고 시리얼 포트의 서비스에서 스트림을 여는 것을 시도합니다.
    /// </summary>
    private static Stream OpenBluetoothStream(DeviceInformation deviceInformation, RfcommServiceId serviceId)
    {
        //서비스 받아오기
        var device   = BluetoothDevice.FromDeviceInformation(deviceInformation);
        var result   = device.GetRfcommServices(BluetoothCacheMode.Cached);
        var services = result.Services;

        //print(serviceId);

        //요청한 서비스를 찾고 접속합니다.
        for (int i = 0; i < services.Count; ++i)
        {
            print(services[0].ServiceId.Uuid);
            print(services[1].ServiceId.Uuid);
            print(services.Count);

            var current = services[i];
            if (current.ServiceId == serviceId)
            {
                return(current.OpenStream());
            }
        }

        return(null);
    }
        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);
        }
Esempio n. 10
0
        /// <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);
            }
        }
Esempio n. 11
0
        /// <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;
        }
Esempio n. 12
0
        /// <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);
        }
        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());
            }
        }
Esempio n. 14
0
        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.");
        }
Esempio n. 15
0
        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>
        /// 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;
        }
Esempio n. 17
0
        /// <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 <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");
            }
        }
Esempio n. 19
0
        //-------------------------------------------------------------------------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);
        }
        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;
            }
        }
        /// <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 <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();
        }
Esempio n. 24
0
 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);
         });
     }));
 }
Esempio n. 25
0
        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]);
        }
Esempio n. 26
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;
            }));
        }
Esempio n. 27
0
        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();
        }
        /// <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);
        }
        public async Task<DeviceInformationCollection> FindSupportedDevicesAsync(RfcommServiceId serviceId)
        {
            // Find all paired instances of the Rfcomm chat service and display them in a list
            DeviceInformationCollection chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(serviceId));

            if (chatServiceDeviceCollection == null || chatServiceDeviceCollection.Count == 0)
            {
                return null;
            }
            return chatServiceDeviceCollection;
        }
Esempio n. 30
0
        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()));
        }
Esempio n. 31
0
        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);
        }