Skip to content

Commit

Permalink
reformat bluetooth module for new kotlin codestyle
Browse files Browse the repository at this point in the history
  • Loading branch information
crc-32 committed Jun 14, 2024
1 parent 1bb8716 commit 49233bc
Show file tree
Hide file tree
Showing 24 changed files with 79 additions and 82 deletions.
4 changes: 2 additions & 2 deletions android/pebble_bt_transport/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ android {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import androidx.test.filters.RequiresDevice
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import io.rebble.cobble.bluetooth.ProtocolIO
import io.rebble.libpebblecommon.PacketPriority
import io.rebble.libpebblecommon.ProtocolHandlerImpl
import io.rebble.libpebblecommon.disk.PbwBinHeader
import io.rebble.libpebblecommon.metadata.WatchType
Expand All @@ -17,7 +16,6 @@ import io.rebble.libpebblecommon.metadata.pbw.manifest.PbwManifest
import io.rebble.libpebblecommon.packets.*
import io.rebble.libpebblecommon.packets.blobdb.BlobCommand
import io.rebble.libpebblecommon.packets.blobdb.BlobResponse
import io.rebble.libpebblecommon.packets.blobdb.PushNotification
import io.rebble.libpebblecommon.protocolhelpers.PebblePacket
import io.rebble.libpebblecommon.protocolhelpers.ProtocolEndpoint
import io.rebble.libpebblecommon.services.AppFetchService
Expand All @@ -30,7 +28,6 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import okio.buffer
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,19 @@ import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.ParcelUuid
import androidx.test.filters.RequiresDevice
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import io.rebble.cobble.bluetooth.ble.connectGatt
import io.rebble.libpebblecommon.ble.LEConstants
import io.rebble.libpebblecommon.util.runBlocking
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.withTimeout
import org.junit.Test
import org.junit.Assert.*
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import timber.log.Timber
import java.util.UUID

@RequiresDevice
@OptIn(FlowPreview::class)
Expand Down Expand Up @@ -54,6 +46,7 @@ class PebbleLEConnectorTest {
val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
bluetoothAdapter = bluetoothManager.adapter
}

private fun removeBond(device: BluetoothDevice) {
device::class.java.getMethod("removeBond").invoke(device) // Internal API
}
Expand All @@ -74,12 +67,12 @@ class PebbleLEConnectorTest {
order.add(it)
}
assertEquals(
listOf(
PebbleLEConnector.ConnectorState.CONNECTING,
PebbleLEConnector.ConnectorState.PAIRING,
PebbleLEConnector.ConnectorState.CONNECTED
),
order
listOf(
PebbleLEConnector.ConnectorState.CONNECTING,
PebbleLEConnector.ConnectorState.PAIRING,
PebbleLEConnector.ConnectorState.CONNECTED
),
order
)
connection.close()
}
Expand All @@ -99,11 +92,11 @@ class PebbleLEConnectorTest {
order.add(it)
}
assertEquals(
listOf(
PebbleLEConnector.ConnectorState.CONNECTING,
PebbleLEConnector.ConnectorState.CONNECTED
),
order
listOf(
PebbleLEConnector.ConnectorState.CONNECTING,
PebbleLEConnector.ConnectorState.CONNECTED
),
order
)
connection.close()
}
Expand Down
1 change: 1 addition & 0 deletions android/pebble_bt_transport/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
Expand Down
6 changes: 2 additions & 4 deletions android/pebble_bt_transport/src/main/assets/logback.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
<configuration
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://tony19.github.io/logback-android/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://tony19.github.io/logback-android/xml https://cdn.jsdelivr.net/gh/tony19/logback-android/logback.xsd"
>
xsi:schemaLocation="https://tony19.github.io/logback-android/xml https://cdn.jsdelivr.net/gh/tony19/logback-android/logback.xsd">
<appender name="timber" class="io.rebble.cobble.TimberLogbackAppender">
<tagEncoder>
<pattern>%logger{12}</pattern>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.UnsynchronizedAppenderBase
import timber.log.Timber

