diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 9ff13f3..d0792ae 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -25,6 +25,7 @@ { - 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("testData").add(data).await() - Response.Success(data._id) - } catch (e: Exception) { - Firebase.crashlytics.recordException(e) - Response.Error(e) - } + TODO("Not yet implemented") } override suspend fun addTestToDatabaseforBufferCheck(data: BufferCheckData?): Response { @@ -247,4 +234,22 @@ class DatabaseRepository @Inject constructor( override fun addTestToDatabase(testDetails: UserData): Any { TODO("Not yet implemented") } + + override suspend fun addTestToDatabasefornew(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("testData").add(data).await() + Response.Success(data._id) + } catch (e: Exception) { + Firebase.crashlytics.recordException(e) + Response.Error(e) + } + } + } \ No newline at end of file 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 8c3f995..6322dc4 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 @@ -25,6 +25,7 @@ import okhttp3.ResponseBody interface Repository { suspend fun addTestToDatabase(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/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index f793da3..33a8c19 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 @@ -1,7 +1,6 @@ package com.example.hpostesting.presentation.dashboard -import android.app.DownloadManager -import android.content.BroadcastReceiver +import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -24,7 +23,7 @@ import androidx.navigation.ui.setupWithNavController import com.example.hpostesting.data.Result import com.example.hpostesting.data.constant.Constants import com.example.hpostesting.data.constant.LanguageManager -import com.example.hpostesting.data.model.patient.DeviceData +import com.example.hpostesting.data.model.updates.DeviceUpdateRequest import com.example.hpostesting.presentation.NatsManager import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel import com.example.hpostesting.presentation.jig.JigActivity @@ -35,10 +34,16 @@ import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import dagger.hilt.android.AndroidEntryPoint +import `in`.sminnovations.hpostesting.BuildConfig import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding import okhttp3.ResponseBody +import java.io.BufferedInputStream import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.InputStream +import java.util.zip.ZipInputStream interface NatsMessageCallback { fun onMessageReceived(topic: String, message: String) @@ -62,7 +67,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) @@ -75,6 +80,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { Log.d(TAG, "Received message on topic $topic: $message") } + @SuppressLint("SetWorldReadable") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -96,15 +102,22 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { when (result) { is Result.Success -> { // Handle success - val apkUrl = result.data -// val apkUrl = "https://dl.dropboxusercontent.com/s/fi/1c3nn7t0co431hicl3hrt/app-debug.apk?rlkey=e4uf13ty1dpcked614vy1aaqp&dl=0" - initiateUpdate(apkUrl.toString()) - Log.d("ApI", "APK URL: $apkUrl") -// Toast.makeText( -// this, -// "APK UPLOAD ${result.data}", -// Toast.LENGTH_SHORT -// ).show() + val apk = result.data + val file = File(getExternalFilesDir("Updates"), "update.apk") + file.setReadable(true, false) // Ensure the file is readable + apk.byteStream().use { input -> + file.outputStream().use { output -> + input.copyTo(output) + } + } + Log.d("Responsebodyformat", "Responsebodyformat: ") + installApk(file) + Log.e("ApI", "APK URL: $apk") + Toast.makeText( + this, + "${result.data}", + Toast.LENGTH_SHORT + ).show() } is Result.Error -> { @@ -154,56 +167,15 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } - private fun initiateUpdate(url: String) { - val apkUrl = url - if (!isValidHttpUrl(apkUrl)) { - return - } - - val request = DownloadManager.Request(Uri.parse(apkUrl)) - request.setTitle("App Update") - request.setDescription("Downloading update...") - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) - request.setDestinationInExternalFilesDir(this, "Updates", "update.apk") - - val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager - downloadId = downloadManager.enqueue(request) - - // Register a BroadcastReceiver to receive the download complete event - val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - isRegistered = true - registerReceiver(downloadReceiver, filter, RECEIVER_EXPORTED) - } - } - private fun extractApkUrl(responseBody: ResponseBody): String { - return responseBody.string() - } - private fun isValidHttpUrl(url: String): Boolean { - return url.startsWith("http://") || url.startsWith("https://") - } - private val downloadReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context?, intent: Intent?) { - val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) - if (id == downloadId) { - installApk() - } - } - } - - private fun installApk() { - val file = File(getExternalFilesDir("Updates"), "update.apk") - file.setReadable(true, false) // Ensure the file is readable + private fun installApk(file: File) { val pInfo = baseContext.packageManager.getPackageInfo(baseContext.packageName, 0) val uri: Uri = FileProvider.getUriForFile( this, - "in.sminnovations.hpostesting.dev.fileprovider", + "${BuildConfig.APPLICATION_ID}.fileprovider", file ) - // Create an intent to install the APK val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) installIntent.data = uri installIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or @@ -278,6 +250,14 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { override fun setResponse(response: String) { responses = responses+response+"\n" println(responses) - Log.d("DashBoardActResponse",response) +// if (response.contains("checkUpdate")) { +// hemocubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) +// } + } + + private fun createDeviceUpdateRequestData(): DeviceUpdateRequest { + return DeviceUpdateRequest( + serial_no = sharedPreference.getString(Constants.DEVICE_ID, "") + ) } } \ No newline at end of file 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 f60891f..6c5de10 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 @@ -21,7 +21,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast -import androidx.core.content.FileProvider +import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController @@ -99,6 +99,7 @@ class HomeFragment : Fragment() { return binding.root } + @RequiresApi(Build.VERSION_CODES.P) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) @@ -148,35 +149,67 @@ class HomeFragment : Fragment() { checkForTokenAndUpdate() } - hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> - val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56",//userData.testTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, - testId = userData._id, - testTime = "2024-02-08 16:33:56",//userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56"//userData.testTime, + // Now re-subscribe to allUserData + hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { originalUserDataList -> + + Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED") + + val resultList = MolbioV2ResultRequest(mutableListOf()) + originalUserDataList.forEach { userData -> + Log.d( + ": USER DATA", + originalUserDataList.count().toString() + " : " + userData._id + ) + var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() + // Upload results after processing all userData to avoid duplicates and ensure all modifications are done + if(accessToken.isNotEmpty()) { + if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { + val currentTimeFormatted = SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + Locale.getDefault() + ).format(Calendar.getInstance().time) + val bufferIntensityThreshold = + Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() + ?: "defaultThreshold" // Handle possible nulls safely + resultList.results?.add( + MolbioV2Result( + rawData = userData, + analysisId = userData._id, + analysisDate = currentTimeFormatted, + analysisStatus = userData.classificationResult + ?: "defaultStatus", // Handle possible nulls + thresholds = bufferIntensityThreshold, + interpretation = userData.classificationResult + ?: "defaultInterpretation", // Handle possible nulls + testId = userData._id, + testTime = currentTimeFormatted, + collectionTime = currentTimeFormatted, + expiryTime = currentTimeFormatted + ) ) - ) - } - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) + } } + } + Log.d("USER DATA LIST SIZE", resultList.results?.count().toString()) - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } + resultList.results?.forEach { result -> + val userData = result.rawData + Log.d("UserData", userData.toString()) + if (userData != null) { + if (!userData.localFlag) { + hemoCubeViewModel.bulkAddResultTestToDb(userData) + } + } + } + resultList.results?.forEach { result -> + result.rawData?.let { sanitizeDoubleValues(it) } + } + +// Then, check if there are any results to upload. + if (resultList.results?.isNotEmpty() == true) { + hemoCubeViewModel.uploadResult(resultList) + Log.d("resultcount1", "Uploading sanitized results") } } @@ -204,7 +237,7 @@ class HomeFragment : Fragment() { } binding.uploadData.setOnClickListener { - showUploadDialog(requireContext()) +// showUploadDialog(requireContext()) } hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userData -> @@ -253,41 +286,32 @@ class HomeFragment : Fragment() { } + @RequiresApi(Build.VERSION_CODES.P) private fun checkForTokenAndUpdate() { var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString() var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() - if (userID.isNotEmpty() && password.isNotEmpty()) { - if (!isTokenAvailable) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { - if (isTokenExpired(accessToken)) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { - isTokenAvailable = true + if(userID.isNotEmpty() && password.isNotEmpty()) { + Log.d("istoken",isTokenAvailable.toString()) + if (!isTokenAvailable) { + Log.d("istoken1",isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + isTokenAvailable = true - hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) - hemoCubeViewModel.uploadLogs() - hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.downloadClientCertificate() - } - } - } else if (deviceId.isNotEmpty()) { + }else if(isTokenAvailable){ + Log.d("istoken7",isTokenAvailable.toString()) + isTokenAvailable = true + hemoCubeViewModel.startPeriodicCheckUpdate() + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + }else{ + if(isTokenExpired(accessToken)) { + Log.d("istoken8",isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + } + } + } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { fetchDeviceCredentials() - // This code will execute after credentials have been successfully fetched and stored. - userID = sharedPreference.getString("username", "").toString() - password = sharedPreference.getString("password", "").toString() - accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() - if (accessToken.isEmpty()) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { - // Continue with your existing logic if the token is not empty. - isTokenAvailable = true - hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) - hemoCubeViewModel.uploadLogs() - hemoCubeViewModel.startPeriodicCheckUpdate() - } } else { Toast.makeText( requireContext(), @@ -300,6 +324,9 @@ class HomeFragment : Fragment() { when (response) { is Result.Success -> { updateTokens(response) + response.data.data?.accessToken + isTokenAvailable = true + Log.d("istoken2",isTokenAvailable.toString()) } is Result.Error -> { @@ -321,6 +348,36 @@ class HomeFragment : Fragment() { } } + hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { + when (it) { + is Result.Success -> { + + Log.d("success,","uploded") + it.data.data?.forEach { id -> + id.rawData?.let { it1 -> + hemoCubeViewModel.updateMolbioFlag( + it1._id + ) + } + } + Toast.makeText(activity, "Molbio Result is successfully uploaded", Toast.LENGTH_LONG) + .show() + } + + is Result.Error -> { + binding.btnSubmit.visibility = View.VISIBLE + //Remove this line of code while deploying to IOCL + it.exception.let { message -> + Toast.makeText(activity, "$message", Toast.LENGTH_LONG) + .show() + Log.d("resultuploadfail", message.toString()) + } + } + + else -> {} + } + } + hemoCubeViewModel.uploadLogs.observe(viewLifecycleOwner) { response -> when (response) { is Result.Success -> { @@ -329,13 +386,14 @@ class HomeFragment : Fragment() { // "Log uploaded ${response.data.data?.filename}", // Toast.LENGTH_SHORT // ).show() + } is Result.Error -> { response.exception.let { message -> Toast.makeText( activity, - "An error occurred in uploading logs: $message", + "$message", Toast.LENGTH_LONG ) .show() @@ -350,28 +408,84 @@ class HomeFragment : Fragment() { } } + hemoCubeViewModel.checkUpdate.observe(viewLifecycleOwner) { response -> + when (response) { + is Result.Success -> { + val updatedversion = response.data.data?.version.toString() + val currentversion = + context?.let { ctx -> + val packageInfo = ctx.packageManager.getPackageInfo(ctx.packageName, 0) + val versionName = packageInfo.versionName + val versionCode: Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + // From Android P (API level 28), versionCode is deprecated and you should use longVersionCode instead. + packageInfo.longVersionCode + } else { + // For older Android versions, use versionCode (cast it to Long for consistency). + packageInfo.versionCode.toLong() + } + + // Use versionName and versionCode as needed + Log.d("AppInfo", "Version Name: $versionName, Version Code: $versionCode") + } + Log.d("versionnow",currentversion.toString()) + Log.d("versionnow",updatedversion.toString()) + if(updatedversion > currentversion.toString()){ + hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + Toast.makeText( + activity, + "new version ${response.data.data?.version} Available", + Toast.LENGTH_LONG + ) + .show() + }else{ + Toast.makeText( + activity, + "App is Up to date", + Toast.LENGTH_LONG + ) + .show() + } + } + + is Result.Error -> { +// response.exception.let { message -> +//// Toast.makeText( +//// activity, +//// "$message", +//// Toast.LENGTH_LONG +//// ) +//// .show() +// } + } + + is Result.Loading -> { + } + + else -> { + } + } + } + hemoCubeViewModel.downloadcertificate.observe(viewLifecycleOwner) { response -> when (response) { is Result.Success -> { val url = response.data - val fileName = "nats_certificate.zip" val downloadDirectory = "NATS" - val file = downloadFile(url, requireContext(), fileName, downloadDirectory) - Toast.makeText( - requireContext(), - "NATS certificate Downloaded", - Toast.LENGTH_SHORT - ).show() + val fileName = "nats_certificate.zip" + val unzipDirectoryPath = requireContext().getExternalFilesDir(null)?.absolutePath + "/$downloadDirectory" + + // Check if the directory with extracted files exists. + val directory = File(unzipDirectoryPath) + if (directory.exists() && directory.isDirectory) { + // Assuming if the directory exists, the certificate has been downloaded and extracted. + // You can add more specific checks here, e.g., checking for specific files within the directory. + Toast.makeText(requireContext(), "NATS certificate already downloaded and extracted.", Toast.LENGTH_SHORT).show() + return@observe + } + val file = downloadFile(url, requireContext(), fileName, downloadDirectory) - val unzipDirectoryPath = - requireContext().getExternalFilesDir(null)?.absolutePath + "/$downloadDirectory" unzip(file.absolutePath, unzipDirectoryPath) - Toast.makeText( - requireContext(), - "NATS certificate Extracted", - Toast.LENGTH_SHORT - ).show() } is Result.Error -> { @@ -393,44 +507,23 @@ class HomeFragment : Fragment() { } } - hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { - when (it) { - is Result.Success -> { - it.data.data?.forEach { id -> - id.rawData?.let { it1 -> - hemoCubeViewModel.updateMolbioFlag( - it1._id - ) - } - } - } - - is Result.Error -> { - binding.btnSubmit.visibility = View.VISIBLE - //Remove this line of code while deploying to IOCL - it.exception.let { message -> - Toast.makeText(activity, "An error occurred: $message", Toast.LENGTH_LONG) - .show() - } - } - - else -> {} - } - } - } private fun isTokenExpired(token: String): Boolean { - val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT)) - val jsonPayload = JSONObject(decodedPayload) + if(token.isNotEmpty()) { + val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT)) + val jsonPayload = JSONObject(decodedPayload) - val exp = jsonPayload.optLong("exp", 0) - val currentTimeSeconds = System.currentTimeMillis() / 1000 + val exp = jsonPayload.optLong("exp", 0) + val currentTimeSeconds = System.currentTimeMillis() / 1000 - return exp <= currentTimeSeconds + return exp <= currentTimeSeconds + }else{ + return false + } } private fun updateTokens(response: Result.Success) { @@ -443,6 +536,7 @@ class HomeFragment : Fragment() { apply() } isTokenAvailable = true + Log.d("istoken3",isTokenAvailable.toString()) } private fun createLoginRequestData(userID: String, password: String): LoginRequest { @@ -553,6 +647,7 @@ class HomeFragment : Fragment() { } } + @RequiresApi(Build.VERSION_CODES.P) private fun fetchDeviceCredentials() { try { val db = Firebase.firestore @@ -579,12 +674,16 @@ class HomeFragment : Fragment() { ) // Save credentials in SharedPreferences with(sharedPreference.edit()) { - putString("username", username) - putString("password", password) + putString(Constants.DEVICE_ID_API, username) + putString(Constants.DEVICE_PASSWORD_API, password) putString(Constants.NATS_TOKEN, natsToken) apply() } - hemoCubeViewModel.login(createLoginRequestData(username, password)) + if (!isTokenAvailable ) { + Log.d("istoken0", isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(username, password)) + } + } ?: Log.e("fetchDeviceCredentials", "Failed to parse device data.") } else { Log.e("fetchDeviceCredentials", "Document does not exist.") @@ -773,13 +872,28 @@ class HomeFragment : Fragment() { } } + private fun sanitizeDoubleValues(hemoCubeTestData: HemoCubeTestData): HemoCubeTestData { + hemoCubeTestData::class.java.declaredFields.forEach { field -> + if (field.type == Double::class.javaObjectType || field.type == Double::class.javaPrimitiveType) { + field.isAccessible = true + val value = field.get(hemoCubeTestData) as Double? + if (value != null && (value.isInfinite() || value.isNaN())) { + field.set(hemoCubeTestData, 0.0) // Replace with a suitable default value + } + } + } + return hemoCubeTestData + } + + + private fun showUploadDialog(context: Context) { val builder = AlertDialog.Builder(context) builder.setTitle(R.string.upload_db_registration_title) builder.setMessage(R.string.upload_db_registration_message) builder.setPositiveButton(R.string.upload) { dialog, _ -> - uploadLocalDBData(dialog) +// uploadLocalDBData(dialog) } builder.setNegativeButton(R.string.cancel) { dialog, _ -> @@ -825,34 +939,34 @@ class HomeFragment : Fragment() { hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> - if (!userData.molbioFlag && isTokenAvailable) { - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56", //userData.reportUploadTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, - testId = userData._id, - testTime = userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56",//userData.testTime, - ) - ) +// userDataList.forEach { userData -> +// if (!userData.molbioFlag && isTokenAvailable) { +// resultList.results?.add( +// MolbioV2Result( +// rawData = userData, +// analysisId = userData._id, +// analysisDate = "2024-02-08 16:33:56", //userData.reportUploadTime, +// analysisStatus = userData.classificationResult, +// thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), +// interpretation = userData.classificationResult, +// testId = userData._id, +// testTime = userData.testTime, +// collectionTime = "2024-02-08 16:33:56",//userData.testTime, +// expiryTime = "2024-02-08 16:33:56",//userData.testTime, +// ) +// ) +// +// } - } - - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) - } - } +// if (!userData.localFlag) { +// userData.localFlag = true +// hemoCubeViewModel.bulkAddResultTestToDb(userData) +// } +// if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { +// userData.molbioFlag = true +// hemoCubeViewModel.uploadResult(resultList) +// } +// } dialog.dismiss() } @@ -865,37 +979,6 @@ class HomeFragment : Fragment() { } dialog.dismiss() } - - hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> - val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> - if (!userData.molbioFlag && isTokenAvailable) { - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56",//userData.testTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, - testId = userData._id, - testTime = "2024-02-08 16:33:56",//userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56"//userData.testTime, - ) - ) - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) - } - - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } - - } - dialog.dismiss() - } } // private fun downloadLocalDBData(dialog: DialogInterface) { 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 172e9f4..fe98a4a 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 @@ -149,6 +149,7 @@ class HemoCubeFragment : Fragment() { hemoCubeViewModel.fireBaseUpload.observe(viewLifecycleOwner) { result -> if (result == "Success") { uploadedToCloud = true + var accessToken = sharedPreferences.getString(Constants.ACCESS_TOKEN, "").toString() showToast(R.string.test_upload) if (Constants.MOLBIO_INTEGRATION) { hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { @@ -161,6 +162,8 @@ class HemoCubeFragment : Fragment() { ) } handleReadingFinish() + hemoCubeViewModel.uploadLogs() + hemoCubeViewModel.downloadClientCertificate() } is Result.Error -> { 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 d50c442..47fc9a3 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 @@ -143,6 +143,14 @@ class HemoCubeViewModel @Inject constructor( } } + + fun uploadResultfornew(molbioV2ResultRequest: MolbioV2ResultRequest) = viewModelScope.launch { + resultUpload.postValue(Result.Loading()) + repository.uploadResults(molbioV2ResultRequest).let { + resultUpload.postValue(it) + } + } + fun checkUpdate(checkUpdateRequest: CheckUpdateRequest) = viewModelScope.launch { checkUpdate.postValue(Result.Loading()) repository.checkUpdate(checkUpdateRequest).let { @@ -367,7 +375,7 @@ class HemoCubeViewModel @Inject constructor( userData.reportUploadTime = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(Calendar.getInstance().time) - when (repository.addTestToDatabase(userData)) { + when (repository.addTestToDatabasefornew(userData)) { is Response.Success -> { fireBaseBulkUpload.postValue("Success") updateLocalFlag(userData._id) diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt index 27c27ca..99707fd 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt @@ -18,6 +18,7 @@ import android.util.Log import android.view.Menu import android.widget.Toast import androidx.activity.viewModels +import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.get @@ -44,6 +45,7 @@ open class HemocubeActivity : AppCompatActivity() { private val TAG = "HemoCube" private val broadcastReceiver = object : BroadcastReceiver() { + @RequiresApi(Build.VERSION_CODES.O) override fun onReceive(context: Context, intent: Intent) { synchronized(this) { @@ -83,6 +85,7 @@ open class HemocubeActivity : AppCompatActivity() { super.attachBaseContext(newBase) } + @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHemocubeBinding.inflate(layoutInflater) @@ -107,6 +110,7 @@ open class HemocubeActivity : AppCompatActivity() { } } + @RequiresApi(Build.VERSION_CODES.O) open fun connectUsb(permissionGranted: Boolean) { Log.d(TAG, "connectUsb() called, permission variable = $permissionGranted") val manager = getSystemService(Context.USB_SERVICE) as UsbManager @@ -126,6 +130,7 @@ open class HemocubeActivity : AppCompatActivity() { } } + @RequiresApi(Build.VERSION_CODES.O) @SuppressLint("MutableImplicitPendingIntent") private fun requestUserPermission(manager: UsbManager, device: UsbDevice) { val mPendingIntent: PendingIntent @@ -151,11 +156,13 @@ open class HemocubeActivity : AppCompatActivity() { manager.requestPermission(device, mPendingIntent) } + fun setupService() { val intent = Intent(this, UsbService::class.java) bindService(intent, connection, Context.BIND_AUTO_CREATE) } + @RequiresApi(Build.VERSION_CODES.O) open fun reconnectDevice() { mService.disconnect() unbindService(connection) diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 6e9c380..f6fa670 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -1,3 +1,3 @@ - + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 51a0b68..269daf3 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Mon Jun 12 17:07:47 IST 2023 +#Tue Feb 27 16:09:58 IST 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip