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");
            }
        }
コード例 #2
0
        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);
        }
コード例 #3
0
        /// <summary>
        /// This is a async task to connect to device and create _socket, _dataReader and _dataWriter object.
        /// </summary>
        /// <param name="BtdeviceId"></param>
        /// <returns> boolean</returns>
        public async Task <Boolean> ConnectAsyncFromId(string BtdeviceId)
        {
            deviceId = BtdeviceId;
            StopDeviceWatcher();

            bluetoothDevice = await BluetoothDevice.FromIdAsync(BtdeviceId);

            if (bluetoothDevice != null)
            {
                if (deviceConnectedCallback != null)
                {
                    deviceConnectedCallback(this, deviceInformation);
                }

                if (appSuspendEventHandler == null || appResumeEventHandler == null)
                {
                    RegisterForAppEvents();
                }

                if (deviceAccessEventHandler == null)
                {
                    RegisterForDeviceAccessStatusChange();
                }


                var _rfcomService = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.SerialPort, BluetoothCacheMode.Uncached);

                if (_rfcomService.Services.Count <= 0)
                {
                    rootPage.StatusBar("Serial service not found on " + bluetoothDevice.Name, BarStatus.Error);
                    return(false);
                }

                var serialService = _rfcomService.Services[0];

                lock (this) { _socket = new StreamSocket(); } // for marking this as crtical section.

                try
                {
                    // socket initializesd
                    await _socket.ConnectAsync(serialService.ConnectionHostName, serialService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                    rootPage.StatusBar("connection to device done sucessfully", BarStatus.Sucess);

                    // reader and writer assingment.
                    _serialWriter = new DataWriter(_socket.OutputStream);
                    _serialReader = new DataReader(_socket.InputStream);
                }
                catch (Exception e)
                {
                    rootPage.StatusBar(e.ToString(), BarStatus.Error);
                }
            }

            return(bluetoothDevice != null);
        }
コード例 #4
0
        public async void Connect(string devid)
        {
            this.Logger.Info("入力デバイスへの接続開始:" + devid);

            this.StartingSendTaskFlag    = true;
            this.StartingReceiveTaskFlag = true;

            this.SelectedDeviceInfo = (from i in KnownDeviceList where i.Id == devid select i).First();

            try {
                SelectedDevice = await BluetoothDevice.FromIdAsync(this.SelectedDeviceInfo.Id);

                var rfcommsrv = await SelectedDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceUuid), BluetoothCacheMode.Uncached);

                RfcommService = rfcommsrv.Services[0];
                var attributes = await RfcommService.GetSdpRawAttributesAsync();

                var attributereader   = DataReader.FromBuffer(attributes[0x100]);
                var attributetype     = attributereader.ReadByte();
                var servicenamelength = attributereader.ReadByte();
                attributereader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16BE;

                Socket = new StreamSocket();
                await Socket.ConnectAsync(RfcommService.ConnectionHostName, RfcommService.ConnectionServiceName);

                SocketWriter = new DataWriter(Socket.OutputStream);
                SocketReader = new DataReader(Socket.InputStream);

                this.RunningFlag = true;
                this.SendTask    = Task.Run(() => { this.RunSend(); });
                this.ReceiveTask = Task.Run(() => { this.RunReceive(); });

                this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Connect));
            } catch (Exception ex) {
                this.Logger.Error(ex, "入力デバイスへの接続失敗");
                this.RunningFlag             = false;
                this.StartingSendTaskFlag    = false;
                this.StartingReceiveTaskFlag = false;
                this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Error));
            }
        }
コード例 #5
0
        /// <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;
                }
            }
        }
コード例 #6
0
ファイル: BluetoothPenClient.cs プロジェクト: chyccs/UWP-SDK
        /// <summary>
        /// Connect the client to a remote bluetooth host using PenInformation instance
        /// </summary>
        /// <param name="penInformation">The instance of PenInformation class</param>
        /// <returns>When this method completes successfully, it returns a boolean result</returns>
        public async Task <bool> Connect(PenInformation penInformation)
        {
            try
            {
                // lock try 블럭 안으로 이동
                await semaphreSlime.WaitAsync();

                if (Alive)
                {
                    return(false);
                }

                bool ret = await Pairing(penInformation);

                if (ret == false)
                {
                    return(false);
                }

                // 소켓을 멤버 변수로 가지고 있게끔
                streamSocket = new StreamSocket();

                //BluetoothDevice bluetoothDevice = await BluetoothDevice.FromIdAsync(penInformation.deviceInformation.Id);
                // le의 deviceinformation id를 이용해 BluetoothDevice를 가져올 수 없기 때문에 이런식으로 우회함
                BluetoothDevice bluetoothDevice = await BluetoothDevice.FromBluetoothAddressAsync(penInformation.BluetoothAddress);

                if (bluetoothDevice == null)
                {
                    return(false);
                }

                //var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.SerialPort, BluetoothCacheMode.Uncached);
                var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached);

                RfcommDeviceService chatService = null;

                if (rfcommServices.Services.Count > 0)
                {
                    chatService = rfcommServices.Services[0];
                }
                else
                {
                    return(false);
                }

                await streamSocket.ConnectAsync(bluetoothDevice.HostName, chatService.ConnectionServiceName);

                // 여기가 좀 지저분함
                PenController.Protocol = penInformation.Protocol == Protocols.V2 || bluetoothDevice.ClassOfDevice.RawValue == ClassOfDeviceV2 ? Protocols.V2 : Protocols.V1;

                await Task.Delay(200);

                Bind(streamSocket);
            }
            catch (Exception ex)
            {
                switch ((uint)ex.HResult)
                {
                case (0x80070490):                         // ERROR_ELEMENT_NOT_FOUND
                    return(false);

                case (0x800710DF):                         // ERROR_DEVICE_NOT_AVAILABLE
                    return(false);

                default:
                    Debug.WriteLine($"Exception : {ex.Message}");
                    Debug.WriteLine($"Exception : {ex.StackTrace}");
                    return(false);
                }
            }
            finally
            {
                semaphreSlime.Release();
            }

            return(true);
        }
コード例 #7
0
        public async void Connect(RfcommDeviceDisplay deviceInfoDisp)
        {
            try
            {
                bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id);
            }
            catch
            {
                //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.

            // 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
            string uuid = "17fcf242-f86d-4e35-805e-" + Constants.BLUETOOTH_ID;
            Guid   RfcommChatServiceUuid = Guid.Parse(uuid);
            var    rfcommServices        = await bluetoothDevice.GetRfcommServicesForIdAsync(
                RfcommServiceId.FromUuid(RfcommChatServiceUuid), BluetoothCacheMode.Uncached);

            if (rfcommServices.Services.Count > 0)
            {
                ConnectService = rfcommServices.Services[0];
            }
            else
            {
                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
            UInt16 SdpServiceNameAttributeId = 0x100;
            var    attributes = await ConnectService.GetSdpRawAttributesAsync();

            if (!attributes.ContainsKey(SdpServiceNameAttributeId))
            {
                Console.WriteLine("sdpAttributeがおかしい");
                return;
            }

            byte SdpServiceNameAttributeType = (4 << 3) | 5;
            var  attributeReader             = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]);
            var  attributeType = attributeReader.ReadByte();

            if (attributeType != SdpServiceNameAttributeType)
            {
                Console.WriteLine("sdpNameAttributeがおかしい");
                return;
            }
            var serviceNameLength = attributeReader.ReadByte();

            lock (this) //lock構文、排他制御
            {
                ConnectSocket = new StreamSocket();
            }

            try
            {
                await ConnectSocket.ConnectAsync(ConnectService.ConnectionHostName, ConnectService.ConnectionServiceName);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80072740)  // WSAEADDRINUSE
            {
                Console.WriteLine("socket接続がおかしい");
            }
        }
コード例 #8
0
        /// <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;
                }
            }

        }
コード例 #9
0
    private async void ConnectToServer()
    {
        try
        {
            //Hololens
            bluetoothDevice = await BluetoothDevice.FromIdAsync("Bluetooth#Bluetooth58:00:e3:cf:52:da-b4:ae:2b:bf:1b:57");

            //Yoga
            //bluetoothDevice = await BluetoothDevice.FromIdAsync("Bluetooth#Bluetooth58:00:e3:cf:52:da-58:00:e3:d0:fa:22");
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
            return;
        }

        if (bluetoothDevice == null)
        {
            Debug.Log("Bluetooth Device returned null.");
        }

        var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(
            RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached);

        if (rfcommServices.Services.Count > 0)
        {
            chatService = rfcommServices.Services[0];
        }
        else
        {
            Debug.Log(
                "Could not discover the chat service on the remote device");
            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))
        {
            Debug.Log(
                "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[Constants.SdpServiceNameAttributeId]);
        var attributeType   = attributeReader.ReadByte();

        if (attributeType != Constants.SdpServiceNameAttributeType)
        {
            Debug.Log(
                "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;

        lock (this)
        {
            chatSocket = new StreamSocket();
        }
        try
        {
            await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName);

            chatWriter = new DataWriter(chatSocket.OutputStream);

            DataReader chatReader = new DataReader(chatSocket.InputStream);
            ReceiveStringLoop(chatReader);
        }
        catch (Exception ex) when((uint)ex.HResult == 0x80070490)          // ERROR_ELEMENT_NOT_FOUND
        {
            Debug.Log("Please verify that you are running the BluetoothRfcommChat server.");
        }
        catch (Exception ex) when((uint)ex.HResult == 0x80072740)          // WSAEADDRINUSE
        {
            Debug.Log("Please verify that there is no other RFCOMM connection to the same device.");
        }
    }
コード例 #10
0
        public async void ConnectAsync(RfcommChatDeviceDisplay deviceInfoDisp)
        {
            // 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)
            {
                throw new UnauthorizedAccessException("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices");
            }
            // If not, try to get the Bluetooth device
            try
            {
                bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // 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)
            {
                throw new InvalidOperationException("Bluetooth Device returned null. Access Status = " + accessStatus.ToString());
            }

            // 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(RfcommChatServiceUuid), BluetoothCacheMode.Uncached);

            if (rfcommServices.Services.Count > 0)
            {
                chatService = rfcommServices.Services[0];
            }
            else
            {
                throw new InvalidOperationException("Could not discover the chat service on the remote device");
            }

            // 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))
            {
                throw new InvalidOperationException("The Chat service is not advertising the Service Name attribute (attribute id=0x100). " +
                                                    "Please verify that you are running the BluetoothRfcommChat server.");
            }
            var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]);
            var attributeType   = attributeReader.ReadByte();

            if (attributeType != SdpServiceNameAttributeType)
            {
                throw new InvalidOperationException(
                          "The Chat service is using an unexpected format for the Service Name attribute. " +
                          "Please verify that you are running the BluetoothRfcommChat server.");
            }
            var serviceNameLength = attributeReader.ReadByte();

            // The Service Name attribute requires UTF-8 encoding.
            attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

            lock (this)
            {
                chatSocket = new StreamSocket();
            }
            try
            {
                await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName);

                // TODO: powiadomienie, że połączono
                //SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name);

                chatWriter = new DataWriter(chatSocket.OutputStream);
                DataReader chatReader = new DataReader(chatSocket.InputStream);

                ReceiveDataLoop(chatReader);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80070490)  // ERROR_ELEMENT_NOT_FOUND
            {
                throw new InvalidOperationException("Please verify that you are running the BluetoothRfcommChat server.");
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80072740)  // WSAEADDRINUSE
            {
                throw new InvalidOperationException("Please verify that there is no other RFCOMM connection to the same device.");
            }
        }
