1+ package com.imsproject.watch.sensors
2+
3+ import android.content.Context
4+ import android.util.Log
5+ import com.imsproject.common.gameserver.SessionEvent
6+ import com.imsproject.watch.viewmodel.GameViewModel
7+ import com.samsung.android.service.health.tracking.ConnectionListener
8+ import com.samsung.android.service.health.tracking.HealthTracker
9+ import com.samsung.android.service.health.tracking.HealthTrackerException
10+ import com.samsung.android.service.health.tracking.HealthTrackingService
11+ import com.samsung.android.service.health.tracking.data.DataPoint
12+ import com.samsung.android.service.health.tracking.data.HealthTrackerType
13+ import com.samsung.android.service.health.tracking.data.ValueKey
14+
15+ class HeartRateSensorHandler () {
16+ private var healthService: HealthTrackingService ? = null
17+ private var tracker: HealthTracker ? = null
18+
19+ fun connect (context : Context , onConnectionResponse : (Boolean , HealthTrackerException ? ) -> Unit ) {
20+ val healthService = HealthTrackingService (
21+ object : ConnectionListener {
22+ override fun onConnectionSuccess () = onConnectionResponse(true ,null )
23+ override fun onConnectionFailed (e : HealthTrackerException ) {
24+ healthService = null
25+ onConnectionResponse(false ,e)
26+ }
27+ override fun onConnectionEnded () {}
28+ }, context)
29+ this .healthService = healthService
30+ healthService.connectService()
31+ }
32+
33+ fun disconnect () {
34+ tracker?.unsetEventListener()
35+ healthService?.disconnectService()
36+ tracker = null
37+ healthService = null
38+ }
39+
40+ fun startTracking (gameViewModel : GameViewModel ) {
41+
42+ // validate healthService and tracker
43+ val healthService = healthService ? : throw IllegalStateException (" Health service not connected" )
44+ val tracker = healthService.getHealthTracker(HealthTrackerType .HEART_RATE_CONTINUOUS )
45+ ? : throw IllegalStateException (" Heart rate tracking not supported" )
46+
47+ tracker.setEventListener(object : HealthTracker .TrackerEventListener {
48+ override fun onDataReceived (dataPoints : List <DataPoint >) = dataPoints.forEach {
49+ val (hr,ibi) = it.toHeartRateData()
50+ gameViewModel.addEvent(
51+ SessionEvent .heartRate(
52+ gameViewModel.playerId,
53+ gameViewModel.getCurrentGameTime(),
54+ " ${hr} ;${ibi} "
55+ )
56+ )
57+ }
58+ override fun onFlushCompleted () = Unit
59+ override fun onError (error : HealthTracker .TrackerError ) {
60+ Log .e(TAG , " Error: $error " )
61+ }
62+ })
63+ this .tracker = tracker
64+ }
65+
66+ private fun DataPoint.toHeartRateData () =
67+ getValue(ValueKey .HeartRateSet .HEART_RATE ) to
68+ (getValue(ValueKey .HeartRateSet .IBI_LIST ).lastOrNull() ? : 0 )
69+
70+ companion object {
71+ private const val TAG = " HeartRateMonitor"
72+ }
73+ }
0 commit comments