Created
August 7, 2017 21:53
-
-
Save anaisbetts/bc18a644cbbb8a65a3add0d1127593e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity | |
import android.bluetooth.BluetoothGattCharacteristic | |
import android.os.Bundle | |
import android.util.Log | |
import com.github.ivbaranov.rxbluetooth.RxBluetooth | |
import com.polidea.rxandroidble.RxBleClient | |
import com.polidea.rxandroidble.RxBleConnection | |
import com.polidea.rxandroidble.RxBleDevice | |
import com.polidea.rxandroidble.scan.ScanSettings | |
import rx.Observable | |
import rx.subscriptions.SerialSubscription | |
import java.sql.Time | |
import java.util.* | |
import java.util.concurrent.TimeUnit | |
val devCharacteristic = UUID.fromString("f000b000-0451-4000-b000-000000000000") | |
class MainActivity : Activity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val scanSub = SerialSubscription() | |
findViewById(R.id.doItButton).setOnClickListener { | |
val sub = this.findTheDevice() | |
.flatMap { x -> x.establishConnection(false) } | |
.doOnNext { _ -> Log.d("main", "Connected!") } | |
.flatMap { x -> pollReadData(x) } | |
.subscribe { x -> | |
Log.d("main", "Data: " + Arrays.toString(x)) | |
} | |
scanSub.set(sub) | |
} | |
} | |
fun findTheDevice(): Observable<RxBleDevice> { | |
val ss = ScanSettings.Builder().build() | |
val rxBleClient = RxBleClient.create(this) | |
return rxBleClient.scanBleDevices(ss) | |
.filter { x -> x.scanRecord.deviceName == "MyDeviceName" } | |
.map { x -> x.bleDevice } | |
.doOnNext { _ -> Log.d("main", "Found MyDeviceName") } | |
.take(1) | |
} | |
fun pollReadData(conn: RxBleConnection): Observable<ByteArray> { | |
return Observable.timer(5, TimeUnit.SECONDS) | |
.flatMap { _ -> conn.readCharacteristic(devCharacteristic) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment