android Ble開(kāi)發(fā)的那些事(一)
android Ble開(kāi)發(fā)的那些事(二)
android Ble開(kāi)發(fā)的那些事(三)--Ble數(shù)據(jù)分包處理
android Ble開(kāi)發(fā)的那些事(四)—— OTA升級(jí)
前一篇文章說(shuō)到要貼自己的相關(guān)代碼煤篙,這篇開(kāi)始會(huì)結(jié)合代碼一起和大家一起分享。要開(kāi)始講數(shù)據(jù)的傳輸了,先講講GATT吧纸巷。
什么是GATT燎斩?
GATT的全名是Generic Attribute Profile(暫且翻譯成:普通屬性協(xié)議)匕垫,它定義兩個(gè)BLE設(shè)備通過(guò)叫做Service和Characteristic的東西進(jìn)行通信雏门。GATT就是使用了ATT(Attribute Protocol)協(xié)議泞莉,ATT協(xié)議把Service鼎姐、 Characteristic遺跡對(duì)應(yīng)的數(shù)據(jù)保存在一個(gè)查找表中钾麸,次查找表使用16 bit ID作為每一項(xiàng)的索引更振。一旦兩個(gè)設(shè)備建立起了連接,GATT就開(kāi)始起作用了饭尝,這也意味著肯腕,你必需完成前面的GAP協(xié)議。這里需要說(shuō)明的是钥平,GATT連接乎芳,必需先經(jīng)過(guò)GAP協(xié)議。實(shí)際上帖池,我們?cè)贏ndroid開(kāi)發(fā)中奈惑,可以直接使用設(shè)備的MAC地址發(fā)起連接,可以不經(jīng)過(guò)掃描的步驟睡汹。這并不意味不需要經(jīng)過(guò)GAP肴甸,實(shí)際上在芯片級(jí)別已經(jīng)給你做好了,藍(lán)牙芯片發(fā)起連接囚巴,總是先掃描設(shè)備原在,掃描到了才會(huì)發(fā)起連接。
GATT 連接需要特別注意的是:GATT連接是獨(dú)占的彤叉。也就是一個(gè) BLE 外設(shè)同時(shí)只能被一個(gè)中心設(shè)備連接庶柿。一旦外設(shè)被連接,它就會(huì)馬上停止廣播秽浇,這樣它就對(duì)其他設(shè)備不可見(jiàn)了浮庐。當(dāng)設(shè)備斷開(kāi),它又開(kāi)始廣播柬焕。中心設(shè)備和外設(shè)需要雙向通信的話审残,唯一的方式就是建立GATT連接。
由上圖可以看出:
- 一個(gè)低功耗藍(lán)牙(ble)可以包括多個(gè)Profile
- 一個(gè)Profile中有多個(gè)Service(通過(guò)uuid就可以找到對(duì)應(yīng)的Service)
- 一個(gè)Service中有多個(gè)Characteristic(通過(guò)uuid就可以找到對(duì)應(yīng)的Characteristic)
- 一個(gè)Characteristic中包括一個(gè)value和多個(gè)Descriptor(通過(guò)uuid就可以找到對(duì)應(yīng)的Descriptor)
如何開(kāi)發(fā)Ble斑举?
在整個(gè)Ble開(kāi)發(fā)中搅轿,我有使用別人比較優(yōu)秀的第三方庫(kù)輔助開(kāi)發(fā),推薦這個(gè)庫(kù):https://github.com/litesuits/android-lite-bluetoothLE 富玷, 開(kāi)發(fā)起來(lái)真的很方便璧坟,使用也比較簡(jiǎn)單。
1. 準(zhǔn)備工作
(1) 聲明權(quán)限
<!-- 應(yīng)用使用藍(lán)牙的權(quán)限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 掃描藍(lán)牙設(shè)備或者操作藍(lán)牙設(shè)置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
(2) 添加lite-ble-0.9.2.jar庫(kù)到工程中
這步應(yīng)該不用講解怎么添加了吧赎懦。
(3) 檢測(cè)藍(lán)牙是否打開(kāi)并且創(chuàng)建藍(lán)牙操作的對(duì)象
private LiteBluetooth liteBluetooth;
// 檢查當(dāng)前手機(jī)是否支持ble 藍(lán)牙,如果不支持退出程序
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
}
// 初始化 Bluetooth adapter, 通過(guò)藍(lán)牙管理器得到一個(gè)參考藍(lán)牙適配器(API必須在以上android4.3或以上和版本)
// 1.獲取bluetoothAdapter
final BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// 2.檢查設(shè)備上是否支持并開(kāi)啟藍(lán)牙
if (mBluetoothAdapter == null) {
Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
return;
}
//創(chuàng)建liteBluetooth的單例對(duì)象雀鹃,(BleUtil是自己寫(xiě)的類,實(shí)現(xiàn)單例的)
if (liteBluetooth == null)
liteBluetooth = BleUtil.getInstance(getApplicationContext());
// 為了確保設(shè)備上藍(lán)牙能使用, 如果當(dāng)前藍(lán)牙設(shè)備沒(méi)啟用,彈出對(duì)話框向用戶要求授予權(quán)限來(lái)啟用
//liteBluetooth.enableBluetoothIfDisabled(activity,REQUEST_ENABLE_BT);
2. 搜索設(shè)備
private void scanDevicesPeriod() {
//liteBluetooth = new LiteBluetooth(getBaseContext());
liteBluetooth.startLeScan(new PeriodScanCallback(SCAN_PERIOD) {
@Override
public void onScanTimeout() {
//超過(guò)搜索時(shí)間后的相關(guān)操作
}
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
//搜到的設(shè)備
if (Math.abs(rssi) <= 90 ){//過(guò)濾掉信號(hào)強(qiáng)度小于-90的設(shè)備
Log.i("test scan", "device: " + device.getName() + " mac: "+ device.getAddress()
+ " rssi: " + rssi + " scanRecord: " + DeviceBytes.byte2hex(scanRecord));
}
}
});
}
- SCAN_PERIOD:搜索的時(shí)長(zhǎng)铲敛,毫秒數(shù)
- ble的mac地址:通過(guò)device.getAddress()就可以得到了
- scanRecord:Ble廣播的數(shù)據(jù)(DeviceBytes是自己寫(xiě)的工具類褐澎,有空分享出來(lái))
這就搜索到設(shè)備啦,而且還打印出來(lái)了伐蒋,是不是so easy啊~
3. 連接設(shè)備(首次連接)
一旦獲取到GATT的Services工三,就可以讀寫(xiě)他們的屬性了
private void connect(final BluetoothDevice device){
liteBluetooth.connect(device, false, new LiteBleGattCallback() {
@Override
public void onConnectSuccess(BluetoothGatt bluetoothGatt, int i) {
bluetoothGatt.discoverServices();
//連接成功后迁酸,還需要發(fā)現(xiàn)服務(wù)成功后才能進(jìn)行相關(guān)操作
}
@Override
public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
BluetoothUtil.printServices(bluetoothGatt);//把服務(wù)打印出來(lái)
//服務(wù)發(fā)現(xiàn)成功后,我們就可以進(jìn)行數(shù)據(jù)相關(guān)的操作了俭正,比如寫(xiě)入數(shù)據(jù)奸鬓、開(kāi)啟notify等等
}
@Override
public void onConnectFailure(BleException e) {
bleExceptionHandler.handleException(e);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//開(kāi)啟notify之后,我們就可以在這里接收數(shù)據(jù)了掸读。
//處理數(shù)據(jù)也是需要注意的串远,在我們項(xiàng)目中需要進(jìn)行類似分包的操作,感興趣的我以后分享
Log.i("notify", "onCharacteristicChanged: "+ DeviceBytes.byte2hex(characteristic.getValue()));
super.onCharacteristicChanged(gatt, characteristic);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//當(dāng)我們對(duì)ble設(shè)備寫(xiě)入相關(guān)數(shù)據(jù)成功后儿惫,這里也會(huì)被調(diào)用
Log.i("test", "onCharacteristicWrite: "+ DeviceBytes.byte2hex(characteristic.getValue()));
super.onCharacteristicWrite(gatt, characteristic, status);
}
});
}
4. 連接設(shè)備(二次重連)
實(shí)現(xiàn)二次重連也挺簡(jiǎn)單的澡罚,在第一次連接成功的會(huì)掉函數(shù)中,我們把設(shè)備的mac地址保存下來(lái)肾请,二次重連的時(shí)候直接把mac地址傳進(jìn)去就好了留搔。
private void scanAndConnect(final String mac) {
liteBluetooth.scanAndConnect(mac, false, new LiteBleGattCallback() {//默認(rèn)搜20s
@Override
public void onConnectSuccess(BluetoothGatt bluetoothGatt, int i) {
bluetoothGatt.discoverServices();
//連接成功后,還需要發(fā)現(xiàn)服務(wù)成功后才能進(jìn)行相關(guān)操作
}
@Override
public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
BluetoothUtil.printServices(bluetoothGatt);//把服務(wù)打印出來(lái)
//服務(wù)發(fā)現(xiàn)成功后铛铁,我們就可以進(jìn)行數(shù)據(jù)相關(guān)的操作了隔显,比如寫(xiě)入數(shù)據(jù)、開(kāi)啟notify等等
}
@Override
public void onConnectFailure(BleException e) {
bleExceptionHandler.handleException(e);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//開(kāi)啟notify之后饵逐,我們就可以在這里接收數(shù)據(jù)了括眠。
//處理數(shù)據(jù)也是需要注意的,在我們項(xiàng)目中需要進(jìn)行類似分包的操作倍权,感興趣的我以后分享
Log.i("notify", "onCharacteristicChanged: "+ DeviceBytes.byte2hex(characteristic.getValue()));
super.onCharacteristicChanged(gatt, characteristic);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//當(dāng)我們對(duì)ble設(shè)備寫(xiě)入相關(guān)數(shù)據(jù)成功后掷豺,這里也會(huì)被調(diào)用
Log.i("test", "onCharacteristicWrite: "+ DeviceBytes.byte2hex(characteristic.getValue()));
super.onCharacteristicWrite(gatt, characteristic, status);
}
});
}
5. 開(kāi)啟notify接收數(shù)據(jù)
如果設(shè)備主動(dòng)給手機(jī)發(fā)信息,則可以通過(guò)notification的方式账锹,這種方式不用手機(jī)去輪詢地讀設(shè)備上的數(shù)據(jù)萌业。手機(jī)可以用如下方式給設(shè)備設(shè)置notification功能。如果notificaiton方式對(duì)于某個(gè)Characteristic是enable的奸柬,那么當(dāng)設(shè)備上的這個(gè)Characteristic改變時(shí),手機(jī)上的[onCharacteristicChanged()](http://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic))回調(diào)就會(huì)被促發(fā)婴程。
我嘗試調(diào)用那個(gè)庫(kù)的方法來(lái)開(kāi)啟notify廓奕,但始終沒(méi)有成功,所以索性自己寫(xiě)了档叔。原理不難桌粉,也是一步步的通過(guò)uuid找到服務(wù)、在服務(wù)中通過(guò)uuid找Characteristic衙四、再通過(guò)uuid找到Descriptor铃肯。有沒(méi)有覺(jué)得很熟悉?就是文章一開(kāi)始放的那張圖传蹈!嘿嘿是不是就理解了
//uuid需要替換成項(xiàng)目中使用的uuid押逼,這只是舉個(gè)例子
private static final String serviceid = "0000fee7-0000-1000-8000-00805f9b34fb";
private static final String charaid = "0000feaa-0000-1000-8000-00805f9b34fb";
private static final String notifyid = "00001202-0000-1000-8000-00805f9b34fb";
private void enableNotificationOfCharacteristic(final boolean enable) {
UUID ServiceUUID = UUID.fromString(serviceid);
UUID CharaUUID = UUID.fromString(charaid);
if(!mBluetoothGatt.equals(null)){
BluetoothGattService service = mBluetoothGatt.getService(ServiceUUID);
if(service != null){
BluetoothGattCharacteristic chara= service.getCharacteristic(CharaUUID);
if(chara != null){
boolean success = mBluetoothGatt.setCharacteristicNotification(chara,enable);
Log.i("success", "setCharactNotify: "+success);
BluetoothGattDescriptor descriptor = chara.getDescriptor(UUID.fromString(notifyid));
if (descriptor != null){
if (enable) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
} else {
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
SystemClock.sleep(200);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
}
}
}
6. 寫(xiě)入數(shù)據(jù)
private void writeDataToCharacteristic(byte[] value) {
if (liteBluetooth.isServiceDiscoered()){
LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(serviceid, get_write_charaid, null)
.writeCharacteristic(connector.getCharacteristic(), value, new BleCharactCallback() {
@Override
public void onSuccess(BluetoothGattCharacteristic characteristic) {
// BleLog.i(TAG, "Write Success, DATA: " + DeviceBytes.byte2hex(characteristic.getValue()));
}
@Override
public void onFailure(BleException exception) {
BleLog.i(TAG, "Write failure: " + exception);
bleExceptionHandler.handleException(exception);
}
});
}else {
return;
}
}
7. 關(guān)閉連接
if (liteBluetooth.isConnectingOrConnected()) {
liteBluetooth.closeBluetoothGatt();
}
在藍(lán)牙的數(shù)據(jù)收發(fā)過(guò)程中步藕,幾乎都是用byte[]數(shù)組來(lái)進(jìn)行的,那么我們調(diào)試保存的數(shù)據(jù)難免會(huì)為數(shù)據(jù)格式的轉(zhuǎn)換而各種百度挑格,下面和大家分享下我項(xiàng)目中用到的一些方法~
數(shù)據(jù)格式轉(zhuǎn)化的工具類
1. 兩個(gè)byte -->int
private int byteToInt(byte b, byte c) {//計(jì)算總包長(zhǎng)咙冗,兩個(gè)字節(jié)表示的
short s = 0;
int ret;
short s0 = (short) (c & 0xff);// 最低位
short s1 = (short) (b & 0xff);
s1 <<= 8;
s = (short) (s0 | s1);
ret = s;
return ret;
}
2. int -->兩個(gè)byte
private byte[] int2byte(int res) {
byte[] targets = new byte[2];
targets[1] = (byte) (res & 0xff);// 最低位
targets[0] = (byte) ((res >> 8) & 0xff);// 次低位
return targets;
}
3. 16進(jìn)制字符串 -->byte[ ]
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
4. byte[ ] -->16進(jìn)制字符串
public static String byte2hex(byte [] buffer){
String h = "";
for(int i = 0; i < buffer.length; i++){
String temp = Integer.toHexString(buffer[i] & 0xFF);
if(temp.length() == 1){
temp = "0" + temp;
}
h = h + temp;
}
return h;
}
Ble基本的操作幾乎都列出來(lái)了,下篇和大家分享低耗藍(lán)牙空中升級(jí)漂彤,網(wǎng)上的demo都太龐大了雾消,下次分享我實(shí)現(xiàn)的demo,代碼一定最少嘿嘿挫望。還有就是數(shù)據(jù)分包那部分立润,如果感興趣的可以留言給我,我看是否需要分享媳板。謝謝觀看
原創(chuàng)作品桑腮,如需轉(zhuǎn)載,請(qǐng)與作者聯(lián)系拷肌,否則將追究法律責(zé)任到旦。