Merge branch 'main' of https://github.com/surya-x/sickle-cell-updated into navigation-db

Updated to main.
This commit is contained in:
vsuryakumar
2023-02-13 13:09:46 +05:30
27 changed files with 15655 additions and 193 deletions

View File

@@ -39,16 +39,16 @@
android:exported="false"
android:windowSoftInputMode="adjustPan"
android:parentActivityName="com.example.hpos.presentation.MainActivity">
<!-- <intent-filter>-->
<!-- <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />-->
<!-- </intent-filter>-->
<!-- <intent-filter>-->
<!-- <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />-->
<!-- </intent-filter>-->
<!-- <meta-data-->
<!-- android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"-->
<!-- android:resource="@xml/device_filter" />-->
<!-- <meta-data-->
<!-- android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"-->
<!-- android:resource="@xml/device_filter" />-->
</activity>
<!-- android:theme="@style/Theme.HPOS.ActionBar"-->
<!-- android:theme="@style/Theme.HPOS.ActionBar"-->
<activity
android:name="com.example.hpos.presentation.MainActivity"
android:exported="true">

View File

@@ -2,10 +2,12 @@ package com.example.hpos.data
import androidx.lifecycle.MutableLiveData
import com.example.hpos.data.model.TestRightDeviceConstants
import com.example.hpos.data.model.TestType
object DataHolder {
// var usbConnected: Boolean = false
// val usbConnected = MutableLiveData(false)
var selectedTestType: TestType = TestType.SICKLECERT
val usbConnected = MutableLiveData(true)
var isStoragePermissionGranted = false
@@ -15,6 +17,7 @@ object DataHolder {
var sampleReadCounter = 0
var deviceConstant: TestRightDeviceConstants? = null
var deviceSerialNumber: String = "ABCD"
/* Contains wavelength -> pixel no.*/
val wavelengthToPixelArray = ArrayList<Double>()

View File

@@ -0,0 +1,27 @@
package com.example.hpos.data
import android.content.Context
import android.content.SharedPreferences
object PreferenceUtility {
private const val PREFS_NAME = "keys_prefs"
private const val KEY_COUNTER = "counter"
fun generateId(context: Context, prefix: String): String {
val prefs: SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val counter = prefs.getInt(KEY_COUNTER, 100)
prefs.edit().putInt(KEY_COUNTER, counter + 1).apply()
return prefix + counter
}
fun generateId(context: Context): String {
val prefs: SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val counter = prefs.getInt(KEY_COUNTER, 100)
prefs.edit().putInt(KEY_COUNTER, counter + 1).apply()
return counter.toString()
}
}

View File

@@ -9,7 +9,7 @@ object Constants {
const val TEST_RIGHT_TOTAL_PIXEL = 3694
const val MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE = 40
const val MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE = 9999
const val RANGE_IN_RESULT_CALCULATIONS = 10
@@ -21,4 +21,9 @@ object Constants {
const val DEVICE_PRODUCT_ID = 24597
const val DEVICE_VENDOR_ID = 1027
const val ERROR_NORMAL = 400
const val ERROR_CRITICAL = 401
const val NO_OF_TIMES_TO_RUN_SAMPLE = 1
}

View File

@@ -0,0 +1,6 @@
package com.example.hpos.data.model
data class ErrorMessage (
val message: String,
val code: Int
)

View File

@@ -4,7 +4,6 @@ data class TestInfo(
val value: String,
val number1: String,
val number2: String,
val device: DeviceType,
val result: String,
val resultConfirmatory: String,
val directoryPath: String,

View File

@@ -0,0 +1,6 @@
package com.example.hpos.data.model
enum class TestType {
SICKLECERT,
SICKLEFIND
}

View File

@@ -57,16 +57,24 @@ class ResultCalculationWithMaxImpl : TestRightResultCalculation {
val value = absorbanceAtWaveTwo / absorbanceAtWaveOne
testRightCalculationData.ratioValue = value
if (value < 0.24 || value == 0.0) {
if (value < 0.28 || value == 0.0) {
testRightCalculationData.ratioMinRange = 0.0
testRightCalculationData.ratioMaxRange = 0.24
testRightCalculationData.ratioMaxRange = 0.28
return TestRightResultType.NORMAL
} else if (value >= 0.24 && value < 0.30) {
testRightCalculationData.ratioMinRange = 0.24
testRightCalculationData.ratioMaxRange = 0.30
} else if (value >= 0.28 && value < 0.285) {
testRightCalculationData.ratioMinRange = 0.28
testRightCalculationData.ratioMaxRange = 0.285
return TestRightResultType.UNDEFINED
} else if (value >= 0.285 && value < 0.52) {
testRightCalculationData.ratioMinRange = 0.285
testRightCalculationData.ratioMaxRange = 0.52
return TestRightResultType.SICKLECELLTRAIT
} else if (value >= 0.30) {
testRightCalculationData.ratioMinRange = 0.30
} else if (value >= 0.52 && value < 0.525) {
testRightCalculationData.ratioMinRange = 0.52
testRightCalculationData.ratioMaxRange = 0.525
return TestRightResultType.UNDEFINED
}else if (value >= 0.525) {
testRightCalculationData.ratioMinRange = 0.525
testRightCalculationData.ratioMaxRange = 999.0
return TestRightResultType.SICKLECELLDISEASE
}

View File

@@ -1,6 +1,8 @@
package com.example.hpos.domain
import android.util.Log
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.PatientData
import com.example.hpos.data.model.TestRightCalculationData
import com.opencsv.CSVWriter
import java.io.File
@@ -9,30 +11,39 @@ import java.util.Collections.sort
class SaveRawData {
private val TAG = "saverawdata"
fun saveCsv(folderPath: String, fileName: String, matrix: ArrayList<ArrayList<Double>>) {
// try {
val fullPath = "$folderPath/$fileName"
val writer = CSVWriter(FileWriter(fullPath))
val fullPath = "$folderPath/$fileName"
val writer = CSVWriter(FileWriter(fullPath))
sort(matrix) { one: ArrayList<Double>, two: ArrayList<Double> ->
one[0].compareTo(two[0])
}
val content = ArrayList<Array<String>>()
content.add(arrayOf("NM", "CA"))
for (eachRow in matrix){
if (eachRow[0] >= Constants.MIN_WAVELENGTH_RANGE_TO_RECORD && eachRow[0] < Constants.MAX_WAVELENGTH_RANGE_TO_RECORD+1) {
// val rowContent = arrayOf(String.format("%.3f", eachRow[0]), String.format("%.3f", eachRow[1]))
val rowContent =
arrayOf(String.format("%.10f", eachRow[0]), String.format("%.10f", eachRow[1]))
content.add(rowContent)
sort(matrix) { one: ArrayList<Double>, two: ArrayList<Double> ->
one[0].compareTo(two[0])
}
}
writer.writeAll(content) // data is adding to csv
writer.close()
val content = ArrayList<Array<String>>()
content.add(arrayOf("NM", "CA"))
for (eachRow in matrix) {
if (eachRow[0] >= Constants.MIN_WAVELENGTH_RANGE_TO_RECORD && eachRow[0] < Constants.MAX_WAVELENGTH_RANGE_TO_RECORD + 1) {
// val rowContent = arrayOf(String.format("%.3f", eachRow[0]), String.format("%.3f", eachRow[1]))
val rowContent =
arrayOf(
String.format("%.10f", eachRow[0]),
String.format("%.10f", eachRow[1])
)
content.add(rowContent)
}
}
writer.writeAll(content) // data is adding to csv
writer.close()
// } catch (e: Exception) {
// Log.e(TAG, e.toString())
// }
}
fun saveLog(folderPath: String, fileName: String, calculationData: TestRightCalculationData) {
@@ -44,16 +55,100 @@ class SaveRawData {
writer.close()
}
fun getLogStringFromObj(calculationData: TestRightCalculationData) : String {
fun getLogStringFromObj(calculationData: TestRightCalculationData): String {
var outputString = "Test calculation logs ==>\n"
outputString += "Absorbance one = ${String.format("%.3f", calculationData.absorbanceOne)}, found at wavelength = ${String.format("%.3f", calculationData.wavelengthOfAbsorbanceOne)}\n"
outputString += "Absorbance two = ${String.format("%.3f", calculationData.absorbanceTwo)}, found at wavelength = ${String.format("%.3f", calculationData.wavelengthOfAbsorbanceTwo)}\n"
outputString += "Absorbance one = ${
String.format(
"%.3f",
calculationData.absorbanceOne
)
}, found at wavelength = ${
String.format(
"%.3f",
calculationData.wavelengthOfAbsorbanceOne
)
}\n"
outputString += "Absorbance two = ${
String.format(
"%.3f",
calculationData.absorbanceTwo
)
}, found at wavelength = ${
String.format(
"%.3f",
calculationData.wavelengthOfAbsorbanceTwo
)
}\n"
outputString += "Calculated Ratio = ${String.format("%.3f", calculationData.ratioValue)}\n"
outputString += "\tlies in range min value = ${String.format("%.3f", calculationData.ratioMinRange)} & range max value = ${String.format("%.3f", calculationData.ratioMaxRange)}\n"
outputString += "\tlies in range min value = ${
String.format(
"%.3f",
calculationData.ratioMinRange
)
} & range max value = ${String.format("%.3f", calculationData.ratioMaxRange)}\n"
outputString += "Results = ${calculationData.result}\n"
return outputString
}
fun saveLogWithPatientData(
folderPath: String,
fileName: String,
calculationData: TestRightCalculationData,
patientData: PatientData
) {
val fileObj = File(folderPath, fileName)
val writer = FileWriter(fileObj)
writer.append(getLogStringFromObjWithPatientData(calculationData, patientData))
writer.flush()
writer.close()
}
private fun getLogStringFromObjWithPatientData(
calculationData: TestRightCalculationData,
patientData: PatientData
): String {
var outputString = "Test calculation logs ==>\n"
outputString += "Name = ${patientData.name}\n"
outputString += "Age = ${patientData.age}\n"
outputString += "Gender = ${patientData.gender}\n"
outputString += "Absorbance one = ${
String.format(
"%.3f",
calculationData.absorbanceOne
)
}, found at wavelength = ${
String.format(
"%.3f",
calculationData.wavelengthOfAbsorbanceOne
)
}\n"
outputString += "Absorbance two = ${
String.format(
"%.3f",
calculationData.absorbanceTwo
)
}, found at wavelength = ${
String.format(
"%.3f",
calculationData.wavelengthOfAbsorbanceTwo
)
}\n"
outputString += "Calculated Ratio = ${String.format("%.3f", calculationData.ratioValue)}\n"
outputString += "\tlies in range min value = ${
String.format(
"%.3f",
calculationData.ratioMinRange
)
} & range max value = ${String.format("%.3f", calculationData.ratioMaxRange)}\n"
outputString += "Results = ${calculationData.result}\n"
Log.d(TAG, outputString)
return outputString
}
}

View File

@@ -13,21 +13,33 @@ class SaveRawDataTest {
fun saveCsv(folderPath: String, fileName: String, calculationData: ArrayList<CalculationVariableForTest>) {
val fullPath = "$folderPath/$fileName"
val writer = CSVWriter(FileWriter(fullPath))
val content = ArrayList<Array<String>>()
// try {
val fullPath = "$folderPath/$fileName"
val writer = CSVWriter(FileWriter(fullPath))
val content = ArrayList<Array<String>>()
// Header
var rowContent = arrayOf("pixel no", "wavelength", "invertedPixelNo", "I0", "I", "absorbance")
content.add(rowContent)
for (eachRow in calculationData){
rowContent = arrayOf(eachRow.pixelNo.toString(), eachRow.wavelength.toString(), eachRow.invertedPixelNo.toString(), eachRow.I0.toString(), eachRow.I.toString(), eachRow.absorbance.toString())
// Header
var rowContent =
arrayOf("pixel no", "wavelength", "invertedPixelNo", "I0", "I", "absorbance")
content.add(rowContent)
}
writer.writeAll(content) // data is adding to csv
writer.close()
for (eachRow in calculationData) {
rowContent = arrayOf(
eachRow.pixelNo.toString(),
eachRow.wavelength.toString(),
eachRow.invertedPixelNo.toString(),
eachRow.I0.toString(),
eachRow.I.toString(),
eachRow.absorbance.toString()
)
content.add(rowContent)
}
writer.writeAll(content) // data is adding to csv
writer.close()
// } catch (e: Exception){
// Log.e(TAG, e.toString())
// }
}
fun saveLog(folderPath: String, fileName: String, isReference: Boolean, fullString: String) {

View File

@@ -0,0 +1,77 @@
package com.example.hpos.domain
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.TestRightCalculationData
import com.example.hpos.data.model.TestRightResultType
class SickleFindResultCaluculationWithMaxImpl : TestRightResultCalculation{
val testRightCalculationData = TestRightCalculationData()
override fun getResults(wavelengthToAbsorbance: ArrayList<ArrayList<Double>>): TestRightCalculationData {
val startWavelengthOne =
Constants.WAVELENGTH_OF_INTEREST_ONE - Constants.RANGE_IN_RESULT_CALCULATIONS
val endWavelengthOne =
Constants.WAVELENGTH_OF_INTEREST_ONE + Constants.RANGE_IN_RESULT_CALCULATIONS + 1
var maxAbsorbanceAtOne = -999999.0
var wavelengthOfAbsorbanceOne = 0.0
val startWavelengthTwo =
Constants.WAVELENGTH_OF_INTEREST_TWO - Constants.RANGE_IN_RESULT_CALCULATIONS
val endWavelengthTwo =
Constants.WAVELENGTH_OF_INTEREST_TWO + Constants.RANGE_IN_RESULT_CALCULATIONS + 1
var maxAbsorbanceAtTwo = -999999.0
var wavelengthOfAbsorbanceTwo = 0.0
for (each in wavelengthToAbsorbance) {
if (each[0] >= startWavelengthOne && each[0] < endWavelengthOne) {
if (each[1] > maxAbsorbanceAtOne) {
maxAbsorbanceAtOne = each[1]
wavelengthOfAbsorbanceOne = each[0]
}
}
if (each[0] >= startWavelengthTwo && each[0] < endWavelengthTwo) {
// maxAbsorbanceAtTwo = max(maxAbsorbanceAtTwo, each[1])
if (each[1] > maxAbsorbanceAtTwo) {
maxAbsorbanceAtTwo = each[1]
wavelengthOfAbsorbanceTwo = each[0]
}
}
}
testRightCalculationData.absorbanceOne = maxAbsorbanceAtOne
testRightCalculationData.wavelengthOfAbsorbanceOne = wavelengthOfAbsorbanceOne
testRightCalculationData.absorbanceTwo = maxAbsorbanceAtTwo
testRightCalculationData.wavelengthOfAbsorbanceTwo = wavelengthOfAbsorbanceTwo
testRightCalculationData.result = calculateResultsAndRatio(maxAbsorbanceAtOne, maxAbsorbanceAtTwo)
return testRightCalculationData
}
private fun calculateResultsAndRatio(
absorbanceAtWaveOne: Double,
absorbanceAtWaveTwo: Double
): TestRightResultType {
if (absorbanceAtWaveOne != Double.MIN_VALUE && absorbanceAtWaveTwo != Double.MIN_VALUE && absorbanceAtWaveOne != 0.0) {
val value = absorbanceAtWaveTwo / absorbanceAtWaveOne
testRightCalculationData.ratioValue = value
if (value < 0.30 || value == 0.0) {
testRightCalculationData.ratioMinRange = 0.0
testRightCalculationData.ratioMaxRange = 0.30
return TestRightResultType.NORMAL
} else if (value >= 0.30 && value < 0.31) {
testRightCalculationData.ratioMinRange = 0.30
testRightCalculationData.ratioMaxRange = 0.31
return TestRightResultType.UNDEFINED
} else if (value >= 0.31) {
testRightCalculationData.ratioMinRange = 0.31
testRightCalculationData.ratioMaxRange = 999.0
return TestRightResultType.SICKLECELLDISEASE
}
}
return TestRightResultType.UNDEFINED
}
}

View File

@@ -21,6 +21,7 @@ import androidx.lifecycle.ViewModelProvider
import com.example.hpos.R
import com.example.hpos.data.DataHolder
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.TestType
import com.example.hpos.databinding.ActivityMainBinding
import com.example.hpos.presentation.testRight.TestRightActivity
import com.example.hpos.util.MyViewModelFactory
@@ -123,12 +124,15 @@ class MainActivity : AppCompatActivity()
private fun setupListeners() {
binding.cvItem1.setOnClickListener {
DataHolder.selectedTestType = TestType.SICKLECERT
val i = Intent(applicationContext, TestRightActivity::class.java)
startActivity(i)
}
binding.cvItem2.setOnClickListener {
Toast.makeText(this, "To be Implemented", Toast.LENGTH_SHORT).show()
DataHolder.selectedTestType = TestType.SICKLEFIND
val i = Intent(applicationContext, TestRightActivity::class.java)
startActivity(i)
}
DataHolder.usbConnected.observe(this){

View File

@@ -119,7 +119,7 @@ class TestRightActivity : AppCompatActivity() {
onBackPressed()
return
}
DataHolder.deviceSerialNumber = mDriver.device.serialNumber.toString()
mConnection = manager.openDevice(mDriver.device)
if (mConnection == null) {

View File

@@ -15,6 +15,7 @@ import com.example.hpos.R
import com.example.hpos.data.DataHolder
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.constant.TestRightCommands
import com.example.hpos.data.model.ErrorMessage
import com.example.hpos.databinding.FragmentTestRightExpReferenceBinding
import com.example.hpos.presentation.UsbServiceListener
import com.example.hpos.presentation.utils.MyDialogListener
@@ -75,8 +76,11 @@ class TestRightExpReference : Fragment() {
}
viewModel.errorTriggered.observe(viewLifecycleOwner) {
if (!it.isNullOrEmpty()){
UIUtils.onShowErrorToast(requireContext(), it)
if (it != null){
UIUtils.onShowErrorToast(requireContext(), it.message)
if (it.code == Constants.ERROR_CRITICAL){
activity?.onBackPressed()
}
}
}
@@ -122,6 +126,7 @@ class TestRightExpReference : Fragment() {
val stringData = String(it)
fullReadOutput.append(stringData)
Log.d(TAG, "fullReadOutput = $fullReadOutput")
if (stringData.contains("OK", true)) {
Log.d(
TAG,
@@ -133,14 +138,16 @@ class TestRightExpReference : Fragment() {
Log.d(TAG, "results = FINE")
viewModel.progressBar.postValue(false)
viewModel.errorTriggered.postValue("Please Try Again this step")
viewModel.errorTriggered.postValue(ErrorMessage("Please Try Again!!", Constants.ERROR_CRITICAL))
}
}
}
override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in sendCmdToFetchDeviceConstant() -> $e")
viewModel.errorTriggered.postValue("Please Try Again this step")
viewModel.errorTriggered.postValue(ErrorMessage("Please Try Again this step", Constants.ERROR_NORMAL))
viewModel.progressBar.postValue(false)
}
})
@@ -257,12 +264,15 @@ class TestRightExpReference : Fragment() {
fullReadOutput.append(stringData)
// Log.d(TAG, stringData)
if (stringData.contains("OK", true)) {
// if (stringData.contains("OK", true)) {
// if (fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK", true)) {
if (stringData.trim().isNotEmpty() && fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK [0]", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToFetchLightIntensities()")
// Log.d(TAG, fullReadOutput.toString())
viewModel.mapIntensityValues(fullReadOutput.toString(), true)
viewModel.saveLogTest(requireContext().applicationContext, true, fullReadOutput.toString())
// viewModel.saveLogTest(requireContext().applicationContext, true, fullReadOutput.toString())
DataHolder.isReferenceTaken = true
@@ -278,7 +288,8 @@ class TestRightExpReference : Fragment() {
override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in sendCmdToFetchLightIntensities() -> $e")
viewModel.errorTriggered.postValue("Please Try Again this step")
viewModel.errorTriggered.postValue(ErrorMessage("Please Try Again this step", Constants.ERROR_NORMAL))
viewModel.progressBar.postValue(false)
}
})

View File

@@ -10,10 +10,14 @@ import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.hpos.R
import com.example.hpos.data.DataHolder
import com.example.hpos.data.PreferenceUtility
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.constant.TestRightCommands
import com.example.hpos.data.model.ErrorMessage
import com.example.hpos.data.model.PatientData
import com.example.hpos.data.model.TestRightResultType
import com.example.hpos.data.model.TestType
import com.example.hpos.databinding.FragmentTestRightExpSampleBinding
import com.example.hpos.presentation.UsbServiceListener
import com.example.hpos.presentation.utils.MyDialogListener
@@ -61,8 +65,11 @@ class TestRightExpSample : Fragment() {
}
viewModel.errorTriggered.observe(viewLifecycleOwner) {
if (!it.isNullOrEmpty()){
UIUtils.onShowErrorToast(requireContext(), it)
if (it != null){
UIUtils.onShowErrorToast(requireContext(), it.message)
if (it.code == Constants.ERROR_CRITICAL){
activity?.onBackPressed()
}
}
}
@@ -133,9 +140,11 @@ class TestRightExpSample : Fragment() {
data?.let {
val stringData = String(it)
fullReadOutput.append(stringData)
if (stringData.contains("OK", true)) {
// viewModel.progressBar.postValue(false)
Log.d(TAG, stringData)
// if (stringData.contains("OK", true)) {
// if (stringData.contains("OK", true) || fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK", true)) {
// if (fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK", true)) {
if (fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK [0]", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToRun()")
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
@@ -151,6 +160,8 @@ class TestRightExpSample : Fragment() {
override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in sendCmdToRun() -> $e")
viewModel.errorTriggered.postValue(ErrorMessage("Please Try Again this step", Constants.ERROR_NORMAL))
viewModel.progressBar.postValue(false)
}
})
@@ -166,28 +177,70 @@ class TestRightExpSample : Fragment() {
data?.let {
val stringData = String(it)
fullReadOutput.append(stringData)
// Log.d(TAG, stringData)
if (stringData.contains("OK", true)) {
Log.d(TAG, stringData)
// if (stringData.contains("OK", true)) {
// if (stringData.contains("OK", true) || stringData.contains("O", true) || stringData.contains("K", true)) {
// if (stringData.contains("OK", true) || fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK", true)) {
// if (fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK", true)) {
if (stringData.trim().isNotEmpty() && fullReadOutput.substring(Math.max(fullReadOutput.length - 15, 0)).contains("OK [0]", true)) {
Log.d(TAG, "onUsbRead() called in sendCmdToFetchLightIntensities()")
viewModel.mapIntensityValues(fullReadOutput.toString(), false)
viewModel.saveLogTest(requireContext().applicationContext, false, fullReadOutput.toString())
// viewModel.saveLogTest(requireContext().applicationContext, false, fullReadOutput.toString())
// showResultsAfterAcquiring()
Handler(Looper.getMainLooper()).postDelayed(
{
checkIfToRunAgain()
},
Constants.DELAY_BETWEEN_COMMANDS
)
showResultsAfterAcquiring()
}
}
}
override fun onUsbError(e: Exception?) {
Log.e(TAG, "onUsbIoError() called in sendCmdToFetchLightIntensities() -> $e")
viewModel.errorTriggered.postValue(ErrorMessage("Please Try Again this step", Constants.ERROR_NORMAL))
viewModel.progressBar.postValue(false)
}
})
}
private fun showResultsAfterAcquiring() {
private fun checkIfToRunAgain() {
viewModel.numberOfSampleRun++
viewModel.mapWavelengthToAbsorbance()
viewModel.calculateResults()
// Todo: Save CSV + Test CSV
if (DataHolder.selectedTestType == TestType.SICKLECERT) {
viewModel.calculateResults()
} else {
viewModel.calculateResultsForSickleFind()
}
// Todo: Save Log
saveDataLocally()
if (viewModel.numberOfSampleRun < Constants.NO_OF_TIMES_TO_RUN_SAMPLE) {
Handler(Looper.getMainLooper()).postDelayed(
{
startAcquiring()
},
Constants.DELAY_BETWEEN_COMMANDS
)
} else {
viewModel.numberOfSampleRun = 0
showResultsAfterAcquiring()
}
}
private fun showResultsAfterAcquiring() {
// viewModel.mapWavelengthToAbsorbance()
// viewModel.calculateResults()
viewModel.progressBar.postValue(false)
// binding.progressBar.visibility = View.GONE
@@ -195,9 +248,40 @@ class TestRightExpSample : Fragment() {
.commit()
}
// fun View.setAllEnabled(enabled: Boolean) {
// isEnabled = enabled
// if (this is ViewGroup) children.forEach { child -> child.setAllEnabled(enabled) }
// }
private fun saveDataLocally() {
val patientName = viewModel.patientDetails.name
// if (patientName.length > 5){
// patientName = patientName.substring(0, 5)
// }
val id = PreferenceUtility.generateId(requireContext())
val prefixCsv: String = if (DataHolder.selectedTestType == TestType.SICKLECERT)
"HPOSSC_${DataHolder.deviceSerialNumber}_${patientName}_"
else
"HPOSSF_${DataHolder.deviceSerialNumber}_${patientName}_"
// val prefixCsv = "HPOSSC_${DataHolder.deviceSerialNumber}_${patientName}_"
val fileExtensionCsv = ".csv"
val fileNameCsv = prefixCsv + id + fileExtensionCsv
saveCsv(fileNameCsv)
val prefixTxt = "log_${DataHolder.deviceSerialNumber}_${patientName}_"
val fileExtensionTxt = ".txt"
val fileNameTxt = prefixTxt + id + fileExtensionTxt
saveLog(fileNameTxt)
}
private fun saveCsv(fileName: String) {
Log.d(TAG, "saveCsv() called")
viewModel.saveCsv(requireContext().applicationContext, fileName)
viewModel.saveCsvForTesting(requireContext().applicationContext, "detailed_$fileName")
}
private fun saveLog(fileName: String) {
Log.d(TAG, "saveLog() called")
viewModel.saveLogWithPatient(requireContext().applicationContext, fileName)
}
}

View File

@@ -6,12 +6,15 @@ import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.hpos.R
import com.example.hpos.data.DataHolder
import com.example.hpos.data.PreferenceUtility
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.TestRightResultType
import com.example.hpos.data.model.TestType
import com.example.hpos.databinding.FragmentTestRightResultsBinding
import com.example.hpos.presentation.MainActivity
import com.example.hpos.util.MyUtils
@@ -38,8 +41,8 @@ class TestRightResults : Fragment() {
super.onViewCreated(view, savedInstanceState)
setupListeners()
updateResults()
saveCsv()
saveLog()
// saveCsv()
// saveLog()
}
private fun setupListeners() {
@@ -48,16 +51,20 @@ class TestRightResults : Fragment() {
startActivity(i)
}
binding.ivNext.setOnClickListener {
if (DataHolder.sampleReadCounter > Constants.MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE) {
DataHolder.sampleReadCounter = 0
DataHolder.isReferenceTaken = false
parentFragmentManager.beginTransaction()
.replace(R.id.fl_main, TestRightExpReference())
.commit()
} else {
parentFragmentManager.beginTransaction().replace(R.id.fl_main, TestRightExpSample())
.commit()
}
moveToSamplePage()
}
}
fun moveToSamplePage() {
if (DataHolder.sampleReadCounter > Constants.MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE) {
DataHolder.sampleReadCounter = 0
DataHolder.isReferenceTaken = false
parentFragmentManager.beginTransaction()
.replace(R.id.fl_main, TestRightExpReference())
.commit()
} else {
parentFragmentManager.beginTransaction().replace(R.id.fl_main, TestRightExpSample())
.commit()
}
}
@@ -107,8 +114,14 @@ class TestRightResults : Fragment() {
private fun saveCsv() {
Log.d(TAG, "saveCsv() called")
val sdfDate = SimpleDateFormat("ddMMyyyy HHmmss")
val fileName: String = sdfDate.format(Date()) + ".csv"
// val sdfDate = SimpleDateFormat("ddMMyyyy HHmmss")
// val fileName: String = sdfDate.format(Date()) + ".csv"
val prefix = "HPOSSC_${DataHolder.deviceSerialNumber}_"
val fileExtension = ".csv"
val fileName = PreferenceUtility.generateId(requireContext(), prefix) + fileExtension
viewModel.saveCsv(requireContext().applicationContext, fileName)
viewModel.saveCsvForTesting(requireContext().applicationContext, "testing$fileName")
@@ -121,22 +134,59 @@ class TestRightResults : Fragment() {
binding.tvGender.text =
getString(R.string.gender_in_textview, viewModel.patientDetails.gender)
// binding.tvResultValue.text = viewModel.patientDetails.results.toString()
when (viewModel.patientDetails.results) {
TestRightResultType.NORMAL -> {
binding.resultNormal.visibility = View.VISIBLE
if (DataHolder.selectedTestType == TestType.SICKLECERT){
when (viewModel.patientDetails.results) {
TestRightResultType.NORMAL -> {
binding.resultNormal.visibility = View.VISIBLE
}
TestRightResultType.SICKLECELLDISEASE -> {
binding.resultDisease.visibility = View.VISIBLE
}
TestRightResultType.SICKLECELLTRAIT -> {
binding.resultTrait.visibility = View.VISIBLE
}
else -> {
// binding.resultUndefined.visibility = View.VISIBLE
Toast.makeText(requireContext().applicationContext, "Please Test Again", Toast.LENGTH_LONG).show()
moveToSamplePage()
// val i = Intent(requireContext().applicationContext, MainActivity::class.java)
// startActivity(i)
}
}
TestRightResultType.SICKLECELLDISEASE -> {
binding.resultDisease.visibility = View.VISIBLE
}
TestRightResultType.SICKLECELLTRAIT -> {
binding.resultTrait.visibility = View.VISIBLE
}
else -> {
binding.resultUndefined.visibility = View.VISIBLE
} else {
when (viewModel.patientDetails.results) {
TestRightResultType.SICKLECELLDISEASE -> {
binding.resultDisease.visibility = View.VISIBLE
binding.resultDisease.text = "Positive"
}
TestRightResultType.NORMAL -> {
binding.resultNormal.visibility = View.VISIBLE
binding.resultNormal.text = "Negative"
}
else -> {
Toast.makeText(requireContext().applicationContext, "Please Test Again", Toast.LENGTH_LONG).show()
moveToSamplePage()
// val i = Intent(requireContext().applicationContext, MainActivity::class.java)
// startActivity(i)
}
}
}
// when (viewModel.patientDetails.results) {
// TestRightResultType.NORMAL -> {
// binding.resultNormal.visibility = View.VISIBLE
// }
// TestRightResultType.SICKLECELLDISEASE -> {
// binding.resultDisease.visibility = View.VISIBLE
// }
// TestRightResultType.SICKLECELLTRAIT -> {
// binding.resultTrait.visibility = View.VISIBLE
// }
// else -> {
// binding.resultUndefined.visibility = View.VISIBLE
// }
// }
// Log.d(TAG, "\n\n\n\nFor intensity Reference array size = ${DataHolder.intensityReferenceArray.size}")
// for (each in DataHolder.intensityReferenceArray){
// Log.d(TAG, "${each}")

View File

@@ -6,14 +6,8 @@ import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.hpos.data.DataHolder
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.CalculationVariableForTest
import com.example.hpos.data.model.PatientData
import com.example.hpos.data.model.TestRightCalculationData
import com.example.hpos.data.model.TestRightDeviceConstants
import com.example.hpos.domain.ResultCalculationWithMaxImpl
import com.example.hpos.domain.SaveRawData
import com.example.hpos.domain.SaveRawDataTest
import com.example.hpos.domain.TestRightResultCalculation
import com.example.hpos.data.model.*
import com.example.hpos.domain.*
import com.example.hpos.util.MyUtils
import java.text.SimpleDateFormat
import java.util.*
@@ -28,7 +22,10 @@ class TestRightViewModel : ViewModel() {
var isServiceConnected = false
val progressBar = MutableLiveData(false)
val errorTriggered = MutableLiveData<String>("")
// val errorTriggered = MutableLiveData<String>("")
val errorTriggered = MutableLiveData<ErrorMessage>()
var numberOfSampleRun = 0
lateinit var patientDetails: PatientData
@@ -43,8 +40,8 @@ class TestRightViewModel : ViewModel() {
val calculationVariableList = ArrayList<CalculationVariableForTest>()
fun mapDeviceConstants(string: String) {
Log.d(TAG, "mapDeviceConstants() called")
// viewModelScope.launch {
// Log.d(TAG, "mapDeviceConstants() called")
// Log.d(TAG, "mapDeviceConstants() value -> $string")
if (string.isNotEmpty()) {
val listOfStrings = string.split(",")
if (listOfStrings.size >= 4) {
@@ -59,12 +56,22 @@ class TestRightViewModel : ViewModel() {
} else {
// Todo: Throws error
// "Error 201: In processing the data from device"
errorTriggered.postValue("Error 201: In processing the data from device")
errorTriggered.postValue(
ErrorMessage(
"Error 201: In processing the data from device",
Constants.ERROR_NORMAL
)
)
}
} else {
// Todo: Throws error (showing error if empty by using a mutable error string)
// "Error 202: Unable to fetch data from device."
errorTriggered.postValue("Error 202: Unable to fetch data from device.")
errorTriggered.postValue(
ErrorMessage(
"Error 202: Unable to fetch data from device.",
Constants.ERROR_NORMAL
)
)
}
// }
}
@@ -88,7 +95,13 @@ class TestRightViewModel : ViewModel() {
} else {
// Todo: Throws error
// "Error 203: Unable to fetch data from device."
errorTriggered.postValue("Error 203: Unable to fetch data from device.")
errorTriggered.postValue(
ErrorMessage(
"Error 203: Unable to fetch data from device.",
Constants.ERROR_NORMAL
)
)
}
// }
}
@@ -98,7 +111,7 @@ class TestRightViewModel : ViewModel() {
if (isReference) DataHolder.intensityReferenceArray.clear()
else intensitySampleArray.clear()
Log.d(TAG, fullString)
Log.d("SURYAKUMAR", fullString)
val listOfString = fullString.split("\n")
for (line in listOfString) {
@@ -114,7 +127,13 @@ class TestRightViewModel : ViewModel() {
intensitySampleArray.add(numbers[1].toDouble())
} else {
// "Error 204: Unable to fetch data from device."
errorTriggered.postValue("Error 204: Unable to fetch data from device.")
errorTriggered.postValue(
ErrorMessage(
"Error 204: Unable to fetch data from device.",
Constants.ERROR_NORMAL
)
)
}
}
}
@@ -152,7 +171,13 @@ class TestRightViewModel : ViewModel() {
fun mapWavelengthToAbsorbance() {
if (DataHolder.intensityReferenceArray.size != intensitySampleArray.size || DataHolder.wavelengthToPixelArray.size != intensitySampleArray.size || DataHolder.wavelengthToPixelArray.size != DataHolder.intensityReferenceArray.size) {
errorTriggered.postValue("Error 205: Unable to fetch data from device, please try again by reopening the app")
errorTriggered.postValue(
ErrorMessage(
"Error 205: Unable to fetch data from device, please try again by reopening the app",
Constants.ERROR_CRITICAL
)
)
throw Exception("Inconsistency in the data, size of arrays are not same. \nintensityReferenceArray.size = ${DataHolder.intensityReferenceArray.size} ; intensitySampleArray.size = ${intensitySampleArray.size} ; wavelengthToPixelArray.size = ${DataHolder.wavelengthToPixelArray.size}")
}
@@ -196,7 +221,8 @@ class TestRightViewModel : ViewModel() {
// Todo: Remove
val calculationVariableForTest = CalculationVariableForTest()
calculationVariableForTest.pixelNo = index + 1
calculationVariableForTest.invertedPixelNo = invertedPixelIndex+1 // 0-based indexing
calculationVariableForTest.invertedPixelNo =
invertedPixelIndex + 1 // 0-based indexing
calculationVariableForTest.wavelength = wavelength
calculationVariableForTest.I0 = i0
calculationVariableForTest.I = i1
@@ -218,53 +244,125 @@ class TestRightViewModel : ViewModel() {
}
fun calculateResultsForSickleFind() {
DataHolder.sampleReadCounter++
val resultCalculation: TestRightResultCalculation =
SickleFindResultCaluculationWithMaxImpl()
calculationData = resultCalculation.getResults(wavelengthToAbsorbance)
patientDetails.results = calculationData.result
}
fun saveCsv(appContext: Context, filename: String) {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawData().saveCsv(folderPath!!, filename, wavelengthToAbsorbance)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null){
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawData().saveCsv(folderPath, filename, wavelengthToAbsorbance)
// try {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawData().saveCsv(folderPath!!, filename, wavelengthToAbsorbance)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null) {
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawData().saveCsv(folderPath, filename, wavelengthToAbsorbance)
} else {
// errorTriggered.postValue("Unable to save CSV, Please try again")
}
}
}
// } catch (e: java.io.FileNotFoundException) {
// errorTriggered.postValue(
// ErrorMessage(
// "File name isn't valid",
// Constants.ERROR_CRITICAL
// )
// )
// }
}
fun saveCsvForTesting(appContext: Context, filename: String) {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawDataTest().saveCsv(folderPath!!, filename, calculationVariableList)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null){
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawDataTest().saveCsv(folderPath, filename, calculationVariableList)
// try {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawDataTest().saveCsv(folderPath!!, filename, calculationVariableList)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null) {
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawDataTest().saveCsv(folderPath, filename, calculationVariableList)
} else {
// errorTriggered.postValue("Unable to save CSV, Please try again")
}
}
}
// } catch (e: java.io.FileNotFoundException) {
// errorTriggered.postValue(
// ErrorMessage(
// "File name isn't valid",
// Constants.ERROR_CRITICAL
// )
// )
// }
}
fun saveLog(appContext: Context, fileName: String) {
var folderPath: String? = DataHolder.appFolderPath
// try {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawData().saveLog(folderPath!!, fileName, calculationData)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null){
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawData().saveLog(folderPath, fileName, calculationData)
if (DataHolder.isAppFolderCreated) {
SaveRawData().saveLog(folderPath!!, fileName, calculationData)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null) {
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawData().saveLog(folderPath, fileName, calculationData)
} else {
// errorTriggered.postValue("Unable to save Log, Please try again")
}
}
}
// } catch (e: java.io.FileNotFoundException) {
// errorTriggered.postValue(
// ErrorMessage(
// "File name isn't valid",
// Constants.ERROR_CRITICAL
// )
// )
// }
}
fun saveLogWithPatient(appContext: Context, fileName: String) {
// try {
var folderPath: String? = DataHolder.appFolderPath
if (DataHolder.isAppFolderCreated) {
SaveRawData().saveLogWithPatientData(
folderPath!!,
fileName,
calculationData,
patientDetails
)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null) {
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawData().saveLogWithPatientData(
folderPath,
fileName,
calculationData,
patientDetails
)
} else {
// errorTriggered.postValue("Unable to save Log, Please try again")
}
}
// } catch (e: java.io.FileNotFoundException) {
// errorTriggered.postValue(
// ErrorMessage(
// "File name isn't valid",
// Constants.ERROR_CRITICAL
// )
// )
// }
}
fun saveLogTest(appContext: Context, isReference: Boolean, fullString: String) {
@@ -281,7 +379,7 @@ class TestRightViewModel : ViewModel() {
SaveRawDataTest().saveLog(folderPath!!, fileName, isReference, fullString)
} else {
folderPath = MyUtils.createAppFolder(appContext)
if (folderPath != null){
if (folderPath != null) {
DataHolder.isAppFolderCreated = true
DataHolder.appFolderPath = folderPath
SaveRawDataTest().saveLog(folderPath, fileName, isReference, fullString)

View File

@@ -10,30 +10,30 @@
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextColor="#FFFFFF"
android:elevation="4dp"
app:menu="@menu/my_menu"
android:theme="@style/ToolbarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextColor="#FFFFFF"
android:elevation="4dp"
app:menu="@menu/my_menu"
android:theme="@style/ToolbarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<FrameLayout
android:id="@+id/fl_main"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/my_toolbar"
app:layout_constraintBottom_toBottomOf="parent"
tools:context=".presentation.testRight.TestRightActivity">
<FrameLayout
android:id="@+id/fl_main"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/my_toolbar"
app:layout_constraintBottom_toBottomOf="parent"
tools:context=".presentation.testRight.TestRightActivity">
</FrameLayout>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,96 @@
package com.example.hpos
import org.junit.Test
class CubicEquationSolver {
@Test
fun test() {
val a: Double = 12.toDouble()
val b: Double = (15).toDouble()
val c: Double = (9).toDouble()
val d: Double = (-2456).toDouble()
solve(a, b, c, d)
}
fun solve(a: Double, b: Double, c: Double, d: Double) {
val f: Double = getF(a, b, c)
val g: Double = getG(a, b, c, d)
val h: Double = getH(f, g)
println("f = $f & g = $g & h = $h")
if (f == 0.0 && g == 0.0 && h == 0.0)
solveOneRoot(a, d)
else if (h <= 0)
solveRealRoots(a, b, g, h)
else
solveNotRealRoots(a, b, g, h)
}
private fun getF(a: Double, b: Double, c: Double): Double {
return (3 * c / a - b * b / (a * a)) / 3
}
private fun getG(a: Double, b: Double, c: Double, d: Double): Double {
var g: Double = 2 * b * b * b / (a * a * a)
g += -9 * b * c / (a * a)
g += 27 * d / a
g /= 27.0
return g
}
private fun getH(f: Double, g: Double): Double {
return g * g / 4 + f * f * f / 27
}
private fun solveOneRoot(a: Double, d: Double) {
val x: Double = -Math.pow(d / a, 1.0 / 3)
println("The solution is: $x")
println("rounded off solutions are:")
println(String.format("%.3g%n", x))
}
private fun solveRealRoots(a: Double, b: Double, g: Double, h: Double) {
val i: Double = Math.sqrt(g * g / 4 - h)
val j: Double = Math.pow(i, 1.0 / 3)
val k: Double = Math.acos(-g / (2 * i))
val l: Double = -j
val m: Double = Math.cos(k / 3)
val n: Double = Math.sqrt(3.0) * Math.sin(k / 3)
val p: Double = -b / (3 * a)
val x1: Double = 2 * j * Math.cos(k / 3) - b / (3 * a)
val x2: Double = l * (m + n) + p
val x3: Double = l * (m - n) + p
println("The solutions are:")
println(x1)
println(x2)
println(x3)
println("rounded off solutions are:")
println(String.format("%.3g", x1))
println(String.format("%.3g", x2))
println(String.format("%.3g", x3))
}
private fun solveNotRealRoots(a: Double, b: Double, g: Double, h: Double) {
val r: Double = -(g / 2) + Math.sqrt(h)
val s: Double = if (r >= 0) Math.pow(r, 1.0 / 3) else -Math.pow(-r, 1.0 / 3)
val t: Double = -(g / 2) - Math.sqrt(h)
val u: Double = if (t >= 0) Math.pow(t, 1.0 / 3) else -Math.pow(-t, 1.0 / 3)
val x1: Double = s + u - b / (3 * a)
val x2: Double = -((s + u) / 2) - b / (3 * a)
val immaginary: Double = (s - u) * Math.sqrt(3.0) / 2
println("The solutions are:")
println(x1)
println(x2.toString() + " + " + immaginary + "i")
println(x2.toString() + " - " + immaginary + "i")
}
}

View File

@@ -1,7 +1,7 @@
package com.example.hpos
class InputData {
val inputRead = "0,1.69989422e-06,1.60642711e-01, 3.85754470e+02,0,0,1,0, FFF-EEEE-PPP-WW-YY-NNNN\nОК [01]"
val inputRead = "0,1.69989422e-06,1.60642711e-01,3.85754470e+02,0,0,1,0,FFF-EEEE-PPPP-WW-YY-NNNN\nOK [0]"
val printForReference: String = """
Buf 1 : 31

View File

@@ -0,0 +1,15 @@
package com.example.hpos
import org.junit.Test
import java.util.*
import java.util.concurrent.atomic.AtomicLong
class OtherTests {
@Test
fun uniqueId() {
val date = Date()
date.day
}
}

View File

@@ -0,0 +1,60 @@
package com.example.hpos
import org.junit.Test
import java.io.File
import java.io.InputStream
import java.util.*
import kotlin.collections.ArrayList
class TestDataGenerator {
fun getOutputMapPixelNumberToWavelength() : ArrayList<Double> {
val path = "/Users/vsuryakumar/SMInnovations/AndroidProjects/refactoredapp/app/src/test/java/com/example/hpos"
val fileName = "mapPixelNumberToWavelength_output.txt"
val file = File("$path/$fileName")
val text = file.readText()
val pixelList = ArrayList<Double>()
for (each in text.split('\n')){
pixelList.add(each.toDouble())
}
return pixelList
}
fun getOutputMapWavelengthToAbsorbance(): ArrayList<Double> {
val path = "/Users/vsuryakumar/SMInnovations/AndroidProjects/refactoredapp/app/src/test/java/com/example/hpos"
val fileName = "getOutputMapWavelengthToAbsorbance_output.txt"
val file = File("$path/$fileName")
val text = file.readText()
val pixelList = ArrayList<Double>()
for (each in text.split('\n')){
pixelList.add(each.toDouble())
}
return pixelList
}
fun getInputReferenceMapIntensityValues(): String {
val path = "/Users/vsuryakumar/SMInnovations/AndroidProjects/refactoredapp/app/src/test/java/com/example/hpos"
val fileName = "getInputReferenceMapIntensityValues_input.txt"
val file = File("$path/$fileName")
return file.readText()
}
fun getInputSampleMapIntensityValues(): String {
val path = "/Users/vsuryakumar/SMInnovations/AndroidProjects/refactoredapp/app/src/test/java/com/example/hpos"
val fileName = "getInputSampleMapIntensityValues_input.txt"
val file = File("$path/$fileName")
return file.readText()
}
// fun getOutputReferenceMapIntensityValues(): ArrayList<Double> {
//
// }
//
// fun getOutputSampleMapIntensityValues(): ArrayList<Double> {
//
// }
}

View File

@@ -1,19 +1,21 @@
package com.example.hpos
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.DataHolder
import com.example.hpos.data.constant.Constants
import com.example.hpos.data.model.PatientData
import com.example.hpos.data.model.TestRightResultType
import com.example.hpos.presentation.testRight.TestRightViewModel
import junit.framework.Assert.assertEquals
import org.junit.Test
import java.math.RoundingMode
import java.text.DecimalFormat
class TestRightViewModelTest {
private val viewModel = TestRightViewModel()
private val data = InputData()
@Test
fun testRightViewModel_mapDeviceConstants() {
fun test_mapDeviceConstants() {
viewModel.mapDeviceConstants(data.inputRead)
assertEquals("0", DataHolder.deviceConstant!!.a)
assertEquals("1.69989422e-06", DataHolder.deviceConstant!!.b)
@@ -22,31 +24,60 @@ class TestRightViewModelTest {
}
@Test
fun testRightViewModel_mapPixelNumberToWavelength() {
fun test_mapPixelNumberToWavelength() {
viewModel.mapDeviceConstants(data.inputRead)
viewModel.mapPixelNumberToWavelength()
var i = 1
for (each in DataHolder.wavelengthToPixelArray){
System.out.print(i)
System.out.print(" -> ")
System.out.println(each)
i++
}
val outputList = TestDataGenerator().getOutputMapPixelNumberToWavelength()
assertEquals(Constants.TEST_RIGHT_TOTAL_PIXEL, DataHolder.wavelengthToPixelArray.size)
assertEquals(Constants.TEST_RIGHT_TOTAL_PIXEL, outputList.size)
val df = DecimalFormat("#.###")
df.roundingMode = RoundingMode.FLOOR
for (i in 0 until Constants.TEST_RIGHT_TOTAL_PIXEL){
assertEquals(df.format(outputList[i]), df.format(DataHolder.wavelengthToPixelArray[i]))
}
}
// @Test
// fun test_mapIntensityValues() {
// val inputReference = TestDataGenerator().getInputReferenceMapIntensityValues()
// val inputSample = TestDataGenerator().getInputSampleMapIntensityValues()
//
// viewModel.mapIntensityValues(inputReference, true)
// viewModel.mapIntensityValues(inputSample, false)
//
// val outputReference = TestDataGenerator().getOutputReferenceMapIntensityValues()
// val outputSample = TestDataGenerator().getOutputSampleMapIntensityValues()
//
// assertEquals(outputReference, DataHolder.intensityReferenceArray)
// assertEquals(outputSample, viewModel.intensitySampleArray)
// }
@Test
fun testRightViewModel_calculateResults() {
fun test_mapWavelengthToAbsorbance() {
viewModel.mapDeviceConstants(data.inputRead)
viewModel.mapPixelNumberToWavelength()
viewModel.mapIntensityValues(data.printForReference, true)
viewModel.mapIntensityValues(data.printForSample, false)
viewModel.mapIntensityValues(TestDataGenerator().getInputReferenceMapIntensityValues(), true)
viewModel.mapIntensityValues(TestDataGenerator().getInputSampleMapIntensityValues(), false)
viewModel.patientDetails = PatientData("Surya", 2, "Male", TestRightResultType.UNDEFINED)
viewModel.calculateResults()
viewModel.mapWavelengthToAbsorbance()
val wavelengthList = TestDataGenerator().getOutputMapPixelNumberToWavelength()
val absorbanceList = TestDataGenerator().getOutputMapWavelengthToAbsorbance()
val df = DecimalFormat("#.###")
df.roundingMode = RoundingMode.FLOOR
assertEquals(Constants.TEST_RIGHT_TOTAL_PIXEL, viewModel.wavelengthToAbsorbance.size)
for (i in 0 until Constants.TEST_RIGHT_TOTAL_PIXEL){
assertEquals(df.format(wavelengthList[i]), df.format(viewModel.wavelengthToAbsorbance[i][0]))
assertEquals(df.format(absorbanceList[i]), df.format(viewModel.wavelengthToAbsorbance[i][1]))
}
}
@@ -67,7 +98,4 @@ class TestRightViewModelTest {
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff