### Install BLESSED Library using Gradle Source: https://context7.com/weliem/blessed-kotlin/llms.txt This snippet shows how to add the BLESSED library and its dependency to your Android project's Gradle configuration. It includes adding the JitPack repository and the library dependency itself. Timber is also included as a recommended logging utility. ```groovy // settings.gradle or root build.gradle allprojects { repositories { maven { url 'https://jitpack.io' } } } // app/build.gradle dependencies { implementation "com.github.weliem:blessed-kotlin:3.0.0" implementation 'com.jakewharton.timber:timber:5.0.1' } ``` -------------------------------- ### Bluetooth Bonding Callbacks in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Callbacks to monitor the Bluetooth bonding process. These include notifications for when bonding starts, succeeds, fails, or is lost. They receive the peripheral object involved in the bonding process. ```kotlin fun onBondingStarted(peripheral: BluetoothPeripheral) fun onBondingSucceeded(peripheral: BluetoothPeripheral) fun onBondingFailed(peripheral: BluetoothPeripheral) fun onBondLost(peripheral: BluetoothPeripheral) ``` -------------------------------- ### Manage Bluetooth Notifications in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Convenience methods to start and stop notifications/indications for Bluetooth characteristics. These methods handle descriptor writes automatically. Input includes characteristic objects or UUIDs. A callback confirms the notification state change. ```kotlin val currentTimeCharacteristic = peripheral.getCharacteristic(CTS_SERVICE_UUID, CURRENT_TIME_CHARACTERISTIC_UUID)?.let { peripheral.startNotify(it) } peripheral.startNotify(CTS_SERVICE_UUID, CURRENT_TIME_CHARACTERISTIC_UUID) ``` -------------------------------- ### Get Bluetooth Peripheral by MAC Address (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Retrieves a BluetoothPeripheral object using its MAC address. This is useful for obtaining a peripheral object to initiate connection or auto-connection when only the address is known. ```kotlin val peripheral = central.getPeripheral("CF:A9:BA:D9:62:9E"); ``` -------------------------------- ### Connect to a Bluetooth Peripheral Immediately (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Attempts to establish an immediate connection to a previously discovered Bluetooth peripheral. This method has a timeout (typically 30 seconds) and only one outstanding connection attempt is allowed at a time. A callback is required for connection status updates. ```kotlin fun connect(peripheral: BluetoothPeripheral, peripheralCallback: BluetoothPeripheralCallback) ``` -------------------------------- ### Initiate and Manage Bluetooth Bonding in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Methods to manually initiate or remove Bluetooth bonding with a peripheral. `createBond` can be called before or after connection. `removeBond` removes the bond and the peripheral from settings. `setPinCodeForPeripheral` automates PIN entry. ```kotlin peripheral.createBond() peripheral.removeBond() peripheral.setPinCodeForPeripheral(pinCode: ByteArray) ``` -------------------------------- ### Batch Auto-Connect to Bluetooth Peripherals (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Initiates auto-connection to multiple Bluetooth peripherals simultaneously. This is useful for re-connecting to many known devices efficiently, especially when individual auto-connect calls might trigger scanner limitations. A map of peripherals to their callbacks is required. ```kotlin fun autoConnectBatch(batch: Map) ``` -------------------------------- ### Add Blessed-Kotlin and Timber Dependencies (Kotlin DSL) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md This snippet demonstrates how to add the Blessed-Kotlin library and the Timber logging library to your Android project using Kotlin DSL for Gradle configuration. Remember to substitute `$version` with the actual latest version. ```kotlin dependencyResolutionManagement { repositories { ... maven { setUrl("https://jitpack.io") } } } dependencies { implementation("com.github.weliem:blessed-kotlin:$version") implementation("com.jakewharton.timber:timber:5.0.1") } ``` -------------------------------- ### Add Blessed-Kotlin and Timber Dependencies (Groovy) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md This snippet shows how to add the Blessed-Kotlin library and the Timber logging library to your Android project's Gradle configuration using Groovy syntax. Ensure you replace `$version` with the latest published version. ```groovy allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation "com.github.weliem:blessed-kotlin:$version" implementation 'com.jakewharton.timber:timber:5.0.1' } ``` -------------------------------- ### Bluetooth Service Discovery Callback (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Callback triggered automatically by the BLESSED library once service discovery for a connected peripheral is complete. After this callback, services and characteristics can be accessed using methods like `getServices()` or `getCharacteristic()`. ```kotlin fun onServicesDiscovered(peripheral: BluetoothPeripheral) ``` -------------------------------- ### Bluetooth Connection Callbacks (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Defines the callbacks received after initiating a connection to a Bluetooth peripheral. These include successful connection, connection failure, and disconnection events, each providing the relevant peripheral object and status information. ```kotlin fun onConnected(peripheral: BluetoothPeripheral) fun onConnectionFailed(peripheral: BluetoothPeripheral, status: HciStatus) fun onDisconnected(peripheral: BluetoothPeripheral, status: HciStatus) ``` -------------------------------- ### Implement BLE Peripheral Role in Kotlin Source: https://context7.com/weliem/blessed-kotlin/llms.txt This snippet demonstrates the core implementation of a BLE peripheral using the `BluetoothPeripheralManager` in Kotlin. It covers initializing the manager, defining services and characteristics, handling GATT operations (read, write, notifications), and managing central connections. Dependencies include Android Bluetooth APIs and the blessed-kotlin library. ```kotlin import android.bluetooth.* import android.bluetooth.le.* import android.os.ParcelUuid import com.welie.blessed.* import java.util.UUID val HEART_RATE_SERVICE_UUID = UUID.fromString("0000180D-0000-1000-8000-00805f9b34fb") val HEART_RATE_MEASUREMENT_UUID = UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb") val CCC_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") // Create peripheral manager callback val peripheralManagerCallback = object : BluetoothPeripheralManagerCallback() { override fun onServiceAdded(status: GattStatus, service: BluetoothGattService) { if (status == GattStatus.SUCCESS) { println("Service ${service.uuid} added successfully") startAdvertising() } } override fun onCentralConnected(central: BluetoothCentral) { println("Central connected: ${central.address}") } override fun onCentralDisconnected(central: BluetoothCentral) { println("Central disconnected: ${central.address}") } override fun onCharacteristicRead( central: BluetoothCentral, characteristic: BluetoothGattCharacteristic ): ReadResponse { return when (characteristic.uuid) { HEART_RATE_MEASUREMENT_UUID -> { val heartRateData = BluetoothBytesBuilder() .addUInt8(0x00) // Flags .addUInt8(72) // Heart rate value .build() ReadResponse(GattStatus.SUCCESS, heartRateData) } else -> ReadResponse(GattStatus.REQUEST_NOT_SUPPORTED, byteArrayOf()) } } override fun onCharacteristicWrite( central: BluetoothCentral, characteristic: BluetoothGattCharacteristic, value: ByteArray ): GattStatus { println("Received write: ${value.asHexString()}") return GattStatus.SUCCESS } override fun onCharacteristicWriteCompleted( central: BluetoothCentral, characteristic: BluetoothGattCharacteristic, value: ByteArray ) { println("Write completed for ${characteristic.uuid}") } override fun onNotifyingEnabled(central: BluetoothCentral, characteristic: BluetoothGattCharacteristic) { println("Notifications enabled for ${characteristic.uuid}") // Start sending notifications } override fun onNotifyingDisabled(central: BluetoothCentral, characteristic: BluetoothGattCharacteristic) { println("Notifications disabled for ${characteristic.uuid}") } override fun onAdvertisingStarted(settingsInEffect: AdvertiseSettings) { println("Advertising started") } override fun onAdvertisingStopped() { println("Advertising stopped") } override fun onAdvertiseFailure(advertiseError: AdvertiseError) { println("Advertising failed: $advertiseError") } } // Initialize peripheral manager val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager val peripheralManager = BluetoothPeripheralManager(context, bluetoothManager, peripheralManagerCallback) peripheralManager.openGattServer() // Create and add a service fun createHeartRateService(): BluetoothGattService { val service = BluetoothGattService(HEART_RATE_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY) val characteristic = BluetoothGattCharacteristic( HEART_RATE_MEASUREMENT_UUID, BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ ) val descriptor = BluetoothGattDescriptor( CCC_DESCRIPTOR_UUID, BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE ) characteristic.addDescriptor(descriptor) service.addCharacteristic(characteristic) return service } peripheralManager.add(createHeartRateService()) // Start advertising fun startAdvertising() { val settings = AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) .setConnectable(true) .setTimeout(0) .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) .build() val advertiseData = AdvertiseData.Builder() .setIncludeDeviceName(true) .addServiceUuid(ParcelUuid(HEART_RATE_SERVICE_UUID)) .build() val scanResponse = AdvertiseData.Builder() .setIncludeTxPowerLevel(true) .build() peripheralManager.startAdvertising(settings, advertiseData, scanResponse) } // Send notification to all connected centrals fun sendHeartRateNotification(heartRate: Int) { val characteristic = peripheralManager.services ``` -------------------------------- ### Scan for Bluetooth Peripherals by Address (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Initiates a scan for Bluetooth peripherals that match a given set of peripheral addresses (MAC addresses). This method is part of the BluetoothCentralManager and requires a callback to be registered for discovered peripherals. Only one scan type can be active at a time. ```kotlin fun scanForPeripheralsWithAddresses(peripheralAddresses: Set) ``` -------------------------------- ### Scan for Bluetooth Peripherals by Name (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Initiates a scan for Bluetooth peripherals that match a given set of peripheral names. This method is part of the BluetoothCentralManager and requires a callback to be registered for discovered peripherals. Only one scan type can be active at a time. ```kotlin fun scanForPeripheralsWithNames(peripheralNames: Set) ``` -------------------------------- ### Configuring Bluetooth 5 PHY Options Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Enables setting preferred Physical Layer (Phy) options for Bluetooth 5 connections to optimize for speed or range. Options include LE_1M, LE_2M, and LE_CODED (with S2/S8 for extended range). The negotiated Phy is reported via `onPhyUpdate`. ```kotlin fun setPreferredPhy(txPhy: PhyType, rxPhy: PhyType, phyOptions: PhyOptions) fun onPhyUpdate(peripheral: BluetoothPeripheral, txPhy: PhyType, rxPhy: PhyType, status: GattStatus) peripheral.readPhy() ``` -------------------------------- ### Scan for Bluetooth Peripherals with Services (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Initiates a scan for Bluetooth peripherals that advertise a specific set of service UUIDs. This method is part of the BluetoothCentralManager and requires a callback to be registered for discovered peripherals. Only one scan type can be active at a time. ```kotlin fun scanForPeripheralsWithServices(serviceUUIDs: Set) ``` ```kotlin val centralManagerCallback = object : BluetoothCentralManagerCallback() { override fun onDiscovered(peripheral: BluetoothPeripheral, scanResult: ScanResult) { Timber.i("Found peripheral '${peripheral.name}' with RSSI ${scanResult.rssi}") centralManager.stopScan() centralManager.connect(peripheral, bluetoothPeripheralCallback) } } // Create BluetoothCentral and receive callbacks on the main thread val central = BluetoothCentralManager(getApplicationContext(), centralManagerCallback, new Handler(Looper.getMainLooper())); // Define blood pressure service UUID val BLP_SERVICE_UUID: UUID = UUID.fromString("00001810-0000-1000-8000-00805f9b34fb") // Scan for peripherals with a certain service UUID central.scanForPeripheralsWithServices(listOf(BLOODPRESSURE_SERVICE_UUID)); ``` -------------------------------- ### Read and Write Bluetooth Characteristics in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Provides methods for asynchronously reading from and writing to Bluetooth characteristics. Operations are queued and callbacks are used to receive results. Input includes characteristic objects or UUIDs, byte arrays for writing, and write types. ```kotlin fun readCharacteristic(characteristic: BluetoothGattCharacteristic) fun readCharacteristic(serviceUUID: UUID, characteristicUUID: UUID) fun writeCharacteristic(characteristic: BluetoothGattCharacteristic, value: ByteArray, writeType: WriteType) fun writeCharacteristic(serviceUUID: UUID, characteristicUUID: UUID, value: ByteArray, writeType: WriteType) ``` -------------------------------- ### Auto-Connect to a Bluetooth Peripheral (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Configures the system to automatically reconnect to a known Bluetooth peripheral when it becomes available. This method does not time out and will connect whenever the device is detected. Multiple auto-connect requests can be outstanding. A callback is required for connection status updates. ```kotlin fun autoConnect(peripheral: BluetoothPeripheral, peripheralCallback: BluetoothPeripheralCallback) ``` -------------------------------- ### BLE Bonding and PIN Code Management (Kotlin) Source: https://context7.com/weliem/blessed-kotlin/llms.txt Manages BLE bonding and PIN code settings for peripherals. Allows setting fixed PIN codes, removing bonds, initiating bonding, and monitoring bonding events through callbacks. ```kotlin // Set a fixed PIN code for a peripheral (avoids system PIN dialog) centralManager.setPinCodeForPeripheral("AA:BB:CC:DD:EE:FF", "123456") // Remove bond for a peripheral centralManager.removeBond("AA:BB:CC:DD:EE:FF") // Initiate bonding before connecting (for peripherals that require it) val peripheral = centralManager.getPeripheral("AA:BB:CC:DD:EE:FF") centralManager.createBond(peripheral, peripheralCallback) // Monitor bonding in peripheral callback val peripheralCallback = object : BluetoothPeripheralCallback() { override fun onBondingStarted(peripheral: BluetoothPeripheral) { println("Bonding started") } override fun onBondingSucceeded(peripheral: BluetoothPeripheral) { println("Bonding succeeded, bond state: ${peripheral.bondState}") } override fun onBondingFailed(peripheral: BluetoothPeripheral) { println("Bonding failed") } override fun onBondLost(peripheral: BluetoothPeripheral) { println("Bond lost - peripheral may have been reset") } } // Helper to start pairing popup in foreground on some devices centralManager.startPairingPopupHack() ``` -------------------------------- ### Scan for Bluetooth Peripherals using Filters (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Initiates a scan for Bluetooth peripherals using a custom list of Android ScanFilters. This method provides more advanced filtering capabilities. Refer to Android documentation for detailed ScanFilter usage. Only one scan type can be active at a time. ```kotlin fun scanForPeripheralsUsingFilters(filters: List) ``` -------------------------------- ### BLE Central Role Management with BluetoothCentralManager Source: https://context7.com/weliem/blessed-kotlin/llms.txt This Kotlin code demonstrates the usage of the BluetoothCentralManager class for BLE central operations. It covers defining service UUIDs, setting up peripheral and central callbacks, initializing the central manager, scanning for peripherals, connecting to them, and handling connection events. It also shows alternative scanning methods and auto-connection. ```kotlin import android.os.Handler import android.os.Looper import com.welie.blessed.* import java.util.UUID // Define service UUIDs val HEART_RATE_SERVICE_UUID = UUID.fromString("0000180D-0000-1000-8000-00805f9b34fb") val BLOOD_PRESSURE_SERVICE_UUID = UUID.fromString("00001810-0000-1000-8000-00805f9b34fb") // Create peripheral callback for handling characteristic operations val peripheralCallback = object : BluetoothPeripheralCallback() { override fun onServicesDiscovered(peripheral: BluetoothPeripheral) { // Services discovered, start reading/writing characteristics peripheral.readCharacteristic( UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb"), // Device Info Service UUID.fromString("00002A29-0000-1000-8000-00805f9b34fb") // Manufacturer Name ) // Enable notifications for heart rate measurement peripheral.startNotify( HEART_RATE_SERVICE_UUID, UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb") ) } override fun onCharacteristicUpdate( peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus ) { if (status == GattStatus.SUCCESS) { println("Received: ${value.asHexString()}") } } override fun onNotificationStateUpdate( peripheral: BluetoothPeripheral, characteristic: BluetoothGattCharacteristic, status: GattStatus ) { val isNotifying = peripheral.isNotifying(characteristic) println("Notification ${if (isNotifying) "enabled" else "disabled"} for ${characteristic.uuid}") } } // Create central manager callback val centralCallback = object : BluetoothCentralManagerCallback() { override fun onDiscovered(peripheral: BluetoothPeripheral, scanResult: ScanResult) { println("Found: ${peripheral.name} (${peripheral.address}) RSSI: ${scanResult.rssi}") centralManager.stopScan() centralManager.connect(peripheral, peripheralCallback) } override fun onConnected(peripheral: BluetoothPeripheral) { println("Connected to ${peripheral.name}") } override fun onDisconnected(peripheral: BluetoothPeripheral, status: HciStatus) { println("Disconnected from ${peripheral.name}: $status") // Auto-reconnect after delay Handler(Looper.getMainLooper()).postDelayed({ centralManager.autoConnect(peripheral, peripheralCallback) }, 5000) } override fun onConnectionFailed(peripheral: BluetoothPeripheral, status: HciStatus) { println("Connection failed: $status") } } // Initialize central manager (use main looper or custom handler thread) val centralManager = BluetoothCentralManager(context, centralCallback, Handler(Looper.getMainLooper())) // Scan for peripherals with specific services centralManager.scanForPeripheralsWithServices(setOf(HEART_RATE_SERVICE_UUID, BLOOD_PRESSURE_SERVICE_UUID)) // Alternative scanning methods centralManager.scanForPeripheralsWithNames(setOf("MyDevice", "SensorTag")) centralManager.scanForPeripheralsWithAddresses(setOf("AA:BB:CC:DD:EE:FF")) centralManager.scanForPeripherals() // Scan for all peripherals // Get peripheral by address and auto-connect val knownPeripheral = centralManager.getPeripheral("AA:BB:CC:DD:EE:FF") centralManager.autoConnect(knownPeripheral, peripheralCallback) // Check and stop scanning if (centralManager.isScanning) { centralManager.stopScan() } ``` -------------------------------- ### Build BLE Data with BluetoothBytesBuilder Source: https://context7.com/weliem/blessed-kotlin/llms.txt The `BluetoothBytesBuilder` class offers a fluent API for constructing byte arrays to be written to BLE characteristics. It supports adding various data types, including integers of different sizes, floats, strings, and raw byte arrays, with configurable byte order. ```kotlin import com.welie.blessed.BluetoothBytesBuilder import java.nio.ByteOrder import java.util.Calendar import java.util.TimeZone // Build a command byte array val command = BluetoothBytesBuilder(byteOrder = ByteOrder.LITTLE_ENDIAN) .addUInt8(0x01) // Command opcode .addUInt8(0x01) // Operator (all records) .build() // peripheral.writeCharacteristic(serviceUUID, characteristicUUID, command, WriteType.WITH_RESPONSE) // Build a timestamp with timezone offset fun buildContourClockCommand(): ByteArray { val calendar = Calendar.getInstance() val offsetInMinutes = calendar.timeZone.rawOffset / 60000 calendar.timeZone = TimeZone.getTimeZone("UTC") return BluetoothBytesBuilder(size = 10u, byteOrder = ByteOrder.LITTLE_ENDIAN) .addUInt8(1) // Command type .addUInt16(calendar[Calendar.YEAR]) // Year .addUInt8(calendar[Calendar.MONTH] + 1) // Month (1-12) .addUInt8(calendar[Calendar.DAY_OF_MONTH]) // Day .addUInt8(calendar[Calendar.HOUR_OF_DAY]) // Hour .addUInt8(calendar[Calendar.MINUTE]) // Minute .addUInt8(calendar[Calendar.SECOND]) // Second .addInt16(offsetInMinutes) // Timezone offset .build() } // Build IEEE 11073 SFLOAT/FLOAT values val measurementData = BluetoothBytesBuilder() .addUInt8(0x00) // Flags .addSFloat(98.6, precision = 1) // Temperature as SFLOAT (2 bytes) .addFloat(120.5, precision = 1) // Value as FLOAT (4 bytes) .build() // Build with various integer sizes val complexData = BluetoothBytesBuilder(byteOrder = ByteOrder.LITTLE_ENDIAN) .addInt8(-10) // Signed 8-bit .addUInt8(255) // Unsigned 8-bit .addInt16(-1000) // Signed 16-bit .addUInt16(65535) // Unsigned 16-bit .addInt24(-100000) // Signed 24-bit .addUInt24(16777215) // Unsigned 24-bit .addInt32(-2000000000) // Signed 32-bit .addUInt32(4294967295u) // Unsigned 32-bit .addInt64(-9000000000000000000) // Signed 64-bit .addUInt64(18446744073709551615u) // Unsigned 64-bit .add(byteArrayOf(0x01, 0x02)) // Append raw bytes .build() ``` -------------------------------- ### Read and Write Bluetooth Characteristics with blessed-kotlin Source: https://context7.com/weliem/blessed-kotlin/llms.txt Demonstrates reading and writing Bluetooth characteristics using the BluetoothPeripheral class. It covers reading by UUID, writing with and without response, enabling/disabling notifications, requesting MTU changes, and setting connection priorities. Dependencies include the blessed-kotlin library. ```kotlin import com.welie.blessed.* import java.util.UUID val peripheralCallback = object : BluetoothPeripheralCallback() { override fun onServicesDiscovered(peripheral: BluetoothPeripheral) { // Read a characteristic by service and characteristic UUID peripheral.readCharacteristic( UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb"), // Battery Service UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb") // Battery Level ) // Write to a characteristic with response val command = byteArrayOf(0x01, 0x02, 0x03) peripheral.writeCharacteristic( UUID.fromString("00001808-0000-1000-8000-00805f9b34fb"), // Glucose Service UUID.fromString("00002A52-0000-1000-8000-00805f9b34fb"), // Record Access Control Point command, WriteType.WITH_RESPONSE ) // Write without response for faster throughput peripheral.writeCharacteristic( serviceUUID, characteristicUUID, data, WriteType.WITHOUT_RESPONSE ) // Enable notifications or indications (library auto-detects) peripheral.startNotify(serviceUUID, characteristicUUID) // Stop notifications peripheral.stopNotify(serviceUUID, characteristicUUID) // Request higher MTU for larger data transfers peripheral.requestMtu(BluetoothPeripheral.MAX_MTU) // Request max MTU (517) // Request high connection priority for faster communication peripheral.requestConnectionPriority(ConnectionPriority.HIGH) // Set preferred PHY for Bluetooth 5.0 devices peripheral.setPreferredPhy(PhyType.LE_2M, PhyType.LE_2M, PhyOptions.NO_PREFERRED) } override fun onCharacteristicUpdate( peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus ) { if (status == GattStatus.SUCCESS) { // Parse received data val parser = BluetoothBytesParser(value) val flags = parser.getUInt8() val heartRate = parser.getUInt8() println("Heart Rate: $heartRate bpm") } } override fun onCharacteristicWrite( peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus ) { if (status == GattStatus.SUCCESS) { println("Successfully wrote ${value.asHexString()} to ${characteristic.uuid}") } } override fun onMtuChanged(peripheral: BluetoothPeripheral, mtu: Int, status: GattStatus) { println("MTU changed to $mtu") val maxWriteLength = peripheral.getMaximumWriteValueLength(WriteType.WITHOUT_RESPONSE) println("Max write length: $maxWriteLength bytes") } override fun onBondingStarted(peripheral: BluetoothPeripheral) { println("Bonding started with ${peripheral.name}") } override fun onBondingSucceeded(peripheral: BluetoothPeripheral) { println("Bonding succeeded with ${peripheral.name}") } override fun onBondingFailed(peripheral: BluetoothPeripheral) { println("Bonding failed with ${peripheral.name}") } } // Access peripheral properties println("Name: ${peripheral.name}") println("Address: ${peripheral.address}") println("Bond State: ${peripheral.bondState}") println("Connection State: ${peripheral.getState()}") println("Current MTU: ${peripheral.currentMtu}") // Get services and characteristics val services = peripheral.services val service = peripheral.getService(serviceUUID) val characteristic = peripheral.getCharacteristic(serviceUUID, characteristicUUID) // Check if characteristic is notifying val isNotifying = peripheral.isNotifying(characteristic) // Manual bonding peripheral.createBond() // Cancel connection centralManager.cancelConnection(peripheral) ``` -------------------------------- ### Understanding Bluetooth Status Codes Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Provides information on status codes used in callbacks for connection and GATT operations. `HciStatus` is used for connection/disconnection events, while `GattStatus` is used for GATT operations. Both replace the standard Android integer status codes with enum values for clarity. ```kotlin // For connection/disconnection callbacks: fun onStatus(status: HciStatus) // For GATT operation callbacks: fun onGattOperation(status: GattStatus) ``` -------------------------------- ### Bluetooth Characteristic Write Callback in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Callback function invoked after a write operation to a Bluetooth characteristic completes. It provides the peripheral, the written byte array value, the characteristic object, and a GattStatus indicating the outcome of the write operation. ```kotlin fun onCharacteristicWrite(peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus) ``` -------------------------------- ### Requesting Higher MTU for Increased Throughput Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Allows requesting a higher Maximum Transmission Unit (MTU) to improve data throughput. The default MTU is 23 bytes. You can request a specific MTU or the maximum supported by the peripheral. Callbacks inform about the negotiated MTU and maximum write length. ```kotlin fun requestMtu(mtu: Int) fun onMtuChanged(peripheral: BluetoothPeripheral, mtu: Int, status: GattStatus) peripheral.requestMtu(BluetoothPeripheral.MAX_MTU) getCurrentMtu() getMaximumWriteValueLength() ``` -------------------------------- ### Handling Long Reads and Writes Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md The library automatically handles 'long reads' and 'long writes' for characteristics or descriptors whose values exceed the current MTU. For long writes, ensure `WriteType.WITH_RESPONSE` is used and the byte array is 512 bytes or less. Note that support for long operations is peripheral-dependent. ```kotlin // Long reads and writes are handled automatically by the Android BLE stack. // Just perform standard read/write operations. // For long writes, use WriteType.WITH_RESPONSE and ensure data <= 512 bytes. ``` -------------------------------- ### Parse BLE Data with BluetoothBytesParser Source: https://context7.com/weliem/blessed-kotlin/llms.txt The `BluetoothBytesParser` class simplifies parsing byte arrays received from BLE characteristics. It supports various data types like integers (signed and unsigned), floats, strings, and timestamps, with configurable byte order (e.g., LITTLE_ENDIAN). ```kotlin import com.welie.blessed.BluetoothBytesParser import java.nio.ByteOrder // Parse blood pressure measurement fun parseBloodPressureMeasurement(value: ByteArray) { val parser = BluetoothBytesParser(value, offset = 0, byteOrder = ByteOrder.LITTLE_ENDIAN) val flags = parser.getUInt8() val isKpa = (flags.toInt() and 0x01) != 0 val hasTimestamp = (flags.toInt() and 0x02) != 0 val hasPulseRate = (flags.toInt() and 0x04) != 0 // Read IEEE 11073 SFLOAT values val systolic = parser.getSFloat() val diastolic = parser.getSFloat() val meanArterialPressure = parser.getSFloat() val unit = if (isKpa) "kPa" else "mmHg" println("Blood Pressure: $systolic/$diastolic $unit (MAP: $meanArterialPressure)") if (hasTimestamp) { val timestamp = parser.getDateTime() println("Timestamp: $timestamp") } if (hasPulseRate) { val pulseRate = parser.getSFloat() println("Pulse Rate: $pulseRate bpm") } } // Parse temperature measurement fun parseTemperatureMeasurement(value: ByteArray) { val parser = BluetoothBytesParser(value) val flags = parser.getUInt8() val isFahrenheit = (flags.toInt() and 0x01) != 0 // IEEE 11073 FLOAT (4 bytes) val temperature = parser.getFloat() val unit = if (isFahrenheit) "°F" else "°C" println("Temperature: $temperature $unit") } // Parse various integer types fun parseCustomData(value: ByteArray) { val parser = BluetoothBytesParser(value, byteOrder = ByteOrder.LITTLE_ENDIAN) val uint8Value = parser.getUInt8() // Unsigned 8-bit val int8Value = parser.getInt8() // Signed 8-bit val uint16Value = parser.getUInt16() // Unsigned 16-bit val int16Value = parser.getInt16() // Signed 16-bit val uint24Value = parser.getUInt24() // Unsigned 24-bit val uint32Value = parser.getUInt32() // Unsigned 32-bit val int32Value = parser.getInt32() // Signed 32-bit val uint64Value = parser.getUInt64() // Unsigned 64-bit // Read string (null-terminated or fixed length) val deviceName = parser.getString() val fixedString = parser.getString(10) // Read exactly 10 bytes as string } ``` -------------------------------- ### Disabling Blessed Kotlin Logging Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Allows disabling all logging output from the Blessed Kotlin library. This is useful in production environments where library-specific logs might be unnecessary. ```kotlin central.disableLogging() ``` -------------------------------- ### Bluetooth Notification State Update Callback in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Callback function invoked when the state of Bluetooth notifications or indications changes. It receives the peripheral, the characteristic, and a GattStatus. Useful for logging success or failure of notification state changes. ```kotlin fun onNotificationStateUpdate(peripheral: BluetoothPeripheral, characteristic: BluetoothGattCharacteristic, status: GattStatus) { if (status == GattStatus.SUCCESS) { Timber.i("SUCCESS: Notify set to '%s' for %s", peripheral.isNotifying(characteristic), characteristic.uuid) } else { Timber.e("ERROR: Changing notification state failed for %s (%s)", characteristic.uuid, status) } } ``` -------------------------------- ### Parse ByteArray Data - Kotlin Source: https://context7.com/weliem/blessed-kotlin/llms.txt Parses various data types from a ByteArray at specified offsets, including unsigned integers, signed floats, IEEE 11073 floats, date-time values, and null-terminated strings. It utilizes extension functions for idiomatic Kotlin data handling. ```kotlin import com.welie.blessed.* import java.nio.ByteOrder import java.util.Calendar // Parse byte array directly using extensions fun parseData(value: ByteArray) { // Get integer values at specific offsets val flags = value.getUInt8(offset = 0u) val heartRate = value.getUInt8(offset = 1u) val energyExpended = value.getUInt16(offset = 2u, order = ByteOrder.LITTLE_ENDIAN) // Parse IEEE 11073 floating point val temperature = value.getSFloat(offset = 1u) // 2-byte SFLOAT val pressure = value.getFloat(offset = 3u) // 4-byte FLOAT // Get date/time (7 bytes) val timestamp = value.getDateTime(offset = 7u) // Get null-terminated string val deviceName = value.getString(offset = 0u) } // Convert to hex string for debugging val hexString = value.asHexString() // "0A1B2C3D" val formattedHex = value.asFormattedHexString(":") // "0A:1B:2C:3D" // Create byte arrays from primitives val uint16Bytes = 0x1234.toUShort().asByteArray(ByteOrder.LITTLE_ENDIAN) // [0x34, 0x12] val int32Bytes = (-1000).asByteArray(ByteOrder.LITTLE_ENDIAN) val uint24Bytes = 0xABCDEFu.asByteArrayOfUInt24() // Create UUID from 16-bit string val heartRateServiceUUID = from16BitString("180D") // 0000180D-0000-1000-8000-00805f9b34fb // Create current time byte array (for Current Time Service) val currentTimeBytes = currentTimeByteArrayOf(Calendar.getInstance()) val dateTimeBytes = dateTimeByteArrayOf(Calendar.getInstance()) // Merge multiple byte arrays val combined = mergeArrays(header, payload, checksum) // Create byte array from hex string val bytes = byteArrayOf("0A1B2C3D") // [0x0A, 0x1B, 0x2C, 0x3D] ``` -------------------------------- ### Bluetooth Characteristic Update Callback in Kotlin Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Callback function invoked when a Bluetooth characteristic's value is updated or a read operation completes. It receives the peripheral, the updated byte array value, the characteristic object, and a GattStatus indicating success or failure. ```kotlin fun onCharacteristicUpdate(peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus) ``` -------------------------------- ### Cancel Bluetooth Connection (Kotlin) Source: https://github.com/weliem/blessed-kotlin/blob/main/README.md Cancels an ongoing connection attempt (either immediate or auto-connect) to a Bluetooth peripheral. A callback will be received on `onDisconnectedPeripheral` once the disconnection is complete. ```kotlin fun cancelConnection(peripheral: BluetoothPeripheral) ``` -------------------------------- ### BLE Peripheral Notification Source: https://context7.com/weliem/blessed-kotlin/llms.txt Sends a notification to a connected peripheral with updated heart rate data. It finds the heart rate service and measurement characteristic, builds the notification value, and sends it using the peripheral manager. ```kotlin .find { it.uuid == HEART_RATE_SERVICE_UUID } ?.getCharacteristic(HEART_RATE_MEASUREMENT_UUID) characteristic?.let { val value = BluetoothBytesBuilder() .addUInt8(0x00) .addUInt8(heartRate) .build() peripheralManager.notifyCharacteristicChanged(value, it) } } // Stop advertising and cleanup peripheralManager.stopAdvertising() peripheralManager.close() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.