La realización de Andorid BLE de conectar múltiples dispositivos

Mirando hacia atrás recientemente, todavía hay muchas empresas que están haciendo proyectos de hogares inteligentes, por supuesto, esto debe volver a utilizar el protocolo de comunicación BLE. Hay miles de publicaciones sobre BLE, pero hay muy pocas conexiones múltiples, por lo que este artículo analizará la conexión múltiple de BLE.

1. Los dispositivos BLE deben ser escaneados por mí. Esto puede llamar directamente startLeScan de btAdapter.

En consecuencia, detenga el escaneo y llame a stopLeScan ().

// 开始扫描	
public void startLeScan() {
    if (mBluetoothAdapter != null) {
	mBluetoothAdapter.startLeScan(mLeScanCallback);
   }
}

//停止扫描
public void stopLeScan() {
	if (mBluetoothAdapter != null) {
		mBluetoothAdapter.stopLeScan(mLeScanCallback);
	}
}

2. Después de llamar a start y stop, se debe implementar mLeScanCallback.

	//扫描回调
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
			String str  = device.getAddress();
			String name = device.getName();
			Log.d(TAG, "--扫描-->"+name+"--"+str+"--count-->"+count+"--Address-->"+lastAddress+"--rssi--->"+rssi/**+"--uuid-->"+guuid_record(scanRecord)**/);
			
			if (count < 2) { // 如果连接上两个设备就不去连了
				if(name == null) return;
				if (guuid_record(scanRecord).equals(keyUUID) || guuid_record(scanRecord).equals(earUUID)) {   // 连接指定的uuid
					
					if (!str.equalsIgnoreCase(lastAddress)) {   // 连接上的同一地址不处理
						if (connect(device, guuid_record(scanRecord))) {
							Log.i(TAG, "---连接上的--->");
						}
					}else{
						Log.i(TAG, "---地址相等---->");
					}
				}
			} else{
				Log.i(TAG, "---count >= 2---->");
			}
		}
	};
//扫描的回调中截取UUID
	private UUID guuid_record(byte[] scanRecord) {
		final int serviceOffset = 5;
		try {
			byte[] service = ArrayUtils.subarray(scanRecord, serviceOffset, serviceOffset + 16);
			ArrayUtils.reverse(service);
			String discoveredServiceID = bytesToHex(service);
			String realId = discoveredServiceID.substring(0, 8) + "-" + discoveredServiceID.substring(8, 12) + "-" + discoveredServiceID.substring(12, 16) + "-" + discoveredServiceID.substring(16, 20) + "-"+ discoveredServiceID.substring(20);
			return UUID.fromString(realId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

3. Mire connect ().

//连接
	public boolean connect(BluetoothDevice device, UUID uuid) {
		String connectAddress =  device.getAddress();
		// 这里弄的一个重连机制 没作用 ,这里注释为断开重连做个参考
		/*if (bGettHearset != null && uuid.toString().startsWith("要连接的设备UUID地址") && connectAddress.equals(lastAddress)) {
			lastAddress = connectAddress;
			
			return bGettHearset.connect();
		}
		
		
		if(bGettKeyboard != null && uuid.toString().startsWith("要连接的设备UUID地址") && connectAddress.equals(lastAddress)){
			lastAddress = connectAddress;
			
			return bGettKeyboard.connect();
		}*/
		
	   final BluetoothDevice deviceTemp = mBluetoothAdapter.getRemoteDevice(connectAddress);
	   
	    //遥控器建立GATT连接
	   if(bGettKeyboard == null && uuid.toString().startsWith("要连接的设备UUID地址")){
		   bGettKeyboard = deviceTemp.connectGatt(mContext, false, gattKeyboard); // 这里是个最关键的一个回调,连接成功后接收数据就是从这个回调
		   if(bGettKeyboard != null){
			   lastAddress = connectAddress;
			   count++;
			  
			   return true;
		   }  
	   }
	   
	   //耳机建立GATT连接
	   if(bGettHearset == null && uuid.toString().startsWith("要连接的设备UUID地址")){
		   bGettHearset = deviceTemp.connectGatt(mContext, false, gettHearset); // 这里是个最关键的一个回调,连接成功后接收数据就是从这个回调
		   if(bGettHearset != null) {
			   lastAddress = connectAddress;
			   count++;
			
			   return true;
		   } 
	   }else{
		   
	   }
		return false;
	}
	

4, devolución de llamada de Gatt

private BluetoothGattCallback gettHearset = new BluetoothGattCallback() {
		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				bGettHearset.discoverServices();
				if(iStatus != null)   iStatus.statusInfo(newState, earUUID);
				if(mIntent != null)   mContext.startService(mIntent);
				
				
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				lastAddress = "****";
				count--;
				bGettHearset.close();
				bGettHearset = null;
				
				if (iStatus != null) 	 iStatus.statusInfo(newState, earUUID);
				
				if (mIntent != null)     mContext.stopService(mIntent);
				
			}
		}

		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			List<BluetoothGattService> earServiceList =  bGettHearset.getServices();
			
			 for (BluetoothGattService earGattService : earServiceList) {
				 if(earGattService.getUuid().equals(earUUID)){
					 List<BluetoothGattCharacteristic> earValueList = earGattService.getCharacteristics();
					 for (BluetoothGattCharacteristic earValue : earValueList) {
						 if(earValue.getUuid().equals(earWriteUUID)){
							 bGettHearset.setCharacteristicNotification(earValue, true); 
							 break; 
						 }
					 }
				 }
			 }
		}

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
			byte[] new_data = characteristic.getValue();
			while (handle_buffer(OP_WRITE, new_data, new_data.length) != null) { // 获取数据
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}
	};

Este es el final del proceso. Si necesita comprender la teoría de BLE, consulte otras publicaciones.

Supongo que te gusta

Origin blog.csdn.net/u011694328/article/details/106456712
Recomendado
Clasificación