Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

byiryu

fastble 라이브러리를 이용한 Ble 연결 본문

안드로이드

fastble 라이브러리를 이용한 Ble 연결

byiryu 2019. 10. 30. 15:38

 

Bluetooth 4.0 중에서도 저전력을 이용하여 무선통신을 하는 Bluetooth Low Energy (이하 BLE)는 스마트 밴드, 웨어러블 무선통신 기기에 많이 사용되고 있습니다. 오늘은 BLE 스캔과 연결하는 어플리케이션을 만들고 포스팅하려고합니다.

 

Bluetooth - 스캔 및 연결

1. Gradle

implementation 'gun0912.ted:tedpermission:2.2.2'

https://github.com/Jasonchenlijian/FastBle

 

 

2. AndroidManifest 설정



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


 

 

3. Application 설정


class BleApplication : Application(){

    override fun onCreate() {
        super.onCreate()
        BleManager.getInstance().init(this)
    }
}

 

4. MainActivity - 블루투스 초기화와 Permission 체크

fun init() {

    tedPermission = PermissionUtil(this)
    tedPermission.setListener(this)

    if (tedPermission.isGranted(PermissionUtil.Permissions.Location)) {
        if (mConnectState == ConnectState.Connecting)
            startScan()
    }


    bluetoothInit()
}
fun bluetoothInit(){
    if(mConnectState == ConnectState.Connecting){
        BleManager.getInstance()
            .enableLog(true)
            .setReConnectCount(1, 5000)
            .setConnectOverTime(20000)
            .operateTimeout = 5000
    }
}
if(!isEnableBlueTooth())
    return@setOnClickListener
fun isEnableBlueTooth() : Boolean{
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

    if(mBluetoothAdapter == null)
        return false

    if(!mBluetoothAdapter.isEnabled){
        startActivity(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
        return false
    }

    return true
}

블루투스 연동을 위해서 Location 권한이 필요합니다

이유는 무엇인지 모르겠지만. 권한이 없으면 오류가 생깁니다

권한 설정을 위해 TedPermission 라이브러리 이용했습니다.

https://github.com/ParkSangGwon/TedPermission

 


5. StartScan()

BleManager.getInstance().scan(callback) 으로 스캔을 시작합니다.

onScanFinished()는 설정한 블루투스 설정시간 만큼 스캔후 종료되었을때 스캔된 모든 디바이스를 리턴합니다 onScanStarted() 스캔시작, onScanning() 스캔중 

fun startScan(){
    BleManager.getInstance().scan(object : BleScanCallback(){
        override fun onScanFinished(scanResultList: MutableList<BleDevice>) { }
        override fun onScanStarted(success: Boolean) {}
        override fun onScanning(bleDevice: BleDevice?) {}
    })
}

 

6. Connection

선택한 디바스를 클릭하면 bleConnect() 함수를 통해 장치를 연결시킵니다. 

override fun onClickItem(bleDevice: BleDevice) {
    BluetoothUtils.bleConnect(bleDevice)
}

아래는 BluetoothUtils bleConnect() 함수입니다

 

fun bleConnect(bleDevice: BleDevice){
    BleManager.getInstance().connect(bleDevice, object : BleGattCallback(){
        override fun onStartConnect() {

        }
        override fun onDisConnected(isActiveDisConnected: Boolean, device: BleDevice, gatt: BluetoothGatt?, status: Int) {
            ObserverManager.disConnected(device)
            mBleDevice = null
        }
        override fun onConnectSuccess(bleDevice: BleDevice, gatt: BluetoothGatt, status: Int) {
            ObserverManager.connected(bleDevice)
            mBleDevice = bleDevice
        }
        override fun onConnectFail(bleDevice: BleDevice, exception: BleException?) {
            ObserverManager.connectFail(bleDevice)
        }
    })

}

MainActivity에서 connected()함수에서 callback 처리를 합니다.

override fun connected(bleDevice: BleDevice) {
    Toast.makeText(this, "블루투스 장치가 연결되었습니다. : " + bleDevice.mac, Toast.LENGTH_LONG).show()
    Log.e(TAG, "connected : " + bleDevice.mac )
}

 

 

이후에 펌웨어 수정과 함께 데이터 프로토콜을 정하고 디바이스와 어플리케이션과의 통신을 만들어 볼 예정입니다.  2019-10-31

어플리케이션 전문은 githup 저장소에서 확인가능합니다 

https://github.com/byiryu/BleApplication