蓝牙之二十二-BLE

来源:互联网 发布:java 获取url视频时长 编辑:程序博客网 时间:2024/05/16 06:33

Bluetooth Low Energy(以下简称LE),使用2.4GHz ISM信号进行通信,采用跳频接收以抗干扰和衰减。传输速率带宽是1Mb/s。

频带和通道

LE频带是2.4GHz-2483.5MHz,40channel,channel的中心频率是2402+K×2MHz,(K=0,...,39)

发射器特性

LE使用两种接入策略FDMA(Frequency division multiple access)和TDMA(time division multiple access)。

频分复用是分成40个物理通道,由2MHz间隔,时分复用是基于轮询的策略,数据传输和对应的应答都在预先设定的时间发生。

时域把物理通道分成时间单位,称为events。有两种类型的event,广播和连接事件。

advertiser在广播PHY传输广播数据包的设备。

scanner在广播通道上接收广播包而并没有打算去连接广播设备的设备

广播事件

initiator:和处于监听设备建立连接的设备

一旦连接建立,处于监听的设备将变成master,而广播的设备变成slave。

连接事件

处于piconet的设备使用特定的跳频方式,调频算法由一个发起设备在连接设备请求阶段发出的一个字段决定。

PDU protocol data unit。

BLE Physical layer

BLE模块可以包括发射器和接收器,或者只有一个。

发射器特性

调制特性

高斯频移键控Gaussian Frequency Shift Keying(GFSK),其带宽周期乘积BT=0.5。调制的索引介于0.45~0.55之间。

BLE专有名词

Generic Attribute Profile (GATT)-GATT profile是发送和接收通过BLE link传输的“attributes”短数据包通用规范。当前所有的LE应用profile基于GATT。

Attribute Protocol (ATT)—GATT是建立在Attribute Protocol(ATT)之上的协议,通常成为GATT/ATT。ATT是针对BLE设备优化的协议。每一个attribute由UUID唯一标识,UUID通常是128-bit格式。ATT传输的attribute被格式化为characteristics和service

Characteristic—包含一个值以及0-n描述特性值的描述符;

Descriptor—描述符用于描述attribute的characteristics值。

Service—是属性的集合。

Roles and Responsibilities

  • Central vs. peripheral.这用于BLE自身连接。中心角色的设备负责扫描,查找广播的设备,而peripheral设备发送广播。
  • GATT server vs. GATT client。用于描述建立连接的设备之间是如何交互的。

BLE权限

应用程序为了使用Bluetooth特性,应用程序必须请求Bluetooth权限BLUETOOTH。

如果应用程序要发起设备发现或者操作蓝牙设置,还需要声明BLUETOOTH_ADMIN权限。

在manifest文件申请权限

<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
如果想要app只在具有BLE能力的设备上运行,则需要在manifest中做如下声明:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
如果想在不具有BLE能力的设备上也使用该app,则要做如下声明

<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
在运行时可以使用PackageManager.hasSystemFeature()检测是否具有BLE能力。

// Use this check to determine whether BLE is supported on the device. Then// you can selectively disable BLE-related features.if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();    finish();}

设置BLE

在应用程序能够使用BLE方式进行通信时,需要确定设备是支持BLE的,并且BLE使能了。如果<uses-feature.../>设置成了false,则需要进行检查。

如果设备支持BLE,但是disable了,则应用程序可以请求用户使能蓝牙。这个过程使用BluetoothAdapter两个步骤完成。

1.获得BlueoothAdapter

任何蓝牙activity需要申请BluetoothAdapter。BluetoothAdapter代表了拥有了蓝牙适配器的设备。

// Initializes Bluetooth adapter.final BluetoothManager bluetoothManager =        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter = bluetoothManager.getAdapter();

2,使能Bluetooth

接下来需要确认蓝牙是使能的,这可以使用isEnabled()方法检查。如果没有使能,则弹窗提示用户使能。

    private BluetoothAdapter mBluetoothAdapter;    ...    // Ensures Bluetooth is available on the device and it is enabled. If not,    // displays a dialog requesting user permission to enable Bluetooth.    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);    }

搜索BLE设备

使用startLeScan()方法索BLE设备,该方法的参数是BluetoothAdapter.LeScanCallback,应用程序必须实现这个回调函数,因为这指明了扫描结果是如何返回的。因为扫描比较耗电,最好遵循如下指导:

1.一旦发现需要的设备,停止扫描。

2.不要循环扫描,设置扫描时限

