Android之Bluetooth通信-经典蓝牙通信BluetoothSocket

简介

通过蓝牙传输文件,其实现流程是怎样的?这里从JAVA/JNI/HAL三个角度分析
注:
服务端为BluetoothServerSocket

以BluetoothSocket创建为案例 -- 7.1代码

JAVA -- Bluetooth.apk

packages/apps/Bluetooth
frameworks/base/core/java/android/bluetooth

1.关键方法

BluetoothOppTransfer.java

BluetoothSocket btSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

btSocket.connect();

2.分析

1.bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

BluetoothDevice.java
    public BluetoothSocket createInsecureRfcommSocketToServiceRecord(UUID uuid) throws IOException {
        if (isBluetoothEnabled() == false) {
            Log.e(TAG, "Bluetooth is not enabled");
            throw new IOException();
        }
        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, -1,
                new ParcelUuid(uuid));//创建BluetoothSocket对象
    }
    
2.btSocket.connect();

BluetoothSocket.java
   public void connect() throws IOException {
        if (mDevice == null) throw new IOException("Connect is called on null device");

        try {
            if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
            IBluetooth bluetoothProxy =
                    BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
            if (bluetoothProxy == null) throw new IOException("Bluetooth is off");
            mPfd = bluetoothProxy.connectSocket(mDevice, mType,
                    mUuid, mPort, getSecurityFlags());//获取ParcelFileDescriptor,即FileDescriptor的Android包装类
            synchronized(this)
            {
                if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
                if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
                if (mPfd == null) throw new IOException("bt socket connect failed");
                FileDescriptor fd = mPfd.getFileDescriptor();//把ParcelFileDescriptor转化为fd
                mSocket = new LocalSocket(fd);//建立Socket连接准备
                mSocketIS = mSocket.getInputStream();
                mSocketOS = mSocket.getOutputStream();
            }
            int channel = readInt(mSocketIS);
            if (channel <= 0)
                throw new IOException("bt socket connect failed");
            mPort = channel;
            waitSocketSignal(mSocketIS);//等待连接。这里代表connect是堵塞的方法
            synchronized(this)
            {
                if (mSocketState == SocketState.CLOSED)
                    throw new IOException("bt socket closed");
                mSocketState = SocketState.CONNECTED;
            }
        } catch (RemoteException e) {
            Log.e(TAG, Log.getStackTraceString(new Throwable()));
            throw new IOException("unable to send RPC: " + e.getMessage());
        }
    }
    
3.接下来我们先分析怎么等待连接,其后再重点讲解mPfd的来源
waitSocketSignal(mSocketIS)

    private String waitSocketSignal(InputStream is) throws IOException {
        byte [] sig = new byte[SOCK_SIGNAL_SIZE];
        int ret = readAll(is, sig);//等待连接的关键方法
        ······
        return RemoteAddr;
    }
    
    private int readAll(InputStream is, byte[] b) throws IOException {
        int left = b.length;
        while(left > 0) {
            int ret = is.read(b, b.length - left, left);//inputstream.read就会阻塞,此方法为常见方法
            if(ret <= 0)
                 throw new IOException("read failed, socket might closed or timeout, read ret: "
                         + ret);
            left -= ret;
            if(left != 0)
                Log.w(TAG, "readAll() looping, read partial size: " + (b.length - left) +
                            ", expect size: " + b.length);
        }
        return b.length;
    }
    
4.现在重点讲解mPfd的来源
IBluetooth bluetoothProxy =
                    BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
mPfd = bluetoothProxy.connectSocket(mDevice, mType,
                    mUuid, mPort, getSecurityFlags());
                    
bluetoothProxy代理的Binder对象,其实就是AdapterService

AdapterService.java

     ParcelFileDescriptor connectSocket(BluetoothDevice device, int type,
                                              ParcelUuid uuid, int port, int flag) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
        int fd = connectSocketNative(Utils.getBytesFromAddress(device.getAddress()),
                   type, Utils.uuidToByteArray(uuid), port, flag, Binder.getCallingUid());//通过jni获取fd
        if (fd < 0) {
            errorLog("Failed to connect socket");
            return null;
        }
        return ParcelFileDescriptor.adoptFd(fd);//通过fd创建ParcelFileDescriptor
    }
来到connectSocketNative代表来到了JNI层,下面我们重点简介JNI层

JNI -- libbluetooth_jni.so (/system/lib/libbluetooth_jni.so)

packages\apps\Bluetooth\jni

jni分析

com_android_bluetooth_btservice_AdapterService.cpp
static int connectSocketNative(JNIEnv *env, jobject object, jbyteArray address, jint type,
                                   jbyteArray uuidObj, jint channel, jint flag, jint callingUid) {
    ···
    if ( (status = sBluetoothSocketInterface->connect((bt_bdaddr_t *) addr, (btsock_type_t) type,
                       (const uint8_t*) uuid, channel, &socket_fd, flag, callingUid))
            != BT_STATUS_SUCCESS) {
        ALOGE("Socket connection failed: %d", status);
        goto Fail;
    }
    ···
    return socket_fd;//sBluetoothSocketInterface->connect函数将socket_fd传进去并被赋值

Fail:
    if (addr) env->ReleaseByteArrayElements(address, addr, 0);
    if (uuid) env->ReleaseByteArrayElements(uuidObj, uuid, 0);

    return -1;
}


这里sBluetoothSocketInterface->connect其实就是进入了HAL层

HAL层 --- bluetooth.default.so

system\bt

