Compare commits

..
4 Commits
10 changed files with 804 additions and 8 deletions

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"
+3 -3
View File
@@ -11,10 +11,10 @@
#define FUNC(RETURN_TYPE, NAME, ...) \
extern "C" { \
JNIEXPORT RETURN_TYPE Java_com_example_ble_1demo_1app_1peripheral_12_AvifCodec_##NAME( \
JNIEXPORT RETURN_TYPE Java_com_example_ble_1demo_1app_1peripheral_12_avif_AvifCodec_##NAME( \
JNIEnv* env, jobject /*thiz*/, ##__VA_ARGS__); \
} \
JNIEXPORT RETURN_TYPE Java_com_example_ble_1demo_1app_1peripheral_12_AvifCodec_##NAME( \
JNIEXPORT RETURN_TYPE Java_com_example_ble_1demo_1app_1peripheral_12_avif_AvifCodec_##NAME( \
JNIEnv* env, jobject /*thiz*/, ##__VA_ARGS__)
namespace {
@@ -91,7 +91,7 @@ jint JNI_OnLoad(JavaVM *vm, void * /*reserved*/) {
return -1;
}
const jclass info_class =
env->FindClass("com/example/ble_demo_app_peripheral_2/AvifCodec$Info");
env->FindClass("com/example/ble_demo_app_peripheral_2/avif/AvifCodec$Info");
global_info_width = env->GetFieldID(info_class, "width", "I");
global_info_height = env->GetFieldID(info_class, "height", "I");
global_info_depth = env->GetFieldID(info_class, "depth", "I");
@@ -6,17 +6,20 @@ import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.util.Log
import androidx.activity.ComponentActivity
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,23 +29,200 @@ 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.avif.AvifCodec
import com.example.ble_demo_app_peripheral_2.avif.encodeAvifFromUri
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
import java.nio.ByteOrder
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 ->
val fileName = queryDisplayName(context, uri)
val encodedImage = encodeAvifFromUri(context, uri!!)
cm.sendByteImage(encodedImage.bytes, encodedImage.fileName)
//cm.sendImage(copyToMemory(ins), fileName)
}
}
}, enabled = imageUri != null) { Text("Send") }
}
}
}
}
@Composable
fun encodeAVIF(uri: Uri, context: Context) {
// 원본 파일명 기반으로 .avif 이름 만들기
val originalName = queryDisplayName(context, uri)
var internalFile by remember { mutableStateOf<File?>(null) }
var exportFileName by remember { mutableStateOf("output.avif") }
// API 28 이하에서 WRITE_EXTERNAL_STORAGE 권한 요청 후 저장 실행
val requestWritePerm = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
val src = internalFile
val fileName = exportFileName
if (granted && src != null) {
try {
val dst = saveToPublicDownloadsLegacy(context, src, fileName)
Log.i("AVIFEncoder", "인코딩 완료!\nDownloads에 저장됨: ${dst.absolutePath}\n앱 내부: ${src.absolutePath}")
} catch (t: Throwable) {
Log.e("AVIFEncoder", "저장 실패(28 이하): ${t.localizedMessage}")
} finally {
internalFile = null
}
} else {
Log.e("AVIFEncoder", "저장 권한 거부됨 (API 28)")
internalFile = null
}
}
try {
// 입력 비트맵 로드
val bitmap = context.contentResolver.openInputStream(uri)?.use { ins ->
BitmapFactory.decodeStream(ins)
}
if (bitmap == null) {
Log.e("AVIFEncoder", "error occurred loading bitmap")
return
}
// ARGB_8888 보장
val bmp = if (bitmap.config == Bitmap.Config.ARGB_8888) {
bitmap
} else {
bitmap.copy(Bitmap.Config.ARGB_8888, false)
}
// 픽셀 버퍼 추출
val width = bmp.width
val height = bmp.height
val byteCount = bmp.rowBytes * height
val buffer = ByteBuffer.allocateDirect(byteCount).apply {
order(ByteOrder.nativeOrder())
}
bmp.copyPixelsToBuffer(buffer)
buffer.rewind()
// JNI 인코딩
val avifBytes = AvifCodec.encodeRGBA8888(buffer, buffer.remaining(), width, height)
if (avifBytes == null) {
Log.e("AVIFEncoder", "error occurred while encoding to avif")
return
}
// 내부 저장소에 먼저 기록 (임시 파일도 같은 이름으로)
val outputFile = File(context.filesDir, exportFileName)
FileOutputStream(outputFile).use { it.write(avifBytes) }
internalFile = outputFile
// API 분기
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Android 10+ : MediaStore(Downloads)로 퍼미션 없이 저장
val savedUri = saveToDownloadsViaMediaStore(context, outputFile, exportFileName)
Log.i("AVIFEncoder", "인코딩 완료!\nDownloads에 저장됨: $savedUri\n앱 내부: ${outputFile.absolutePath}")
internalFile = null
} else {
// Android 9 이하 : 권한 요청 후 /sdcard/Download에 저장
requestWritePerm.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
// 콜백에서 statusText 설정 및 internalFile 해제
}
} catch (e: Exception) {
e.printStackTrace()
Log.i("AVIFEncoder", "오류 발생: ${e.localizedMessage}")
internalFile = null
}
}
@Composable
@@ -134,7 +314,7 @@ fun EncodeAvifScreen(modifier: Modifier = Modifier) {
val height = bmp.height
val byteCount = bmp.rowBytes * height
val buffer = ByteBuffer.allocateDirect(byteCount).apply {
order(java.nio.ByteOrder.nativeOrder())
order(ByteOrder.nativeOrder())
}
bmp.copyPixelsToBuffer(buffer)
buffer.rewind()
@@ -239,7 +419,7 @@ fun saveToPublicDownloadsLegacy(context: Context, src: File, fileName: String =
FileOutputStream(dst).use { output -> input.copyTo(output) }
}
// 파일 앱/다운로드 앱에서 즉시 보이도록 스캔
android.media.MediaScannerConnection.scanFile(
MediaScannerConnection.scanFile(
context, arrayOf(dst.absolutePath), arrayOf("image/avif"), null
)
return dst
@@ -1,9 +1,8 @@
package com.example.ble_demo_app_peripheral_2
package com.example.ble_demo_app_peripheral_2.avif
import android.graphics.Bitmap
import java.nio.ByteBuffer
/** An AVIF Decoder. AVIF Specification: https://aomediacodec.github.io/av1-avif/. */
object AvifCodec {
init {
@@ -0,0 +1,92 @@
package com.example.ble_demo_app_peripheral_2.avif
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.OpenableColumns
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** 결과: 인코딩된 AVIF 바이트와 다운로드/전송에 쓸 파일명 (*.avif) */
data class EncodedAvif(val bytes: ByteArray, val fileName: String)
/** Uri의 표시 이름을 얻는다. (없으면 "image") */
fun queryDisplayName(context: Context, uri: Uri): String {
return context.contentResolver.query(
uri,
arrayOf(OpenableColumns.DISPLAY_NAME),
null, null, null
)?.use { c ->
if (c.moveToFirst()) c.getString(0) ?: "image" else "image"
} ?: "image"
}
/** Bitmap을 ARGB_8888로 보장해서 리턴 (필요 시 copy) */
private fun ensureArgb8888(src: Bitmap): Bitmap {
return if (src.config == Bitmap.Config.ARGB_8888) src
else src.copy(Bitmap.Config.ARGB_8888, /* mutable = */ false)
}
/**
* Uri에서 이미지를 로드하여 AVIF로 인코딩.
* - 디스크에 쓰지 않고 메모리에서 바로 인코딩
* - 파일명은 원본 이름 기반으로 ".avif"로 바꿔서 생성
*/
fun encodeAvifFromUri(context: Context, uri: Uri): EncodedAvif {
val resolver = context.contentResolver
// 1) 이미지 로드
val bmp0 = resolver.openInputStream(uri)?.use { ins ->
BitmapFactory.decodeStream(ins)
} ?: error("Failed to decode bitmap from uri: $uri")
val bmp = ensureArgb8888(bmp0)
// 2) 픽셀 버퍼 추출 (RGBA8888)
val width = bmp.width
val height = bmp.height
val byteCount = bmp.rowBytes * height
val buf = ByteBuffer.allocateDirect(byteCount).apply {
order(ByteOrder.nativeOrder())
}
bmp.copyPixelsToBuffer(buf)
buf.rewind()
// 3) JNI 인코딩 (AvifCodec.encodeRGBA8888)
val avifBytes = AvifCodec.encodeRGBA8888(buf, buf.remaining(), width, height)
?: error("AVIF encoding failed")
// 4) 파일명 생성 (*.avif)
val original = queryDisplayName(context, uri)
val base = original.substringBeforeLast('.', original)
val fileName = if (base.isBlank()) "image.avif" else "$base.avif"
return EncodedAvif(avifBytes, fileName)
}
/**
* 이미 로드된 Bitmap을 AVIF로 인코딩하고 파일명을 돌려준다.
* (직접 Bitmap을 다루는 경로가 필요할 때 사용)
*/
fun encodeAvifFromBitmap(bitmap: Bitmap, suggestedName: String = "image"): EncodedAvif {
val bmp = ensureArgb8888(bitmap)
val width = bmp.width
val height = bmp.height
val byteCount = bmp.rowBytes * height
val buf = ByteBuffer.allocateDirect(byteCount).apply {
order(ByteOrder.nativeOrder())
}
bmp.copyPixelsToBuffer(buf)
buf.rewind()
val avifBytes = AvifCodec.encodeRGBA8888(buf, buf.remaining(), width, height)
?: error("AVIF encoding failed")
val base = suggestedName.substringBeforeLast('.', suggestedName).ifBlank { "image" }
val fileName = "$base.avif"
return EncodedAvif(avifBytes, fileName)
}
@@ -0,0 +1,474 @@
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.ParcelUuid
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: InputStream, fileName: String?) {
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(), fileName = fileName)
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)
}
}
}
@SuppressLint("MissingPermission")
fun sendByteImage(bytes: ByteArray, fileName: String) {
val g = gatt ?: run { progressText.value = "Not connected"; return }
val w = rxWrite ?: run { progressText.value = "Not ready (no RX char)"; return }
if (connState.value != "Ready") { progressText.value = "Not ready (notify not enabled)"; return }
if (sending.getAndSet(true)) return
scope.launch(kotlinx.coroutines.Dispatchers.IO) {
try {
// 전체 길이/CRC 초기화
totalLen = bytes.size.toLong()
wholeCrc = java.util.zip.CRC32().apply { update(bytes) }
sentBytes = 0
percent.value = 0
// Start 프레임 (ATT 20B, 확장자 5자 포함) 전송
val started = sendStartFrameWithStabilize(
g = g,
totalLen = totalLen,
wholeCrc = wholeCrc.value.toInt(), // 시그니처 유지(내부에선 미사용)
fileName = fileName
)
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()) // u32 seq
.putShort(chunk.toShort()) // u16 len
.putInt(crc) // u32 crc
.put(payload)
.array()
val ok = gattWriteCharacteristicSafe(
g, w, packet,
android.bluetooth.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)
}
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, // 사용 안 함 (보내지 않음)
fileName: String? = "" // ★ 원본 파일명 전달 가능하면 넣기
): Boolean {
// CCC 직후 안정화
kotlinx.coroutines.delay(50)
// 확장자 추출 (최대 5자, 영숫자만)
val ext = fileName!!.substringAfterLast('.', "")
.lowercase()
.take(5)
.filter { it.isLetterOrDigit() }
// 파일 크기 24-bit 제한
val total = totalLen.toInt()
if (totalLen > 0xFFFFFFL) {
progressText.value = "File too large for 24-bit len: $totalLen"
return false
}
// Start Body (10B): ver(1) | totalLen24(3,LE) | extLen(1) | ext[5]
val body = ByteArray(10).apply {
this[0] = 1 // ver
this[1] = ( total and 0xFF).toByte()
this[2] = ((total shr 8) and 0xFF).toByte()
this[3] = ((total shr 16)and 0xFF).toByte()
this[4] = ext.length.toByte()
for (i in 0 until 5) this[5 + i] = if (i < ext.length) ext[i].code.toByte() else 0
}
// Start Header (10B)
val header = java.nio.ByteBuffer.allocate(10).order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putInt(-1) // seq = 0xFFFFFFFF
.putShort(10) // len = 10 (payload length)
.putInt(0) // crc (unused)
.array()
val packet = header + body
val ok = gattWriteCharacteristicSafe(
g, rxWrite!!, packet, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
)
if (!ok) progressText.value = "start write fail"
return ok
}
@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"
}