/** * Activity for scanning and displaying available BLE devices. */public class DeviceScanActivity extends ListActivity {    private BluetoothAdapter mBluetoothAdapter;    private boolean mScanning;    private Handler mHandler;    // Stops scanning after 10 seconds.    private static final long SCAN_PERIOD = 10000;    ...    private void scanLeDevice(final boolean enable) {        if (enable) {            // Stops scanning after a pre-defined scan period.            mHandler.postDelayed(new Runnable() {                @Override                public void run() {                    mScanning = false;                    mBluetoothAdapter.stopLeScan(mLeScanCallback);                }            }, SCAN_PERIOD);            mScanning = true;            mBluetoothAdapter.startLeScan(mLeScanCallback);        } else {            mScanning = false;            mBluetoothAdapter.stopLeScan(mLeScanCallback);        }        ...    }...}
如果想只扫描特定类型的BLE设备,可以提供UUID参数调用startLeScan(UUID[], BluetoothAdapter.LeScanCallback)方法进行扫描。
如下BluetoothAdapter.LeScanCallback,用于发送BLE扫描结果。

private LeDeviceListAdapter mLeDeviceListAdapter;...// Device scan callback.private BluetoothAdapter.LeScanCallback mLeScanCallback =        new BluetoothAdapter.LeScanCallback() {    @Override    public void onLeScan(final BluetoothDevice device, int rssi,            byte[] scanRecord) {        runOnUiThread(new Runnable() {           @Override           public void run() {               mLeDeviceListAdapter.addDevice(device);               mLeDeviceListAdapter.notifyDataSetChanged();           }       });   }};

连接GATT Server

和BLE设备交互的第一步是和其建立连接,也就是和GATT server建立连接。使用connectGatt()方法建立这种连接。该方法有三个参数:Context对象,autoConnect(bool值,用于指示是否自动连接),以及一个BluetoothGattCallback引用。

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

其返回BluetoothGatt实例,获得该实例后可以执行GATT client操作了。调用这(Android app)是GATT client。BluetoothGattCallback用于将结果返回给client,如连接状态等。

在这个例子中,BLE app提供一个activity(DeviceControlActivity)来连接,显示数据以及显示GATT服务和特性。基于用户输入,该activity与BluetoothLeService交互。

// A service that interacts with the BLE device via the Android BLE API.public class BluetoothLeService extends Service {    private final static String TAG = BluetoothLeService.class.getSimpleName();    private BluetoothManager mBluetoothManager;    private BluetoothAdapter mBluetoothAdapter;    private String mBluetoothDeviceAddress;    private BluetoothGatt mBluetoothGatt;    private int mConnectionState = STATE_DISCONNECTED;    private static final int STATE_DISCONNECTED = 0;    private static final int STATE_CONNECTING = 1;    private static final int STATE_CONNECTED = 2;    public final static String ACTION_GATT_CONNECTED =            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";    public final static String ACTION_GATT_DISCONNECTED =            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";    public final static String ACTION_GATT_SERVICES_DISCOVERED =            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";    public final static String ACTION_DATA_AVAILABLE =            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";    public final static String EXTRA_DATA =            "com.example.bluetooth.le.EXTRA_DATA";    public final static UUID UUID_HEART_RATE_MEASUREMENT =            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);    // Various callback methods defined by the BLE API.    private final BluetoothGattCallback mGattCallback =            new BluetoothGattCallback() {        @Override        public void onConnectionStateChange(BluetoothGatt gatt, int status,                int newState) {            String intentAction;            if (newState == BluetoothProfile.STATE_CONNECTED) {                intentAction = ACTION_GATT_CONNECTED;                mConnectionState = STATE_CONNECTED;                broadcastUpdate(intentAction);                Log.i(TAG, "Connected to GATT server.");                Log.i(TAG, "Attempting to start service discovery:" +                        mBluetoothGatt.discoverServices());            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {                intentAction = ACTION_GATT_DISCONNECTED;                mConnectionState = STATE_DISCONNECTED;                Log.i(TAG, "Disconnected from GATT server.");                broadcastUpdate(intentAction);            }        }        @Override        // New services discovered        public void onServicesDiscovered(BluetoothGatt gatt, int status) {            if (status == BluetoothGatt.GATT_SUCCESS) {                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);            } else {                Log.w(TAG, "onServicesDiscovered received: " + status);            }        }        @Override        // Result of a characteristic read operation        public void onCharacteristicRead(BluetoothGatt gatt,                BluetoothGattCharacteristic characteristic,                int status) {            if (status == BluetoothGatt.GATT_SUCCESS) {                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);            }        }     ...    };...}
不论哪个回调被触发,其调用broadcastUpdate()方法。本节数据格式的解析基于Bluetooth Heart RateMeasurement profile 规范。

private void broadcastUpdate(final String action) {    final Intent intent = new Intent(action);    sendBroadcast(intent);}private void broadcastUpdate(final String action,                             final BluetoothGattCharacteristic characteristic) {    final Intent intent = new Intent(action);    // This is special handling for the Heart Rate Measurement profile. Data    // parsing is carried out as per profile specifications.    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {        int flag = characteristic.getProperties();        int format = -1;        if ((flag & 0x01) != 0) {            format = BluetoothGattCharacteristic.FORMAT_UINT16;            Log.d(TAG, "Heart rate format UINT16.");        } else {            format = BluetoothGattCharacteristic.FORMAT_UINT8;            Log.d(TAG, "Heart rate format UINT8.");        }        final int heartRate = characteristic.getIntValue(format, 1);        Log.d(TAG, String.format("Received heart rate: %d", heartRate));        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));    } else {        // For all other profiles, writes the data formatted in HEX.        final byte[] data = characteristic.getValue();        if (data != null && data.length > 0) {            final StringBuilder stringBuilder = new StringBuilder(data.length);            for(byte byteChar : data)                stringBuilder.append(String.format("%02X ", byteChar));            intent.putExtra(EXTRA_DATA, new String(data) + "\n" +                    stringBuilder.toString());        }    }    sendBroadcast(intent);}

回到DeviceControlActivity,这些事件由BroadcastReceiver处理。

// Handles various events fired by the Service.// ACTION_GATT_CONNECTED: connected to a GATT server.// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.// ACTION_DATA_AVAILABLE: received data from the device. This can be a// result of read or notification operations.private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {    @Override    public void onReceive(Context context, Intent intent) {        final String action = intent.getAction();        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {            mConnected = true;            updateConnectionState(R.string.connected);            invalidateOptionsMenu();        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {            mConnected = false;            updateConnectionState(R.string.disconnected);            invalidateOptionsMenu();            clearUI();        } else if (BluetoothLeService.                ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {            // Show all the supported services and characteristics on the            // user interface.            displayGattServices(mBluetoothLeService.getSupportedGattServices());        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));        }    }};

获取BLE设备Attribute

一旦应用和GATT server建立连接。其可以读写attribute,如下代码片段迭代查询server的服务和特性并且用UI显示出来。

public class DeviceControlActivity extends Activity {    ...    // Demonstrates how to iterate through the supported GATT    // Services/Characteristics.    // In this sample, we populate the data structure that is bound to the    // ExpandableListView on the UI.    private void displayGattServices(List<BluetoothGattService> gattServices) {        if (gattServices == null) return;        String uuid = null;        String unknownServiceString = getResources().                getString(R.string.unknown_service);        String unknownCharaString = getResources().                getString(R.string.unknown_characteristic);        ArrayList<HashMap<String, String>> gattServiceData =                new ArrayList<HashMap<String, String>>();        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData                = new ArrayList<ArrayList<HashMap<String, String>>>();        mGattCharacteristics =                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();        // Loops through available GATT Services.        for (BluetoothGattService gattService : gattServices) {            HashMap<String, String> currentServiceData =                    new HashMap<String, String>();            uuid = gattService.getUuid().toString();            currentServiceData.put(                    LIST_NAME, SampleGattAttributes.                            lookup(uuid, unknownServiceString));            currentServiceData.put(LIST_UUID, uuid);            gattServiceData.add(currentServiceData);            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =                    new ArrayList<HashMap<String, String>>();            List<BluetoothGattCharacteristic> gattCharacteristics =                    gattService.getCharacteristics();            ArrayList<BluetoothGattCharacteristic> charas =                    new ArrayList<BluetoothGattCharacteristic>();           // Loops through available Characteristics.            for (BluetoothGattCharacteristic gattCharacteristic :                    gattCharacteristics) {                charas.add(gattCharacteristic);                HashMap<String, String> currentCharaData =                        new HashMap<String, String>();                uuid = gattCharacteristic.getUuid().toString();                currentCharaData.put(                        LIST_NAME, SampleGattAttributes.lookup(uuid,                                unknownCharaString));                currentCharaData.put(LIST_UUID, uuid);                gattCharacteristicGroupData.add(currentCharaData);            }            mGattCharacteristics.add(charas);            gattCharacteristicData.add(gattCharacteristicGroupData);         }    ...    }...}

接收GATT通知

在特定属性改变时。BLE app被要求通知server。这使用setCharacteristicNotification()实现。

private BluetoothGatt mBluetoothGatt;BluetoothGattCharacteristic characteristic;boolean enabled;...mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);...BluetoothGattDescriptor descriptor = characteristic.getDescriptor(        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(descriptor);
一旦对一些特性注册了通知,如果远端设备的特性变化,则会触发onCharacteristicChanged()回调函数。

@Override// Characteristic notificationpublic void onCharacteristicChanged(BluetoothGatt gatt,        BluetoothGattCharacteristic characteristic) {    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}

关闭Client App

调用close方法完成。

public void close() {    if (mBluetoothGatt == null) {        return;    }    mBluetoothGatt.close();    mBluetoothGatt = null;}

蓝牙5.0核心规范已发布,一些新特性如下:有效传输距离是4.2LE版本的4倍(理论上可达300米),传输速度将是4.2LE版本的2倍(速度上限为24Mbps)。蓝牙5.0还支持室内定位导航功能(结合WiFi可以实现精度小于1米的室内定位),允许无需配对接受信标的数据(比如广告、Beacon(点对多点)、位置信息等,传输率提高了8倍),针对物联网进行了很多底层优化。

client端示例下载地址:http://download.csdn.net/detail/shichaog/9707586



0 0