1.在分析HAL层代码之前,我们先搞清楚jni怎么关联上HAL成的

讲解sBluetoothSocketInterface->connect之前,我们先了解一下sBluetoothSocketInterface的由来

1.在jni的initNative初始化
static bool initNative(JNIEnv* env, jobject obj) {
    ALOGV("%s:",__FUNCTION__);
    ···
    if ( (sBluetoothSocketInterface = (btsock_interface_t *)
                  sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID)) == NULL) {
                ALOGE("Error getting socket interface");
        }
    ···
    return JNI_FALSE;
}
要弄清楚sBluetoothSocketInterface,则一定要弄清楚sBluetoothInterface

2.在jni的classInitNative初始化
static void classInitNative(JNIEnv* env, jclass clazz) {
    int err;
    hw_module_t* module;
    ····
    if (!strncmp(type, "RTL", 3)) {
        ALOGD("%s, load %s.default.so", __func__, BT_STACK_RTK_MODULE_ID);
        err = hw_get_module(BT_STACK_RTK_MODULE_ID, (hw_module_t const**)&module);
    } else {
        ALOGD("%s, load %s.default.so", __func__, id);
        err = hw_get_module(id, (hw_module_t const**)&module);
    }

    if (err == 0) {
        hw_device_t* abstraction;
        err = module->methods->open(module, id, &abstraction);//关键点1
        if (err == 0) {
            bluetooth_module_t* btStack = (bluetooth_module_t *)abstraction;
            sBluetoothInterface = btStack->get_bluetooth_interface();//通过btStack获取
        } else {
           ALOGE("Error while opening Bluetooth library");
        }
    } else {
        ALOGE("No Bluetooth Library found");
    }
}
想要弄清楚sBluetoothInterface的来路,则一定要弄清楚btStack的来源

2.真正HAL层代码来了。btStack的来源就是Android标准的JNI到HAL层架构方式

注意:
blutooth.default.so的源码来自system/bt

1)查看bluetooth.c
static int open_bluetooth_stack(const struct hw_module_t *module, UNUSED_ATTR char const *name, struct hw_device_t **abstraction) {
  static bluetooth_device_t device = {
    .common = {
      .tag = HARDWARE_DEVICE_TAG,
      .version = 0,
      .close = close_bluetooth_stack,
    },
    .get_bluetooth_interface = bluetooth__get_bluetooth_interface
  };

  device.common.module = (struct hw_module_t *)module;
  *abstraction = (struct hw_device_t *)&device;//abstraction就是btStack
  return 0;
}

static struct hw_module_methods_t bt_stack_module_methods = {
    .open = open_bluetooth_stack,//关键点1的真实调用方法open_bluetooth_stack
};

a)btStack调用get_bluetooth_interface,其实调用的是bluetooth__get_bluetooth_interface

b)bluetoothInterface的来源
const bt_interface_t* bluetooth__get_bluetooth_interface ()
{
    /* fixme -- add property to disable bt interface ? */

    return &bluetoothInterface;
}

bluetoothInterface的结构体bt_interface_t

c)查看bt_interface_t
static const bt_interface_t bluetoothInterface = {
    ···
    get_profile_interface,
    ···
};

3.至此已经解锁sBluetoothInterface的来源,反推sBluetoothSocketInterface的来源

sBluetoothSocketInterface = (btsock_interface_t *)
                  sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID)
static const void* get_profile_interface (const char *profile_id)
{
    ···
    if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID))
        return btif_sock_get_interface();
    ···
    return NULL;
}

btif_sock.c
btsock_interface_t *btif_sock_get_interface(void) {
  static btsock_interface_t interface = {
    sizeof(interface),
    btsock_listen,
    btsock_connect
  };
  return &interface;
}

bt_sock.h
typedef struct {
    /** set to size of this struct*/
    size_t          size;

    bt_status_t (*listen)(btsock_type_t type, const char* service_name,
            const uint8_t* service_uuid, int channel, int* sock_fd, int flags, int callingUid);

    bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t* uuid,
            int channel, int* sock_fd, int flags, int callingUid);
} btsock_interface_t

connect 对应到 btsock_connect

4.至此已经来到HAL层的connect处

btif_sock.c

static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t *uuid, int channel, int *sock_fd, int flags, int app_uid) {
  ···
  bt_status_t status = BT_STATUS_FAIL;

  switch (type) {
    case BTSOCK_RFCOMM://选择此通道
      status = btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags, app_uid);
      break;
    ···
  }
  return status;
}


bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t *service_uuid, int channel, int *sock_fd, int flags, int app_uid) {
  ···
  *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
  slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
  slot->app_uid = app_uid;
  btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);//发数据发送出去
  status = BT_STATUS_SUCCESS;

out:;
  pthread_mutex_unlock(&slot_lock);
  return status;
}


btif_sock_thread.c 发送数据
int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id)
{
    ···
    OSI_NO_INTR(ret = send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0));//socket发送数据

    return ret == sizeof(cmd);
}

总结

1.apk -- jni -- hal 整个过程有很多Android定制的代码实现的框架格式
2.弄清楚基础的框架格式,再分析源码的流程就方便很多
3.跨设备,其实通信用的就是socket

demo案例

1.development\samples\BluetoothChat
2.https://github.com/googlearchive/android-BluetoothChat#readme
3.https://blog.csdn.net/mo_android/article/details/76472824

你可能感兴趣的:(Android之Bluetooth通信-经典蓝牙通信BluetoothSocket)