이전 블로그
2025.07.08 - [분류 전체보기] - [ Android / Kotlin ] (1) 안드로이드에서 시리얼포트 통신하기 (android-serialport-api 오픈소스)
[ Android / Kotlin ] (1) 안드로이드에서 시리얼포트 통신하기 (android-serialport-api 오픈소스)
sslee92.tistory.com
시리얼 통신 코드 예제
import android.util.Log
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import android_serialport_api.SerialPort
import kotlin.concurrent.thread
class SerialPortManager(
private val devicePath: String, // 예: "/dev/ttyS1"
private val baudRate: Int // 예: 115200
) {
private var serialPort: SerialPort? = null
private var inputStream: InputStream? = null
private var outputStream: OutputStream? = null
var isListening = false
// 시리얼 포트 열기
fun open(): Boolean {
return try {
val device = File(devicePath)
serialPort = SerialPort(device, baudRate, 0)
inputStream = serialPort?.inputStream
outputStream = serialPort?.outputStream
Log.d("SerialPortManager", "Serial port opened: $devicePath at $baudRate")
true
} catch (e: Exception) {
Log.e("SerialPortManager", "Failed to open serial port: ${e.message}", e)
false
}
}
// 명령어 전송
fun send(command: String) {
try {
outputStream?.write(command.toByteArray())
outputStream?.flush()
} catch (e: Exception) {
Log.e("SerialPortManager", "Send error: ${e.message}", e)
}
}
// 포트 닫기
fun close() {
isListening = false
inputStream?.close()
outputStream?.close()
serialPort = null
}
// 비동기로 데이터 수신 (콜백 방식)
fun listen(callback: (String) -> Unit) {
isListening = true
thread(start = true) {
val buffer = ByteArray(64)
while (isListening) {
try {
val size = inputStream?.read(buffer) ?: break
if (size > 0) {
val data = String(buffer, 0, size)
callback(data)
}
} catch (e: Exception) {
e.printStackTrace()
break
}
}
}
}
}
사용예제
val serial = SerialPortManager("/dev/ttyS1", 115200)
if (serial.open()) {
// 데이터 수신(콜백)
serial.listen { data ->
Log.d("SerialTest", "수신 데이터: $data")
}
// 명령 전송
serial.send("message")
// ... 필요시 close()
// serial.close()
}
'Android > Kotlin' 카테고리의 다른 글
| [Android / Kotlin] (1) 안드로이드에서 시리얼포트 통신하기 (android-serialport-api 오픈소스) (0) | 2025.07.08 |
|---|---|
| [Android / Kotlin] Empty Activity와 Empty Views Activity / 안드로이드 버전 선택 (0) | 2025.03.05 |