Android BLE开发: BLE Peripheral开发流程

Android从lolipop开始支持了BLE Peripheral开发。网上也有关于Framework的文章。真的关于应用开发的确不多,google官网也只给出了一个Central的Demo。之前做了一个BLE Peripheral的Demo,这里将Peripheral开发的一些流程简单整理一下。不多说,直接上代码。

初始化

//初始化BluetoothManager和BluetoothAdapter
if(mBluetoothManager == null)
    mBluetoothManager = (BluetoothManager) mActivity.
                        getSystemService(Context.BLUETOOTH_SERVICE);

if (mBluetoothManager != null && mBluetoothAdapter == null) {
    mBluetoothAdapter = mBluetoothManager.getAdapter();
}

//打开蓝牙的套路
if ((mBluetoothAdapter == null) || (!mBluetoothAdapter.isEnabled())) {
    Toast.makeText(mActivity, R.string.bt_unavailable, Toast.LENGTH_SHORT).show();
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    mActivity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

开始广播

//获取BluetoothLeAdvertiser,BLE发送BLE广播用的一个API
if (mBluetoothAdvertiser == null) {
    mBluetoothAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
}
//创建BluetoothGattServerCallback,
//MockServerCallBack这个类继承自BluetoothGattServerCallback
//后面会贴出MockServerCallBack这个类的代码
//BluetoothGattServerCallback这个回调类主要是一些BLE读写的接口
//关于BLE读写的操作都在这个Callback中完成
if (mBluetoothAdvertiser != null) {
    mMockServerCallBack = new MockServerCallBack(mActivity);
    //打开BluetoothGattServer
    mGattServer = mBluetoothManager.openGattServer(mActivity, mMockServerCallBack);
    if(mGattServer == null){
        Log.d(TAG , "gatt is null");
    }
    try{
        mMockServerCallBack.setupServices(mGattServer);
        //创建BLE Adevertising并且广播
        mBluetoothAdvertiser.startAdvertising(createAdvSettings(true, 0), createFMPAdvertiseData(),mAdvCallback);
    }catch(InterruptedException e){
        Log.v(TAG, "Fail to setup BleService");
    }
}

创建Advertising

public static AdvertiseSettings createAdvSettings(boolean connectable, int timeoutMillis) {
    AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
    //设置广播的模式,应该是跟功耗相关
    builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
    builder.setConnectable(connectable);
    builder.setTimeout(timeoutMillis);
    builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
    return builder.build();
}

//设置一下FMP广播数据
public static AdvertiseData createFMPAdvertiseData() {
    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    builder.setIncludeDeviceName(true);
    AdvertiseData adv = builder.build();
    return adv;
}

//发送广播的回调,onStartSuccess/onStartFailure很明显的两个Callback
private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
    public void onStartSuccess(android.bluetooth.le.AdvertiseSettings settingsInEffect) {
        if (settingsInEffect != null) {
            Log.d(TAG, "onStartSuccess TxPowerLv="+ settingsInEffect.getTxPowerLevel()+ " mode=" + settingsInEffect.getMode()+ " timeout=" + settingsInEffect.getTimeout());
        } else {
            Log.d(TAG, "onStartSuccess, settingInEffect is null");
        }
    }

    public void onStartFailure(int errorCode) {
        Log.d(TAG, "onStartFailure errorCode=" + errorCode);
    };
};

BLE需要的BluetoothGattServerCallback

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.util.Log;

public class MockServerCallBack extends BluetoothGattServerCallback {
    private static final String TAG = "BleServer";
    private byte[] mAlertLevel = new byte[] {(byte) 0x00};
    private Activity mActivity;
    private HomePager mHomepager;
    private boolean mIsPushStatic = false;
    private BluetoothGattServer mGattServer;
    private BluetoothGattCharacteristic mDateChar;
    private BluetoothDevice btClient;
    private BluetoothGattCharacteristic mHeartRateChar;
    private BluetoothGattCharacteristic mTemperatureChar;
    private BluetoothGattCharacteristic mBatteryChar;
    private BluetoothGattCharacteristic mManufacturerNameChar;
    private BluetoothGattCharacteristic mModuleNumberChar;
    private BluetoothGattCharacteristic mSerialNumberChar;

    public void setupServices(BluetoothGattServer gattServer) throws InterruptedException{
        if (gattServer == null) {
            throw new IllegalArgumentException("gattServer is null");
        }
        mGattServer = gattServer;
        // 设置一个GattService以及BluetoothGattCharacteristic 
        { 
            //immediate alert
            BluetoothGattService ias = new BluetoothGattService( UUID.fromString(IMXUuid.SERVICE_IMMEDIATE_ALERT),
                    BluetoothGattService.SERVICE_TYPE_PRIMARY);
            //alert level char.
            BluetoothGattCharacteristic alc = new BluetoothGattCharacteristic(
                    UUID.fromString(IMXUuid.CHAR_ALERT_LEVEL),
                    BluetoothGattCharacteristic.PROPERTY_READ |BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_NOTIFY ,
                    BluetoothGattCharacteristic.PERMISSION_READ |BluetoothGattCharacteristic.PERMISSION_WRITE);
            alc.setValue("");
            ias.addCharacteristic(alc);
            if(mGattServer!=null && ias!=null)
                mGattServer.addService(ias);
        }
    }

    //当添加一个GattService成功后会回调改接口。
    public void onServiceAdded(int status, BluetoothGattService service) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.d(TAG, "onServiceAdded status=GATT_SUCCESS service=" + service.getUuid().toString());
        } else {
            Log.d(TAG, "onServiceAdded status!=GATT_SUCCESS");
        }
    }

    //BLE连接状态改变后回调的接口
    public void onConnectionStateChange(android.bluetooth.BluetoothDevice device, int status,
            int newState) {
        Log.d(TAG, "onConnectionStateChange status=" + status + "->" + newState);
    }

    //当有客户端来读数据时回调的接口
    public void onCharacteristicReadRequest(android.bluetooth.BluetoothDevice device,
            int requestId, int offset, BluetoothGattCharacteristic characteristic) {
        Log.d(TAG, "onCharacteristicReadRequest requestId=" 
                    + requestId + " offset=" + offset);
        mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset,characteristic.getValue());
    }

    //当有客户端来写数据时回调的接口
    @Override
    public void onCharacteristicWriteRequest(android.bluetooth.BluetoothDevice device,
            int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite,
            boolean responseNeeded, int offset, byte[] value) {
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null);
    }

    //当有客户端来写Descriptor时回调的接口
    @Override
    public void onDescriptorWriteRequest (BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {

        btClient = device;
        Log.d(TAG, "onDescriptorWriteRequest");
        // now tell the connected device that this was all successfull
        mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
    }
}

至此,BLE Peripheral发送广播所需要的工作都完成了,并且当有Central设备读写该Peripheral设备时候也能通过BluetoothGattServerCallback回调到。

停止广播

//关闭BluetoothLeAdvertiser,BluetoothAdapter,BluetoothGattServer 
if (mBluetoothAdvertiser != null) {
    mBluetoothAdvertiser.stopAdvertising(mAdvCallback);
    mBluetoothAdvertiser = null;
}

if(mBluetoothAdapter != null){
    mBluetoothAdapter = null;
}

if (mGattServer != null) {
    mGattServer.clearServices();
    mGattServer.close();
}       

这样,Android设备就停止了BLE的广播,外部的Central设备就搜索不到该设备并且连接上它了。
BLE Peripheral的API乍一看有些多,其实仔细理一理非常简单,工作重点在于那个Callback的编写。

猜你喜欢

转载自blog.csdn.net/u011280717/article/details/51820879