Fixes in usbservice (making usbserviceconnector global) + relevant changes in other fragments

This commit is contained in:
vsuryakumar
2023-01-27 13:21:04 +05:30
parent ea757d2b5f
commit a43365268f
8 changed files with 376 additions and 96 deletions

View File

@@ -6,6 +6,6 @@ enum class TestRightCommands(val command: String) {
read("read\r"), read("read\r"),
autoset("autoset\r"), autoset("autoset\r"),
run("run\r"), run("run\r"),
printInRange("print 239 2719\r"), printInRange("print 239 339\r"),
printAll("print\r"), printAll("print\r"),
} }

View File

@@ -4,5 +4,5 @@ data class PatientData(
val name: String, val name: String,
val age: Int, val age: Int,
val gender: String, val gender: String,
val results: String? var results: String?
) )

View File

@@ -66,10 +66,16 @@ class TestRightActivity : AppCompatActivity() {
setContentView(binding.root) setContentView(binding.root)
viewModel = ViewModelProvider(this, MyViewModelFactory(this.applicationContext))[TestRightViewModel::class.java] viewModel = ViewModelProvider(this, MyViewModelFactory(this.applicationContext))[TestRightViewModel::class.java]
// Connected or not connected icon with livetime status using live data
connectUsb(false)
// testing()
connectUsb(false); }
private fun testing() {
supportFragmentManager.beginTransaction()
.replace(binding.flMain.id, TestRightExpSample()).commit()
} }
private fun connectUsb(permissionGranted: Boolean) { private fun connectUsb(permissionGranted: Boolean) {
@@ -91,8 +97,8 @@ class TestRightActivity : AppCompatActivity() {
} }
/* /*
* Request user permission. The response will be received in the BroadcastReceiver * Request user permission. The response will be received in the BroadcastReceiver
*/ */
private fun requestUserPermission(manager: UsbManager, device: UsbDevice) { private fun requestUserPermission(manager: UsbManager, device: UsbDevice) {
Log.d(TAG, String.format("requestUserPermissions", device.vendorId, device.productId)) Log.d(TAG, String.format("requestUserPermissions", device.vendorId, device.productId))
@@ -115,7 +121,6 @@ class TestRightActivity : AppCompatActivity() {
} }
private fun moveToNext(){ private fun moveToNext(){
// setupService()
if (supportFragmentManager.isDestroyed) if (supportFragmentManager.isDestroyed)
return return

View File

@@ -1,6 +1,8 @@
package com.example.refactoredapp.presentation.testRight package com.example.refactoredapp.presentation.testRight
import android.os.Bundle import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
@@ -23,7 +25,7 @@ class TestRightExpReference : Fragment() {
private val TAG = "TestRightExpReference" private val TAG = "TestRightExpReference"
val fullReadOutput = StringBuilder() private val fullReadOutput = StringBuilder()
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, inflater: LayoutInflater, container: ViewGroup?,
@@ -40,12 +42,40 @@ class TestRightExpReference : Fragment() {
if (viewModel.isReferenceDone && viewModel.sampleReadCounter <= Constants.MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE) if (viewModel.isReferenceDone && viewModel.sampleReadCounter <= Constants.MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE)
moveToSamplePage() moveToSamplePage()
//
if (viewModel.deviceConstant == null) { if (viewModel.deviceConstant == null) {
sendCmdToFetchDeviceConstant() sendCmdToFetchDeviceConstant()
} }
} }
private fun testing(commands: TestRightCommands) {
viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.printInRange,
object : UsbServiceListener {
override fun onUsbRead(data: ByteArray?) {
data?.let {
val stringData = String(it)
fullReadOutput.append(stringData)
Log.d(TAG, fullReadOutput.toString())
if (stringData.contains("OK", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToFetchLightIntensities()")
viewModel.mapIntensityValues(fullReadOutput.toString(), true)
viewModel.isReferenceDone = true
viewModel.progressBar.postValue(false)
moveToSamplePage()
}
}
}
override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
viewModel.progressBar.postValue(false)
}
})
}
private fun setupListeners() { private fun setupListeners() {
binding.btnSetReference.setOnClickListener { binding.btnSetReference.setOnClickListener {
UIUtils().createAlertDialog( UIUtils().createAlertDialog(
@@ -59,16 +89,32 @@ class TestRightExpReference : Fragment() {
startTakingReference() startTakingReference()
} }
override fun onClickBtnTwo() {} override fun onClickBtnTwo() {
// Todo: Only for testing
// testing(TestRightCommands.led2Set50)
// testing(TestRightCommands.autoset)
// testing(TestRightCommands.run)
// requireActivity().runOnUiThread {
testing(TestRightCommands.run)
// }
}
}) })
} }
binding.btnRead.setOnClickListener { viewModel.progressBar.observe(viewLifecycleOwner) {
// Log.d(TAG, "clicked on text") if (it) {
// val mService = (activity as TestRightActivity).mService binding.progressBar.visibility = View.VISIBLE
// mService.read() } else {
Log.d(TAG, "FULL STRING IS -> $fullReadOutput") binding.progressBar.visibility = View.GONE
}
} }
// binding.btnRead.setOnClickListener {
//// Log.d(TAG, "clicked on text")
//// val mService = (activity as TestRightActivity).mService
//// mService.read()
// Log.d(TAG, "FULL STRING IS -> $fullReadOutput")
// }
} }
/** /**
@@ -79,11 +125,13 @@ class TestRightExpReference : Fragment() {
* 4. command print * 4. command print
*/ */
private fun startTakingReference() { private fun startTakingReference() {
// requireActivity().runOnUiThread {
sendCmdToSetLed() sendCmdToSetLed()
// }
} }
private fun sendCmdToFetchDeviceConstant() { private fun sendCmdToFetchDeviceConstant() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.read, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.read,
object : UsbServiceListener { object : UsbServiceListener {
@@ -93,93 +141,135 @@ class TestRightExpReference : Fragment() {
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToFetchDeviceConstant()")
viewModel.mapDeviceConstants(fullReadOutput.toString()) viewModel.mapDeviceConstants(fullReadOutput.toString())
binding.progressBar.visibility = View.GONE viewModel.mapPixelNumberToWavelength()
viewModel.progressBar.postValue(false)
} }
} }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun sendCmdToSetLed() { private fun sendCmdToSetLed() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.led2Set50, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.led2Set50,
object : UsbServiceListener { object : UsbServiceListener {
override fun onUsbRead(data: ByteArray?) { override fun onUsbRead(data: ByteArray?) {
// requireActivity().runOnUiThread {
data?.let { data?.let {
val stringData = String(it) val stringData = String(it)
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
binding.progressBar.visibility = View.GONE Log.d(TAG, "onUsbRead() called in sendCmdToSetLed()")
sendCmdToAutoset() // viewModel.progressBar.postValue(false)
// requireActivity().runOnUiThread {
// Thread.sleep(2000)
// sendCmdToAutoset()
// }
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
viewModel.progressBar.postValue(false)
sendCmdToAutoset()
},
2000
)
// sendCmdToAutoset()
} }
} }
// }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun sendCmdToAutoset() { private fun sendCmdToAutoset() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.autoset, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.autoset,
object : UsbServiceListener { object : UsbServiceListener {
override fun onUsbRead(data: ByteArray?) { override fun onUsbRead(data: ByteArray?) {
// requireActivity().runOnUiThread {
data?.let { data?.let {
val stringData = String(it) val stringData = String(it)
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
binding.progressBar.visibility = View.GONE Log.d(TAG, "onUsbRead() called in sendCmdToAutoset()")
sendCmdToRun() // viewModel.progressBar.postValue(false)
// sendCmdToRun()
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
viewModel.progressBar.postValue(false)
sendCmdToRun()
},
2000
)
} }
} }
// }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun sendCmdToRun() { private fun sendCmdToRun() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.run, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.run,
object : UsbServiceListener { object : UsbServiceListener {
override fun onUsbRead(data: ByteArray?) { override fun onUsbRead(data: ByteArray?) {
// requireActivity().runOnUiThread {
data?.let { data?.let {
val stringData = String(it) val stringData = String(it)
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
binding.progressBar.visibility = View.GONE Log.d(TAG, "onUsbRead() called in sendCmdToRun()")
sendCmdToFetchLightIntensities() // viewModel.progressBar.postValue(false)
// sendCmdToFetchLightIntensities()
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
viewModel.progressBar.postValue(false)
sendCmdToFetchLightIntensities()
},
2000
)
} }
} }
// }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun sendCmdToFetchLightIntensities() { private fun sendCmdToFetchLightIntensities() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.printAll, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.printAll,
object : UsbServiceListener { object : UsbServiceListener {
@@ -187,19 +277,28 @@ class TestRightExpReference : Fragment() {
data?.let { data?.let {
val stringData = String(it) val stringData = String(it)
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
Log.d(TAG, stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToFetchLightIntensities()")
viewModel.mapIntensityValues(fullReadOutput.toString(), true) viewModel.mapIntensityValues(fullReadOutput.toString(), true)
binding.progressBar.visibility = View.GONE
viewModel.isReferenceDone = true viewModel.isReferenceDone = true
moveToSamplePage() // viewModel.progressBar.postValue(false)
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
viewModel.progressBar.postValue(false)
moveToSamplePage()
},
2000
)
} }
} }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }

View File

@@ -1,6 +1,8 @@
package com.example.refactoredapp.presentation.testRight package com.example.refactoredapp.presentation.testRight
import android.os.Bundle import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
@@ -37,6 +39,14 @@ class TestRightExpSample : Fragment() {
} }
private fun setupListeners() { private fun setupListeners() {
viewModel.progressBar.observe(viewLifecycleOwner) {
if (it) {
binding.progressBar.visibility = View.VISIBLE
} else {
binding.progressBar.visibility = View.GONE
}
}
binding.btnAcquire.setOnClickListener { binding.btnAcquire.setOnClickListener {
val details = isValidInput() val details = isValidInput()
if (details != null) { if (details != null) {
@@ -49,14 +59,14 @@ class TestRightExpSample : Fragment() {
binding.etGenderBlock.setOnClickListener { binding.ddGender.isErrorEnabled = false } binding.etGenderBlock.setOnClickListener { binding.ddGender.isErrorEnabled = false }
} }
private fun isValidInput() : PatientData? { private fun isValidInput(): PatientData? {
val name = binding.etName.editText?.text?.trim() val name = binding.etName.editText?.text?.trim()
if (name.isNullOrEmpty()){ if (name.isNullOrEmpty()) {
binding.etName.error = getString(R.string.name_error) binding.etName.error = getString(R.string.name_error)
return null return null
} }
val age = binding.etAge.editText?.text?.trim() val age = binding.etAge.editText?.text?.trim()
if (age.isNullOrEmpty()){ if (age.isNullOrEmpty()) {
binding.etAge.error = getString(R.string.age_error) binding.etAge.error = getString(R.string.age_error)
return null return null
} else if (age.toString().toInt() < 0 || age.toString().toInt() > 199) { } else if (age.toString().toInt() < 0 || age.toString().toInt() > 199) {
@@ -64,7 +74,7 @@ class TestRightExpSample : Fragment() {
return null return null
} }
val gender = binding.ddGender.editText?.text val gender = binding.ddGender.editText?.text
if (gender.isNullOrEmpty()){ if (gender.isNullOrEmpty()) {
binding.ddGender.error = getString(R.string.gender_error) binding.ddGender.error = getString(R.string.gender_error)
return null return null
} }
@@ -77,11 +87,12 @@ class TestRightExpSample : Fragment() {
* 2. command print * 2. command print
*/ */
private fun startAcquiring() { private fun startAcquiring() {
// binding.progressBar.visibility = View.VISIBLE
sendCmdToRun() sendCmdToRun()
} }
private fun sendCmdToRun() { private fun sendCmdToRun() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite( (activity as TestRightActivity).mService.eventDrivenWrite(
TestRightCommands.run, TestRightCommands.run,
@@ -92,21 +103,29 @@ class TestRightExpSample : Fragment() {
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
binding.progressBar.visibility = View.GONE // viewModel.progressBar.postValue(false)
sendCmdToFetchLightIntensities()
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
viewModel.progressBar.postValue(false)
sendCmdToFetchLightIntensities()
},
2000
)
} }
} }
} }
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun sendCmdToFetchLightIntensities() { private fun sendCmdToFetchLightIntensities() {
binding.progressBar.visibility = View.VISIBLE viewModel.progressBar.postValue(true)
val fullReadOutput = StringBuilder() val fullReadOutput = StringBuilder()
(activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.printAll, (activity as TestRightActivity).mService.eventDrivenWrite(TestRightCommands.printAll,
object : UsbServiceListener { object : UsbServiceListener {
@@ -114,10 +133,10 @@ class TestRightExpSample : Fragment() {
data?.let { data?.let {
val stringData = String(it) val stringData = String(it)
fullReadOutput.append(stringData) fullReadOutput.append(stringData)
// Log.d(TAG, "Values of print cmd -> $stringData")
if (stringData.contains("OK", true)) { if (stringData.contains("OK", true)) {
viewModel.mapIntensityValues(fullReadOutput.toString(), false) viewModel.mapIntensityValues(fullReadOutput.toString(), false)
binding.progressBar.visibility = View.GONE // viewModel.progressBar.postValue(false)
showResultsAfterAcquiring() showResultsAfterAcquiring()
} }
} }
@@ -125,14 +144,17 @@ class TestRightExpSample : Fragment() {
override fun onUsbError(e: Exception?) { override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e") Log.e(TAG, "onUsbIoError() called in writeUsbFetchDeviceConstant() -> $e")
binding.progressBar.visibility = View.GONE viewModel.progressBar.postValue(false)
} }
}) })
} }
private fun showResultsAfterAcquiring() { private fun showResultsAfterAcquiring() {
viewModel.calculateResults() viewModel.calculateResults()
viewModel.progressBar.postValue(false)
// binding.progressBar.visibility = View.GONE
parentFragmentManager.beginTransaction().replace(R.id.fl_main, TestRightResults())
.commit()
} }
private fun Button.disable() { private fun Button.disable() {

View File

@@ -1,16 +1,13 @@
package com.example.refactoredapp.presentation.testRight package com.example.refactoredapp.presentation.testRight
import android.util.Log import android.util.Log
import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.refactoredapp.data.Constants import com.example.refactoredapp.data.Constants
import com.example.refactoredapp.data.model.PatientDetails import com.example.refactoredapp.data.model.PatientData
import com.example.refactoredapp.data.model.TestRightDeviceConstants import com.example.refactoredapp.data.model.TestRightDeviceConstants
import kotlinx.coroutines.Dispatchers import com.example.refactoredapp.domain.SaveRawData
import kotlinx.coroutines.launch import kotlin.math.log10
import kotlin.math.pow import kotlin.math.pow
class TestRightViewModel : ViewModel() { class TestRightViewModel : ViewModel() {
@@ -19,22 +16,24 @@ class TestRightViewModel : ViewModel() {
var isReferenceDone = false var isReferenceDone = false
var isServiceConnected = false var isServiceConnected = false
val progressBar = MutableLiveData(false)
val isUsbConnected = MutableLiveData(false) val isUsbConnected = MutableLiveData(false)
lateinit var patientDetails: PatientDetails lateinit var patientDetails: PatientData
var sampleReadCounter = 0
var deviceConstant: TestRightDeviceConstants? = null var deviceConstant: TestRightDeviceConstants? = null
/* Contains wavelength -> pixel no.*/ /* Contains wavelength -> pixel no.*/
val wavelengthToPixelArray = ArrayList<ArrayList<Double>>() val wavelengthToPixelArray = ArrayList<ArrayList<Double>>()
/* (For reference/baseline) Contains pixel no. -> Intensity of light falling on that pixel */ /* (For reference/baseline) Contains pixel no. -> Intensity of light falling on that pixel */
val intensityReferenceArray = ArrayList<ArrayList<Double>>() val intensityReferenceArray = ArrayList<ArrayList<Double>>()
/* (For exp sample) Contains pixel no. -> Intensity of light falling on that pixel */ /* (For exp sample) Contains pixel no. -> Intensity of light falling on that pixel */
val intensitySampleArray = ArrayList<ArrayList<Double>>() val intensitySampleArray = ArrayList<ArrayList<Double>>()
val wavelengthToAbsorbance = ArrayList<ArrayList<Double>>()
fun mapDeviceConstants(string: String) { fun mapDeviceConstants(string: String) {
// viewModelScope.launch { // viewModelScope.launch {
if (string.isNotEmpty()) { if (string.isNotEmpty()) {
@@ -79,6 +78,13 @@ class TestRightViewModel : ViewModel() {
fun mapIntensityValues(fullString: String, isReference: Boolean) { fun mapIntensityValues(fullString: String, isReference: Boolean) {
// viewModelScope.launch { // viewModelScope.launch {
val listOfString = fullString.split("\n") val listOfString = fullString.split("\n")
// Log.d(TAG, "inside mapIntensityValues() -> isReference = $isReference")
// Log.d(TAG, "listOfString size = ${listOfString.size}")
// if(!isReference){
// Log.d(TAG, "fullString = $fullString")
// }
for (line in listOfString) { for (line in listOfString) {
if ("Buf" in line) { if ("Buf" in line) {
/* Removing trailing spaces and "Buf" from the string then taking lhs & rhs of ':' */ /* Removing trailing spaces and "Buf" from the string then taking lhs & rhs of ':' */
@@ -88,8 +94,15 @@ class TestRightViewModel : ViewModel() {
val temp = ArrayList<Double>(2) val temp = ArrayList<Double>(2)
temp.add(numbers[0].toDouble()) temp.add(numbers[0].toDouble())
temp.add(numbers[1].toDouble()) temp.add(numbers[1].toDouble())
if (isReference) intensityReferenceArray.add(temp)
else intensitySampleArray.add(temp) // if(!isReference){
// Log.d(TAG, "temp[0] = ${temp[0]} & temp[1] = ${temp[1]}")
// }
if (isReference)
intensityReferenceArray.add(temp)
else
intensitySampleArray.add(temp)
} else { } else {
// Todo: Error handling // Todo: Error handling
} }
@@ -98,28 +111,128 @@ class TestRightViewModel : ViewModel() {
// } // }
} }
// fun isValidInput() : Boolean{
// name = email.trim() fun calculateDataForCSV(){
// return when { var indexInReference = intensityReferenceArray.size - 1
// email.isEmpty() -> { var indexInSample = intensitySampleArray.size - 1
// Log.d(TAG, "email is empty") for (each in wavelengthToPixelArray){
// _emailError.value = context.getString(R.string.malformed_email_empty_error) val wavelength = each[0]
// false val invertedPixel = (Constants.TEST_RIGHT_TOTAL_PIXEL + 1) - each[1]
// }
// !Patterns.EMAIL_ADDRESS.matcher(email).matches() -> { var Io = 0.0
// Log.d(TAG, "email pattern mismatched") if (intensityReferenceArray[indexInReference][0].toInt() == invertedPixel.toInt()){
// _emailError.value = context.getString(R.string.malformed_email_error) Io = intensityReferenceArray[indexInReference][1]
// false }
// }
// password.length < 6 -> { var I = 0.0
// Log.d(TAG, "password is empty") if (intensitySampleArray[indexInSample][0].toInt() == invertedPixel.toInt()){
// _passwordError.value = context.getString(R.string.malformed_password_error) I = intensitySampleArray[indexInSample][1]
// false }
// }
// else -> { val absorbance = log10(Io/I)
// Log.d(TAG, "isValidInput: returning true")
// true val temp = ArrayList<Double>(2)
// } temp.add(wavelength)
// } temp.add(absorbance)
// } wavelengthToAbsorbance.add(temp)
indexInReference--
indexInSample--
}
}
fun saveRawData(folderPath: String, filename: String) {
SaveRawData().saveCsv(folderPath, filename, wavelengthToAbsorbance)
}
fun calculateResults() {
Log.d(TAG, "DEBUGGINGGGGG--------------------------------------------------------------------------------")
sampleReadCounter++
var pixelNoWithWave_427 = 0;
var pixelNoWithWave_555 = 0;
Log.d(TAG, "wavelengthToPixelArray size = ${wavelengthToPixelArray.size}")
// println("wavelengthToPixelArray size = ${wavelengthToPixelArray.size}")
for (each in wavelengthToPixelArray){
var diff = each[0] - 427
if (pixelNoWithWave_427 == 0 && diff >= 0 && diff < 1){
pixelNoWithWave_427 = each[1].toInt()
}
diff = each[0] - 555
if (pixelNoWithWave_555 == 0 && diff >= 0 && diff < 1){
pixelNoWithWave_555 = each[1].toInt()
}
if (pixelNoWithWave_427 != 0 && pixelNoWithWave_555 != 0) {
break
}
}
Log.d(TAG, "pixelOfInterest_427 = ${pixelNoWithWave_427}")
Log.d(TAG, "pixelOfInterest_555 = ${pixelNoWithWave_555}")
// println("pixelOfInterest_427 = ${pixelNoWithWave_427}")
// println("pixelOfInterest_555 = ${pixelNoWithWave_555}")
val invertedPixel_427 = (Constants.TEST_RIGHT_TOTAL_PIXEL + 1) - pixelNoWithWave_427
val invertedPixel_555 = (Constants.TEST_RIGHT_TOTAL_PIXEL + 1) - pixelNoWithWave_555
var io_427 = 0.0
var io_555 = 0.0
for (each in intensityReferenceArray){
if (each[0].toInt() == invertedPixel_427){
io_427 = each[1]
}
if (each[0].toInt() == invertedPixel_555){
io_555 = each[1]
}
}
Log.d(TAG, "I0 values are I0_427 = $io_427 , IO_555 = $io_555")
// println("I0 values are I0_427 = $io_427 , IO_555 = $io_555")
var i_427 = 0.0
var i_555 = 0.0
for (each in intensitySampleArray){
if (each[0].toInt() == invertedPixel_427){
i_427 = each[1]
}
if (each[0].toInt() == invertedPixel_555){
i_555 = each[1]
}
}
Log.d(TAG, "I values are I_427 = $i_427 , I_555 = $i_555")
// println("I values are I_427 = $i_427 , I_555 = $i_555")
val absorbanceAtPixelWithWave_427 = log10(io_427/i_427)
val absorbanceAtPixelWithWave_555 = log10(io_555/i_555)
Log.d(TAG, "absorbance values are for 427 = $absorbanceAtPixelWithWave_427 , for 555 = $absorbanceAtPixelWithWave_555")
// println("absorbance values are for 427 = $absorbanceAtPixelWithWave_427 , for 555 = $absorbanceAtPixelWithWave_555")
var value = 0.0;
if (absorbanceAtPixelWithWave_427 != 0.0 && absorbanceAtPixelWithWave_555 != 0.0) {
value = absorbanceAtPixelWithWave_555 / absorbanceAtPixelWithWave_427
}
Log.d(TAG, "value = $value")
// println("value = $value")
var results: String = ""
if (value < 0.24 || value == 0.0) {
results = "Normal"
} else if (value >= 0.24 && value < 0.30) {
results = "Sickle Cell Trait"
} else if (value >= 0.30) {
results = "Sickle-Cell Disease"
}
Log.d(TAG, "Results = $results")
// println("Results = $results")
patientDetails.results = results
}
} }

View File

@@ -33,6 +33,16 @@ class UsbService : Service() {
return binder return binder
} }
// fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) {
// mPort = driver.ports[0] // Most devices have just one port (port 0)
// mPort.open(connection)
// mPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
//
// isUsbConnected = true
// Log.d(TAG, "My Usb Connected ${mPort.driver}")
// }
var listener: UsbServiceListener? = null
fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) { fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) {
mPort = driver.ports[0] // Most devices have just one port (port 0) mPort = driver.ports[0] // Most devices have just one port (port 0)
mPort.open(connection) mPort.open(connection)
@@ -40,6 +50,20 @@ class UsbService : Service() {
isUsbConnected = true isUsbConnected = true
Log.d(TAG, "My Usb Connected ${mPort.driver}") Log.d(TAG, "My Usb Connected ${mPort.driver}")
val usbIoManager = SerialInputOutputManager(mPort,
object : SerialInputOutputManager.Listener{
override fun onNewData(data: ByteArray?) {
// Log.e(TAG, "onNewData() called inside eventDrivenWrite()")
listener?.onUsbRead(data)
}
override fun onRunError(e: Exception?) {
Log.e(TAG, "onRunError() called inside eventDrivenWrite()")
listener?.onUsbError(e)
}
})
usbIoManager.start();
} }
fun disconnect() { fun disconnect() {
@@ -50,20 +74,30 @@ class UsbService : Service() {
} }
} }
// fun eventDrivenWrite(command: TestRightCommands, listener: UsbServiceListener) {
// val usbIoManager = SerialInputOutputManager(mPort,
// object : SerialInputOutputManager.Listener{
// override fun onNewData(data: ByteArray?) {
// Log.e(TAG, "onNewData() called inside eventDrivenWrite() :: command = ${command.command}")
// listener.onUsbRead(data)
// }
// override fun onRunError(e: Exception?) {
// Log.e(TAG, "onRunError() called inside eventDrivenWrite()")
// listener.onUsbError(e)
// }
//
// })
// usbIoManager.start();
//
// try {
// mPort.write(command.command.toByteArray(), Constants.WRITE_TIMEOUT_MILLIS)
// } catch (e: IOException) {
// listener.onUsbError(e)
// }
// }
fun eventDrivenWrite(command: TestRightCommands, listener: UsbServiceListener) { fun eventDrivenWrite(command: TestRightCommands, listener: UsbServiceListener) {
val usbIoManager = SerialInputOutputManager(mPort, this.listener = listener
object : SerialInputOutputManager.Listener{
override fun onNewData(data: ByteArray?) {
listener.onUsbRead(data)
}
override fun onRunError(e: Exception?) {
Log.e(TAG, "onRunError() called inside eventDrivenWrite()")
listener.onUsbError(e)
}
})
usbIoManager.start();
try { try {
mPort.write(command.command.toByteArray(), Constants.WRITE_TIMEOUT_MILLIS) mPort.write(command.command.toByteArray(), Constants.WRITE_TIMEOUT_MILLIS)
} catch (e: IOException) { } catch (e: IOException) {

View File

@@ -5,7 +5,14 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder
class UIUtils { class UIUtils {
fun createAlertDialog(context: Context, title: String, subtitle: String, btnOneText: String, btnTwoText: String, listener: MyDialogListener){ fun createAlertDialog(
context: Context,
title: String,
subtitle: String,
btnOneText: String,
btnTwoText: String,
listener: MyDialogListener
) {
MaterialAlertDialogBuilder(context) MaterialAlertDialogBuilder(context)
.setTitle(title) .setTitle(title)
.setMessage(subtitle) .setMessage(subtitle)