Initial Commit
This commit is contained in:
@@ -0,0 +1,413 @@
|
||||
package com.hawhamburg.micr0bu.service
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.google.android.gms.location.FusedLocationProviderClient
|
||||
import com.google.android.gms.location.LocationCallback
|
||||
import com.google.android.gms.location.LocationRequest
|
||||
import com.google.android.gms.location.LocationResult
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
import com.hawhamburg.micr0bu.MainActivity
|
||||
import com.hawhamburg.micr0bu.R
|
||||
import com.hawhamburg.micr0bu.data.TripRepository
|
||||
import com.hawhamburg.micr0bu.data.db.AppDatabase
|
||||
import com.hawhamburg.micr0bu.domain.detection.DetectionConfig
|
||||
import com.hawhamburg.micr0bu.domain.detection.EventDetector
|
||||
import com.hawhamburg.micr0bu.domain.detection.EventType
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Foreground service that runs event detection while the screen is off.
|
||||
*
|
||||
* Start with [ACTION_START], stop with [ACTION_STOP].
|
||||
*
|
||||
* Sensor pipeline:
|
||||
* • Accelerometer + Gyroscope at [SensorManager.SENSOR_DELAY_GAME] (~50 Hz)
|
||||
* • FusedLocationProviderClient at 1 Hz
|
||||
* • Accel/gyro magnitudes + last GPS state → [EventDetector] → Room via [TripRepository]
|
||||
*/
|
||||
class TripRecordingService : Service() {
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
companion object {
|
||||
const val ACTION_START = "com.hawhamburg.micr0bu.TRIP_START"
|
||||
const val ACTION_STOP = "com.hawhamburg.micr0bu.TRIP_STOP"
|
||||
|
||||
private const val NOTIFICATION_ID = 9001
|
||||
private const val CHANNEL_ID = "trip_recording"
|
||||
private const val CHANNEL_NAME = "Trip Recording"
|
||||
private const val GPS_INTERVAL_MS = 1_000L
|
||||
private const val GRAVITY = 9.81
|
||||
}
|
||||
|
||||
// ── Service scope ─────────────────────────────────────────────────────────
|
||||
|
||||
private val serviceJob = SupervisorJob()
|
||||
private val serviceScope = CoroutineScope(Dispatchers.Default + serviceJob)
|
||||
private var timerJob: Job? = null
|
||||
|
||||
// ── Dependencies ──────────────────────────────────────────────────────────
|
||||
|
||||
private lateinit var sensorManager: SensorManager
|
||||
private lateinit var fusedLocation: FusedLocationProviderClient
|
||||
private lateinit var repository: TripRepository
|
||||
private val detector = EventDetector(
|
||||
DetectionConfig(
|
||||
brakingSpeedDropThreshold = 1.0,
|
||||
brakingAccelStdDevThreshold = 1.8,
|
||||
brakingSustainedFrames = 25,
|
||||
turningGyroMeanThreshold = 0.6,
|
||||
turningBearingChangeThreshold = 15.0,
|
||||
turningSustainedFrames = 30,
|
||||
stoppingSpeedThreshold = 0.3,
|
||||
stoppingFrames = 150,
|
||||
stoppingAccelStdDevThreshold = 0.10,
|
||||
)
|
||||
)
|
||||
|
||||
// ── Sensor fusion state ───────────────────────────────────────────────────
|
||||
|
||||
// Latest accel xyz (updated at ~50 Hz)
|
||||
@Volatile private var ax = 0f
|
||||
@Volatile private var ay = 0f
|
||||
@Volatile private var az = 0f
|
||||
|
||||
// Latest gyro xyz (updated at ~50 Hz)
|
||||
@Volatile private var gx = 0f
|
||||
@Volatile private var gy = 0f
|
||||
@Volatile private var gz = 0f
|
||||
|
||||
// Latest GPS state (updated at 1 Hz)
|
||||
@Volatile private var currentLat = 0.0
|
||||
@Volatile private var currentLon = 0.0
|
||||
@Volatile private var currentSpeedMps = 0f
|
||||
@Volatile private var currentBearing = 0f
|
||||
@Volatile private var previousBearing = 0f
|
||||
@Volatile private var bearingChangeDps = 0.0 // °/s
|
||||
|
||||
// ── Trip accounting ───────────────────────────────────────────────────────
|
||||
|
||||
private var currentTripId: Long = -1L
|
||||
private var distanceMetres = 0f
|
||||
private var prevLat = Double.NaN
|
||||
private var prevLon = Double.NaN
|
||||
|
||||
// GPS track for map replay: list of JSON objects built as a StringBuilder
|
||||
private val gpsTrackBuilder = StringBuilder("[")
|
||||
private var gpsPointCount = 0
|
||||
|
||||
// Event counts
|
||||
private var brakingCount = 0
|
||||
private var turningCount = 0
|
||||
private var stoppingCount = 0
|
||||
|
||||
// ── SensorEventListener ───────────────────────────────────────────────────
|
||||
|
||||
private val sensorListener = object : SensorEventListener {
|
||||
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit
|
||||
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
when (event.sensor.type) {
|
||||
Sensor.TYPE_ACCELEROMETER -> {
|
||||
ax = event.values[0]
|
||||
ay = event.values[1]
|
||||
az = event.values[2]
|
||||
}
|
||||
Sensor.TYPE_GYROSCOPE -> {
|
||||
gx = event.values[0]
|
||||
gy = event.values[1]
|
||||
gz = event.values[2]
|
||||
}
|
||||
}
|
||||
|
||||
// Compute orientation-independent magnitudes and feed the detector
|
||||
val accelMag = sqrt((ax * ax + ay * ay + az * az).toDouble()) - GRAVITY
|
||||
val gyroMag = sqrt((gx * gx + gy * gy + gz * gz).toDouble())
|
||||
|
||||
detector.processSample(
|
||||
accelMagnitude = accelMag,
|
||||
gyroMagnitude = gyroMag,
|
||||
speedMps = currentSpeedMps.toDouble(),
|
||||
bearingChangeDegPerSec = bearingChangeDps,
|
||||
latitude = currentLat,
|
||||
longitude = currentLon,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── LocationCallback ─────────────────────────────────────────────────────
|
||||
|
||||
private val locationCallback = object : LocationCallback() {
|
||||
override fun onLocationResult(result: LocationResult) {
|
||||
val loc = result.lastLocation ?: return
|
||||
|
||||
// Update bearing-change rate before overwriting previous bearing
|
||||
val newBearing = loc.bearing
|
||||
bearingChangeDps = normaliseBearingDiff(previousBearing, newBearing)
|
||||
previousBearing = currentBearing
|
||||
currentBearing = newBearing
|
||||
|
||||
currentLat = loc.latitude
|
||||
currentLon = loc.longitude
|
||||
currentSpeedMps = loc.speed
|
||||
|
||||
TripServiceBus.update { copy(currentSpeedMs = loc.speed) }
|
||||
|
||||
accumulateDistance(loc)
|
||||
appendGpsPoint(loc)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lifecycle ─────────────────────────────────────────────────────────────
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
|
||||
fusedLocation = LocationServices.getFusedLocationProviderClient(this)
|
||||
repository = TripRepository(AppDatabase.getInstance(applicationContext))
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_START -> startTrip()
|
||||
ACTION_STOP -> stopTrip()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceJob.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
// ── Trip control ─────────────────────────────────────────────────────────
|
||||
|
||||
private fun startTrip() {
|
||||
detector.reset()
|
||||
brakingCount = 0
|
||||
turningCount = 0
|
||||
stoppingCount = 0
|
||||
distanceMetres = 0f
|
||||
prevLat = Double.NaN
|
||||
prevLon = Double.NaN
|
||||
gpsTrackBuilder.clear()
|
||||
gpsTrackBuilder.append("[")
|
||||
gpsPointCount = 0
|
||||
|
||||
val startTime = System.currentTimeMillis()
|
||||
|
||||
// Insert placeholder trip row and get the auto-generated ID
|
||||
serviceScope.launch {
|
||||
currentTripId = repository.insertTrip(startTime = startTime)
|
||||
TripServiceBus.update {
|
||||
copy(
|
||||
isRecording = true,
|
||||
currentTripId = currentTripId,
|
||||
elapsedSeconds = 0L,
|
||||
brakingCount = 0,
|
||||
turningCount = 0,
|
||||
stoppingCount = 0,
|
||||
currentSpeedMs = 0f,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Collect detector events and persist them
|
||||
serviceScope.launch {
|
||||
detector.events.collect { event ->
|
||||
if (currentTripId < 0) return@collect
|
||||
repository.insertEvent(currentTripId, event)
|
||||
when (event.type) {
|
||||
EventType.BRAKING -> brakingCount++
|
||||
EventType.TURNING -> turningCount++
|
||||
EventType.STOPPING -> stoppingCount++
|
||||
}
|
||||
TripServiceBus.update {
|
||||
copy(
|
||||
brakingCount = this@TripRecordingService.brakingCount,
|
||||
turningCount = this@TripRecordingService.turningCount,
|
||||
stoppingCount = this@TripRecordingService.stoppingCount,
|
||||
)
|
||||
}
|
||||
updateNotification()
|
||||
}
|
||||
}
|
||||
|
||||
// Elapsed-time ticker
|
||||
timerJob = serviceScope.launch {
|
||||
var elapsed = 0L
|
||||
while (true) {
|
||||
delay(1_000)
|
||||
elapsed++
|
||||
TripServiceBus.update { copy(elapsedSeconds = elapsed) }
|
||||
updateNotification()
|
||||
}
|
||||
}
|
||||
|
||||
// Register sensors
|
||||
registerSensors()
|
||||
requestLocationUpdates()
|
||||
|
||||
// Start foreground ASAP (within 5 s required by Android)
|
||||
startForeground(NOTIFICATION_ID, buildNotification(0L, 0))
|
||||
}
|
||||
|
||||
private fun stopTrip() {
|
||||
timerJob?.cancel()
|
||||
unregisterSensors()
|
||||
removeLocationUpdates()
|
||||
|
||||
val endTime = System.currentTimeMillis()
|
||||
val totalEvents = brakingCount + turningCount + stoppingCount
|
||||
|
||||
// Close GPS track JSON
|
||||
gpsTrackBuilder.append("]")
|
||||
val gpsJson = gpsTrackBuilder.toString()
|
||||
|
||||
serviceScope.launch {
|
||||
if (currentTripId >= 0) {
|
||||
repository.finaliseTrip(
|
||||
tripId = currentTripId,
|
||||
endTime = endTime,
|
||||
distanceMetres = distanceMetres,
|
||||
eventCount = totalEvents,
|
||||
gpsTrackJson = gpsJson,
|
||||
)
|
||||
}
|
||||
currentTripId = -1L
|
||||
TripServiceBus.reset()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sensors ───────────────────────────────────────────────────────────────
|
||||
|
||||
private fun registerSensors() {
|
||||
listOf(Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE).forEach { type ->
|
||||
sensorManager.getDefaultSensor(type)?.let { sensor ->
|
||||
sensorManager.registerListener(
|
||||
sensorListener, sensor, SensorManager.SENSOR_DELAY_GAME
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun unregisterSensors() =
|
||||
sensorManager.unregisterListener(sensorListener)
|
||||
|
||||
// ── Location ─────────────────────────────────────────────────────────────
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
private fun requestLocationUpdates() {
|
||||
val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, GPS_INTERVAL_MS)
|
||||
.setMinUpdateIntervalMillis(GPS_INTERVAL_MS / 2)
|
||||
.build()
|
||||
fusedLocation.requestLocationUpdates(request, locationCallback, Looper.getMainLooper())
|
||||
}
|
||||
|
||||
private fun removeLocationUpdates() =
|
||||
fusedLocation.removeLocationUpdates(locationCallback)
|
||||
|
||||
// ── GPS track helpers ─────────────────────────────────────────────────────
|
||||
|
||||
private fun accumulateDistance(loc: Location) {
|
||||
val pLat = prevLat
|
||||
val pLon = prevLon
|
||||
if (!pLat.isNaN() && !pLon.isNaN()) {
|
||||
val results = FloatArray(1)
|
||||
Location.distanceBetween(pLat, pLon, loc.latitude, loc.longitude, results)
|
||||
distanceMetres += results[0]
|
||||
}
|
||||
prevLat = loc.latitude
|
||||
prevLon = loc.longitude
|
||||
}
|
||||
|
||||
private fun appendGpsPoint(loc: Location) {
|
||||
if (gpsPointCount > 0) gpsTrackBuilder.append(",")
|
||||
gpsTrackBuilder.append(
|
||||
"""{"lat":${loc.latitude},"lon":${loc.longitude},"ts":${loc.time}}"""
|
||||
)
|
||||
gpsPointCount++
|
||||
}
|
||||
|
||||
private fun normaliseBearingDiff(a: Float, b: Float): Double {
|
||||
// Returns absolute bearing change in °/s (GPS updates at ~1 Hz)
|
||||
var diff = (b - a).toDouble()
|
||||
while (diff > 180) diff -= 360
|
||||
while (diff < -180) diff += 360
|
||||
return abs(diff) // per second because GPS is 1 Hz
|
||||
}
|
||||
|
||||
// ── Notification ─────────────────────────────────────────────────────────
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
CHANNEL_NAME,
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = "Shown while a trip is being recorded"
|
||||
}
|
||||
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
|
||||
.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun buildNotification(elapsedSeconds: Long, eventCount: Int) =
|
||||
NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("Recording trip")
|
||||
.setContentText(
|
||||
"⏱ ${formatElapsed(elapsedSeconds)} · " +
|
||||
"🚨 $brakingCount 🔄 $turningCount 🛑 $stoppingCount"
|
||||
)
|
||||
.setSmallIcon(R.mipmap.ic_launcher_foreground)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setContentIntent(
|
||||
PendingIntent.getActivity(
|
||||
this, 0,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
)
|
||||
.build()
|
||||
|
||||
private fun updateNotification() {
|
||||
val elapsed = TripServiceBus.state.value.elapsedSeconds
|
||||
val total = brakingCount + turningCount + stoppingCount
|
||||
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
nm.notify(NOTIFICATION_ID, buildNotification(elapsed, total))
|
||||
}
|
||||
|
||||
private fun formatElapsed(seconds: Long): String {
|
||||
val h = seconds / 3600
|
||||
val m = (seconds % 3600) / 60
|
||||
val s = seconds % 60
|
||||
return if (h > 0) "%d:%02d:%02d".format(h, m, s)
|
||||
else "%02d:%02d".format(m, s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.hawhamburg.micr0bu.service
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
/**
|
||||
* Process-level singleton that bridges [TripRecordingService] (writes) and
|
||||
* [TripRecordingViewModel] (reads) without requiring a bound service.
|
||||
*
|
||||
* The service updates [state] on every relevant change; the ViewModel collects
|
||||
* it as a cold StateFlow.
|
||||
*/
|
||||
object TripServiceBus {
|
||||
|
||||
data class State(
|
||||
val isRecording: Boolean = false,
|
||||
val currentTripId: Long = -1L,
|
||||
val elapsedSeconds: Long = 0L,
|
||||
val brakingCount: Int = 0,
|
||||
val turningCount: Int = 0,
|
||||
val stoppingCount: Int = 0,
|
||||
val currentSpeedMs: Float = 0f,
|
||||
)
|
||||
|
||||
private val _state = MutableStateFlow(State())
|
||||
val state: StateFlow<State> = _state.asStateFlow()
|
||||
|
||||
/** Called exclusively from [TripRecordingService]. */
|
||||
internal fun update(transform: State.() -> State) {
|
||||
_state.value = _state.value.transform()
|
||||
}
|
||||
|
||||
/** Resets to idle — called when recording stops. */
|
||||
internal fun reset() {
|
||||
_state.value = State()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user