在 Kotlin Android 应用程序中处理传入的蓝牙数据流

Handling incoming bluetooth data stream in Kotlin Android app

我正在开发一个小应用程序,它通过蓝牙连接到带有蓝牙屏蔽的 Arduino。我的蓝牙连接很好,我可以从我的应用程序向 Arduino 发送命令。我在科特林做这个。我边走边学,所以我误解了一些东西。我希望有人能指出正确的方向。

您可以假设所有蓝牙连接都工作正常(确实如此)。

这是我的代码中处理向 Arduino 发送数据的部分。

private fun writeDataSendToMothership(outputToBt: String) {
    try {
        bluetoothSocket.outputStream.write(outputToBt.toByteArray())
        Log.i(LOGTAG, "Button clicked, info sent: $outputToBt")
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

button_led_on.setOnClickListener { writeDataSendToMothership("1")}
button_led_off.setOnClickListener { writeDataSendToMothership("0")}

我遇到问题的部分是从 Arduino(Mothership)接收数据并用它做一些事情。我不知道我需要做什么。

我想做的是根据按下 Arduino 上的按钮后 Arduino 发送的内容在应用程序中显示图像。

我目前拥有的是:

private fun readDataFromMothership(inputFromBt: String) {
    try {
        bluetoothSocket.inputStream.read(inputFromBt.toByteArray())
        Log.i(LOGTAG, "Incoming data from Mothership recieved: $inputFromBt")
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

private fun View.showOrInvisible(imageShow: Boolean) {
    visibility = if (imageShow) {
        View.VISIBLE
    } else {
        View.INVISIBLE
    }
}

这是我失败的地方。

if (readDataFromMothership()) {
        imageView_mothership_button_pushed.showOrInvisible(true)
    } else {
        imageView_mothership_button_pushed.showOrInvisible(false)
    }

我遗漏了那个函数调用中的任何内容。我尝试过很多不同的东西,但我只是不明白我需要什么参数,或者我离题太远了。我在正确的街区吗?

编辑 除了我缺乏关于编程的一般知识外,我认为我的挂断与如何处理 "inputFromBt" 字符串有关。我需要使用某种缓冲区吗?我 trying/researching/reading 尽我所能。但停滞不前。

这是我的代码,目前在我的应用程序中运行:

private fun readBlueToothDataFromMothership(bluetoothSocket: BluetoothSocket) {
    Log.i(LOGTAG, Thread.currentThread().name)
    val bluetoothSocketInputStream = bluetoothSocket.inputStream
    val buffer = ByteArray(1024)
    var bytes: Int
    //Loop to listen for received bluetooth messages
    while (true) {
        try {
            bytes = bluetoothSocketInputStream.read(buffer)
            val readMessage = String(buffer, 0, bytes)
            liveData.postValue(readMessage)
        } catch (e: IOException) {
            e.printStackTrace()
            break
        }
    }
}

// display or don't star image
private fun View.showOrHideImage(imageShow: Boolean) {
    visibility = if (imageShow) View.VISIBLE else View.GONE
}

我在给用户 frnnd 的评论中提到,我的主要问题是从我的 arduino 发送的数据。我使用的是 println() 而不是 print() 并且换行符把事情搞砸了。