Skip to content

Instantly share code, notes, and snippets.

@cdflynn
Created September 12, 2018 19:03
Show Gist options
  • Save cdflynn/16b49de79974ad211fa195c3e801488c to your computer and use it in GitHub Desktop.
Save cdflynn/16b49de79974ad211fa195c3e801488c to your computer and use it in GitHub Desktop.
TiltService.kt
package com.github.cdflynn.tilt.service
import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import com.github.cdflynn.tilt.model.Tilt
import com.jakewharton.rxrelay2.PublishRelay
import com.jakewharton.rxrelay2.Relay
import io.reactivex.Observable
class TiltService(context: Context) {
private val sensorManager = context.getSystemService(Activity.SENSOR_SERVICE) as SensorManager
private val rotationSensor: Sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
private val tiltStream: PublishRelay<Tilt> = PublishRelay.create()
fun observeTilt(): Observable<Tilt> {
if (tiltStream.hasObservers()) {
return tiltStream.hide()
}
val rotationListener = RotationListener(tiltStream)
return tiltStream
.doOnSubscribe {
sensorManager.registerListener(
rotationListener,
rotationSensor,
SENSOR_INTERVAL_MICROSECONDS
)
}
.doOnDispose { sensorManager.unregisterListener(rotationListener) }
}
companion object {
const val SENSOR_INTERVAL_MICROSECONDS = 16 * 1000
}
}
class RotationListener(private val relay: Relay<Tilt>) : SensorEventListener {
private val rotationMatrix = FloatArray(9)
private val orientation = FloatArray(3)
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
val tilt = rotationVectorToTiltInternal(event.values)
relay.accept(tilt)
}
private fun rotationVectorToTiltInternal(vector: FloatArray): Tilt {
SensorManager.getRotationMatrixFromVector(rotationMatrix, vector)
SensorManager.getOrientation(rotationMatrix, orientation)
return Tilt(orientation[0], orientation[1], orientation[2])
}
}
data class Tilt(val yaw: Float, val pitch: Float, val roll: Float)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment