Data transfer service rewritten

This commit is contained in:
2024-03-01 22:11:06 +07:00
parent 5e0f2f1bb7
commit 3ac39136c6

View File

@@ -2,28 +2,19 @@ package com.helible.pilot.viewmodels
import android.bluetooth.BluetoothSocket
import android.util.Log
import com.helible.pilot.dataclasses.DeviceState
import com.helible.pilot.dataclasses.DeviceStatusJsonAdapter
import com.helible.pilot.dataclasses.GeneralMessage
import com.helible.pilot.dataclasses.MessageType
import com.helible.pilot.dataclasses.PidSettings
import com.helible.pilot.exceptions.TransferFailedException
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonEncodingException
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import java.io.BufferedInputStream
import java.io.IOException
const val maxPackageSize = 512; // bytes
const val maxPackageSize = 512 // [bytes]
@ExperimentalStdlibApi
class BluetoothDataTransferService(
private val socket: BluetoothSocket,
) {
@@ -32,25 +23,23 @@ class BluetoothDataTransferService(
if (!socket.isConnected)
return@flow
val buffer = ByteArray(maxPackageSize)
val buffer = BufferedInputStream(socket.inputStream, maxPackageSize)
while (true) {
val byteCount: Int = try {
socket.inputStream.read(buffer)
val message: String = try {
buffer.bufferedReader().readLine()
} catch (e: IOException) {
Log.e("BluetoothController", "Failed to receive incoming data")
throw TransferFailedException()
}
var messageData: String = buffer.decodeToString(endIndex = byteCount)
val messageType: MessageType? = MessageType.values()
.elementAtOrNull(messageData.split(";")[0].toInt())
if (messageData.endsWith("\n\r") && messageType != null) {
messageData = messageData.dropLast(2).split(";")[1]
try {
val messageType =
MessageType.values().elementAtOrNull(message.split(";").first().toInt())
val messageData = message.split(";").last()
if (messageType != null) {
emit(GeneralMessage(messageType, messageData))
Log.d("BluetoothController", "Received: $messageData")
} else {
Log.i("BluetoothController", "Package end isn't valid.")
Log.i("BluetoothController", messageData)
}
} catch (e: NoSuchElementException) {
Log.e("BluetoothController", "Message type is invalid: $message")
}
}
}.flowOn(Dispatchers.IO)