コード例 #11
0
        private async void Connect(DeviceInformation devInfo)
        {
            try
            {
                Logging.Log.Trace("Attempting to connect to Bluetooth Device: " + devInfo.Name);
                targetDevice = await BluetoothDevice.FromIdAsync(devInfo.Id);

                targetDevice.ConnectionStatusChanged += new TypedEventHandler <BluetoothDevice, object>(async(btd, obj) =>
                {
                    Logging.Log.Trace("Changed Connection Status for " + btd.Name + " to " + btd.ConnectionStatus);
                });

                if (targetDevice != null)
                {
                    const BluetoothCacheMode bluetoothCacheMode = BluetoothCacheMode.Uncached;
                    var targetBluetoothServices = await targetDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(Constants.Constants.broadcastGuid), bluetoothCacheMode);

                    Logging.Log.Trace("Searching Target Device " + devInfo.Name + " for Bluetooth Chat Service.");

                    var retrievedServices = targetBluetoothServices.Services;

                    if (retrievedServices.Count > 0)
                    {
                        Logging.Log.Trace("Bluetooth Chat Service Found on " + devInfo.Name);
                        var retrievedService = retrievedServices[0];
                        var attributes       = await retrievedService.GetSdpRawAttributesAsync();

                        var          attributeReader   = DataReader.FromBuffer(attributes[Constants.Constants.serviceNameID]);
                        var          attributeType     = attributeReader.ReadByte();
                        var          serviceNameLength = attributeReader.ReadByte();
                        StreamSocket bluetoothSocket   = null;
                        DataWriter   bluetoothWriter   = null;

                        //lock (this)
                        //  {
                        bluetoothSocket = new StreamSocket();
                        //}

                        await bluetoothSocket.ConnectAsync(retrievedService.ConnectionHostName, retrievedService.ConnectionServiceName);

                        bluetoothWriter = new DataWriter(bluetoothSocket.OutputStream);
                        DataReader chatReader = new DataReader(bluetoothSocket.InputStream);

                        Logging.Log.Trace("Connection to " + devInfo.Name + " Chat Service Established. Awaiting data...");

                        var connectedDevice = new ConnectedDevice(devInfo.Name, targetDevice, bluetoothWriter, chatReader, netctl);
                        netctl.AddDevice(connectedDevice);
                    }
                    else
                    {
                        Logging.Log.Trace("No valid services could be found on " + devInfo.Name + ". Ignoring.");
                    }
                }
                else
                {
                    Logging.Log.Trace("Target Device is Null.");
                }
            }
            catch (Exception ex)
            {
                Logging.Log.Error("An Exception Occured. The target device may not have an active service, or something went wrong.\n" + ex.Message);
                return;
            }
        }
コード例 #12
0
        /// <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>
        public async Task <bool> ConnectAsync(RomeRemoteSystem system)
        {
            // Make sure user has selected a device first
            if (system != null)
            {
                Debug.WriteLine("Connecting to remote device. Please wait...");
            }
            else
            {
                Debug.WriteLine("Please select an item to connect to");
                return(false);
            }

            // 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(system.Id).CurrentStatus;

            if (accessStatus == DeviceAccessStatus.DeniedByUser)
            {
                Debug.WriteLine("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices");
                return(false);
            }

            // If not, try to get the Bluetooth device
            try
            {
                _bluetoothDevice = await BluetoothDevice.FromIdAsync(system.Id);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                StopWatcher();
                return(false);
            }

            // 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)
            {
                Debug.WriteLine("Bluetooth Device returned null. Access Status = " + accessStatus.ToString());
            }

            if (_bluetoothDevice == null)
            {
                return(false);
            }

            // 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.SERVICE_UUID), BluetoothCacheMode.Uncached);

            if (rfcommServices?.Services.Count > 0)
            {
                _chatService = rfcommServices.Services[0];
            }
            else
            {
                Debug.WriteLine("Could not discover the chat service on the remote device");
                StopWatcher();
                return(false);
            }

            // 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.SERVICE_ATTRIBUTE_ID))
            {
                Debug.WriteLine(
                    "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " +
                    "Please verify that you are running the BluetoothRfcommChat server.");
                StopWatcher();
                return(false);
            }
            var attributeReader = DataReader.FromBuffer(attributes[Constants.SERVICE_ATTRIBUTE_ID]);
            var attributeType   = attributeReader.ReadByte();

            if (attributeType != Constants.SERVICE_ATTRIBUTE_TYPE)
            {
                Debug.WriteLine(
                    "The Chat service is using an unexpected format for the Service Name attribute. " +
                    "Please verify that you are running the BluetoothRfcommChat server.");
                StopWatcher();
                return(false);
            }

            var serviceNameLength = attributeReader.ReadByte();

            // The Service Name attribute requires UTF-8 encoding.
            attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

            StopWatcher();

            lock (this)
            {
                _chatSocket = new StreamSocket();
            }
            try
            {
                await _chatSocket.ConnectAsync(_chatService.ConnectionHostName, _chatService.ConnectionServiceName);

                Debug.WriteLine("Connected to : " + attributeReader.ReadString(serviceNameLength) + _bluetoothDevice.Name);
                _chatWriter = new DataWriter(_chatSocket.OutputStream);

                DataReader chatReader = new DataReader(_chatSocket.InputStream);
                ReceiveStringLoop(chatReader);

                return(true);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80070490)  // ERROR_ELEMENT_NOT_FOUND
            {
                Debug.WriteLine("Please verify that you are running the BluetoothRfcommChat server.");
                StopWatcher();
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80072740)  // WSAEADDRINUSE
            {
                Debug.WriteLine("Please verify that there is no other RFCOMM connection to the same device.");
                StopWatcher();
            }

            return(false);
        }
