-
Notifications
You must be signed in to change notification settings - Fork 0
/
SensorViewModel.kt
338 lines (290 loc) · 11.9 KB
/
SensorViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package com.trime.f4r4w4y.autorr
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.graphics.Typeface
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.AudioManager
import android.media.ToneGenerator
import android.os.Handler
import android.os.Looper
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.*
import org.mozilla.javascript.NativeArray
import kotlin.math.roundToInt
class SensorViewModel(application: Application) : AndroidViewModel(application),
SensorEventListener {
private lateinit var sensorManager: SensorManager
private lateinit var gyroscope: Sensor
private lateinit var accelerometer: Sensor
private lateinit var fUtil: FileUtil
private lateinit var job: Job
private var gravity = FloatArray(3) { 0F }
private var accValue = FloatArray(3) { 0F }
private var gyrValue = FloatArray(3) { 0F }
private var calculationType = "respiration_rate"
companion object {
private const val dataSizeRR: Int = 6000 // takes 1 minute to acquired
private const val dataSizeHR: Int = 7500 // takes 1 minute to acquired
}
private fun registerSensors(calculationType: String) {
this.calculationType = calculationType
sensorManager =
getApplication<Application>().getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)?.let {
this.gyroscope = it
sensorManager.registerListener(
this,
this.gyroscope,
SensorManager.SENSOR_DELAY_FASTEST
)
} ?: run {
Snackbar.make(
View(getApplication<Application>().applicationContext),
"Your device have no gyroscope sensors !!!",
Snackbar.LENGTH_LONG
).show()
}
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.let {
this.accelerometer = it
sensorManager.registerListener(
this,
this.accelerometer,
SensorManager.SENSOR_DELAY_FASTEST
)
} ?: run {
Snackbar.make(
View(getApplication<Application>().applicationContext),
"Your device have no accelerometer sensors !!!",
Snackbar.LENGTH_LONG
).show()
}
}
fun unregisterSensors() {
if (this::sensorManager.isInitialized) sensorManager.unregisterListener(this)
}
@SuppressLint("SetTextI18n")
fun getAndEvaluateData(
jsCode: String,
funcName: String,
libs: Array<String>,
loadingBar: LinearProgressIndicator?,
progressText: TextView?,
loadingText: TextView?,
controllerButton: Button?,
finishCallback: (result: String) -> Unit
) {
fUtil = FileUtil(getApplication<Application>().applicationContext)
job = viewModelScope.launch {
registerSensors(if (funcName == "startCalculationRR") "respiration_rate" else "heart_rate")
// Get sensor data for 1 minute
val sensorData = getSensorData(
if (funcName == "startCalculationRR") dataSizeRR else dataSizeHR,
loadingBar,
progressText,
loadingText,
controllerButton
)
// Unregister sensor to not waste any batteries
unregisterSensors()
// Calculate respiration rate from acquired data and return the result
val result: NativeArray? = calculateData(jsCode, funcName, libs, sensorData)
result?.joinToString(",\n")
?.let { finishCallback(it) }
}
}
fun cancelJob() {
if (this::job.isInitialized && job.isActive) {
job.cancel()
unregisterSensors()
}
}
@Suppress("UNCHECKED_CAST")
private suspend fun <T> calculateData(
jsCode: String,
funcName: String,
libs: Array<String>,
sensorData: Array<FloatArray>
): T? = withContext(Dispatchers.Default) {
delay(50) // Weirdly needed, to let the suspend works ?
val (timeArr, accX, accY, accZ, gyrX, gyrY, gyrZ) = sensorData
val rhinoInterpreter = RhinoInterpreter()
// Load all the libraries first
libs.forEach {
rhinoInterpreter.loadLib(it)
}
// Load the main script
rhinoInterpreter.evalScript(jsCode, "javascriptEvaluation")
// Run the corresponding function
val result: Any?
if (calculationType == "respiration_rate")
result = rhinoInterpreter.callJsFunction(
funcName,
timeArr,
accX,
accY,
accZ,
gyrX,
gyrY,
gyrZ
)
else
result = rhinoInterpreter.callJsFunction(
funcName,
timeArr,
accX,
accY,
accZ
)
return@withContext result as T
}
private fun makeSectionOfTextBold(text: String, textToBold: String): SpannableStringBuilder? {
val builder = SpannableStringBuilder()
if (textToBold.isNotEmpty() && textToBold.trim { it <= ' ' } != "") {
//for counting start/end indexes
val testText = text.lowercase()
val testTextToBold = textToBold.lowercase()
val startingIndex = testText.indexOf(testTextToBold)
val endingIndex = startingIndex + testTextToBold.length
//for counting start/end indexes
if (startingIndex < 0 || endingIndex < 0) {
return builder.append(text)
} else if (startingIndex >= 0 && endingIndex >= 0) {
builder.append(text)
builder.setSpan(StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0)
}
} else {
return builder.append(text)
}
return builder
}
@SuppressLint("SetTextI18n")
private suspend fun getSensorData(
dataSize: Int,
loadingBar: LinearProgressIndicator?,
progressText: TextView?,
loadingText: TextView?,
controllerButton: Button?
): Array<FloatArray> {
delay(1000) // Weirdly needed, to let the sensor register itself first
val firstVal = if (dataSize == dataSizeRR) "0.01" else "0.008"
val formatter = if (dataSize == dataSizeRR) "%.2f" else "%.3f"
val delaySize: Long = if (dataSize == dataSizeRR) 1 else 6
var time = 0L
var lastSeconds = String.format(formatter, -1F).toFloat()
var seconds: Float
var timeArr: FloatArray = floatArrayOf()
var accX: FloatArray = floatArrayOf()
var accY: FloatArray = floatArrayOf()
var accZ: FloatArray = floatArrayOf()
var gyrX: FloatArray = floatArrayOf()
var gyrY: FloatArray = floatArrayOf()
var gyrZ: FloatArray = floatArrayOf()
while (timeArr.size != dataSize) {
delay(delaySize) // Weirdly needed, to let the sensor update the value first
if (time == 0L) time = System.currentTimeMillis()
seconds =
String.format(formatter, (System.currentTimeMillis() - time) / 1000F).toFloat()
val progress = ((timeArr.size.toDouble() / dataSize.toDouble()) * 100).roundToInt()
loadingText?.text = "${progress}/100"
loadingBar?.progress = progress
// Dirty trick because apparently it didn't work if you put it
// in other place without rendering it multiple times ¯\_(ツ)_/¯
if (progress > 98) {
val text = makeSectionOfTextBold(
(if (dataSize == dataSizeRR) getApplication<Application>().applicationContext.getString(
R.string.wait2RR_text
) else getApplication<Application>().applicationContext.getString(R.string.wait2HR_text)).toString(),
if (dataSize == dataSizeRR) "respiration rate" else "heart rate"
)
progressText?.text = text
}
if (!formatter.format(lastSeconds).contentEquals(formatter.format(seconds))) {
lastSeconds = seconds
timeArr = timeArr.plus(seconds)
accX = accX.plus(accValue[0])
accY = accY.plus(accValue[1])
accZ = accZ.plus(accValue[2])
gyrX = gyrX.plus(gyrValue[0])
gyrY = gyrY.plus(gyrValue[1])
gyrZ = gyrZ.plus(gyrValue[2])
Log.d(
"AAA",
"getSensorData: $seconds, ${accValue[0]}, ${accValue[1]}, ${accValue[2]}, ${gyrValue[0]}, ${gyrValue[1]}, ${gyrValue[2]}"
)
}
// Reset calculation if first two frequencies is not aligned correctly
if (timeArr.size > 1 && !formatter.format(timeArr[1] - timeArr[0])
.contentEquals(firstVal)
) {
time = 0L
lastSeconds = String.format(formatter, -1F).toFloat()
timeArr = floatArrayOf()
accX = floatArrayOf()
accY = floatArrayOf()
accZ = floatArrayOf()
gyrX = floatArrayOf()
gyrY = floatArrayOf()
gyrZ = floatArrayOf()
}
}
playSound()
loadingBar?.isIndeterminate = true
controllerButton?.isEnabled = false
return arrayOf(timeArr, accX, accY, accZ, gyrX, gyrY, gyrZ)
}
private fun playSound(duration: Int = 300) {
val toneG = ToneGenerator(AudioManager.STREAM_MUSIC, 100)
toneG.startTone(ToneGenerator.TONE_DTMF_S, duration)
Handler(Looper.getMainLooper()).postDelayed({
toneG.release()
}, (duration + 50).toLong())
}
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor.type == Sensor.TYPE_GYROSCOPE) {
gyrValue[0] = event.values[0]
gyrValue[1] = event.values[1]
gyrValue[2] = event.values[2]
} else if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
// In this example, alpha is calculated as t / (t + dT),
// where t is the low-pass filter's time-constant and
// dT is the event delivery rate.
val alpha = 0.8f
// Isolate the force of gravity with the low-pass filter.
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0]
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1]
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2]
if (calculationType == "respiration_rate") {
// Remove the gravity contribution with the high-pass filter.
accValue[0] = event.values[0] - gravity[0]
accValue[1] = event.values[1] - gravity[1]
accValue[2] = event.values[2] - gravity[2] - gravity[2]
} else {
accValue[0] = event.values[0] * gravity[0]
accValue[1] = event.values[1] * gravity[1]
accValue[2] = event.values[2] * gravity[2] - gravity[2]
}
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
// Do nothing
}
}
private operator fun <T> Array<T>.component6(): T {
return get(5)
}
private operator fun <T> Array<T>.component7(): T {
return get(6)
}