ADD BLE TRANSFER FUNC

This commit is contained in:
dahyeon committed 2025-10-22 18:50:03 +09:00
1 parent 2fa3c468e1
commit 128ad644f4
7 files changed
+527 -1

No files matched your search

+8
View File
@@ -4,6 +4,14 @@
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2025-10-22T07:29:37.457575115Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=W119ES04241290000178" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
+3
View File
@@ -0,0 +1,3 @@
<component name="ProjectDictionaryState">
<dictionary name="project" />
</component>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Kotlin2JsCompilerArguments">
<option name="moduleKind" value="plain" />
</component>
<component name="Kotlin2JvmCompilerArguments">
<option name="jvmTarget" value="1.8" />
</component>
<component name="KotlinCommonCompilerArguments">
<option name="apiVersion" value="2.1" />
<option name="languageVersion" value="2.1" />
</component>
</project>
+8
View File
@@ -5,6 +5,14 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<!-- Android 9 이하: 고전 권한 -->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
@@ -17,6 +17,7 @@ import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.PickVisualMediaRequest
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
@@ -26,25 +27,108 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.ble_demo_app_peripheral_2.ble.CentralManager
import com.example.ble_demo_app_peripheral_2.ui.theme.Bledemoappperipheral2Theme
import kotlinx.coroutines.MainScope
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.nio.ByteBuffer
class MainActivity : ComponentActivity() {
private val scope = MainScope()
private lateinit var cm: CentralManager
private val permsLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { /* no-op */ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cm = CentralManager(this, scope)
requestPerms()
enableEdgeToEdge()
setContent {
Bledemoappperipheral2Theme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
EncodeAvifScreen(modifier = Modifier.padding(innerPadding))
SendBLEScreen(cm)
//EncodeAvifScreen(modifier = Modifier.padding(innerPadding))
}
}
}
}
private fun requestPerms() {
val perms = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
)
permsLauncher.launch(perms)
}
}
fun copyToMemory(ins: InputStream): InputStream {
val bytes = ins.readBytes()
return bytes.inputStream()
}
@Composable
fun SendBLEScreen(cm: CentralManager) {
val context = LocalContext.current
val scan by cm.scanState.collectAsState()
val conn by cm.connState.collectAsState()
val prog by cm.progressText.collectAsState()
val pct by cm.percent.collectAsState()
var imageUri by remember { mutableStateOf<Uri?>(null) }
val picker = rememberLauncherForActivityResult(
ActivityResultContracts.PickVisualMedia()
) { uri -> imageUri = uri }
Surface(Modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Central (Android 9)", style = MaterialTheme.typography.titleLarge)
Text("Scan: $scan")
Text("Conn: $conn")
if (pct > 0) {
LinearProgressIndicator(progress = pct / 100f, modifier = Modifier.fillMaxWidth())
Text("$pct% • $prog")
} else {
Text(prog)
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button(onClick = { cm.startScan() }) { Text("Scan & Connect") }
Button(onClick = { cm.disconnect() }) { Text("Disconnect") }
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button(onClick = {
picker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}) { Text("Pick Image") }
Button(onClick = {
imageUri?.let { uri ->
context.contentResolver.openInputStream(uri)?.use { ins ->
cm.sendImage(copyToMemory(ins))
}
}
}, enabled = imageUri != null) { Text("Send") }
}
}
}
}
@Composable
fun EncodeAvifScreen(modifier: Modifier = Modifier) {
val context = LocalContext.current
@@ -0,0 +1,391 @@
package com.example.ble_demo_app_peripheral_2.ble
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.*
import android.bluetooth.le.*
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.ParcelUuid
import android.util.Log
import androidx.core.app.ActivityCompat
import com.inhandplus.shared.ble.BleSpec
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.zip.CRC32
class CentralManager(
private val context: Context,
private val scope: CoroutineScope
) {
private val btManager = context.getSystemService(BluetoothManager::class.java)
private val btAdapter: BluetoothAdapter? = btManager?.adapter
// UI state
val scanState = MutableStateFlow("Idle")
val connState = MutableStateFlow("Disconnected")
val progressText = MutableStateFlow("")
val percent = MutableStateFlow(0)
// BLE
private var scanner: BluetoothLeScanner? = null
private var gatt: BluetoothGatt? = null
private var rxWrite: BluetoothGattCharacteristic? = null
private var txNotify: BluetoothGattCharacteristic? = null
// Flow control
private var mtuAgreed = 23
private var inCredits = 0 // CCC 구독 완료 전 0
private var sending = AtomicBoolean(false)
// File state
private var totalLen: Long = 0
private var sentBytes: Long = 0
private var wholeCrc = CRC32()
// ---------- Scan ----------
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
val name = result.scanRecord?.deviceName ?: ""
if (name.contains(BleSpec.ADV_NAME)) {
stopScan()
connect(result.device)
}
}
override fun onScanFailed(errorCode: Int) {
scanState.value = "Scan failed: $errorCode"
}
}
@SuppressLint("MissingPermission")
fun startScan() {
val ad = btAdapter ?: run { scanState.value = "No Bluetooth adapter"; return }
if (!ad.isEnabled) { scanState.value = "Bluetooth is OFF"; return }
if (!hasScanPermission()) { scanState.value = "Missing scan permission"; return }
scanner = ad.bluetoothLeScanner ?: run { scanState.value = "Scanner unavailable"; return }
scanState.value = "Scanning..."
val filter = ScanFilter.Builder()
.setServiceUuid(ParcelUuid(BleSpec.SERVICE_UUID))
.build()
val settings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
scanner!!.startScan(listOf(filter), settings, scanCallback)
}
@SuppressLint("MissingPermission")
fun stopScan() {
try { scanner?.stopScan(scanCallback) } catch (_: Exception) {}
scanState.value = "Scan stopped"
}
private fun hasScanPermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) ==
PackageManager.PERMISSION_GRANTED
} else {
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
}
}
// ---------- Connect / Discover ----------
@SuppressLint("MissingPermission")
private fun connect(device: BluetoothDevice) {
connState.value = "Connecting ${device.address}"
gatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
}
@SuppressLint("MissingPermission")
fun disconnect() {
gatt?.disconnect()
gatt?.close()
gatt = null
connState.value = "Disconnected"
}
@SuppressLint("MissingPermission")
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
connState.value = "Connected"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
g.setPreferredPhy(
BluetoothDevice.PHY_LE_2M_MASK,
BluetoothDevice.PHY_LE_2M_MASK,
BluetoothDevice.PHY_OPTION_NO_PREFERRED
)
}
g.requestMtu(BleSpec.TARGET_MTU)
g.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connState.value = "Disconnected"
}
}
override fun onPhyUpdate(gatt: BluetoothGatt, txPhy: Int, rxPhy: Int, status: Int) {
progressText.value = "PHY tx=$txPhy rx=$rxPhy"
}
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
mtuAgreed = mtu
progressText.value = "MTU=$mtu"
gatt.discoverServices()
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
val svc = gatt.getService(BleSpec.SERVICE_UUID) ?: return
rxWrite = svc.getCharacteristic(BleSpec.CHAR_RX_WRITE_UUID)
txNotify = svc.getCharacteristic(BleSpec.CHAR_TX_NOTIFY_UUID)
if (txNotify != null) {
gatt.setCharacteristicNotification(txNotify, true)
val ccc = txNotify!!.getDescriptor(UUID.fromString(CCC_UUID))
ccc?.let { writeDescriptorSafe(gatt, it, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) }
} else {
connState.value = "RX only (no notify)"
}
}
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
if (descriptor.uuid.toString().equals(CCC_UUID, ignoreCase = true)) {
connState.value = "Ready" // 이 시점 이후 send 가능
}
}
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
if (characteristic.uuid == BleSpec.CHAR_TX_NOTIFY_UUID) {
handleNotify(characteristic.value)
}
}
}
private fun handleNotify(data: ByteArray) {
if (data.size < 10) return
val bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
val code = bb.get().toInt() and 0xFF
val creditsFromServer = bb.get().toInt() and 0xFF
val arg = bb.long
when (code) {
0 -> inCredits = creditsFromServer
1 -> progressText.value = "Peripheral CRC=$arg"
2 -> { progressText.value = "Seq mismatch exp=$arg → restart"; sending.set(false) }
3 -> { progressText.value = "Chunk CRC fail → restart"; sending.set(false) }
}
}
// ---------- Send File ----------
// 3) sendImage()에서 위 함수 사용 + 데이터 write 실패에도 재시도 경로 유지
@SuppressLint("MissingPermission")
fun sendImage(input: java.io.InputStream) {
val g = gatt ?: run { progressText.value = "Not connected"; return }
if (rxWrite == null || connState.value != "Ready") {
progressText.value = "Not ready (notify not enabled)"
return
}
if (sending.getAndSet(true)) return
scope.launch(kotlinx.coroutines.Dispatchers.IO) {
try {
val bytes = input.readBytes()
totalLen = bytes.size.toLong()
wholeCrc = java.util.zip.CRC32().apply { update(bytes) }
sentBytes = 0
percent.value = 0
// ★ 안정화된 Start frame 전송
val started = sendStartFrameWithStabilize(g, totalLen, wholeCrc.value.toInt())
if (!started) {
progressText.value = "Start frame write failed"
return@launch
}
var seq = 0L
val payloadMax = calcSafePayload()
var offset = 0
while (offset < bytes.size && sending.get()) {
waitWindow()
val remain = bytes.size - offset
val chunk = if (remain > payloadMax) payloadMax else remain
val payload = bytes.copyOfRange(offset, offset + chunk)
val crc = java.util.zip.CRC32().apply { update(payload) }.value.toInt()
val packet = java.nio.ByteBuffer.allocate(10 + chunk).order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putInt(seq.toInt())
.putShort(chunk.toShort())
.putInt(crc)
.put(payload)
.array()
val ok = gattWriteCharacteristicSafe(
g, rxWrite!!, packet, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
)
if (!ok) {
progressText.value = "writeCharacteristic=false (retry exhausted) at seq=$seq"
break
}
sentBytes += chunk
offset += chunk
seq++
percent.value = (100.0 * sentBytes / totalLen).toInt()
progressText.value = "Sent $sentBytes / $totalLen (${percent.value}%)"
}
} catch (t: Throwable) {
progressText.value = "Error: ${t.message}"
} finally {
sending.set(false)
}
}
}
private fun calcSafePayload(): Int {
val att = (mtuAgreed - 3).coerceAtLeast(20)
val payload = (att - 10).coerceAtLeast(1)
return payload.coerceAtMost(BleSpec.DEFAULT_PAYLOAD)
}
/** Start frame: seq=FFFFFFFF, len=0, payload=[ totalLen(u64) | wholeCrc(u32) ] */
@SuppressLint("MissingPermission")
private suspend fun sendStartFrame(g: BluetoothGatt, totalLen: Long, wholeCrc: Int) {
val body = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN)
.putLong(totalLen).putInt(wholeCrc).array()
val header = ByteBuffer.allocate(10).order(ByteOrder.LITTLE_ENDIAN)
.putInt(-1).putShort(0).putInt(0).array()
val packet = header + body
gattWriteCharacteristicSafe(g, rxWrite!!, packet, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE)
}
private suspend fun waitWindow() {
while (inCredits <= 0 && sending.get()) {
delay(2)
}
inCredits--
}
// ---------- Safe wrappers ----------
@SuppressLint("MissingPermission")
private suspend fun gattWriteCharacteristicSafe(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
value: ByteArray,
writeType: Int,
maxRetries: Int = 10
): Boolean {
// 길이 검증 (ATT_MTU - 3)
val maxAtt = (mtuAgreed - 3).coerceAtLeast(20)
if (value.size > maxAtt) {
progressText.value = "Value too large (${value.size} > $maxAtt)"
return false
}
var attempt = 0
var delayMs = 1L
while (attempt < maxRetries) {
val ok: Boolean = if (Build.VERSION.SDK_INT >= 33) {
try {
val rc = gatt.writeCharacteristic(characteristic, value, writeType)
rc == BluetoothStatusCodes.SUCCESS
} catch (_: Throwable) {
// 폴백
characteristic.writeType = writeType
characteristic.value = value
gatt.writeCharacteristic(characteristic)
}
} else {
characteristic.writeType = writeType
characteristic.value = value
gatt.writeCharacteristic(characteristic)
}
if (ok) return true
// 실패 → 지수 백오프
attempt++
kotlinx.coroutines.delay(delayMs)
delayMs = (delayMs * 2).coerceAtMost(16L)
// 마지막 한 번은 메인스레드에서 시도 (벤더 이슈 회피)
if (attempt == maxRetries - 1) {
val result = kotlinx.coroutines.suspendCancellableCoroutine<Boolean> { cont ->
android.os.Handler(android.os.Looper.getMainLooper()).post {
val okMain = try {
if (Build.VERSION.SDK_INT >= 33) {
gatt.writeCharacteristic(characteristic, value, writeType) == BluetoothStatusCodes.SUCCESS
} else {
characteristic.writeType = writeType
characteristic.value = value
gatt.writeCharacteristic(characteristic)
}
} catch (_: Throwable) { false }
cont.resume(okMain, onCancellation = null)
}
}
if (result) return true
}
}
return false
}
// 2) Start frame 전 안정화 지연 (CentralManager.kt)
@SuppressLint("MissingPermission")
private suspend fun sendStartFrameWithStabilize(g: BluetoothGatt, totalLen: Long, wholeCrc: Int): Boolean {
// CCC 쓰기 직후 스택 안정화 (권장 50ms)
kotlinx.coroutines.delay(50)
val body = java.nio.ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)
.putLong(totalLen)
.array()
val header = java.nio.ByteBuffer.allocate(10).order(ByteOrder.LITTLE_ENDIAN)
.putInt(-1) // seq = 0xFFFFFFFF (Start)
.putShort(8) // ★ len = 8 (payload 길이!)
.putInt(0) // crc 필드는 의미 없음(0)
.array()
val packet = header + body
val writeStartPacketResult = gattWriteCharacteristicSafe(
g, rxWrite!!, packet, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
)
if (!writeStartPacketResult) {
progressText.value = "staet write fail"
}
return writeStartPacketResult
}
@SuppressLint("MissingPermission")
private fun writeDescriptorSafe(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, value: ByteArray) {
if (Build.VERSION.SDK_INT >= 33) {
val rc = gatt.writeDescriptor(descriptor, value)
if (rc != BluetoothStatusCodes.SUCCESS) {
descriptor.value = value
gatt.writeDescriptor(descriptor)
}
} else {
descriptor.value = value
gatt.writeDescriptor(descriptor)
}
}
companion object {
private const val CCC_UUID = "00002902-0000-1000-8000-00805f9b34fb"
}
}
@@ -0,0 +1,19 @@
package com.inhandplus.shared.ble
import java.util.*
object BleSpec {
// 서비스 및 캐릭터리스틱 UUID (고정)
val SERVICE_UUID: UUID = UUID.fromString("0000feed-0000-1000-8000-00805f9b34fb")
// 중앙 → 주변 : 파일 청크 쓰기 (Write Without Response)
val CHAR_RX_WRITE_UUID: UUID = UUID.fromString("0000beef-0000-1000-8000-00805f9b34fb")
// 주변 → 중앙 : ACK/크레딧/완료 알림 (Notify)
val CHAR_TX_NOTIFY_UUID: UUID = UUID.fromString("0000cafe-0000-1000-8000-00805f9b34fb")
// 전송 파라미터
const val TARGET_MTU = 517 // 요청값 (실제 협상값은 달라질 수 있음)
const val DEFAULT_PAYLOAD = 244 // MTU 517일 때 안전한 payload (~244) (10B 헤더 포함 총 254B 이내)
const val WINDOW_CREDITS = 8 // 슬라이딩 윈도 크레딧
const val ACK_EVERY = 8 // N개마다 ACK (가용 크레딧 통지)
const val ADV_NAME = "BLE-IMG-DEMO"
}