何为蓝牙

蓝牙是一种短距离无线传输技术,使用ISM 2.4GHz频段(2400-2483.5MHz),为避免此频段的其它设备干扰,采用每秒1600次跳频技术。 目前根据传输距离的远近,分为3类。

  • Class1 100米左右 100mW
  • Class2 10米左右 2.5mW 键鼠产品
  • Class3 1米左右 1mW

蓝牙基本架构

总体上分3层,从上到下分别为应用端、主机和控制器。

  • 应用端(Apps)
  • 主机(Host)
  • 控制器(Controller)
    实现射频相关的模拟和数字部分,完成最基本的数据发送和接收,对外接口是天线,对内接口是HCI(Host Controller Interface).
    包含PHY(Physical Layer)、LL(Linker Layer)、DTM(Direct Test Mode).

Bluetooth architecture

协议文档


Android平台的实现

权限

AndroidManifest.xml需要添加以下权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

蓝牙APIs提供的功能

  • 搜索其它蓝牙设备,包括BLE设备
  • 查询与本地蓝牙适配器配对的设备
  • 建立RFCOMM channels
  • 与其它设备建立连接
  • 与其它设备传输数据

基本概念

蓝牙设备之间要传输数据,首先要用配对流程(pairing process)建立通信信道。 一个设备必须是discoverable device,另一个设备使用服务发现流程(service discovery process)来发现该设备,然后发起连接请求,可发现设备接受该请求后,两个设备就完成了bonding流程。这一流程会交换安全密钥,设备会将它缓存在本地以便将来使用。当session完成之后,发起配对请求的设备会释放掉之前建立起来的信道。

获取BluetoothAdapter getDefaultAdapter

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // 如果返回的Adapter为null,表示设备不支持蓝牙
}

Enable Bluetooth

if (!mBluetoothAdapter.isEnabled()) {
    // 通过以下代码,会弹出一个对话框请求打开蓝牙,“A app wants to turn Bluethooth ON for this device.”
    Intent enableBtIntent = new
        Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

获取已配对设备 getBondedDevices

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) {
    // There are paired devices. Get the name and address of each paired device.
    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress();
    }
}

发现其它设备 startDiscovery

该流程是异步的,应用需要注册ACTION_FOUND广播,当发现设备时,系统会发送该广播。 广播的intent会包含EXTRA_DEVICE和EXTRA_CLASS字段,分别表示BluetoothDevice和BluetoothClass。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device =
                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress();
        }
    }
};

让自身可被发现

默认的可发现时间为120秒,也可以通过EXTRA_DISCOVERABLE_DURATION定义不同的时间间隔,最大为3600秒。

Intent discoverableIntent =
        new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

可注册ACTION_SCAN_MODE_CHANGED,来观察discoverable mode的变化。这个intent里面包含EXTRA_SCAN_MODE和EXTRA_PREVIOUS_SCAN_MODE字段,分别表示新的和之前的扫描模式。

extra字段可能为如下的值:

  • SCAN_MODE_CONNECTABLE_DISCOVERABLE
    The device is in discoverable mode.
  • SCAN_MODE_CONNECTABLE
    The device is not in discoverable mode but can still receive connections.
  • SCAN_MODE_NONE
    The device is not in discoverable mode and cannot receive connections.

基本Profile

  • A2DP (Advanced Audi​​o Distribution Profile)
  • AVRCP (Audio/Video Remote Control Profile)
  • BIP (Basic Imaging Profile)
  • HFP (Hands-Free Profile)
  • HSP (Headset Profile)
  • MAP (Message Access Profile)
  • PBAP (Phone Book Access Profile)
Profile Roles Details
A2DP SNK/SRC Sink/Source
AVRCP CT/TG Controller/Target
BIP Imaging Initiator/Imaging Responder  
HFP HF/AG Hands-Free unit/Audio Gateway
HSP HS/AG Headset/Audio Gateway
MAP MCE/MSE Message Client Equipment/Message Server Equipment
PBAP PCE/PSE Phone Book Client Equipment/Phone Book Server Equipment

Protocol Specification

AVCTP A/V Control Transport Protocol _transport command and response messages for controlling Audio Video features_
AVDTP A/V Distribution Transport Protocol _defines A/V stream negotiation, establishment, and transmission procedures. specify the message formats that are exchanged between such devices to transport their A/V streams._
RFCOMM _provides emulation of serial ports over the L2CAP protocol_

工具