藍牙( Bluetooth® ):是一種無線技術標准,可實現固定設備、移動設備和樓宇個人域網之間的短距離數據交換(使用2.4—2.485GHz的ISM波段的UHF無線電波)。藍牙技術最初由電信巨頭
愛立信公司於1994年創制,當時是作為
RS232數據線的替代方案。藍牙可連接多個設備,克服了數據同步的難題。
如今藍牙由藍牙技術聯盟(Bluetooth Special Interest Group,簡稱SIG)管理。藍牙技術聯盟在全球擁有超過25,000家成員公司,它們分布在電信、計算機、網絡、和消費電子等多重領域。IEEE將藍牙技術列為IEEE 802.15.1,但如今已不再維持該標准。藍牙技術聯盟負責監督藍牙規范的開發,管理認證項目,並維護商標權益。制造商的設備必須符合藍牙技術聯盟的標准才能以“藍牙設備”的名義進入市場。藍牙技術擁有一套專利網絡,可發放給符合標准的設備。
一、藍牙的分類
目前為止藍牙分為兩類:一是經典藍牙(傳統藍牙),二是低功耗藍牙(BLE)。顧名思義低功耗藍牙功耗要比傳統藍牙低,所以廣泛使用在智能穿戴設備上。要使安卓設備連接上智能穿戴設備(如智能手表),通過經典藍牙的socket連接一般是連接不上的(為什么說一般呢,因為有些不良廠家和雜牌智能手環用的不是低功耗藍牙,這個可以使用經典藍牙連接上),必須要使用BLE的 GATT連接才能連接上。
二、GATT中的服務、特征值、描述、UUID
GATT連接涉及到四個比較陌生的名詞:服務(service)、特征值(Characteristic)、描述(discript)、UUID,下面以智能手環為例分別來解釋一下這些名詞是什么意思。
- service:服務是包含了若干個數據包(特征值)的集合,一個智能設備可能包含多個服務,使用之恩那個設備生產廠商提供的UUID碼來識別。比如之恩那個手環中有測心率的服務、步數的服務,心率和步數的數據包(特征值)都包含在服務中,通過指定的UUID來辨別到底是心率的服務還是步數的服務。
- characteristic:特征值包含在服務里面,顧名思義就是一種數據值,特征值包含一個或者多個描述。如心率是多少,今天走了多少步都可以放進特征值里面,服務中有多個特征值,也是通過UUID來識別
- discript:描述一般是對特征值的值進行描述,比如單位等等的描述,開發中一般用不到(我用不到)
- UUID:由藍牙設備廠商提供的UUID,UUID是在硬件編程里已經確定了的,想要草所特定的服務、特征值都需要通過UUID來找。
三、安卓中GATT的操作
和經典藍牙最開始一樣,要檢測藍牙是否可用和藍牙是否打開,這部分代碼就不貼出來了。
一般操作GATT的教程都把操作放在安卓的server里面,具體原因還請大神指教。下面的server代碼可以直接當作操作GATT的模板來使用,大部分都是些回調函數和對服務、特征值進行操作的方法:
public class UartService extends Service { private final static String TAG = UartService.class.getSimpleName(); List<BluetoothGattService> serviceList = new ArrayList<BluetoothGattService>();//發現的服務列表 private BluetoothAdapter mBluetoothAdapter;//本地藍牙適配器 private String mBluetoothDeviceAddress;//本地藍牙MAC地址 private BluetoothGatt mBluetoothGatt;//GTAA /** * 假設生產商提供了一個服務,該服務里面有兩個特征值 */ private BluetoothGattService mBluetoothGattService;//gatt服務 private BluetoothGattCharacteristic mBluetoothGattCharacteristic1;//gatt特征值1 private BluetoothGattCharacteristic mBluetoothGattCharacteristic2;//gatt特征值2 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; //藍牙廠商提供的UUID private static final UUID UUID_SERVICE = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"); //服務 private static final UUID UUID_CHARA1 = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"); //特征值1 private static final UUID UUID_CHARA2 = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb"); //特征值2 // Implements callback methods for GATT events that the app cares about. For example, // connection change and services discovered. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { mConnectionState = STATE_CONNECTED; Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { mConnectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) {//服務被發現 if (status == BluetoothGatt.GATT_SUCCESS) { System.out.println("Service has bean discover."); mBluetoothGattService = gatt.getService(UUID_SERVICE);//發現服務 } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Utiles.setData(characteristic); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { } }; public class LocalBinder extends Binder { UartService getService() { return UartService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { // After using a given device, you should make sure that BluetoothGatt.close() is called // such that resources are cleaned up properly. In this particular example, close() is // invoked when the UI is disconnected from the Service. close(); return super.onUnbind(intent); } private final IBinder mBinder = new LocalBinder(); /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() {//初始化 // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } return true; } /** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) {//連接服務 if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; } /** * Disconnects an existing connection or cancel a pending connection. The disconnection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public void disconnect() { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.disconnect(); } /** * After using a given BLE device, the app must call this method to ensure resources are * released properly. */ public void close() { if (mBluetoothGatt == null) { return; } mBluetoothGatt.close(); mBluetoothGatt = null; } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.readCharacteristic(characteristic); } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void writeCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.writeCharacteristic(characteristic); } public boolean writeCharacteristic1Info(String s){ if(mBluetoothGattService==null){ return false; } mBluetoothGattCharacteristic1 = mBluetoothGattService.getCharacteristic(UUID_CHARA1);//獲得特征值1 mBluetoothGattCharacteristic1.setValue(s.getBytes()); writeCharacteristic(mBluetoothGattCharacteristic1); return true; } /** * Enables or disables notification on a give characteristic. * * @param characteristic Characteristic to act on. * @param enabled If true, enable notification. False otherwise. */ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); } /** * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully. * * @return A {@code List} of supported services. */ public List<BluetoothGattService> getSupportedGattServices() { if (mBluetoothGatt == null) return null; return mBluetoothGatt.getServices(); } @Override//使用startService啟動服務時回調 public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("UartService Start"); return super.onStartCommand(intent, flags, startId); } }
ps:在發現服務后,最好把特征值取出來成一個列表,然后使用 setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled)方法對所有特征值進行設置,確保服務的特征值都可讀可寫。
mBluetoothGattService = gatt.getService(UUID_SERVICE);//發現服務 List<BluetoothGattCharacteristic> characteristics = mBluetoothGattService.getCharacteristics(); if(characteristics.size()!=2){return;}//如果此服務不是有2個特征值,說明不是我們要的服務 for (BluetoothGattCharacteristic bluetoothGattCharacteristic : characteristics) { setCharacteristicNotification(bluetoothGattCharacteristic, true); } mBluetoothGattCharacteristic1 = characteristics.get(0); mBluetoothGattCharacteristic2 = characteristics.get(1);
寫完Service之后就可以用Service了
四、Service的使用
- 在activity中綁定服務或者開啟服務。綁定服務時,當activity銷毀時服務跟着銷毀;開啟服務時,activity銷毀,service不會跟着銷毀
- 初始化本地藍牙設備
mUartService.initialize();//初始化本地設備
- 連接
mUartService.connect(String MacAddress);//通過遠程設備地址鏈接到遠程設備
- 鏈接后,回掉service中的onConnectionStateChange方法,其他的回掉方法也是字面意思,非常簡單
- 給設備發送數據
writeCharacteristic1Info(String s);
總結
- 要使用service
- 拿到服務之后馬上設置特征值為可讀可寫,否則有可能導致收發數據不正常
- UUID不一定是我的這個,是藍牙廠商提供的,找硬件編程的小伙伴要UUID
- 有什么問題望各位指教