[U] Update usage in service

This commit is contained in:
Azalea Gui
2023-01-24 12:10:52 -05:00
parent 595ae7b70a
commit 7f09f6ab6c
2 changed files with 13 additions and 8 deletions
@@ -12,11 +12,12 @@ import com.influxdb.client.kotlin.InfluxDBClientKotlin
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.hydev.wearsync.BatteryInfo.Companion.batteryInfo import org.hydev.wearsync.BatteryInfo.Companion.batteryInfo
import org.hydev.wearsync.bles.BluetoothHandler.Companion.ble import org.hydev.wearsync.bles.BluetoothHandler.Companion.ble
import org.hydev.wearsync.bles.decoders.BatteryDecoder
import org.hydev.wearsync.bles.decoders.HeartRateDecoder
import org.hydev.wearsync.bles.decoders.IDecoder
import timber.log.Timber import timber.log.Timber
@@ -41,13 +42,13 @@ class MyService : Service()
fun startCollect() fun startCollect()
{ {
collect(ble.heartRateChannel) observe<BatteryDecoder>()
collect(ble.batteryChannel) observe<HeartRateDecoder>()
} }
private fun <T : Any> collect(channel: Channel<T>) { private inline fun <reified T : IDecoder<out Any>> observe() {
scope.launch { ble.observeAny<T> {
channel.consumeAsFlow().collect { scope.launch {
try { try {
println("Adding ${it.javaClass.simpleName} to influxdb") println("Adding ${it.javaClass.simpleName} to influxdb")
influx add it influx add it
@@ -33,11 +33,15 @@ internal class BluetoothHandler private constructor(context: Context) {
val listeners = HashMap<KClass<*>, MutableList<(Any) -> Unit>>() val listeners = HashMap<KClass<*>, MutableList<(Any) -> Unit>>()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
inline fun <M : Any, reified D : IDecoder<M>> observe(crossinline cb: (M) -> Unit) { inline fun <M : Any, reified D : IDecoder<out M>> observe(crossinline cb: (M) -> Unit) {
(listeners[D::class] ?: error("Cannot observe unknown decoder class ${D::class}")) (listeners[D::class] ?: error("Cannot observe unknown decoder class ${D::class}"))
.add { cb(it as M) } .add { cb(it as M) }
} }
inline fun <reified D : IDecoder<out Any>> observeAny(noinline cb: (Any) -> Unit) {
(listeners[D::class] ?: error("Cannot observe unknown decoder class ${D::class}")).add(cb)
}
private suspend fun <T : Any> BluePeri.observe(dec: IDecoder<T>) { private suspend fun <T : Any> BluePeri.observe(dec: IDecoder<T>) {
val cls = dec::class val cls = dec::class
listeners[cls] = ArrayList() listeners[cls] = ArrayList()