class TimberLogbackAppender: UnsynchronizedAppenderBase<ILoggingEvent>() {
class TimberLogbackAppender : UnsynchronizedAppenderBase<ILoggingEvent>() {
override fun append(eventObject: ILoggingEvent?) {
if (eventObject == null) {
return
Expand All @@ -31,27 +31,31 @@ class TimberLogbackAppender: UnsynchronizedAppenderBase<ILoggingEvent>() {
Timber.tag(eventObject.loggerName).v(message)
}
}

Level.DEBUG_INT -> {
if (throwable != null) {
Timber.tag(eventObject.loggerName).d(throwable, message)
} else {
Timber.tag(eventObject.loggerName).d(message)
}
}

Level.INFO_INT -> {
if (throwable != null) {
Timber.tag(eventObject.loggerName).i(throwable, message)
} else {
Timber.tag(eventObject.loggerName).i(message)
}
}

Level.WARN_INT -> {
if (throwable != null) {
Timber.tag(eventObject.loggerName).w(throwable, message)
} else {
Timber.tag(eventObject.loggerName).w(message)
}
}

Level.ERROR_INT -> {
if (throwable != null) {
Timber.tag(eventObject.loggerName).e(throwable, message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package io.rebble.cobble.bluetooth

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.pm.PackageManager
import androidx.annotation.RequiresPermission
import androidx.core.app.ActivityCompat
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow

Expand All @@ -14,7 +12,7 @@ interface BlueIO {
fun startSingleWatchConnection(device: PebbleDevice): Flow<SingleConnectionStatus>
}

data class PebbleDevice (
data class PebbleDevice(
val bluetoothDevice: BluetoothDevice?,
val emulated: Boolean,
val address: String
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.rebble.cobble.bluetooth

import io.rebble.libpebblecommon.ProtocolHandler
import io.rebble.libpebblecommon.protocolhelpers.PebblePacket
import io.rebble.libpebblecommon.protocolhelpers.ProtocolEndpoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ class BlueGATTConnection(val device: BluetoothDevice, private val cbTimeout: Lon
}

fun getService(uuid: UUID): BluetoothGattService? = gatt!!.getService(uuid)

@Throws(SecurityException::class)
fun setCharacteristicNotification(characteristic: BluetoothGattCharacteristic, enable: Boolean) = gatt!!.setCharacteristicNotification(characteristic, enable)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ class BlueLEDriver(
private val gattServerManager: GattServerManager,
private val incomingPacketsListener: MutableSharedFlow<ByteArray>,
private val workaroundResolver: (WorkaroundDescriptor) -> Boolean
): BlueIO {
) : BlueIO {
private val scope = CoroutineScope(coroutineContext)

@OptIn(FlowPreview::class)
@Throws(SecurityException::class)
override fun startSingleWatchConnection(device: PebbleDevice): Flow<SingleConnectionStatus> {
Expand Down Expand Up @@ -93,7 +94,8 @@ class BlueLEDriver(
}
val rxJob = gattServer.rxFlowFor(device.address)?.onEach {
rxStream.write(it)
}?.flowOn(Dispatchers.IO)?.launchIn(scope) ?: throw IOException("Failed to get rxFlow")
}?.flowOn(Dispatchers.IO)?.launchIn(scope)
?: throw IOException("Failed to get rxFlow")
val sendLoop = scope.launch(Dispatchers.IO) {
protocolHandler.startPacketSendingLoop {
gattServer.sendMessageToDevice(device.address, it.asByteArray())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package io.rebble.cobble.bluetooth.ble
import io.rebble.libpebblecommon.ble.LEConstants
import timber.log.Timber
import java.nio.ByteBuffer
import java.util.*
import java.util.UUID

/**
* Handles negotiating and reading changes to connection parameters, currently this feature is unused by us so it just tells the pebble to disable it
Expand All @@ -26,7 +26,7 @@ class ConnectionParamManager(val gatt: BlueGATTConnection) {
val configDescriptor = characteristic.getDescriptor(UUID.fromString(LEConstants.UUIDs.CHARACTERISTIC_CONFIGURATION_DESCRIPTOR))
if (gatt.readDescriptor(configDescriptor)?.descriptor?.value.contentEquals(LEConstants.CHARACTERISTIC_SUBSCRIBE_VALUE)) {
Timber.w("Already subscribed to conn params")
}else {
} else {
if (gatt.writeDescriptor(configDescriptor, LEConstants.CHARACTERISTIC_SUBSCRIBE_VALUE)?.isSuccess() == true) {
if (gatt.setCharacteristicNotification(characteristic, true)) {
val mgmtData = ByteBuffer.allocate(2)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import android.bluetooth.BluetoothGattCharacteristic
import io.rebble.libpebblecommon.ble.LEConstants
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.mapNotNull
import timber.log.Timber
import java.util.*
import java.util.UUID
import kotlin.experimental.and
import kotlin.properties.Delegates

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import android.content.Context
import androidx.annotation.RequiresPermission
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterNotNull
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package io.rebble.cobble.bluetooth.ble

import android.bluetooth.BluetoothGatt
import java.util.*
import java.util.Locale

class GattStatus(val value: Int) {
override fun toString(): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,20 @@ import no.nordicsemi.android.kotlin.ble.server.main.service.ServerBleGattCharact
import no.nordicsemi.android.kotlin.ble.server.main.service.ServerBleGattDescriptorConfig
import no.nordicsemi.android.kotlin.ble.server.main.service.ServerBleGattServiceConfig
import no.nordicsemi.android.kotlin.ble.server.main.service.ServerBleGattServiceType
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.LoggerFactoryFriend
import timber.log.Timber
import java.io.Closeable
import java.io.IOException
import java.util.UUID
import kotlin.coroutines.CoroutineContext

@OptIn(FlowPreview::class)
class NordicGattServer(private val ioDispatcher: CoroutineContext = Dispatchers.IO, private val context: Context): Closeable {
class NordicGattServer(private val ioDispatcher: CoroutineContext = Dispatchers.IO, private val context: Context) : Closeable {
enum class State {
INIT,
OPEN,
CLOSED
}

private val _state = MutableStateFlow(State.INIT)
val state = _state.asStateFlow()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package io.rebble.cobble.bluetooth.ble

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

object PPoGLinkStateManager {
private val states = mutableMapOf<String, MutableStateFlow<PPoGLinkState>>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ package io.rebble.cobble.bluetooth.ble

import androidx.annotation.RequiresPermission
import io.rebble.libpebblecommon.ble.GATTPacket
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.Closeable
import java.util.LinkedList
import kotlin.jvm.Throws

class PPoGPacketWriter(private val scope: CoroutineScope, private val stateManager: PPoGSession.StateManager, private val onTimeout: () -> Unit): Closeable {
class PPoGPacketWriter(private val scope: CoroutineScope, private val stateManager: PPoGSession.StateManager, private val onTimeout: () -> Unit) : Closeable {
private var metaWaitingToSend: GATTPacket? = null
val dataWaitingToSend: LinkedList<GATTPacket> = LinkedList()
val inflightPackets: LinkedList<GATTPacket> = LinkedList()
Expand Down Expand Up @@ -134,7 +135,7 @@ class PPoGPacketWriter(private val scope: CoroutineScope, private val stateManag
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private suspend fun sendPacket(packet: GATTPacket) {
val data = packet.toByteArray()
require(data.size <= (stateManager.mtuSize-3)) {"Packet too large to send: ${data.size} > ${stateManager.mtuSize}-3"}
require(data.size <= (stateManager.mtuSize - 3)) { "Packet too large to send: ${data.size} > ${stateManager.mtuSize}-3" }
_packetWriteFlow.emit(packet)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class PPoGPebblePacketAssembler {
val ep = SUShort(meta)
meta.fromBytes(DataBuffer(header.asUByteArray()))
val packetLength = length.get()
data = ByteBuffer.allocate(packetLength.toInt()+4)
data = ByteBuffer.allocate(packetLength.toInt() + 4)
data!!.put(header)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import java.io.Closeable
import java.util.UUID

@OptIn(FlowPreview::class)
class PPoGServiceConnection(private var serverConnection: ServerBluetoothGattConnection, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO): Closeable {
class PPoGServiceConnection(private var serverConnection: ServerBluetoothGattConnection, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO) : Closeable {
private var scope = serverConnection.connectionScope + ioDispatcher + CoroutineName("PPoGServiceConnection-${serverConnection.device.address}")
private val sessionScope = CoroutineScope(ioDispatcher) + CoroutineName("PPoGSession-${serverConnection.device.address}")
private val ppogSession = PPoGSession(sessionScope, serverConnection.device.address, LEConstants.DEFAULT_MTU)
Expand Down Expand Up @@ -96,6 +96,7 @@ class PPoGServiceConnection(private var serverConnection: ServerBluetoothGattCon
it.result.complete(false)
}
}

is PPoGSession.PPoGSessionResponse.PebblePacket -> {
_incomingPebblePackets.trySend(it.packet).getOrThrow()
}
Expand Down
Loading

0 comments on commit 49233bc

Please sign in to comment.