Android/Bluetooth

[Android][Compose] Bluetooth Connect 하기

O_Gyong 2023. 7. 10.
 

[Android][Compose] Bluetooth Scan 하기

안드로이드에서 제공하는 BluetoothLeScanner를 사용해서 Bluetooth 주변기기를 Scan 해보려고 한다. Scan 데이터를 얻으면 아래 이미지와 같이 리스트로 그릴 것이다. (UI는 Compose를 사용) 권한 처리하기

ogyong.tistory.com

Bluetooth Scan 하기에 이어서 Connect를 해보려고 한다.


GATT(Generic Attribute Profile)

Connect를 하고 디바이스의 정보를 구하는 과정에서 GATT가 사용된다.

 

GATT는 ATT를 프로토콜로하여 BLE 기기 간에 데이터를 주고 받기 위한 방식을 정의해 놓은 프로파일이다. ATT는 UUID를 고유 식별자라는 속성을 지니며, 이 속성은 ServiceCharacteristic로 구성된다.

◾ Service
Characteristic의 모음으로 예를 들어 "심장 박동"이라는 Service에 "심박수"라는 Characteristic이 포함된다.

◾ Characteristic
Characteristic은 단일 값 데이터를 나타내고, 이 값에 대한 설명을 하는 Descriptor가 포함된다.
(Characteristic은 특정한 데이터를 표현하고, 해당 데이터에 대한 세부 정보를 포함한다.)


BluetoothGatt

안드로이드에서는 Bluetooth 기기와 통신할 수 있도록 Bluetooth GATT 기능을 제공한다. 

 

bluetoothAdapter
    .getRemoteDevice(deviceData.address)
    .connectGatt(context, false, gattCallback)

위와 같이 BluetoothAdapter에 기기 정보를 넘겨주고 연결을 시도한다.(Mac-Adrress를 넘김)

여기서 3번째 값인 gattCallback은 BluetoothGattCallback의 인스턴스로 GATT 연결과 관련된 이벤트를 수신하고 처리한다.

 

private val gattCallback = object : BluetoothGattCallback() {
    // GATT의 연결 상태 변경을 감지하는 콜백
    @SuppressLint("MissingPermission")
    override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
        super.onConnectionStateChange(gatt, status, newState)

        // 연결이 성공적으로 이루어진 경우
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // GATT 서버에서 사용 가능한 서비스들을 비동기적으로 탐색
            Log.d("BleManager", "연결 성공")
            gatt?.discoverServices()
            
            // ...
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // 연결 끊김
            Log.d("BleManager", "연결 해제")
            
            // ...
        }
    }

    // 장치에 대한 새로운 서비스가 발견되었을 때 호출되는 콜백
    @SuppressLint("MissingPermission")
    override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
        super.onServicesDiscovered(gatt, status)

        // 원격 장치가 성공적으로 탐색된 경우
        if(status == BluetoothGatt.GATT_SUCCESS) {
            MainScope().launch {
                Toast.makeText(context, " ${gatt?.device?.name} 연결 성공", Toast.LENGTH_SHORT).show()
                
                // ...
            }.cancel()
        }
    }
}

onConnectionStateChange는 GATT 클라이언트가 원격 GATT 서버에 연결/연결 해제된 상태를 감지하는 콜백이다. 연결에 성공하면 Service와 Characteristic 조회를 위해 discoverServices()를 호출하여 onServicesDiscovered 콜백이 실행되도록 한다.

 

onServicesDiscovered는 기기의 Service, Characteristic이 업데이트(발견)되었을 때 실행된다. 이곳에서 원하는 Service를 찾거나 해당 Service에 대한 작업을 수행한다.

 

참고로 Service에 대한 Characteristic 정보를 조회하는 코드는 아래와 같다.

for(service in gatt?.services!!) {
    println(service.uuid.toString())
    for(characteristics in service.characteristics) {
        println("    "+ characteristics.uuid.toString())
    }
}

 

 

전체 코드

 

Android_Study/Ble Sample at master · OhGyong/Android_Study

안드로이드 개발 공부. Contribute to OhGyong/Android_Study development by creating an account on GitHub.

github.com

 

'Android > Bluetooth' 카테고리의 다른 글

[Android][Compose] Bluetooth Scan 하기  (0) 2023.06.22

댓글