コード例 #1
0
        /// <summary>
        /// Connect to the device given host name
        /// </summary>
        /// <param name="deviceHostName">Raw host name of the device</param>
        /// <returns>True if connected successfully. Else False</returns>
        public async Task <bool> ConnectAsync(string deviceHostName)
        {
            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (!_adapter.IsEnabled)
            {
                throw new Exception("Bluetooth is off. Please turn it on from settings.");
            }

            SelectedDevice = _adapter.BondedDevices.FirstOrDefault(d => d.Address == deviceHostName);

            if (SelectedDevice != null)
            {
                var uuids = SelectedDevice.GetUuids();
                if (uuids != null && uuids.Length > 0)
                {
                    return(await Task.Run <bool>(() =>
                    {
                        _socket = SelectedDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuids[0].ToString()));
                        _socket.Connect();
                        return IsConnected;
                    }));
                }
            }

            return(IsConnected);
        }