take message as frames

This commit is contained in:
Pritimay Sarkar
2023-08-05 12:50:50 +05:30
parent 7ca2d78325
commit 013dc569a1
3 changed files with 122 additions and 57 deletions

View File

@@ -16,6 +16,7 @@ data class HemoCubeTestData(
var testTime: String? = "", var testTime: String? = "",
var testStatus: Boolean? = false, var testStatus: Boolean? = false,
var deviceSerialNumber: String = "", var deviceSerialNumber: String = "",
var deviceType: String = "HEMOCUBE",
var kitSerial: String = "", var kitSerial: String = "",
var resultData: String = "", var resultData: String = "",
var led1Buffer: Double? = null, var led1Buffer: Double? = null,

View File

@@ -4,7 +4,6 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
import android.os.Bundle import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@@ -39,7 +38,7 @@ class HemoCubeFragment : Fragment() {
private var deviceData: DeviceData? = null private var deviceData: DeviceData? = null
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
): View { ): View {
binding = FragmentHemoCubeReferenceBinding.inflate(inflater, container, false) binding = FragmentHemoCubeReferenceBinding.inflate(inflater, container, false)
return binding.root return binding.root
@@ -69,9 +68,7 @@ class HemoCubeFragment : Fragment() {
binding.progressBar.visibility = View.GONE binding.progressBar.visibility = View.GONE
} }
hemoCubeViewModel.getDeviceData("DEVICE1") // TODO hemoCubeViewModel.getDeviceData(sharedPreference.getString(Constants.USER_ID, "").toString())
// hemoCubeViewModel.getDeviceData(sharedPreference.getString(Constants.USER_ID, "").toString())
hemoCubeViewModel.deviceData.observe(viewLifecycleOwner) { hemoCubeViewModel.deviceData.observe(viewLifecycleOwner) {
deviceData = it deviceData = it
@@ -104,7 +101,8 @@ class HemoCubeFragment : Fragment() {
listenToHemoCube() listenToHemoCube()
startSample() startSample()
} }
}) }
)
} else { } else {
listenToHemoCube() listenToHemoCube()
startBuffer() startBuffer()
@@ -116,8 +114,8 @@ class HemoCubeFragment : Fragment() {
&& sharedPreference.getString(Constants.BUFFER_VALUE_2, "") != "" && sharedPreference.getString(Constants.BUFFER_VALUE_2, "") != ""
) { ) {
sharedPreference.getString(Constants.BUFFER_VALUE_1, "") sharedPreference.getString(Constants.BUFFER_VALUE_1, "")
?.toInt()!! > 0 && sharedPreference.getString(Constants.BUFFER_VALUE_2, "") ?.toDouble()!! > 0.0 && sharedPreference.getString(Constants.BUFFER_VALUE_2, "")
?.toInt()!! > 0 ?.toDouble()!! > 0.0
} else { } else {
false false
} }
@@ -128,7 +126,6 @@ class HemoCubeFragment : Fragment() {
binding.btnSubmit.setOnClickListener { binding.btnSubmit.setOnClickListener {
binding.progressBar.visibility = View.VISIBLE binding.progressBar.visibility = View.VISIBLE
getResult() getResult()
} }
binding.btnSubmit.isEnabled = false binding.btnSubmit.isEnabled = false
@@ -154,6 +151,7 @@ class HemoCubeFragment : Fragment() {
} }
hemoCubeViewModel.progressBar.postValue(true) hemoCubeViewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as HemocubeActivity).mService.listenToHemoCube(object : UsbServiceListener { (activity as HemocubeActivity).mService.listenToHemoCube(object : UsbServiceListener {
override fun onUsbRead(data: ByteArray?) { override fun onUsbRead(data: ByteArray?) {
@@ -164,35 +162,75 @@ class HemoCubeFragment : Fragment() {
if (stringData.contains("#")) { if (stringData.contains("#")) {
binding.tvSubtitle4.text = stringData binding.tvSubtitle4.text = stringData
} }
if (stringData.contains("ERROR")) {
UIUtils.createAlertDialog(requireContext(),
"ERROR",
"Do you want to continue with existing buffer",
getString(R.string.no),
"Yes",
object : MyDialogListener {
override fun onClickNegativeButton() {
listenToHemoCube()
startBuffer()
}
override fun onClickPositiveButton() {
listenToHemoCube()
startSample()
}
}
)
}
resultData += fullReadOutput.toString() resultData += fullReadOutput.toString()
DataHolder.hemoCubeTestData?.resultData DataHolder.hemoCubeTestData?.resultData
if (stringData.contains("Completed")) { if (stringData.contains("#Sample Completed")) {
binding.btnSubmit.isEnabled = true activity?.runOnUiThread {
binding.btnSubmit.isClickable = true binding.btnSubmit.isEnabled = true
binding.btnSubmit.isClickable = true
}
} }
hemoCubeViewModel.progressBar.postValue(false) hemoCubeViewModel.progressBar.postValue(false)
if (resultData.contains("RESULT")) { if (stringData.contains("RESULT") || resultData.contains("REND")) {
// DEVICE RESPONSE FORMAT: RESULT SN <DEVICE_SERIAL_NUMBER> <GREEN_BUFFER_INTENSITY> <BLUE_BUFFER_INTENSITY> <GREEN_SAMPLE_INTENSITY> <BLUE_SAMPLE_INTENSITY> // DEVICE RESPONSE FORMAT: RESULT SN <DEVICE_SERIAL_NUMBER> <GREEN_BUFFER_INTENSITY> <BLUE_BUFFER_INTENSITY> <GREEN_SAMPLE_INTENSITY> <BLUE_SAMPLE_INTENSITY> REND
// // For example, "RESULT SN 18291 1937.23 2828.11 28211.20 121829.12" // // For example, "RESULT SN 18291 1937.23 2828.11 28211.20 121829.12 REND"
val results = resultData.split("\n") var validString = ""
val validStringFound = checkAndFindResults(results) var results: List<String>
if (!validStringFound.isNullOrEmpty()) { if (stringData.contains("RESULT")) {
val response = validStringFound validString = isValidResult(stringData)
val result = response.split(" ") if (validString.isNullOrEmpty()) {
results = resultData.split("\n")
validString = parseResult(results)
}
} else {
results = resultData.split("\n")
validString = parseResult(results)
}
if (!validString.isNullOrEmpty()) {
val result = validString.split(" ")
if (result.size == 8) { if (result.size == 8) {
val deviceSerialNo = result[2] val deviceSerialNo = result[2]
val led1Buffer = result[3].toDoubleOrNull() val led1Buffer = result[3].toDoubleOrNull()
val led2Buffer = result[4].toDoubleOrNull() val led2Buffer = result[4].toDoubleOrNull()
// TODO: Check old buffer
val led1Sample = result[5].toDoubleOrNull() val led1Sample = result[5].toDoubleOrNull()
val led2Sample = result[6].toDoubleOrNull() val led2Sample = result[6].toDoubleOrNull()
val led1Average = log10(led1Buffer?.div(led1Sample!!) ?: 0.0) val led1Average = log10(led1Buffer?.div(led1Sample!!) ?: 0.0)
val led2Average = log10(led2Buffer?.div(led2Sample!!) ?: 0.0) val led2Average = log10(led2Buffer?.div(led2Sample!!) ?: 0.0)
val deviceRatio = led1Average / led2Average val deviceRatio = led1Average / led2Average
DataHolder.hemoCubeTestData?.deviceSerialNumber = deviceSerialNo DataHolder.hemoCubeTestData?.deviceSerialNumber = deviceSerialNo
DataHolder.hemoCubeTestData?.led1Buffer = led1Buffer val kitCount = sharedPreference.getInt(Constants.KIT_COUNT, 0)?.toInt()
DataHolder.hemoCubeTestData?.led2Buffer = led2Buffer if (kitCount != null && kitCount < 35 && sharedPreference.getString(Constants.BUFFER_VALUE_1, "").isNullOrEmpty())
DataHolder.hemoCubeTestData?.led1Buffer = led1Buffer
else
DataHolder.hemoCubeTestData?.led1Buffer = sharedPreference.getString(Constants.BUFFER_VALUE_1, "")?.toDoubleOrNull()
if (kitCount != null && kitCount < 35 && sharedPreference.getString(Constants.BUFFER_VALUE_2, "").isNullOrEmpty())
DataHolder.hemoCubeTestData?.led2Buffer = led2Buffer
else
DataHolder.hemoCubeTestData?.led2Buffer = sharedPreference.getString(Constants.BUFFER_VALUE_2, "")?.toDoubleOrNull()
DataHolder.hemoCubeTestData?.led1Sample = led1Sample DataHolder.hemoCubeTestData?.led1Sample = led1Sample
DataHolder.hemoCubeTestData?.led2Sample = led2Sample DataHolder.hemoCubeTestData?.led2Sample = led2Sample
DataHolder.hemoCubeTestData?.led1Average = led1Average DataHolder.hemoCubeTestData?.led1Average = led1Average
@@ -201,6 +239,7 @@ class HemoCubeFragment : Fragment() {
DataHolder.hemoCubeTestData?.calculatedRatio = DataHolder.hemoCubeTestData?.calculatedRatio =
calculateRatio(deviceRatio) calculateRatio(deviceRatio)
resultRatio = deviceRatio?.toString()
if (!checkBufferValue()) { if (!checkBufferValue()) {
with(sharedPreference.edit()) { with(sharedPreference.edit()) {
putString(Constants.BUFFER_VALUE_1, led1Buffer.toString()) putString(Constants.BUFFER_VALUE_1, led1Buffer.toString())
@@ -211,19 +250,31 @@ class HemoCubeFragment : Fragment() {
} }
} }
hemoCubeViewModel.progressBar.postValue(false) hemoCubeViewModel.progressBar.postValue(false)
// TODO
if (isOnline) { if (isOnline) {
resultRatio?.let { ratio -> resultRatio?.let { ratio ->
Log.e("Testdb", "upload") activity?.runOnUiThread {
binding.btnSubmit.isEnabled = false
binding.btnSubmit.isClickable = false
}
hemoCubeViewModel.uploadHemoCubeResultToDatabase( hemoCubeViewModel.uploadHemoCubeResultToDatabase(
isOnline, true, kitSerial isOnline, true, kitSerial
) )
} }
binding.progressBar.visibility = View.VISIBLE binding.progressBar.visibility = View.VISIBLE
findNavController().navigate(R.id.action_hemocubeFragment_to_homeFragment)
} else { } else {
resultRatio?.let { ratio -> resultRatio?.let { ratio ->
activity?.runOnUiThread {
binding.btnSubmit.isEnabled = false
binding.btnSubmit.isClickable = false
}
hemoCubeViewModel.uploadHemoCubeResultToDatabase( hemoCubeViewModel.uploadHemoCubeResultToDatabase(
isOnline, true, kitSerial isOnline, true, kitSerial
) )
findNavController().navigate(R.id.action_hemocubeFragment_to_homeFragment)
} }
Toast.makeText( Toast.makeText(
requireContext(), requireContext(),
@@ -266,7 +317,6 @@ class HemoCubeFragment : Fragment() {
}) })
} }
private fun getResult() { private fun getResult() {
hemoCubeViewModel.progressBar.postValue(true) hemoCubeViewModel.progressBar.postValue(true)
@@ -285,18 +335,26 @@ class HemoCubeFragment : Fragment() {
return c1 * ratio + c2 return c1 * ratio + c2
} }
private fun checkAndFindResults(results: List<String>): String { private fun parseResult(frames: List<String>): String {
val reversedResults = results.reversed() val lines = mutableListOf<String>()
for (line in reversedResults) { for (frame in frames.reversed()) {
if (isValidFormat(line)) return line if (frame.contains("REND") || frame.contains("RESULT"))
lines += frame
if (frame.contains("RESULT")) {
break
}
}
val line = lines.reversed().joinToString("").trim()
if (line.contains("RESULT") && line.split(" ").size == 8) {
return line
} }
return "" return ""
} }
private fun isValidFormat(line: String): Boolean { private fun isValidResult(line: String): String {
if (line.contains("RESULT") && line.split(" ").size == 8) { if (line.contains("RESULT") && line.split(" ").size == 8) {
return true return line
} }
return false return ""
} }
} }

View File

@@ -1,7 +1,7 @@
package com.example.hpostesting.presentation.hemocube package com.example.hpostesting.presentation.hemocube
import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import android.util.Log import android.util.Log
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
@@ -9,6 +9,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.hpostesting.data.DataHolder import com.example.hpostesting.data.DataHolder
import com.example.hpostesting.data.NetworkStatusLiveData import com.example.hpostesting.data.NetworkStatusLiveData
import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.dao.HemoCubeDao import com.example.hpostesting.data.dao.HemoCubeDao
import com.example.hpostesting.data.model.Response import com.example.hpostesting.data.model.Response
import com.example.hpostesting.data.model.patient.DeviceData import com.example.hpostesting.data.model.patient.DeviceData
@@ -25,12 +26,12 @@ import javax.inject.Inject
class HemoCubeViewModel @Inject constructor( class HemoCubeViewModel @Inject constructor(
private val hemoCubeDao: HemoCubeDao, private val hemoCubeDao: HemoCubeDao,
private val repository: DatabaseRepository, private val repository: DatabaseRepository,
context: Context context: Context,
) : ViewModel() { ) : ViewModel() {
var isServiceConnected = false var isServiceConnected = false
val progressBar = MutableLiveData(false) val progressBar = MutableLiveData(false)
private val testDetails = DataHolder.selectedTest?.toHemoCubeTestData() private val testDetails = DataHolder.selectedTest?.toHemoCubeTestData()
private val sharedPreference: SharedPreferences = context.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
// Get the device ID of the device you want to retrieve data for (e.g., the first device in the list) // Get the device ID of the device you want to retrieve data for (e.g., the first device in the list)
@@ -39,28 +40,26 @@ class HemoCubeViewModel @Inject constructor(
val networkStatusLiveData: LiveData<Boolean> val networkStatusLiveData: LiveData<Boolean>
get() = _networkStatusLiveData get() = _networkStatusLiveData
val fireBaseUpload = MutableLiveData<String>() val fireBaseUpload = MutableLiveData<String>()
fun uploadHemoCubeResultToDatabase(isOnline: Boolean, testStatus: Boolean, kitSerial: String?) = viewModelScope.launch { fun uploadHemoCubeResultToDatabase(isOnline: Boolean, testStatus: Boolean, kitSerial: String?) =
if (kitSerial != null) { viewModelScope.launch {
testDetails?.kitSerial = kitSerial if (kitSerial != null) {
} testDetails?.kitSerial = kitSerial
testDetails?.testStatus = testStatus }
testDetails?.testStatus = testStatus
try {
if (isOnline) { try {
Log.e("Testdb", "Uploading data to Firestore...") if (isOnline) {
addResultTestToDb() addResultTestToDb()
Log.e("Testdb", "Upload successful!") } else {
} else { testDetails?.testTime = SimpleDateFormat(
testDetails?.testTime = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault()
"yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(Calendar.getInstance().time)
).format(Calendar.getInstance().time) hemoCubeDao.insertAll(testDetails!!)
hemoCubeDao.insertAll(testDetails!!) }
Log.e("Testdb", "Data saved locally.") } catch (e: Exception) {
Log.e("Testdb", "Upload failed: ${e.message}")
} }
} catch (e: Exception) {
Log.e("Testdb", "Upload failed: ${e.message}")
} }
}
fun getDeviceData(deviceId: String) = viewModelScope.launch { fun getDeviceData(deviceId: String) = viewModelScope.launch {
deviceData.postValue(repository.getDeviceDataById(deviceId)) deviceData.postValue(repository.getDeviceDataById(deviceId))
@@ -73,7 +72,9 @@ class HemoCubeViewModel @Inject constructor(
testDetails?.testTime = SimpleDateFormat( testDetails?.testTime = SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault() "yyyy-MM-dd HH:mm:ss", Locale.getDefault()
).format(Calendar.getInstance().time) ).format(Calendar.getInstance().time)
testDetails?.deviceSerialNumber = DataHolder.hemoCubeTestData?.deviceSerialNumber.toString()
testDetails?.deviceSerialNumber = sharedPreference.getString(Constants.USER_ID, "").toString()
testDetails?.kitSerial = sharedPreference.getString(Constants.KIT_NUMBER, "").toString()
testDetails?.led1Buffer = DataHolder.hemoCubeTestData?.led1Buffer testDetails?.led1Buffer = DataHolder.hemoCubeTestData?.led1Buffer
testDetails?.led2Buffer = DataHolder.hemoCubeTestData?.led2Buffer testDetails?.led2Buffer = DataHolder.hemoCubeTestData?.led2Buffer
testDetails?.led1Sample = DataHolder.hemoCubeTestData?.led1Sample testDetails?.led1Sample = DataHolder.hemoCubeTestData?.led1Sample
@@ -91,7 +92,12 @@ class HemoCubeViewModel @Inject constructor(
when (val response = repository.addTestToDatabase(testDetails)) { when (val response = repository.addTestToDatabase(testDetails)) {
is Response.Success -> { is Response.Success -> {
Log.e("Testdb", "Data uploaded to Firestore successfully") val kitCount = sharedPreference.getString(Constants.KIT_COUNT, "")?.toInt()
with(sharedPreference.edit()) {
putInt(Constants.KIT_COUNT, kitCount?.plus(1) ?: 0)
apply()
}
Log.i("Testdb", "Data uploaded to Firestore successfully")
fireBaseUpload.postValue("Success") fireBaseUpload.postValue("Success")
} }