コード例 #13
0
        public async void Connect(String devID)
        {
            // Perform device access checks before trying to get the device.
            // First, we check if consent has been explicitly denied by the user.
            lastDevID   = devID;
            isCanceled  = false;
            isConnected = false;
            WriteDebug("Check Connection");

            DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(devID).CurrentStatus;

            if (accessStatus == DeviceAccessStatus.DeniedByUser)
            {
                return;
            }
            // If not, try to get the Bluetooth device
            try
            {
                bluetoothDevice = await BluetoothDevice.FromIdAsync(devID);
            }
            catch (Exception)
            {
                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)
            {
                return;
            }
            WriteDebug("Sync Devices..");

            // 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
            long start = DateTime.Now.Ticks;

            RfcommDeviceServicesResult rfcommServices = null;

            while (true)
            {
                rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(
                    RfcommServiceId.FromUuid(guid), BluetoothCacheMode.Uncached);

                if (rfcommServices.Services.Count > 0)
                {
                    WriteDebug($"{rfcommServices.Error}.");
                    RfService = rfcommServices.Services[0];
                    break;
                }
                lock (this)
                {
                    long current = DateTime.Now.Ticks;
                    if (current - 10_00000000 > start)
                    {
                        break;
                    }
                }
            }

            if (RfService == null)
            {
                isCanceled = true;
                Disconnect();
                onDisconnect();
                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 RfService.GetSdpRawAttributesAsync();

            if (!attributes.ContainsKey(0x100))
            {
                return;
            }
            var attributeReader = DataReader.FromBuffer(attributes[0x100]);
            var attributeType   = attributeReader.ReadByte();

            if (attributeType != ((4 << 3) | 5))
            {
                return;
            }
            var serviceNameLength = attributeReader.ReadByte();

            // The Service Name attribute requires UTF-8 encoding.
            attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;



            //------------bind Stream------
            lock (this)
            {
                streamSocket = new StreamSocket();
            }
            try
            {
                await streamSocket.ConnectAsync(RfService.ConnectionHostName, RfService.ConnectionServiceName);

                WriteDebug($"{RfService.ConnectionHostName} : {RfService.Device.ConnectionStatus}");

                dataRegister.conditionText.Text = "Checking Connection...";

                dataWriter = new DataWriter(streamSocket.OutputStream);

                DataReader chatReader = new DataReader(streamSocket.InputStream);

                isConnected = true;

                ReceiveStringLoop(chatReader);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80070490)  // ERROR_ELEMENT_NOT_FOUND
            {
                return;
            }
            catch (Exception ex) when((uint)ex.HResult == 0x80072740)  // WSAEADDRINUSE
            {
                return;
            }
            catch
            {
            }
        }