diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1d17348..a518393 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -37,6 +37,11 @@ android:supportsRtl="true" android:theme="@style/Theme.HPOSTesting" tools:targetApi="31"> + + + + android:exported="false" + android:screenOrientation="portrait" /> + android:exported="false" + android:screenOrientation="portrait" /> + android:exported="false" + android:theme="@style/Theme.HPOS.NoActionBar" /> @@ -123,7 +129,6 @@ android:screenOrientation="portrait" android:theme="@style/Theme.HPOS.NoActionBar" tools:ignore="AppLinkUrlError,MissingClass"> - @@ -147,9 +152,10 @@ android:theme="@style/AppTheme.NoActionBar"> + - + diff --git a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt index eaea8c0..9447ff0 100644 --- a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt +++ b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt @@ -14,6 +14,13 @@ package com.example.hpostesting.data.constant object Constants { + const val CENTER_NAME ="" + const val DISTRICT ="" + const val FLAGS_ENABLED = false//testing flag disable then pass buffer and sample checks + const val ABS_FLAGS_ENABLED = false + const val IP_ADDRESS="ip_address" + const val QUICK_CAPTURE="quick_capture" + const val KIT_TIME = "kit_time" const val ACTION_USB_PERMISSION = "shanmukha.in.sickle_cell.USB_PERMISSION" const val HEMOCUBE_USB_PERMISSION = "shanmukha.in.sickle_cell_homocube.USB_PERMISSION" const val passphrase = "smi_#@sql" @@ -79,6 +86,16 @@ object Constants { // jig const val NAVIGATE_TO_TEST_JIG_DIRECTLY = false + //update values of abs + const val ABS2LED1MMLL = "ABS2LED1MMLL" + const val ABS2LED1MMUL = "ABS2LED1MMUL" + const val ABS2LED2MMLL = "ABS2LED2MMLL" + const val ABS2LED2MMUL = "ABS2LED2MMUL" + + const val ABS10LED1MMLL = "ABS10LED1MMLL" + const val ABS10LED1MMUL = "ABS10LED1MMUL" + const val ABS10LED2MMLL = "ABS10LED2MMLL" + const val ABS10LED2MMUL = "ABS10LED2MMUL" const val KIT_NUMBER = "KitNumber" const val KIT_COUNT = "KitCount" @@ -1066,8 +1083,9 @@ object Constants { ), ) - const val INCUBATION_TIME_MIN = 15 - const val INCUBATION_TIME_MAX = 30 + const val INCUBATION_TIME_MIN = 0 + const val INCUBATION_TIME_MAX = 300 + const val MAX_KIT_TIME = 240 const val BATTERY_LEVEL_MIN = Int.MIN_VALUE const val PQ_MODE = true @@ -1595,6 +1613,14 @@ object Constants { const val sickleCellDiseaseMin2mm = 0.45 const val sickleCellDiseaseMax2mm = 0.7 + const val min2mmLed1 = 0.34 + const val max2mmLed1 = 1.48 + const val min2mmLed2 = 0.04 + const val max2mmLed2 = 0.33 + const val min10mmLed1 = 0.22 + const val max10mmLed1 = 1.12 + const val min10mmLed2 = 0.05 + const val max10mmLed2 = 0.41 // val STATICID = listOf( diff --git a/app/src/main/java/com/example/hpostesting/data/dao/MyDataBase.kt b/app/src/main/java/com/example/hpostesting/data/dao/MyDataBase.kt index bc1b3bb..b0b21d1 100644 --- a/app/src/main/java/com/example/hpostesting/data/dao/MyDataBase.kt +++ b/app/src/main/java/com/example/hpostesting/data/dao/MyDataBase.kt @@ -23,7 +23,7 @@ import com.example.hpostesting.data.model.patient.UserData @Database( entities = [UserData::class, HemoCubeTestData::class, DeviceData::class, BufferCheckData::class], - version = 34, + version = 35, exportSchema = false ) @TypeConverters(Converters::class) diff --git a/app/src/main/java/com/example/hpostesting/data/model/patient/HemoCubeTestData.kt b/app/src/main/java/com/example/hpostesting/data/model/patient/HemoCubeTestData.kt index 31db977..a35d266 100644 --- a/app/src/main/java/com/example/hpostesting/data/model/patient/HemoCubeTestData.kt +++ b/app/src/main/java/com/example/hpostesting/data/model/patient/HemoCubeTestData.kt @@ -109,5 +109,6 @@ data class HemoCubeTestData( var labName: String? = "", var cuvetteSize: String? = "", var district: String? = "", - var centerName: String? = "" + var centerName: String? = "", + var ipAddress:String?= "" ) diff --git a/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt b/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt index d42646e..cc673ab 100644 --- a/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt +++ b/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt @@ -120,6 +120,21 @@ class DatabaseRepository @Inject constructor( Response.Error(e) } } + override suspend fun addQcTestToDatabase(data: HemoCubeTestData?): Response { + return try { + val userdata = + db.collection("patientData").whereEqualTo("_id", data!!._id).get().await() + if (userdata.documents.isNotEmpty()) { + userdata.documents.forEach { + db.collection("patientData").document(it.id).update("testStatus", true) + } + } + db.collection("qcData").add(data).await() + Response.Success(data._id) + } catch (e: Exception) { + Response.Error(e) + } + } override suspend fun addTestToDatabase(data: UserData?): Response { TODO("Not yet implemented") diff --git a/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt b/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt index 88f3225..aa5064d 100644 --- a/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt +++ b/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt @@ -38,6 +38,7 @@ import okhttp3.ResponseBody interface Repository { suspend fun addTestToDatabase(data: HemoCubeTestData?): Response + suspend fun addQcTestToDatabase(data: HemoCubeTestData?): Response suspend fun addTestToDatabasefornew(data: HemoCubeTestData?): Response suspend fun addTestToDatabase(data: UserData?): Response diff --git a/app/src/main/java/com/example/hpostesting/presentation/KitScanActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/KitScanActivity.kt index e5faaa7..c2db823 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/KitScanActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/KitScanActivity.kt @@ -44,6 +44,11 @@ import com.zebra.scannercontrol.IDcsSdkApiDelegate import com.zebra.scannercontrol.SDKHandler import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.ActivityKitScanBinding +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.Locale +import kotlin.math.max class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { @@ -134,9 +139,23 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { }else{ Constants.MAXIMUM_TEST_ALLOWED_BEFORE_REFERENCE10MM } - if (DataHolder.sampleReadCounter <= maxTest) { - DataHolder.selectedTest!!.kitSerial = DataHolder.kitSerial + val time = timeDifference(sharedPreference.getString(Constants.KIT_TIME, "").toString()) + val kitNum = sharedPreference.getString(Constants.KIT_NUMBER, "").toString() + // Toast.makeText(this@KitScanActivity,"Test MAx time"+ time+"-Test count-"+kitNum,Toast.LENGTH_SHORT).show() + + if (DataHolder.sampleReadCounter <= maxTest && kitNum != "" && time < Constants.MAX_KIT_TIME) { moveToNext() + } else { + Toast.makeText(this@KitScanActivity, "Limit Reached, Use New KIT for testing", Toast.LENGTH_SHORT).show() + DataHolder.sampleReadCounter = 0 + DataHolder.kitSerial = "" + + with(sharedPreference.edit()) { + putString(Constants.KIT_NUMBER, "") + putString(Constants.BUFFER_VALUE_1, "") + putString(Constants.BUFFER_VALUE_2, "") + apply() + } } // if (checkHemoCubeKitData()) { @@ -153,31 +172,31 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { // } // } - try { - if (checkHemoCubeKitData()) { - DataHolder.selectedTest!!.kitSerial = - sharedPreference.getString(Constants.KIT_NUMBER, "").toString() - moveToNext() - } else { - // Handle the case when checkHemoCubeKitData() returns false - with(sharedPreference.edit()) { - putString(Constants.KIT_NUMBER, "") - putInt(Constants.KIT_COUNT, 0) - putString(Constants.BUFFER_VALUE_1, "") - putString(Constants.BUFFER_VALUE_2, "") - apply() - } - } - } catch (e: NullPointerException) { - // Handle the NullPointerException here - e.printStackTrace() // You can log the exception for debugging - FirebaseCrashlytics.getInstance().recordException(e) - val errorMessage = "An error occurred: ${e.message}" - val rootView = findViewById(android.R.id.content) - Snackbar.make(rootView, errorMessage, Snackbar.LENGTH_LONG).show() - // Optionally, show a user-friendly error message to the user - // Toast.makeText(applicationContext, "An error occurred", Toast.LENGTH_SHORT).show() - } +// try { +// if (checkHemoCubeKitData()) { +// DataHolder.selectedTest!!.kitSerial = +// sharedPreference.getString(Constants.KIT_NUMBER, "").toString() +// moveToNext() +// } else { +// // Handle the case when checkHemoCubeKitData() returns false +// with(sharedPreference.edit()) { +// putString(Constants.KIT_NUMBER, "") +// putInt(Constants.KIT_COUNT, 0) +// putString(Constants.BUFFER_VALUE_1, "") +// putString(Constants.BUFFER_VALUE_2, "") +// apply() +// } +// } +// } catch (e: NullPointerException) { +// // Handle the NullPointerException here +// e.printStackTrace() // You can log the exception for debugging +// FirebaseCrashlytics.getInstance().recordException(e) +// val errorMessage = "An error occurred: ${e.message}" +// val rootView = findViewById(android.R.id.content) +// Snackbar.make(rootView, errorMessage, Snackbar.LENGTH_LONG).show() +// // Optionally, show a user-friendly error message to the user +// // Toast.makeText(applicationContext, "An error occurred", Toast.LENGTH_SHORT).show() +// } setSupportActionBar(binding.toolbar) binding.btnScanNow.setOnClickListener { @@ -201,20 +220,26 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { } Toast.makeText(this, "Selected cuvette size: 10mm", Toast.LENGTH_SHORT).show() } + val kitTime = SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss", Locale.getDefault() + ).format(Calendar.getInstance().time).toString() if (DataHolder.selectedTest == null) { with(sharedPreference.edit()) { putString( Constants.KIT_NUMBER, binding.nameEditText.text.toString() ) + putString(Constants.BUFFER_VALUE_1, "") + putString(Constants.BUFFER_VALUE_2, "") + putString(Constants.KIT_TIME, kitTime) putInt(Constants.KIT_COUNT, 1) apply() } + DataHolder.kitSerial = binding.nameEditText.text.toString() Toast.makeText( applicationContext, R.string.kit_updated, Toast.LENGTH_SHORT ).show() - val i = Intent(applicationContext, DashboardActivity::class.java) startActivity(i) finish() @@ -222,6 +247,9 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { DataHolder.kitSerial = binding.nameEditText.text.toString() DataHolder.selectedTest?.kitSerial = binding.nameEditText.text.toString() with(sharedPreference.edit()) { + putString(Constants.BUFFER_VALUE_1, "") + putString(Constants.BUFFER_VALUE_2, "") + putString(Constants.KIT_TIME, kitTime) putString(Constants.KIT_NUMBER, binding.nameEditText.text.toString()) putInt(Constants.KIT_COUNT, 1) apply() @@ -232,21 +260,21 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { Toast.makeText(this, R.string.invalid_kit_number, Toast.LENGTH_LONG).show() return@setOnClickListener } - if (serialNumber.isNotEmpty() && checkDataNotNull() && isSerialValid( - serialNumber - ) - ) { - DataHolder.kitSerial = binding.nameEditText.text.toString() - DataHolder.selectedTest?.kitSerial = binding.nameEditText.text.toString() - with(sharedPreference.edit()) { - putString(Constants.KIT_NUMBER, binding.nameEditText.text.toString()) - putInt(Constants.KIT_COUNT, 1) - apply() - } - moveToNext() - } else { - Toast.makeText(this, R.string.invalid_kit_number, Toast.LENGTH_LONG).show() - } +// if (serialNumber.isNotEmpty() && checkDataNotNull() && isSerialValid( +// serialNumber +// ) +// ) { +// DataHolder.kitSerial = binding.nameEditText.text.toString() +// DataHolder.selectedTest?.kitSerial = binding.nameEditText.text.toString() +// with(sharedPreference.edit()) { +// putString(Constants.KIT_NUMBER, binding.nameEditText.text.toString()) +// putInt(Constants.KIT_COUNT, 1) +// apply() +// } +// moveToNext() +// } else { +// Toast.makeText(this, R.string.invalid_kit_number, Toast.LENGTH_LONG).show() +// } } //Setting up the SDK handler @@ -310,17 +338,17 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { } } - private fun checkHemoCubeKitData(): Boolean { - return sharedPreference.getString(Constants.KIT_NUMBER, "") - ?.isNotBlank() == true && sharedPreference.getInt( - Constants.KIT_COUNT, 0 - ) > 0 && sharedPreference.getInt(Constants.KIT_COUNT, 0) < Constants.KIT_CAPACITY - } +// private fun checkHemoCubeKitData(): Boolean { +// return sharedPreference.getString(Constants.KIT_NUMBER, "") +// ?.isNotBlank() == true && sharedPreference.getInt( +// Constants.KIT_COUNT, 0 +// ) > 0 && sharedPreference.getInt(Constants.KIT_COUNT, 0) < Constants.KIT_CAPACITY +// } private fun isSerialValid(s: String): Boolean { if (s.contains("SMI/SC/")) { if(s.length != 17){ - binding.nameEditText.error = getString(R.string.invalid_kit) + binding.nameEditText.error = "Invalid Kit Serial Number, correct example SMI/SC/000/00/000" return false } }else if(s.contains("SMI/SC-2-D10/")){ @@ -386,4 +414,18 @@ class KitScanActivity : AppCompatActivity(), IDcsSdkApiDelegate { true } } + private fun timeDifference(createdAt: String): Long { + val currentTime = Calendar.getInstance().time + val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) + + val createdAtDate: Date = if (createdAt.isEmpty()) { + currentTime + } else { + formatter.parse(createdAt) ?: currentTime + } + + val diffMillis = currentTime.time - createdAtDate.time + + return diffMillis / (60 * 1000) // Convert milliseconds to minutes + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/hpostesting/presentation/adapter/OfflineUserListAdapter.kt b/app/src/main/java/com/example/hpostesting/presentation/adapter/OfflineUserListAdapter.kt index 5c3cf73..987deea 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/adapter/OfflineUserListAdapter.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/adapter/OfflineUserListAdapter.kt @@ -16,6 +16,7 @@ package com.example.hpostesting.presentation.adapter import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources +import android.provider.ContactsContract.Data import android.view.LayoutInflater import android.view.View import android.view.ViewGroup diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index 180a59f..1155d4d 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -75,7 +75,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { private var downloadId: Long = 0 // TODO: Remove hemocube viewmodel private val hemocubeViewModel: HemoCubeViewModel by viewModels() - private lateinit var sharedPreference: SharedPreferences + override fun attachBaseContext(newBase: Context?) { val languageCode = LanguageManager.getSavedLanguage(newBase!!) LanguageManager.setLocale(newBase, languageCode) @@ -100,6 +100,11 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { nats.connect() } + val savedKitSerial = sharedPreferences.getString(Constants.KIT_NUMBER, "") + + Log.d("DashboardActivity", "Saved Kit Serial: $savedKitSerial") + // Toast.makeText(this, "Saved Kit Serial: $savedKitSerial", Toast.LENGTH_SHORT).show() + val versionName = getAppVersion(this@DashboardActivity) + " [ " + getAppEnvironment(this@DashboardActivity) + " ]" binding.appBarDashboard.versionName.text = versionName @@ -276,7 +281,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { private fun createDeviceUpdateRequestData(): DeviceUpdateRequest { return DeviceUpdateRequest( - serial_no = sharedPreference.getString(Constants.DEVICE_ID, "") + serial_no = sharedPreferences.getString(Constants.DEVICE_ID, "") ) } private fun getAppVersion(context: Context): String { diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/GalleryFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/GalleryFragment.kt index 72fd714..a4dd620 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/GalleryFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/GalleryFragment.kt @@ -88,6 +88,7 @@ class GalleryFragment : Fragment() { binding.btnSubmit.visibility = View.VISIBLE binding.btnDeviceInfo.visibility = View.VISIBLE binding.btnResetPassword.visibility = View.VISIBLE + binding.btnUpdateValues.visibility = View.VISIBLE }else{ binding.btnResetPassword.visibility = View.GONE binding.btnDeviceProvision.visibility = View.GONE @@ -100,6 +101,7 @@ class GalleryFragment : Fragment() { binding.btnUsbTerminal.visibility = View.GONE binding.btnSubmit.visibility = View.GONE binding.btnDeviceInfo.visibility = View.VISIBLE + binding.btnUpdateValues.visibility = View.GONE } binding.btnResetPassword.setOnClickListener{ @@ -108,6 +110,9 @@ class GalleryFragment : Fragment() { binding.btnDeviceProvision.setOnClickListener { startActivity(Intent(requireContext(), DeviceProvisionActivity::class.java)) } + binding.btnUpdateValues.setOnClickListener { + startActivity(Intent(requireContext(), UpdateValuesActivity::class.java)) + } binding.btnUsbTerminal.setOnClickListener { startActivity(Intent(requireContext(), UsbTerminalActivity::class.java)) } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 2627877..6a9d7e0 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -148,6 +148,10 @@ class HomeFragment : Fragment() { }else if(it.testStatus == true){ userList.removeAll(userData) } + + if (timeDifference(it.incubationTime) >= 50){ + userList.removeAll(userData) + } } val bm = requireContext().getSystemService(BATTERY_SERVICE) as BatteryManager val batLevel: Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) @@ -223,15 +227,19 @@ class HomeFragment : Fragment() { binding.btnNewKitoffline.setOnClickListener { - with(sharedPreference.edit()) { - putString(Constants.KIT_NUMBER, "") - putInt(Constants.KIT_COUNT, 0) - apply() - } +// with(sharedPreference.edit()) { +// putString(Constants.KIT_NUMBER, "") +// putInt(Constants.KIT_COUNT, 0) +// apply() +// } startActivity(Intent(requireContext(), KitScanActivity::class.java)) // requireActivity().finish() } binding.btnQuickCapture.setOnClickListener { + with(sharedPreference.edit()) { + putBoolean(Constants.QUICK_CAPTURE, true) + apply() + } DataHolder.quickCapture = true DataHolder.hemoCubeTestData = HemoCubeTestData() @@ -262,11 +270,10 @@ class HomeFragment : Fragment() { setUserId() // loadUserData() // setSearch() - checkForLocalDBData() + //checkForLocalDBData() if (Constants.MOLBIO_INTEGRATION) { checkForTokenAndUpdate() } - // Now re-subscribe to allUserData /* hemoCubeViewModel.allLocalData.observe(viewLifecycleOwner) { originalUserDataList -> @@ -667,7 +674,7 @@ class HomeFragment : Fragment() { val version = pInfo.versionName var labname = sharedPreference.getString(Constants.LABNAME,"") return LoginRequest( - latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.ipAddress, password = password, serialNumber = userID, username = userID, version = version, lab = labname + location = DataHolder.ipAddress, password = password, serialNumber = userID, username = userID, version = version, lab = labname ) } private fun createCheckUpdateRequestData(): CheckUpdateRequest { @@ -983,11 +990,11 @@ class HomeFragment : Fragment() { // binding.uploadData.visibility = uploadDataVisibility // } - hemoCubeViewModel.allKitTestData.observe(viewLifecycleOwner) { bufferData -> - val uploadDataVisibility = - if (bufferData.any { !it.localFlag }) View.VISIBLE else View.GONE + // hemoCubeViewModel.allKitTestData.observe(viewLifecycleOwner) { bufferData -> + // val uploadDataVisibility = + // if (bufferData.any { !it.localFlag }) View.VISIBLE else View.GONE // binding.uploadData.visibility = uploadDataVisibility - } + // } } private fun checkUnprocessedCSVData() { @@ -1191,7 +1198,11 @@ class HomeFragment : Fragment() { override fun onDestroyView() { super.onDestroyView() hemoCubeViewModel.networkStatusLiveData.removeObservers(viewLifecycleOwner) - + hemoCubeViewModel.allKitTestData.removeObservers(viewLifecycleOwner) + hemoCubeViewModel.allUserData.removeObservers(viewLifecycleOwner) + hemoCubeViewModel.uploadLogs.removeObservers(viewLifecycleOwner) + hemoCubeViewModel.checkUpdate.removeObservers(viewLifecycleOwner) + hemoCubeViewModel.downloadcertificate.removeObservers(viewLifecycleOwner) } private fun downloadCsv() { @@ -1532,6 +1543,10 @@ class HomeFragment : Fragment() { getPublicIpAddr { ipAddress -> if(ipAddress != "fail"){ DataHolder.ipAddress = ipAddress + with(sharedPreference.edit()) { + putString(Constants.IP_ADDRESS, ipAddress) + apply() + } } hemoCubeViewModel.login(createLoginRequestData(userID, password)) } @@ -1539,7 +1554,20 @@ class HomeFragment : Fragment() { hemoCubeViewModel.login(createLoginRequestData(userID, password)) } } + private fun timeDifference(createdAt: String): Long { + val currentTime = Calendar.getInstance().time + val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) + val createdAtDate: Date = if (createdAt.isEmpty()) { + currentTime + } else { + formatter.parse(createdAt) ?: currentTime + } + + val diffMillis = currentTime.time - createdAtDate.time + + return diffMillis / (60 * 1000) // Convert milliseconds to minutes + } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/UpdateValuesActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/UpdateValuesActivity.kt new file mode 100644 index 0000000..fe961ab --- /dev/null +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/UpdateValuesActivity.kt @@ -0,0 +1,50 @@ +/* + * // Copyright (c) 2024 ShanMukha Innovations Pvt. Ltd. All rights reserved. + * // Notice: All information contained herein is, and remains + * // the property of ShanMukha Innovations Pvt. Ltd. and its suppliers, + * // if any. The intellectual and technical concepts contained + * // herein are proprietary to ShanMukha Innovations Pvt. Ltd. + * // and its suppliers and may be covered by Indian and Foreign Patents, + * // patents in process, and are protected by trade secret or copyright law. + * // Dissemination of this information or reproduction of this material + * // is strictly forbidden unless prior written permission is obtained + * // from ShanMukha Innovations Pvt. Ltd. + */ + +package com.example.hpostesting.presentation.dashboard + +import android.content.Context +import android.content.SharedPreferences +import android.os.Bundle +import androidx.activity.enableEdgeToEdge +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import com.example.hpostesting.data.constant.Constants +import `in`.sminnovations.hpostesting.R +import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding +import `in`.sminnovations.hpostesting.databinding.ActivityUpdateValuesBinding + +class UpdateValuesActivity : AppCompatActivity() { + private lateinit var binding: ActivityUpdateValuesBinding + lateinit var sharedPreferences: SharedPreferences + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityUpdateValuesBinding.inflate(layoutInflater) + sharedPreferences = this.getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE) + setContentView(binding.root) + binding.btnSubmit.setOnClickListener { + saveStringToPreferences(Constants.ABS2LED1MMLL, binding.et2mmled1Ll.text.toString()) + saveStringToPreferences(Constants.ABS2LED1MMUL, binding.et2mmled1Ul.text.toString()) + saveStringToPreferences(Constants.ABS2LED2MMLL, binding.et2mmled2Ll.text.toString()) + saveStringToPreferences(Constants.ABS2LED2MMUL, binding.et2mmled2Ul.text.toString()) + saveStringToPreferences(Constants.ABS10LED1MMLL, binding.et10mmled1Ll.text.toString()) + saveStringToPreferences(Constants.ABS10LED1MMUL, binding.et10mmled1Ul.text.toString()) + saveStringToPreferences(Constants.ABS10LED2MMLL, binding.et10mmled2Ll.text.toString()) + saveStringToPreferences(Constants.ABS10LED2MMUL, binding.et10mmled2Ul.text.toString()) + } + } + private fun saveStringToPreferences(key: String, value: String) { + sharedPreferences.edit().putString(key, value).apply() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt index cf8a224..914c1bb 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt @@ -181,6 +181,12 @@ class LoginFragment : Fragment() { } DataHolder.centerName = binding.centerName.text.toString() DataHolder.district = binding.etDistrict.text.toString() + with(sharedPreference.edit()) { + putString(Constants.CENTER_NAME, binding.centerName.text.toString().lowercase().trim()) + putString(Constants.DISTRICT, binding.etDistrict.text.toString()) + apply() + } + } override fun onDestroyView() { diff --git a/app/src/main/java/com/example/hpostesting/presentation/deviceprovision/DeviceProvisionFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/deviceprovision/DeviceProvisionFragment.kt index a48c365..f728ebb 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/deviceprovision/DeviceProvisionFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/deviceprovision/DeviceProvisionFragment.kt @@ -118,12 +118,7 @@ class DeviceProvisionFragment : Fragment() { ) apply() } - startActivity( - Intent( - requireContext(), - DashboardActivity::class.java - ) - ) + Toast.makeText( activity, "Device registered successfully", Toast.LENGTH_LONG ).show() @@ -148,7 +143,13 @@ class DeviceProvisionFragment : Fragment() { // viewModel.addDeviceId(DeviceData(deviceId = sharedPreferences.getString(Constants.DEVICE_ID, "").toString())) Log.e("idpass", response.toString()) Log.e("idpass", response.data.data?.credentials?.username.toString()) - Log.e("idpass", deviceProvisionResponse) + // Log.e("idpass", deviceProvisionResponse) + startActivity( + Intent( + requireContext(), + DashboardActivity::class.java + ) + ) } else { Toast.makeText( activity, diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt index 3178e95..084d3d2 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt @@ -19,6 +19,7 @@ import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.os.Bundle +import android.text.method.ScrollingMovementMethod import android.util.Log import android.view.LayoutInflater import android.view.View @@ -47,6 +48,7 @@ import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.FragmentHemoCubeReferenceBinding import kotlin.math.abs import kotlin.math.log10 +import kotlin.random.Random @Suppress("MemberVisibilityCanBePrivate") class HemoCubeFragment : Fragment() { @@ -88,6 +90,7 @@ class HemoCubeFragment : Fragment() { private var uploadedToCloud = false private var uploadedToMolbio = false lateinit var testState: TestState + var quickCapture:Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, @@ -100,7 +103,7 @@ class HemoCubeFragment : Fragment() { testState = TestState( testDetails = DataHolder.selectedTest?.toHemoCubeTestData(), ) - + quickCapture = sharedPreferences.getBoolean(Constants.QUICK_CAPTURE, false) return binding.root } @@ -114,7 +117,13 @@ class HemoCubeFragment : Fragment() { @SuppressLint("SetTextI18n") private fun initViews() { + binding.tvSubtitle4.movementMethod = ScrollingMovementMethod() + binding.tvDeviceMessages.movementMethod = ScrollingMovementMethod() binding.btnSubmit.setOnClickListener { + with(sharedPreferences.edit()) { + putBoolean(Constants.QUICK_CAPTURE, false) + apply() + } DataHolder.sampleReadCounter++ binding.btnSubmit.isEnabled = false binding.btnSubmit.isClickable = false @@ -124,7 +133,7 @@ class HemoCubeFragment : Fragment() { binding.btnSubmit.visibility = View.GONE } hemoCubeViewModel.uploadHemoCubeResultToDatabase( - isOnline, true, sharedPreferences.getString(Constants.KIT_NUMBER, "") + isOnline, true, sharedPreferences.getString(Constants.KIT_NUMBER, ""),quickCapture ) } @@ -140,6 +149,7 @@ class HemoCubeFragment : Fragment() { binding.tvSubtitle4.text = "Config" if (isBufferValueAvailable()){ + hemoCubeViewModel.messages.postValue("Ready to test") binding.btnPlacebuffer.apply { setBackgroundColor(Color.GREEN) // Set button background color to green text = "Refresh Buffer" // Change button text to "Buffer Exists" @@ -147,9 +157,10 @@ class HemoCubeFragment : Fragment() { binding.btnSamplestart.isClickable = true binding.btnSamplestart.isEnabled = true }else{ + hemoCubeViewModel.messages.postValue("Fresh Kit - Please take Buffer Blank reading") binding.btnPlacebuffer.apply { setBackgroundColor(Color.RED) // Set button background color to green - text = "No Buffer" // Change button text to "Buffer Exists" + text = "Fresh Buffer" // Change button text to "Buffer Exists" } binding.btnSamplestart.isClickable = false binding.btnSamplestart.isEnabled = false @@ -481,7 +492,7 @@ class HemoCubeFragment : Fragment() { //#EC for v0 and v1 and #RC for v2 (resultData.contains("#EC") && this.testStatusCode < TestStatus.EPROM_ADC_RETRIEVAL_COMPLETED.code) -> { this.testStatusCode = TestStatus.EPROM_ADC_RETRIEVAL_COMPLETED.code - hemoCubeViewModel.messages.postValue("Ready to test")//EPROM ADC Loaded + //EPROM ADC Loaded //checkCuvettePresence() activity?.runOnUiThread { binding.btnPlacebuffer.visibility = View.VISIBLE @@ -492,7 +503,7 @@ class HemoCubeFragment : Fragment() { (resultData.contains("#AC") && this.testStatusCode < TestStatus.TEMPERATURE_CHECK.code) -> { this.testStatusCode = TestStatus.TEMPERATURE_CHECK.code temperature = resultData.substringAfter("#AS").substringBefore("#AC") - hemoCubeViewModel.messages.postValue("Ready to test \n Temperature : $temperature") + //hemoCubeViewModel.messages.postValue("Ready to test \n Temperature : $temperature") } resultData.contains("#CIN") && sampleClick && this.testStatusCode < TestStatus.CUVETTE_PRESENTS.code -> { hemoCubeViewModel.messages.postValue(getString(R.string.cuvette_present)) @@ -546,18 +557,53 @@ class HemoCubeFragment : Fragment() { resultData.contains("#BC") && this.testStatusCode < TestStatus.BUFFER_COMPLETED.code -> { activity?.runOnUiThread { resultData = "" - // resultData.replace("#AIN","#BAIN",false) - Log.d("resultDataBC",resultData) - binding.testing.visibility = View.GONE - binding.tvSubtitle4.text = getString(R.string.buffer_completed) + if(Constants.FLAGS_ENABLED){ + fetchResult() + }else{ + Log.d("resultDataBC",resultData) + activity?.runOnUiThread { + binding.testing.visibility = View.GONE + binding.tvSubtitle4.text = getString(R.string.buffer_completed) // binding.btnSamplestart.visibility = View.VISIBLE - binding.btnPlacebuffer.visibility = View.GONE - binding.btnSamplestart.isClickable = true - binding.btnSamplestart.isEnabled = true + binding.btnPlacebuffer.visibility = View.GONE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = true + binding.btnSamplestart.isEnabled = true + } + } + // resultData.replace("#AIN","#BAIN",false) } this.testStatusCode = TestStatus.BUFFER_COMPLETED.code } + resultData.contains("REND") && this.testStatusCode < TestStatus.BUFFER_PRINT_COMPLETED.code -> { + resultData = resultData.replace("REND","Buffer print complete"+ generateTwoDigitRandomNumber()) + hemoCubeViewModel.deviceMessages.postValue(resultData) + if(handleBufferCompleted()){ + this.testStatusCode = TestStatus.TEMPERATURE_CHECK.code + activity?.runOnUiThread { + checkCuvette = false + binding.testing.visibility = View.GONE + binding.btnRetryCheckCuvette.visibility = View.GONE + binding.btnPlacebuffer.visibility = View.VISIBLE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = false + binding.btnSamplestart.isEnabled = false + } + }else{ + this.testStatusCode = TestStatus.BUFFER_PRINT_COMPLETED.code + Log.d("resultDataBC",resultData) + activity?.runOnUiThread { + binding.testing.visibility = View.GONE + binding.tvSubtitle4.text = getString(R.string.buffer_completed) +// binding.btnSamplestart.visibility = View.VISIBLE + binding.btnPlacebuffer.visibility = View.GONE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = true + binding.btnSamplestart.isEnabled = true + } + } + } (resultData.contains("#SS") || resultData.contains("#SS1")) && this.testStatusCode < TestStatus.SAMPLE_STARTED.code -> { this.testStatusCode = TestStatus.SAMPLE_STARTED.code @@ -637,6 +683,8 @@ class HemoCubeFragment : Fragment() { } resultData.contains("REND") && this.testStatusCode < TestStatus.SAMPLE_PRINT_COMPLETED.code -> { + resultData = resultData.replace("REND","Sample print complete"+ generateTwoDigitRandomNumber()) + hemoCubeViewModel.deviceMessages.postValue(resultData) handleSampleCompleted() } @@ -733,6 +781,34 @@ class HemoCubeFragment : Fragment() { } } + private fun handleBufferCompleted(): Boolean { + val lb1Regex = Regex("""LB1 (\d+\.\d+)""") + val lb2Regex = Regex("""LB2 (\d+\.\d+)""") + + val lb1Match = lb1Regex.find(resultData) + val lb2Match = lb2Regex.find(resultData) + + val lb1Value = lb1Match!!.groupValues[1].toFloat() + val lb2Value = lb2Match!!.groupValues[1].toFloat() + + val led1Min = 21000.00 + val led1Max = 23000.00 + + val led2Min = 17000.00 + val led2Max = 19000.00 + + val isLb1InRange = lb1Value in led1Min..led1Max + val isLb2InRange = lb2Value in led2Min..led2Max + if(!isLb1InRange || !isLb2InRange){ + hemoCubeViewModel.messages.postValue("Buffer Reading Out of Range - Please Take Buffer/Blank Reading. If problem persists, Calibrate device") + return true + } + + Log.d("HemoCube", "LB1 ($lb1Value) is in range LED1 ($led1Min-$led1Max): $isLb1InRange") + Log.d("HemoCube", "LB2 ($lb2Value) is in range LED2 ($led2Min-$led2Max): $isLb2InRange") + return false + } + private fun showRetryButtonForCuvette() { activity?.runOnUiThread { // binding.btnPlacebuffer.visibility = View.GONE @@ -756,7 +832,7 @@ class HemoCubeFragment : Fragment() { } } else { hemoCubeViewModel.uploadHemoCubeResultToDatabase( - isOnline, true, sharedPreferences.getString(Constants.KIT_NUMBER, "") + isOnline, true, sharedPreferences.getString(Constants.KIT_NUMBER, ""),false ) } } @@ -800,12 +876,7 @@ class HemoCubeFragment : Fragment() { led4SampleForDevice = resultLines[8].split(' ')[1].split('\r')[0].trim().toDoubleOrNull()!! processResult() - if (Constants.PQ_MODE) { - finishReading() - } else { - sendFirstGainCommand() - } - currentResultData = "" + } fun processV1HardwareId(resultData: String) { @@ -918,7 +989,7 @@ class HemoCubeFragment : Fragment() { requireActivity().packageName, 0 ) val version = pInfo.versionName - +//absorbance val led1Average = log10(led1BufferForDevice.div(led1SampleForDevice)) val led2Average = log10(led2BufferForDevice.div(led2SampleForDevice)) val led3Average = log10(led3BufferForDevice.div(led3SampleForDevice)) @@ -927,6 +998,60 @@ class HemoCubeFragment : Fragment() { val deviceRatio = led2Average / led1Average val borderlineMetric = (led1Average - led2Average) / deviceRatio + if(Constants.ABS_FLAGS_ENABLED){ + val inRange2mmLed1: Boolean + val inRange2mmLed2: Boolean + val inRange10mmLed1: Boolean + val inRange10mmLed2: Boolean + val min2mmLed1 = getDoubleFromPreferences(Constants.ABS2LED1MMLL, Constants.min2mmLed1) + val max2mmLed1 = getDoubleFromPreferences(Constants.ABS2LED1MMUL, Constants.max2mmLed1) + val min2mmLed2 = getDoubleFromPreferences(Constants.ABS2LED2MMLL, Constants.min2mmLed2) + val max2mmLed2 = getDoubleFromPreferences(Constants.ABS2LED2MMUL, Constants.max2mmLed2) + val min10mmLed1 = getDoubleFromPreferences(Constants.ABS10LED1MMLL, Constants.min10mmLed1) + val max10mmLed1 = getDoubleFromPreferences(Constants.ABS10LED1MMUL, Constants.max10mmLed1) + val min10mmLed2 = getDoubleFromPreferences(Constants.ABS10LED2MMLL, Constants.min10mmLed2) + val max10mmLed2 = getDoubleFromPreferences(Constants.ABS10LED2MMUL, Constants.max10mmLed2) + if(led1Average < 0 || led2Average < 0){ + hemoCubeViewModel.messages.postValue("Negative Absorbance - Repeat test with reading Buffer first and sample second") + this.testStatusCode = TestStatus.BUFFER_PRINT_COMPLETED.code + binding.testing.visibility = View.GONE + binding.btnPlacebuffer.visibility = View.GONE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = true + binding.btnSamplestart.isEnabled = true + return + }else{ + if(cuvetteSize == "10mm"){ + inRange10mmLed1 = led1Average in min10mmLed1..max10mmLed1 + inRange10mmLed2 = led2Average in min10mmLed2..max10mmLed2 + if(!inRange10mmLed1 || !inRange10mmLed2){ + hemoCubeViewModel.messages.postValue("Absorbance out-of-Range - Repeat test with adequate blood volume and Incubation time") + this.testStatusCode = TestStatus.BUFFER_PRINT_COMPLETED.code + binding.testing.visibility = View.GONE + binding.btnPlacebuffer.visibility = View.GONE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = true + binding.btnSamplestart.isEnabled = true + return + } + }else if(cuvetteSize == "2mm"){ + inRange2mmLed1 = led1Average in min2mmLed1..max2mmLed1 + inRange2mmLed2 = led2Average in min2mmLed2..max2mmLed2 + if(!inRange2mmLed1 || !inRange2mmLed2){ + hemoCubeViewModel.messages.postValue("Absorbance out-of-Range - Repeat test with adequate blood volume and Incubation time") + this.testStatusCode = TestStatus.BUFFER_PRINT_COMPLETED.code + binding.testing.visibility = View.GONE + binding.btnPlacebuffer.visibility = View.GONE + binding.btnSamplestart.visibility = View.VISIBLE + binding.btnSamplestart.isClickable = true + binding.btnSamplestart.isEnabled = true + return + } + } + } + } + + if (led1BufferForDevice < Constants.BUFFER_INTENSITY_THRESHOLDS[deviceHardwareId]?.get(0) ?.get(0)!! @@ -1119,6 +1244,13 @@ class HemoCubeFragment : Fragment() { ).show() Firebase.crashlytics.recordException(e) } + + if (Constants.PQ_MODE) { + finishReading() + } else { + sendFirstGainCommand() + } + currentResultData = "" } fun reclassifyWithBorderlineMethod2(deviceRatio: Double?, deviceRatioClass: String?, led2Average: Double?): String { @@ -1477,4 +1609,10 @@ class HemoCubeFragment : Fragment() { val coefficient2 = currentDeviceData?.coefficients?.get(1) ?: 0.0 return coefficient1 * ratio + coefficient2 } + fun getDoubleFromPreferences(key: String, defaultValue: Double): Double { + return sharedPreferences.getString(key, defaultValue.toString())?.toDouble() ?: defaultValue + } + private fun generateTwoDigitRandomNumber(): Int { + return Random.nextInt(10, 100) + } } diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt index 9aac332..aaaa0d0 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt @@ -122,7 +122,7 @@ class HemoCubeViewModel @Inject constructor( } fun uploadHemoCubeResultToDatabase( - isOnline: Boolean, testStatus: Boolean, kitSerial: String?, + isOnline: Boolean, testStatus: Boolean, kitSerial: String?,quickCapture:Boolean ) = viewModelScope.launch { if (kitSerial != null) { testDetails?.kitSerial = kitSerial @@ -132,9 +132,10 @@ class HemoCubeViewModel @Inject constructor( try { if (isOnline) { parseData() - addResultTestToDb() + addResultTestToDb(quickCapture) } else { parseData() + addResultTestToDb(quickCapture) testDetails?.testTime = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(Calendar.getInstance().time) @@ -417,66 +418,93 @@ class HemoCubeViewModel @Inject constructor( testDetails?.volume = DataHolder.hemoCubeTestData?.volume testDetails?.filter = DataHolder.hemoCubeTestData?.filter testDetails?.labName = DataHolder.hemoCubeTestData?.labName - testDetails?.cuvetteSize = DataHolder.hemoCubeTestData?.cuvetteSize - testDetails?.centerName = DataHolder.centerName - testDetails?.district = DataHolder.district + testDetails?.cuvetteSize = sharedPreference.getString(Constants.CUVETTE_SIZE, "").toString() + testDetails?.centerName = sharedPreference.getString(Constants.CENTER_NAME, "").toString() + testDetails?.district = sharedPreference.getString(Constants.DISTRICT, "").toString() + testDetails?.ipAddress = sharedPreference.getString(Constants.IP_ADDRESS, "").toString() } - private fun addResultTestToDb() { + private fun addResultTestToDb(quickCapture: Boolean) { viewModelScope.launch { try { - testDetails!!.reportUploadTime = SimpleDateFormat( + testDetails!!.quickCapture = quickCapture + testDetails.reportUploadTime = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(Calendar.getInstance().time) val currentTimeFormatted = SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.getDefault() ).format(Calendar.getInstance().time) - when (val response = repository.addTestToDatabase(testDetails)) { - is Response.Success -> { - val kitCount = sharedPreference.getInt(Constants.KIT_COUNT, 0) - with(sharedPreference.edit()) { - putInt(Constants.KIT_COUNT, kitCount.plus(1)) - apply() + if(quickCapture){ + when (val response = repository.addQcTestToDatabase(testDetails)) { + is Response.Success -> { + val kitCount = sharedPreference.getInt(Constants.KIT_COUNT, 0) + with(sharedPreference.edit()) { + putInt(Constants.KIT_COUNT, kitCount.plus(1)) + apply() + } + Log.i("Testdb", "Data uploaded to Firestore successfully") + fireBaseUpload.postValue("Success") + testDetails.localFlag = true + hemoCubeDao.updateTest(testDetails) } - Log.i("Testdb", "Data uploaded to Firestore successfully") - fireBaseUpload.postValue("Success") - testDetails.localFlag = true - if (Constants.MOLBIO_INTEGRATION) { - // Sanitize testDetails before using it in the API call - val sanitizedTestDetails = sanitizeDoubleValues(testDetails) - // Now, use sanitizedTestDetails for the API call - uploadResult( - MolbioV2ResultRequest( - mutableListOf( - MolbioV2Result( - rawData = sanitizedTestDetails, - analysisId = sanitizedTestDetails._id, - analysisDate = currentTimeFormatted, - analysisStatus = sanitizedTestDetails.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[sanitizedTestDetails.deviceId]?.toString(), - interpretation = sanitizedTestDetails.classificationResult, - testId = sanitizedTestDetails._id, - testTime = currentTimeFormatted, - collectionTime = currentTimeFormatted, - expiryTime = currentTimeFormatted, + is Response.Error -> { + Log.e("Testdb", "Error uploading data to Firestore: $response") + fireBaseUpload.postValue("Error") + hemoCubeDao.updateTest(testDetails) + } + + else -> {} + } + }else{ + when (val response = repository.addTestToDatabase(testDetails)) { + is Response.Success -> { + val kitCount = sharedPreference.getInt(Constants.KIT_COUNT, 0) + with(sharedPreference.edit()) { + putInt(Constants.KIT_COUNT, kitCount.plus(1)) + apply() + } + Log.i("Testdb", "Data uploaded to Firestore successfully") + fireBaseUpload.postValue("Success") + testDetails.localFlag = true + if (Constants.MOLBIO_INTEGRATION) { + // Sanitize testDetails before using it in the API call + val sanitizedTestDetails = sanitizeDoubleValues(testDetails) + + // Now, use sanitizedTestDetails for the API call + uploadResult( + MolbioV2ResultRequest( + mutableListOf( + MolbioV2Result( + rawData = sanitizedTestDetails, + analysisId = sanitizedTestDetails._id, + analysisDate = currentTimeFormatted, + analysisStatus = sanitizedTestDetails.classificationResult, + thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[sanitizedTestDetails.deviceId]?.toString(), + interpretation = sanitizedTestDetails.classificationResult, + testId = sanitizedTestDetails._id, + testTime = currentTimeFormatted, + collectionTime = currentTimeFormatted, + expiryTime = currentTimeFormatted, + ) ) ) ) - ) + } + hemoCubeDao.updateTest(testDetails) } - hemoCubeDao.updateTest(testDetails) - } - is Response.Error -> { - Log.e("Testdb", "Error uploading data to Firestore: $response") - fireBaseUpload.postValue("Error") - hemoCubeDao.updateTest(testDetails) - } + is Response.Error -> { + Log.e("Testdb", "Error uploading data to Firestore: $response") + fireBaseUpload.postValue("Error") + hemoCubeDao.updateTest(testDetails) + } - else -> {} + else -> {} + } } + } catch (e: Exception) { Log.e("Testdb", "Exception during data upload: ${e.message}") fireBaseUpload.postValue("Error") diff --git a/app/src/main/res/layout/activity_update_values.xml b/app/src/main/res/layout/activity_update_values.xml new file mode 100644 index 0000000..d9a6036 --- /dev/null +++ b/app/src/main/res/layout/activity_update_values.xml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + +