logo

English

이곳의 프로그래밍관련 정보와 소스는 마음대로 활용하셔도 좋습니다. 다만 쓰시기 전에 통보 정도는 해주시는 것이 예의 일것 같습니다. 질문이나 오류 수정은 siseong@gmail.com 으로 주세요. 감사합니다.

Android - 블루투스 BLE 개발하기

by digipine posted Nov 02, 2017
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print

Bluetooth Low Energy

 

4.3부터 BLE central role을 지원하기 시작했다. 그리고 디바이스 검색과 서비스 검색 그리고 속성들의 읽기/쓰기를 지원한다. BLE를 통해 저전력으로 설계된 다양한 디바이스와통신이 가능해졌다.

 

Key Terms and Concepts

Generic Attribute Profile (GATT) - BLE link상에서 송수신 가능한 일반적인 사양을 말하며 모든 LE 애플리케이션프로파일은 GATT에 기반한다.

블루투스 SIG는 많은 프로파일을 정의하였는데 하나의 프로파일은 앱에서 어떻게 동작할지에 대한 사양을 의미한다. 하나의 장치는 여러 프로파일을 구현할 수 있다. 

Attribute Protocol (ATT) - GATT는 ATT의 최상위 구현체이며 GATT/ATT로 참조되기도 한다. ATT는 BLE장치에서 동작하도록 최적화 되어 있다. 개개의 속성(Attribute)은 UUID를 가지며 128비트로 구성된다. ATT에 의해 부여된 속성은 특성과 서비스를 결정한다.

Characteristic - 하나의 특성(characteristic)은 하나의 값과 n개의 디스크립터를 포함하는데 디스크립터는 특성 값을 기술한다. 하나의 특성은 클래스와 유사한 타입으로 생각하면 된다. 

Descriptor - 디스크립터는 특성의 값을 기술한다.

Service - 하나의 서비스는 특성드의 집합니다. 예를 들어 "Heart Rate Monitor"라고 불리는 서비스를 가지고 있다면 그 서비스는 "heart rate measurement"같은 특성을 포함한다. GATT-based profile의 리스트와 서비스를 확인하려면 bluetooth.org를 방문하라.

 

Roles and Responsibilities

이 문서에서 설명하는 역할과 책임은 Android장치가  BLE장치와 연동하는데 적용되는것들이다.

Central vs. peripheral - BLE 연결에 적용된다. central 역할은 scan, 게시검색(looking for advertisement), 그리고 peripheral역할은 게시를 만든다.

GATT server vs. GATT client - 디바이스가 연결된 이 후 서로 어떻게 대화하는지에 대해 정의한다. 

차이점을 이해하려면 안드로이드폰하나와 움직임을 감지하는 BLE장치를 가지고 있다고 가정 해보자. 폰은 central역할을 한다. BLE장치는 peripheral역할을 한다. 

 

폰과 BLE장치가 한번 연결이 되면 두 장치는 서로  GATT metadata를 주고 받는다. 주고받는 데이터에 따라 하나이상의 서버 액션이 있을 수 있다. 예를 들어 BLE장치가 폰에 센서정보를 전달하려고 할 수 있다. 이 때 장치는 서버로 동작한다. 장치가 폰으로부터 업데이트를 받고자 할수 있다 이 때는 폰이 서버로 동작한다.

 

이 문서에서 제공하는 샘플은 안드로이드 디바이스로 동작하는 앱으로 GATT client이다. 앱은 GATT server로부터 데이터를 가져오는데 그것은 Heart Rate Profile을 지원하는 BLE heart rate monitor이다.

반면에 앱을 GATT 서버역할을 하도록 구현할 수 도 있다. BluetoothGattServer를 참조하라.

 

BLE permissions

블루투스통신(연결요청, 연결수락, 데이터 전송)을 하려면 BLUETOOTH 퍼미션을 추가해야 함다.

블루투스장치를 검색하고 설정을 조작하려면 BLUETOOTH_ADMIN 퍼미션을 추가해야 한다.

BLUETOOTH_ADMIN은 BLUETOOTH퍼미션과 함께 정의되어야 한다.

 

<uses-permission android:name="android.permission.BLUETOOTH"/>

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

블루투스 BLE만 사용할거라면 아래와 같이 manifest에 포함시켜야 한다.

 

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

BLE를 지원하지 않는 앱으로 만들고자 한다면 여전히 동일한  feature를 추가해야 하며 다만 required="false"로 하면 된다. 런타임에 BLE활성화 여부를 PackageManager.hasSystemFeature로 알아낼 수 있다.

 

// Use this check to determine whether BLE is supported on the device. Then

// you can selectively disable BLE-related features.

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {

    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();

    finish();

}

 

Setting Up BLE

BLE로 통신하기 전에 디바이스가 BLE를 지원하는지 확이해야 한다. 지원한다면 활성화되어야 한다. 

만일  BLE를 지원하지 않는다면 BLE feature들을 비활성화해야 한다. 지원한다면 사용자에게 BT를 앱을 떠나지 않고 활성화하도록 유도해야 한다. 이 과정은 BluetoothAdapter를 사용하여 2단계로 가능하다.

1. BluetoothAdapter얻기

 

BluetoothAdapter는 블루투스관련 일부 또는 모든 블루투스 동작들을 필요로 한다. BluetoothAdapter는 디바이스자체의 BluetoothAdapter를 나타낸다.  전체시스템을 위한 하나의 어댑터가 있고 앱은 이 객체를 통해서 상호작용을 한다. 다음 코드조각은 어댑터를 얻는 방법을 보여준다.

 

 

// Initializes Bluetooth adapter.

final BluetoothManager bluetoothManager =

        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = bluetoothManager.getAdapter();

 

2. Bluetooth 활성화.

다음에 블루투스를 활성화해야 한다. isEnabled()로 활성화여부를 확인 가능하다. false면 비활성화이다. 다음은 그 샘플이다.

private BluetoothAdapter mBluetoothAdapter;

...

// Ensures Bluetooth is available on the device and it is enabled. If not,

// displays a dialog requesting user permission to enable Bluetooth.

if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {

    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

 

BLE 장치 찾기

BLE장치를 찾으려면 startLeScan() 메소드를 호출한다. LeScanCallack이 파라메터로 호출된다. 이 메소드를 구현해야 하고 스캔결과를 받을 수 있다. 배터리 소모가 심심하기 때문에 다음의 가이드라인을 잘 지켜야 한다.

원하는 디바이스를 찾으면 바로 스캔을 중단해야 한다.

하나의 루프에서 스캔하지 말고 타임아웃을 적용해라. 디바이스가 범위안에서 벗어났을 수도 있고 그럴경우 배터리 는 골로 간다.

다음 코드는 스캔을 시작하고 중단하는 예이다.

/**

 * Activity for scanning and displaying available BLE devices.

 */

public class DeviceScanActivity extends ListActivity {

 

    private BluetoothAdapter mBluetoothAdapter;

    private boolean mScanning;

    private Handler mHandler;

 

    // Stops scanning after 10 seconds.

    private static final long SCAN_PERIOD = 10000;

    ...

    private void scanLeDevice(final boolean enable) {

        if (enable) {

            // Stops scanning after a pre-defined scan period.

            mHandler.postDelayed(new Runnable() {

                @Override

                public void run() {

                    mScanning = false;

                    mBluetoothAdapter.stopLeScan(mLeScanCallback);

                }

            }, SCAN_PERIOD);

 

            mScanning = true;

            mBluetoothAdapter.startLeScan(mLeScanCallback);

        } else {

            mScanning = false;

            mBluetoothAdapter.stopLeScan(mLeScanCallback);

        }

        ...

    }

...

}

 

특정타입의 페리퍼렁만 스캔하고자 한다면 startLeScan(UUID[], BluetoothAdapter.LeScanCallback)을 사용할 수 있다. UUID[]에는 앱에서 지원하고자 하는  GATT 서비스목록이 들어간다.

다음코드 예를 보아라.

 

private LeDeviceListAdapter mLeDeviceListAdapter;

...

// Device scan callback.

private BluetoothAdapter.LeScanCallback mLeScanCallback =

        new BluetoothAdapter.LeScanCallback() {

    @Override

    public void onLeScan(final BluetoothDevice device, int rssi,

            byte[] scanRecord) {

        runOnUiThread(new Runnable() {

           @Override

           public void run() {

               mLeDeviceListAdapter.addDevice(device);

               mLeDeviceListAdapter.notifyDataSetChanged();

           }

       });

   }

};

BLE또는 Class BT장치를 검색할 수 는 있지만 두가지를 동시에 검색은 할 수 없다.

 

GATT 서버에 연결하기

첫번째 연동을 위한 과정은 BLE디바이스에 연결하는것인데 좀더 자세히 말하면 디바이스의 GATT서버에 연결하는 것이다. connectGatt()메소드로 하면 된다. 이 메소드는 3개의 파라메터가 있는데 context, autoConnect, 그리고 BluetoothGattCallback이 있다. autoConnect는 검색되었을 때 자동으로 연결할지에 대한 파라메터다.

 

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

 

이 코드는 BLE device를 GATT 서버 호스트로 연결한다. 그리고 BluetoothGatt 인스턴스를 반환한다. 이 인스턴스로 GATT client를 운영한다.

BluetoothGattCallback은 클라이언트에 연결상태나 client 운영에 대한 결과를 전달한다.

 

이 예제에서 BLE 앱은 하나의 액티비티가 연결하고 데이터를 표시하고 GATT 서비스와 특성들을 표시한다. 사용자 입력에 기반하여 BluetoothLeService로 불리는 서비스와 통신을 수행하도 Android BLE API를 통해 장치와 상호연동을 한다.

 

 

// A service that interacts with the BLE device via the Android BLE API.

public class BluetoothLeService extends Service {

    private final static String TAG = BluetoothLeService.class.getSimpleName();

 

    private BluetoothManager mBluetoothManager;

    private BluetoothAdapter mBluetoothAdapter;

    private String mBluetoothDeviceAddress;

    private BluetoothGatt mBluetoothGatt;

    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;

 

    public final static String ACTION_GATT_CONNECTED =

            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";

    public final static String ACTION_GATT_DISCONNECTED =

            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";

    public final static String ACTION_GATT_SERVICES_DISCOVERED =

            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";

    public final static String ACTION_DATA_AVAILABLE =

            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";

    public final static String EXTRA_DATA =

            "com.example.bluetooth.le.EXTRA_DATA";

 

    public final static UUID UUID_HEART_RATE_MEASUREMENT =

            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

 

    // Various callback methods defined by the BLE API.

    private final BluetoothGattCallback mGattCallback =

            new BluetoothGattCallback() {

        @Override

        public void onConnectionStateChange(BluetoothGatt gatt, int status,

                int newState) {

            String intentAction;

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                intentAction = ACTION_GATT_CONNECTED;

                mConnectionState = STATE_CONNECTED;

                broadcastUpdate(intentAction);

                Log.i(TAG, "Connected to GATT server.");

                Log.i(TAG, "Attempting to start service discovery:" +

                        mBluetoothGatt.discoverServices());

 

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                intentAction = ACTION_GATT_DISCONNECTED;

                mConnectionState = STATE_DISCONNECTED;

                Log.i(TAG, "Disconnected from GATT server.");

                broadcastUpdate(intentAction);

            }

        }

 

        @Override

        // New services discovered

        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);

            } else {

                Log.w(TAG, "onServicesDiscovered received: " + status);

            }

        }

 

        @Override

        // Result of a characteristic read operation

        public void onCharacteristicRead(BluetoothGatt gatt,

                BluetoothGattCharacteristic characteristic,

                int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

            }

        }

     ...

    };

...

}

 

콜백이 호출되면 broadcastUpdate()를 호출한다. 여기서 데이터 파싱은 Bluetooth Heart Rate Measurement profile 사양에 맞춰서 수행하고 있다.

 

private void broadcastUpdate(final String action) {

    final Intent intent = new Intent(action);

    sendBroadcast(intent);

}

 

private void broadcastUpdate(final String action,

                             final BluetoothGattCharacteristic characteristic) {

    final Intent intent = new Intent(action);

 

    // This is special handling for the Heart Rate Measurement profile. Data

    // parsing is carried out as per profile specifications.

    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {

        int flag = characteristic.getProperties();

        int format = -1;

        if ((flag & 0x01) != 0) {

            format = BluetoothGattCharacteristic.FORMAT_UINT16;

            Log.d(TAG, "Heart rate format UINT16.");

        } else {

            format = BluetoothGattCharacteristic.FORMAT_UINT8;

            Log.d(TAG, "Heart rate format UINT8.");

        }

        final int heartRate = characteristic.getIntValue(format, 1);

        Log.d(TAG, String.format("Received heart rate: %d", heartRate));

        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));

    } else {

        // For all other profiles, writes the data formatted in HEX.

        final byte[] data = characteristic.getValue();

        if (data != null && data.length > 0) {

            final StringBuilder stringBuilder = new StringBuilder(data.length);

            for(byte byteChar : data)

                stringBuilder.append(String.format("%02X ", byteChar));

            intent.putExtra(EXTRA_DATA, new String(data) + "\n" +

                    stringBuilder.toString());

        }

    }

    sendBroadcast(intent);

}

이 이벤드들은 B roadcastReceiver에 의해 처리된다.

// Handles various events fired by the Service.

// ACTION_GATT_CONNECTED: connected to a GATT server.

// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.

// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.

// ACTION_DATA_AVAILABLE: received data from the device. This can be a

// result of read or notification operations.

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

    @Override

    public void onReceive(Context context, Intent intent) {

        final String action = intent.getAction();

        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

            mConnected = true;

            updateConnectionState(R.string.connected);

            invalidateOptionsMenu();

        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

            mConnected = false;

            updateConnectionState(R.string.disconnected);

            invalidateOptionsMenu();

            clearUI();

        } else if (BluetoothLeService.

                ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

            // Show all the supported services and characteristics on the

            // user interface.

            displayGattServices(mBluetoothLeService.getSupportedGattServices());

        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {

            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));

        }

    }

};

 

BLE 속성 읽기

앱이 GATT 서버에 연결하고 서비스를 찾게 되면 속성을  읽고/쓸수 있게 된다. 다음 코드는 서비스와 특성들을 나열하여 표시해준다.

 

public class DeviceControlActivity extends Activity {

    ...

    // Demonstrates how to iterate through the supported GATT

    // Services/Characteristics.

    // In this sample, we populate the data structure that is bound to the

    // ExpandableListView on the UI.

    private void displayGattServices(List<BluetoothGattService> gattServices) {

        if (gattServices == null) return;

        String uuid = null;

        String unknownServiceString = getResources().

                getString(R.string.unknown_service);

        String unknownCharaString = getResources().

                getString(R.string.unknown_characteristic);

        ArrayList<HashMap<String, String>> gattServiceData =

                new ArrayList<HashMap<String, String>>();

        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData

                = new ArrayList<ArrayList<HashMap<String, String>>>();

        mGattCharacteristics =

                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

 

        // Loops through available GATT Services.

        for (BluetoothGattService gattService : gattServices) {

            HashMap<String, String> currentServiceData =

                    new HashMap<String, String>();

            uuid = gattService.getUuid().toString();

            currentServiceData.put(

                    LIST_NAME, SampleGattAttributes.

                            lookup(uuid, unknownServiceString));

            currentServiceData.put(LIST_UUID, uuid);

            gattServiceData.add(currentServiceData);

 

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =

                    new ArrayList<HashMap<String, String>>();

            List<BluetoothGattCharacteristic> gattCharacteristics =

                    gattService.getCharacteristics();

            ArrayList<BluetoothGattCharacteristic> charas =

                    new ArrayList<BluetoothGattCharacteristic>();

           // Loops through available Characteristics.

            for (BluetoothGattCharacteristic gattCharacteristic :

                    gattCharacteristics) {

                charas.add(gattCharacteristic);

                HashMap<String, String> currentCharaData =

                        new HashMap<String, String>();

                uuid = gattCharacteristic.getUuid().toString();

                currentCharaData.put(

                        LIST_NAME, SampleGattAttributes.lookup(uuid,

                                unknownCharaString));

                currentCharaData.put(LIST_UUID, uuid);

                gattCharacteristicGroupData.add(currentCharaData);

            }

            mGattCharacteristics.add(charas);

            gattCharacteristicData.add(gattCharacteristicGroupData);

         }

    ...

    }

...

}

 

GATT 통지 수신

디바이스의 특성이 변경에 대한 통지를 앱이 알수 있다. 다음 코드는 setCharacteristicNotification()메소드로 어떻게 통지를 설정하는지 보여준다.

 

private BluetoothGatt mBluetoothGatt;

BluetoothGattCharacteristic characteristic;

boolean enabled;

...

mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

...

BluetoothGattDescriptor descriptor = characteristic.getDescriptor(

        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));

descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

mBluetoothGatt.writeDescriptor(descriptor);

하나의 특성에 대해 통지가 활성화되면 onCharacteristicChanged()가 장치에서 해당 특성정보가 변경이 되면 호출된다.

@Override

// Characteristic notification

public void onCharacteristicChanged(BluetoothGatt gatt,

        BluetoothGattCharacteristic characteristic) {

    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

}

 

클라이언트 앱의 종료

BLE 장치를 사용하는 앱이 종료되면 반드시 close()를 호출하여 시스템이 관련 리소스를 반환하도록 해야 한다.

public void close() {

    if (mBluetoothGatt == null) {

        return;

    }

    mBluetoothGatt.close();

    mBluetoothGatt = null;

}

TAG •

List of Articles
No. Subject Author Date Views
22 안드로이드 개발시 API Key, 암호화 정보 코드에서 숨기는 방법, Kotlin DSL의 경우 lizard2019 2023.06.20 193
21 구글에서 제공하는 안드로이드 개발 기초 학습코스 file digipine 2022.03.18 378
20 Toolchain Error 'No such file or directory' 해결방법 lizard2019 2019.12.19 1371
19 Ubuntu 16.0.4 openjdk 7 설치방법 lizard2019 2019.12.19 826
18 Ubuntu 리눅스 fastboot 설치 lizard2019 2019.12.13 1502
17 atomic vs volatile vs synchronized file 엉뚱도마뱀 2017.12.18 1186
16 Atomic Operation에 대해서 엉뚱도마뱀 2017.12.18 1226
15 Android 하드웨어 코덱 포팅하기, OpenCore, OpenMAX digipine 2017.11.03 1609
14 Ubuntu 기본 쉘 dash 대신 bash로 설정 digipine 2017.11.02 703
13 [안드로이드] 가속도 (Accelerometer)센서 Shake 이벤트 예제 digipine 2017.11.02 1627
» Android - 블루투스 BLE 개발하기 digipine 2017.11.02 16583
11 안드로이드 Native C 코드에서 Intent 보내는 방법 digipine 2017.11.02 1296
10 안드로이드 시스템 개발시 mmm 커멘드 사용법 digipine 2017.11.01 1169
9 Android - 이미지(비트맵) 리사이징 digipine 2017.11.01 1306
8 [Java] SortedSet과 Comparable을 이용한 정렬(Sort) digipine 2017.10.29 772
7 Android - AlarmManager를 이용해서 서비스 실행 시키는 코드 digipine 2017.10.29 498
6 Android - 슬립모드 (Sleep Mode) 방지 코드 digipine 2017.10.29 2395
5 Android - Browser 에서 Activity 실행하기 file digipine 2017.10.29 712
4 안드로이드 파일 입출력시 한글 깨짐 문제 digipine 2017.10.29 1643
3 Android 기반 Application Ant 빌드 방법 digipine 2017.10.29 538
Board Pagination Prev 1 2 Next
/ 2