Skip to content

Commit

Permalink
Added custom logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Reedyuk committed Aug 8, 2024
1 parent 7de964a commit 1f6960d
Show file tree
Hide file tree
Showing 17 changed files with 96 additions and 70 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Include the library in your own KMP project as a dependancy on your common targe

```
commonMain.dependancies {
implementation("dev.bluefalcon:blue-falcon:1.1.0")
implementation("dev.bluefalcon:blue-falcon:1.2.0")
}
```

Expand Down Expand Up @@ -94,6 +94,12 @@ This example can only be ran on a Raspberry pi, it will crash otherwise.

Open the index.html file in a web browser.

## Logger

BlueFalcon has a constructor that takes a Logger, you can implement your own logger, to handle and reduce or add to the noise generated.

Look at the PrintLnLogger object of an example of how to do this.

## Support

For a **bug, feature request, or cool idea**, please [file a Github issue](https://github.com/Reedyuk/blue-falcon/issues/new).
Expand Down
2 changes: 1 addition & 1 deletion library/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ org.gradle.configureondemand = false
android.useAndroidX=true
android.enableJetifier=true

version=1.1.1
version=1.2.0
group=dev.bluefalcon
libraryName=blue-falcon
kotlinx_coroutines_version=1.8.1
Expand Down
38 changes: 18 additions & 20 deletions library/src/androidMain/kotlin/dev/bluefalcon/BlueFalcon.kt
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
package dev.bluefalcon

import AdvertisementDataRetrievalKeys
import android.Manifest
import android.bluetooth.*
import android.bluetooth.BluetoothAdapter.STATE_CONNECTED
import android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED
import android.bluetooth.le.*
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.ParcelUuid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.nio.ByteBuffer
import java.util.*

actual class BlueFalcon actual constructor(private val context: ApplicationContext) {
actual class BlueFalcon actual constructor(
private val log: Logger,
private val context: ApplicationContext
) {
actual val delegates: MutableSet<BlueFalconDelegate> = mutableSetOf()
private val bluetoothManager: BluetoothManager =
context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
Expand All @@ -32,7 +30,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
actual val peripherals: NativeFlow<Set<BluetoothPeripheral>> = _peripherals.toNativeType(scope)

actual fun connect(bluetoothPeripheral: BluetoothPeripheral, autoConnect: Boolean) {
log("connect")
log.info("connect")
bluetoothPeripheral.bluetoothDevice.connectGatt(
context,
autoConnect,
Expand All @@ -42,7 +40,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

actual fun disconnect(bluetoothPeripheral: BluetoothPeripheral) {
log("disconnect")
log.info("disconnect")
val gatt = mGattClientCallback.gattForDevice(bluetoothPeripheral.bluetoothDevice)
gatt?.apply {
disconnect()
Expand All @@ -61,7 +59,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

actual fun scan(serviceUUID :String?) {
log("BT Scan started")
log.info("BT Scan started")
isScanning = true

val filterBuilder = ScanFilter.Builder()
Expand Down Expand Up @@ -220,7 +218,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
) {
mGattClientCallback.gattForDevice(bluetoothPeripheral.bluetoothDevice)
?.readDescriptor(bluetoothCharacteristicDescriptor)
log("readDescriptor -> ${bluetoothCharacteristicDescriptor.uuid}")
log.debug("readDescriptor -> ${bluetoothCharacteristicDescriptor.uuid}")
}

actual fun changeMTU(bluetoothPeripheral: BluetoothPeripheral, mtuSize: Int) {
Expand All @@ -238,7 +236,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

override fun onScanFailed(errorCode: Int) {
log("Failed to scan with code $errorCode")
log.error("Failed to scan with code $errorCode")
}

private fun addScanResult(result: ScanResult?) {
Expand Down Expand Up @@ -288,7 +286,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte

override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState)
log("onConnectionStateChange")
log.info("onConnectionStateChange")
gatt?.let { bluetoothGatt ->
bluetoothGatt.device.let {
//BluetoothProfile#STATE_DISCONNECTED} or {@link BluetoothProfile#STATE_CONNECTED}
Expand All @@ -311,13 +309,13 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
log("onServicesDiscovered")
log.info("onServicesDiscovered")
if (status != BluetoothGatt.GATT_SUCCESS) {
return
}
gatt?.device?.let { bluetoothDevice ->
gatt.services.let { services ->
log("onServicesDiscovered -> $services")
log.debug("onServicesDiscovered -> $services")
val bluetoothPeripheral = BluetoothPeripheral(bluetoothDevice)
bluetoothPeripheral._servicesFlow.tryEmit(services.map { BluetoothService(it) })
delegates.forEach {
Expand All @@ -330,7 +328,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte

override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
super.onMtuChanged(gatt, mtu, status)
log("onMtuChanged$mtu status:$status")
log.info("onMtuChanged$mtu status:$status")
if (status != BluetoothGatt.GATT_SUCCESS) {
return
}
Expand All @@ -342,7 +340,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) {
log("onReadRemoteRssi $rssi")
log.info("onReadRemoteRssi $rssi")
gatt?.device?.let { bluetoothDevice ->
val bluetoothPeripheral = BluetoothPeripheral(bluetoothDevice)
bluetoothPeripheral.rssi = rssi.toFloat()
Expand Down Expand Up @@ -374,10 +372,10 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
descriptor: BluetoothGattDescriptor?,
status: Int
) {
log("onDescriptorRead $descriptor")
log.info("onDescriptorRead $descriptor")
descriptor?.let { forcedDescriptor ->
gatt?.device?.let { bluetoothDevice ->
log("onDescriptorRead value ${forcedDescriptor.value}")
log.debug("onDescriptorRead value ${forcedDescriptor.value}")
delegates.forEach {
it.didReadDescriptor(
BluetoothPeripheral(bluetoothDevice),
Expand All @@ -393,10 +391,10 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
descriptor: BluetoothGattDescriptor?,
status: Int
) {
log("onDescriptorWrite $descriptor")
log.info("onDescriptorWrite $descriptor")
descriptor?.let { forcedDescriptor ->
gatt?.device?.let { bluetoothDevice ->
log("onDescriptorWrite value ${forcedDescriptor.value}")
log.debug("onDescriptorWrite value ${forcedDescriptor.value}")
delegates.forEach {
it.didWriteDescriptor(
BluetoothPeripheral(bluetoothDevice),
Expand Down
7 changes: 0 additions & 7 deletions library/src/androidMain/kotlin/dev/bluefalcon/Log.kt

This file was deleted.

9 changes: 6 additions & 3 deletions library/src/appleMain/kotlin/dev/bluefalcon/BlueFalcon.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import kotlinx.coroutines.flow.MutableStateFlow
import platform.CoreBluetooth.*
import platform.Foundation.*

actual class BlueFalcon actual constructor(private val context: ApplicationContext) {
actual class BlueFalcon actual constructor(
private val log: Logger,
private val context: ApplicationContext
) {
actual val delegates: MutableSet<BlueFalconDelegate> = mutableSetOf()

private val centralManager: CBCentralManager
private val bluetoothPeripheralManager = BluetoothPeripheralManager(this)
private val bluetoothPeripheralManager = BluetoothPeripheralManager(log, this)
actual var isScanning: Boolean = false

actual val scope = CoroutineScope(Dispatchers.Default)
Expand Down Expand Up @@ -177,7 +180,7 @@ actual class BlueFalcon actual constructor(private val context: ApplicationConte
}

actual fun changeMTU(bluetoothPeripheral: BluetoothPeripheral, mtuSize: Int) {
println("Change MTU size called but not needed.")
log.debug("Change MTU size called but not needed.")
delegates.forEach {
it.didUpdateMTU(bluetoothPeripheral)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
package dev.bluefalcon

import AdvertisementDataRetrievalKeys
import platform.CoreBluetooth.*
import platform.Foundation.NSData
import platform.Foundation.NSError
import platform.Foundation.NSNumber
import platform.darwin.NSObject

class BluetoothPeripheralManager constructor(
private val log: Logger,
private val blueFalcon: BlueFalcon
) : NSObject(), CBCentralManagerDelegateProtocol {
private val delegate = PeripheralDelegate(blueFalcon)
private val delegate = PeripheralDelegate(log, blueFalcon)

override fun centralManagerDidUpdateState(central: CBCentralManager) {
when (central.state) {
CBManagerStateUnknown -> log("State 0 is .unknown")
CBManagerStateResetting -> log("State 1 is .resetting")
CBManagerStateUnsupported -> log("State 2 is .unsupported")
CBManagerStateUnauthorized -> log("State 3 is .unauthorised")
CBManagerStatePoweredOff -> log("State 4 is .poweredOff")
CBManagerStatePoweredOn -> log("State 5 is .poweredOn")
else -> log("State ${central.state.toInt()}")
CBManagerStateUnknown -> log.info("State 0 is .unknown")
CBManagerStateResetting -> log.info("State 1 is .resetting")
CBManagerStateUnsupported -> log.info("State 2 is .unsupported")
CBManagerStateUnauthorized -> log.info("State 3 is .unauthorised")
CBManagerStatePoweredOff -> log.info("State 4 is .poweredOff")
CBManagerStatePoweredOn -> log.info("State 5 is .poweredOn")
else -> log.info("State ${central.state.toInt()}")
}
}

Expand All @@ -31,7 +31,7 @@ class BluetoothPeripheralManager constructor(
RSSI: NSNumber
) {
if (blueFalcon.isScanning) {
log("Discovered device ${didDiscoverPeripheral.name}:${didDiscoverPeripheral.identifier.UUIDString}")
log.info("Discovered device ${didDiscoverPeripheral.name}:${didDiscoverPeripheral.identifier.UUIDString}")
val device = BluetoothPeripheral(didDiscoverPeripheral, rssiValue = RSSI.floatValue)
val sharedAdvertisementData = mapNativeAdvertisementDataToShared(advertisementData)
blueFalcon._peripherals.tryEmit(blueFalcon._peripherals.value.plus(device))
Expand All @@ -45,7 +45,7 @@ class BluetoothPeripheralManager constructor(
}

override fun centralManager(central: CBCentralManager, didConnectPeripheral: CBPeripheral) {
log("DidConnectPeripheral ${didConnectPeripheral.name}")
log.info("DidConnectPeripheral ${didConnectPeripheral.name}")
val device = BluetoothPeripheral(didConnectPeripheral, rssiValue = null)
blueFalcon.delegates.forEach {
it.didConnect(device)
Expand All @@ -59,7 +59,7 @@ class BluetoothPeripheralManager constructor(
didDisconnectPeripheral: CBPeripheral,
error: NSError?
) {
log("DidDisconnectPeripheral ${didDisconnectPeripheral.name}")
log.info("DidDisconnectPeripheral ${didDisconnectPeripheral.name}")
val device = BluetoothPeripheral(didDisconnectPeripheral, rssiValue = null)
blueFalcon.delegates.forEach {
it.didDisconnect(device)
Expand Down
3 changes: 0 additions & 3 deletions library/src/appleMain/kotlin/dev/bluefalcon/Log.kt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import platform.Foundation.NSNumber
import platform.darwin.NSObject

class PeripheralDelegate constructor(
private val log: Logger,
private val blueFalcon: BlueFalcon
) : NSObject(), CBPeripheralDelegateProtocol {

override fun peripheral(peripheral: CBPeripheral, didDiscoverServices: NSError?) {
if (didDiscoverServices != null) {
println("Error with service discovery ${didDiscoverServices}")
log.error("Error with service discovery ${didDiscoverServices}")
} else {
val device = BluetoothPeripheral(peripheral, rssiValue = null)
blueFalcon.delegates.forEach {
Expand All @@ -31,7 +32,7 @@ class PeripheralDelegate constructor(
error: NSError?
) {
if (error != null) {
println("Error with characteristic discovery ${didDiscoverCharacteristicsForService}")
log.error("Error with characteristic discovery ${didDiscoverCharacteristicsForService}")
}
val device = BluetoothPeripheral(peripheral, rssiValue = null)
blueFalcon.delegates.forEach {
Expand All @@ -48,7 +49,7 @@ class PeripheralDelegate constructor(
error: NSError?
) {
if (error != null) {
println("Error with characteristic update ${error}")
log.error("Error with characteristic update ${error}")
}
println("didUpdateValueForCharacteristic")
val device = BluetoothPeripheral(peripheral, rssiValue = null)
Expand All @@ -66,10 +67,10 @@ class PeripheralDelegate constructor(
error: NSError?
) {
if (error != null) {
println("Error during characteristic write $error")
log.error("Error during characteristic write $error")
}

println("didWriteValueForCharacteristic")
log.info("didWriteValueForCharacteristic")
val device = BluetoothPeripheral(peripheral, rssiValue = null)
didWriteValueForDescriptor.characteristic?.let { characteristic ->
val characteristic = BluetoothCharacteristic(characteristic)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package dev.bluefalcon

enum class AdvertisementDataRetrievalKeys {
LocalName,
ManufacturerData,
ServiceUUIDsKey,
IsConnectable,
}
}
5 changes: 4 additions & 1 deletion library/src/commonMain/kotlin/dev/bluefalcon/BlueFalcon.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package dev.bluefalcon
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow

expect class BlueFalcon(context: ApplicationContext) {
expect class BlueFalcon(
log: Logger = PrintLnLogger,
context: ApplicationContext
) {

val scope: CoroutineScope

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package dev.bluefalcon

import AdvertisementDataRetrievalKeys
import kotlin.js.JsName

@JsName("BlueFalconDelegate")
Expand Down
18 changes: 17 additions & 1 deletion library/src/commonMain/kotlin/dev/bluefalcon/Log.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
package dev.bluefalcon

expect fun log(message: String)
object PrintLnLogger: Logger {
override fun error(message: String, cause: Throwable?) {
println("e: $message ${cause ?: ""}")
}

override fun warn(message: String, cause: Throwable?) {
println("w: $message ${cause ?: ""}")
}

override fun info(message: String, cause: Throwable?) {
println("i: $message ${cause ?: ""}")
}

override fun debug(message: String, cause: Throwable?) {
println("d: $message ${cause ?: ""}")
}
}
9 changes: 9 additions & 0 deletions library/src/commonMain/kotlin/dev/bluefalcon/Logger.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package dev.bluefalcon

interface Logger {
fun error(message: String, cause: Throwable? = null)
fun warn(message: String, cause: Throwable? = null)
fun info(message: String, cause: Throwable? = null)
fun debug(message: String, cause: Throwable? = null)
}

Loading

0 comments on commit 1f6960d

Please sign in to comment.