본문 바로가기

Android/통신

안드로이드 RxBle 사용하기, 예제

728x90
반응형

 

안드로이드에서의 ble 예제를 올렸었는데요.

[Android/통신] - [안드로이드 Kotlin] BLE(Bluetooth Low Energy) 통신 예제

[Android/Architecutre] - [안드로이드 Service] MVVM구조에서 BluetoothLE Service 사용하기

 

이번 포스트에서는 Rx를 사용하는 편리한 RxBle 라이브러리를 소개합니다.

 

Polidea/RxAndroidBle

An Android Bluetooth Low Energy (BLE) Library with RxJava2 interface - Polidea/RxAndroidBle

github.com

 

위의 라이브리러리를 사용해 반응형으로 Ble를 구현한것으로,

RxJava에 생소하다면 어려울 수 있습니다.

예제 소스는 아래 깃허브에 올라가 있습니다. MVVM구조로 되어 있습니다.

https://github.com/DDANGEUN/RxBle_MVVM

 

DDANGEUN/RxBle_MVVM

RxBle + MVVM. Contribute to DDANGEUN/RxBle_MVVM development by creating an account on GitHub.

github.com

 

  • Preview

https://github.com/DDANGEUN/RxBle_MVVM

 

 

  • dependecy 추가
implementation "com.polidea.rxandroidble2:rxandroidble:1.12.1"

 

 

  • Start Scan
 mScanSubscription = rxBleClient.scanBleDevices(settings, scanFilter)
            .subscribe({ scanResult ->
                addScanResult(scanResult)
            }, { throwable ->
                if (throwable is BleScanException) {
                    _requestEnableBLE.postValue(Event(throwable.reason))
                } else {
                    Util.showNotification("UNKNOWN ERROR")
                }

            })

 

  • Connect
// register connectionStateListener
connectionStateDisposable = device.observeConnectionStateChanges()
      .subscribe(
           { connectionState ->
                connectionStateListener(device, connectionState)
            }
       ) { throwable ->
            throwable.printStackTrace()
       }

// connect
mConnectSubscription = repository.bleConnectObservable(device)

/**
 * connectionState
 */

private fun connectionStateListener(
        device: RxBleDevice,
        connectionState: RxBleConnection.RxBleConnectionState
    ){
        when(connectionState){
            RxBleConnection.RxBleConnectionState.CONNECTED -> {
            
            }
            RxBleConnection.RxBleConnectionState.CONNECTING -> {
              
            }
            RxBleConnection.RxBleConnectionState.DISCONNECTED -> {
               
            }
            RxBleConnection.RxBleConnectionState.DISCONNECTING -> {

            }
        }
    }



...
-repository

/**
 * Connect & Discover Services
 * @Saved rxBleConnection, rxBleDeviceServices, bleGattServices
 */
fun bleConnectObservable(device: RxBleDevice): Disposable =
     device.establishConnection(false) // <-- autoConnect flag
        .subscribe({ _rxBleConnection->
            // All GATT operations are done through the rxBleConnection.
            rxBleConnection = _rxBleConnection

            // Discover services
             _rxBleConnection.discoverServices().subscribe ({ _rxBleDeviceServices ->
                  rxBleDeviceServices = _rxBleDeviceServices
                  bleGattServices = _rxBleDeviceServices.bluetoothGattServices
              },{ discoverServicesThrowable->
                  discoverServicesThrowable.printStackTrace()
              })

          },{ connectionThrowable->
                connectionThrowable.printStackTrace()
          })

ConnectState를 관찰할 수 있는 Disposable을 추가하고, connectionStateListener를 따로 함수로 만들어 상태를 관리했습니다.

bleConnectObservable()을 통해 RxBleDevice를 인자로 연결합니다.

연결되면 rxBleConnection을 저장하고, 바로 service를 찾아 rxBleDeviceServices도 저장해 놓았습니다.

mConnectSubscription?.dispose()를 통해 연결을 해제할 수 있습니다.

 

  • Read(Notify)
mNotificationSubscription = repository.rxBleConnection
     ?.setupNotification(UUID.fromString(CHARACTERISTIC_RESPONSE_STRING))
     ?.doOnNext { notificationObservable->
            // Notification has been set up
     }
     ?.flatMap { notificationObservable -> notificationObservable }
     ?.subscribe({ bytes ->
           // Given characteristic has been changes, here is the value.
           readTxt.postValue(byteArrayToHex(bytes))
           isRead = true

     }, { throwable ->
            // Handle an error here
            throwable.printStackTrace()
            mConnectSubscription?.dispose()
            isRead = false
      })
      

 

setupNotification()을 통해 notify할 수 있습니다.

 

  • write
mWriteSubscription = rxBleConnection?.writeCharacteristic(
        UUID.fromString(CHARACTERISTIC_COMMAND_STRING),
        sendByteData
    )?.subscribe({ writeBytes ->
        // Written data.
         val str: String = byteArrayToHex(writeBytes)
         Log.d("writtenBytes", str)
    }, { throwable ->
          // Handle an error here.
          throwable.printStackTrace()
   })

 

byte array sendByteData를 write합니다.

 

rxble를 사용하니 코드가 아주 간단해졌습니다 ^^ 예제코드를 참조해주세요!

 

 

 

 

728x90
반응형