Compare commits
1 Commits
dev-server
...
dev-server
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67d98b1b27 |
@@ -125,4 +125,4 @@ publishTestResults:
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
junit: app/build/test-results/testDebugUnitTest/*.xml
|
||||
junit: app/build/test-results/testDebugUnitTest/*.xml
|
||||
@@ -21,7 +21,7 @@ android {
|
||||
minSdk 21
|
||||
targetSdk 34
|
||||
versionCode 130
|
||||
versionName "2.1.130 -usb"
|
||||
versionName "2.1.130"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ android {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
signingConfig signingConfigs.debug
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
@@ -64,7 +63,6 @@ android {
|
||||
dependencies {
|
||||
implementation "com.google.dagger:hilt-android:2.46"
|
||||
implementation 'androidx.activity:activity:1.8.0'
|
||||
implementation 'androidx.compose.ui:ui-android:1.7.6'
|
||||
kapt "com.google.dagger:hilt-android-compiler:2.46"
|
||||
|
||||
implementation 'androidx.core:core-ktx:1.12.0'
|
||||
|
||||
@@ -68,7 +68,6 @@
|
||||
<activity
|
||||
android:name="com.example.hpostesting.presentation.usb_teminal.UsbTerminalActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleInstance"
|
||||
android:screenOrientation="portrait" />
|
||||
<activity
|
||||
android:name="com.example.hpostesting.presentation.deviceinfo.DeviceActivity"
|
||||
@@ -199,7 +198,6 @@
|
||||
android:exported="true"
|
||||
android:permission=""
|
||||
android:screenOrientation="portrait"
|
||||
android:launchMode="singleInstance"
|
||||
android:theme="@style/AppTheme.NoActionBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
|
||||
|
||||
@@ -73,15 +73,8 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
sharedPreference = getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE)
|
||||
val action = intent?.action
|
||||
if (action == UsbManager.ACTION_USB_DEVICE_ATTACHED || action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
|
||||
// If the activity is triggered by USB events, simply finish it
|
||||
checkAndUpdateUsbConnection()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
binding = ActivityMainBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
binding.myToolbar.title = "Test Type"
|
||||
@@ -157,7 +150,7 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
(device.productId == 24577 && device.vendorId == 1027) || (device.productId == 8963 && device.vendorId == 1659) || (device.productId == 4614 && device.vendorId == 7111) -> {
|
||||
// changeUI()
|
||||
changeUI()
|
||||
DataHolder.deviceType.postValue(Constants.DEVICE_TYPE_TRUEHEME)
|
||||
Constants.DEVICE_TYPE_TRUEHEME
|
||||
}
|
||||
|
||||
@@ -116,7 +116,6 @@ class GalleryFragment : Fragment() {
|
||||
binding.btnUsbTerminal.setOnClickListener {
|
||||
startActivity(Intent(requireContext(), UsbTerminalActivity::class.java))
|
||||
}
|
||||
|
||||
binding.btnSubmit.setOnClickListener {
|
||||
startActivity(Intent(requireContext(), HemocubeBufferCheckActivity::class.java))
|
||||
}
|
||||
|
||||
@@ -36,7 +36,11 @@ import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.get
|
||||
import com.example.hpostesting.data.constant.Constants
|
||||
import com.example.hpostesting.data.constant.DataHolder
|
||||
import com.example.hpostesting.data.constant.HemoCubeCommands
|
||||
import com.example.hpostesting.data.constant.LanguageManager
|
||||
import com.example.hpostesting.presentation.deviceinfo.DeviceFragment
|
||||
import com.example.hpostesting.presentation.utils.DeviceCommunicationHandler
|
||||
import com.example.hpostesting.presentation.utils.UsbServiceListener
|
||||
import com.example.hpostesting.util.UsbService
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
@@ -55,47 +59,35 @@ class UsbTerminalActivity : AppCompatActivity() {
|
||||
private var mConnection: UsbDeviceConnection? = null
|
||||
lateinit var mService: UsbService
|
||||
private var deviceId = ""
|
||||
private var isResuming = false
|
||||
private val TAG = "Calibration"
|
||||
|
||||
private val broadcastReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
|
||||
synchronized(this) {
|
||||
val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
|
||||
|
||||
when (intent.action) {
|
||||
UsbManager.ACTION_USB_DEVICE_DETACHED -> {
|
||||
Log.d(TAG, "USB device detached")
|
||||
cleanupUsb()
|
||||
DataHolder.usbConnected.postValue(false)
|
||||
}
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
|
||||
Log.d(TAG, "USB device attached")
|
||||
isResuming = true
|
||||
connectUsb(false)
|
||||
}
|
||||
else -> {
|
||||
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
|
||||
device?.let {
|
||||
connectUsb(true)
|
||||
DataHolder.usbConnected.postValue(true)
|
||||
}
|
||||
} else {
|
||||
Log.e(TAG, "USB permission denied")
|
||||
DataHolder.usbConnected.postValue(false)
|
||||
}
|
||||
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
|
||||
device?.apply {
|
||||
connectUsb(true)
|
||||
DataHolder.usbConnected.postValue(true)
|
||||
}
|
||||
} else {
|
||||
onErrorReported("permission denied for device")
|
||||
DataHolder.usbConnected.postValue(true)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private val connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(className: ComponentName, service: IBinder) {
|
||||
val binder = service as UsbService.UsbServiceBinder
|
||||
mService = binder.getService()
|
||||
usbTerminalViewModel.isServiceConnected = true
|
||||
mConnection?.let { mService.connect(mDriver, it) }
|
||||
mConnection.let { mService.connect(mDriver, mConnection!!) }
|
||||
moveToNext()
|
||||
}
|
||||
|
||||
@@ -114,34 +106,21 @@ class UsbTerminalActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityUsbTerminalBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
sharedPreferences = getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE)
|
||||
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
addAction(Constants.HEMOCUBE_USB_PERMISSION)
|
||||
}
|
||||
registerReceiver(broadcastReceiver, filter)
|
||||
|
||||
// setSupportActionBar(binding.myToolbar)
|
||||
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
||||
setupListener()
|
||||
connectUsb(false)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
isResuming = true
|
||||
connectUsb(false)
|
||||
}
|
||||
|
||||
private fun setupListener() {
|
||||
DataHolder.usbConnected.observe(this) { isConnected ->
|
||||
Log.d("USB OBSERVE", "HemoCube called -> $isConnected")
|
||||
myMenu?.get(0)?.icon = ContextCompat.getDrawable(
|
||||
this,
|
||||
if (isConnected) R.drawable.ic_baseline_usb_24
|
||||
else R.drawable.ic_baseline_usb_off_24
|
||||
)
|
||||
if (!isConnected) {
|
||||
DataHolder.usbConnected.observe(this) {
|
||||
Log.d("USB OBSERVE", "HemoCube called -> $it")
|
||||
if (it) {
|
||||
myMenu?.get(0)?.icon =
|
||||
ContextCompat.getDrawable(this, R.drawable.ic_baseline_usb_24)
|
||||
} else {
|
||||
myMenu?.get(0)?.icon =
|
||||
ContextCompat.getDrawable(this, R.drawable.ic_baseline_usb_off_24)
|
||||
Toast.makeText(this, "Device is Disconnected", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
@@ -149,78 +128,55 @@ class UsbTerminalActivity : AppCompatActivity() {
|
||||
|
||||
open fun connectUsb(permissionGranted: Boolean) {
|
||||
Log.d(TAG, "connectUsb() called, permission variable = $permissionGranted")
|
||||
val manager = getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
|
||||
|
||||
try {
|
||||
val manager = getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
|
||||
|
||||
if (availableDrivers.isEmpty()) {
|
||||
onErrorReported("No Device Connected")
|
||||
DataHolder.usbConnected.postValue(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (availableDrivers.isEmpty()) {
|
||||
onErrorReported("No Device is Connected")
|
||||
} else {
|
||||
mDriver = availableDrivers[0]
|
||||
mConnection = manager.openDevice(mDriver.device)
|
||||
|
||||
when {
|
||||
mConnection == null -> requestUserPermission(manager, mDriver.device)
|
||||
else -> {
|
||||
setupService()
|
||||
DataHolder.usbConnected.postValue(true)
|
||||
|
||||
// Ensure fragment is loaded and state is restored
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
(supportFragmentManager.findFragmentById(binding.fgDevice.id) as? UsbTerminalFragment)?.let {
|
||||
it.loadCommandState()
|
||||
it.resumeExecution()
|
||||
}
|
||||
}, 1000) // Slightly longer delay to ensure stability
|
||||
|
||||
isResuming = false
|
||||
}
|
||||
if (mConnection == null) {
|
||||
requestUserPermission(manager, mDriver.device)
|
||||
} else {
|
||||
setupService()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "USB Connection Error: ${e.message}")
|
||||
onErrorReported("USB Connection Failed: ${e.localizedMessage}")
|
||||
DataHolder.usbConnected.postValue(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun onErrorReported(msg: String) {
|
||||
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
||||
if (!isFinishing) onBackPressed()
|
||||
}
|
||||
|
||||
private fun moveToNext() {
|
||||
if (!supportFragmentManager.isDestroyed) {
|
||||
supportFragmentManager.beginTransaction()
|
||||
.replace(binding.fgDevice.id, UsbTerminalFragment())
|
||||
.commit()
|
||||
}
|
||||
if (supportFragmentManager.isDestroyed) return
|
||||
|
||||
supportFragmentManager.beginTransaction().replace(binding.fgDevice.id, UsbTerminalFragment())
|
||||
.commit()
|
||||
}
|
||||
|
||||
@SuppressLint("MutableImplicitPendingIntent")
|
||||
private fun requestUserPermission(manager: UsbManager, device: UsbDevice) {
|
||||
val mPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
PendingIntent.getBroadcast(
|
||||
this, 0,
|
||||
Intent(Constants.HEMOCUBE_USB_PERMISSION),
|
||||
PendingIntent.FLAG_MUTABLE
|
||||
val mPendingIntent: PendingIntent
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
|
||||
mPendingIntent = PendingIntent.getBroadcast(
|
||||
this, 0, Intent(Constants.HEMOCUBE_USB_PERMISSION), PendingIntent.FLAG_MUTABLE
|
||||
)
|
||||
} else {
|
||||
PendingIntent.getBroadcast(
|
||||
this, 0,
|
||||
mPendingIntent = PendingIntent.getBroadcast(
|
||||
this,
|
||||
0,
|
||||
Intent(Constants.HEMOCUBE_USB_PERMISSION),
|
||||
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
|
||||
registerReceiver(
|
||||
broadcastReceiver,
|
||||
IntentFilter(Constants.HEMOCUBE_USB_PERMISSION)
|
||||
)
|
||||
val filter = IntentFilter(Constants.HEMOCUBE_USB_PERMISSION)
|
||||
registerReceiver(broadcastReceiver, filter)
|
||||
manager.requestPermission(device, mPendingIntent)
|
||||
}
|
||||
|
||||
fun onErrorReported(msg: String) {
|
||||
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
fun setupService() {
|
||||
val intent = Intent(this, UsbService::class.java)
|
||||
bindService(intent, connection, Context.BIND_AUTO_CREATE)
|
||||
@@ -228,31 +184,15 @@ class UsbTerminalActivity : AppCompatActivity() {
|
||||
|
||||
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
|
||||
menuInflater.inflate(R.menu.my_menu, menu)
|
||||
myMenu = menu
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
unregisterReceiver(broadcastReceiver)
|
||||
if (usbTerminalViewModel.isServiceConnected) {
|
||||
mService.disconnect()
|
||||
unbindService(connection)
|
||||
usbTerminalViewModel.isServiceConnected = false
|
||||
}
|
||||
cleanupUsb()
|
||||
}
|
||||
|
||||
private fun cleanupUsb() {
|
||||
try {
|
||||
if (usbTerminalViewModel.isServiceConnected) {
|
||||
mService.disconnect()
|
||||
unbindService(connection)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during USB cleanup: ${e.message}")
|
||||
}
|
||||
mConnection?.close()
|
||||
mConnection = null
|
||||
}
|
||||
}
|
||||
@@ -13,276 +13,94 @@
|
||||
|
||||
package com.example.hpostesting.presentation.usb_teminal
|
||||
|
||||
// Fragment Class
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.text.method.ScrollingMovementMethod
|
||||
import android.util.Log
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import com.example.hpostesting.data.constant.HemoCubeCommands
|
||||
import com.example.hpostesting.presentation.utils.UsbServiceListener
|
||||
import com.google.firebase.crashlytics.ktx.crashlytics
|
||||
import com.google.firebase.ktx.Firebase
|
||||
import `in`.sminnovations.hpostesting.databinding.FragmentUsbTerminalBinding
|
||||
// UsbTerminalFragment.kt
|
||||
|
||||
|
||||
class UsbTerminalFragment : Fragment() {
|
||||
private lateinit var binding: FragmentUsbTerminalBinding
|
||||
private val usbTerminalViewModel: UsbTerminalViewModel by activityViewModels()
|
||||
private lateinit var sharedPreferences: SharedPreferences
|
||||
private var startListening = MutableLiveData(false)
|
||||
private var resultData = StringBuilder()
|
||||
private var commandQueue: MutableList<String> = mutableListOf()
|
||||
private var currentCommand: String? = null
|
||||
private var isExecuting = false
|
||||
|
||||
companion object {
|
||||
private const val PREF_COMMAND_QUEUE = "command_queue"
|
||||
private const val PREF_CURRENT_COMMAND = "current_command"
|
||||
private const val PREF_RESULT_DATA = "result_data"
|
||||
private const val PREF_EXECUTION_STATE = "execution_state"
|
||||
}
|
||||
|
||||
private var resultData: String = ""
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
|
||||
): View {
|
||||
binding = FragmentUsbTerminalBinding.inflate(inflater, container, false)
|
||||
sharedPreferences = requireContext().getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE)
|
||||
setupClickListeners()
|
||||
sharedPreferences =
|
||||
requireContext().getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
initViews()
|
||||
loadCommandState()
|
||||
}
|
||||
|
||||
private fun setupClickListeners() {
|
||||
binding.clearQueueButton.setOnClickListener { clearQueue() }
|
||||
binding.sendCommand.setOnClickListener {
|
||||
binding.etCommands.text.toString().trim().let { commands ->
|
||||
if (commands.isNotEmpty()) {
|
||||
addToQueue(commands)
|
||||
binding.etCommands.text.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initViews() {
|
||||
binding.messageCommand.apply {
|
||||
movementMethod = ScrollingMovementMethod()
|
||||
binding.messageCommand.movementMethod = ScrollingMovementMethod()
|
||||
usbTerminalViewModel.messages.observe(viewLifecycleOwner) {
|
||||
binding.messageCommand.text = it
|
||||
}
|
||||
|
||||
usbTerminalViewModel.messages.observe(viewLifecycleOwner) { message ->
|
||||
binding.messageCommand.text = message
|
||||
scrollToBottom()
|
||||
binding.sendCommand.setOnClickListener {
|
||||
callCommand(binding.etCommands.text.trim().toString())
|
||||
}
|
||||
|
||||
listenToHemoCube()
|
||||
callCommand("I")
|
||||
}
|
||||
|
||||
private fun addToQueue(commandStr: String) {
|
||||
val commands = if (commandStr.contains(" ")) {
|
||||
commandStr.split("").filter { it.isNotBlank() }
|
||||
} else {
|
||||
listOf(commandStr)
|
||||
}
|
||||
|
||||
commandQueue.addAll(commands)
|
||||
saveCommandState()
|
||||
appendFormattedMessage("\nAdded commands to queue: ${commands.joinToString(" ")}")
|
||||
processNextCommand()
|
||||
}
|
||||
|
||||
|
||||
|
||||
fun loadCommandState() {
|
||||
val prefs = sharedPreferences
|
||||
prefs.apply {
|
||||
// Restore command queue
|
||||
val savedQueue = getStringSet(PREF_COMMAND_QUEUE, setOf())?.toMutableList() ?: mutableListOf()
|
||||
commandQueue.clear()
|
||||
commandQueue.addAll(savedQueue)
|
||||
|
||||
// Restore current command
|
||||
currentCommand = getString(PREF_CURRENT_COMMAND, null)
|
||||
|
||||
// Restore result data
|
||||
getString(PREF_RESULT_DATA, null)?.let {
|
||||
resultData = StringBuilder(it)
|
||||
usbTerminalViewModel.messages.postValue(it)
|
||||
}
|
||||
|
||||
// Restore execution state
|
||||
isExecuting = getBoolean(PREF_EXECUTION_STATE, false)
|
||||
}
|
||||
}
|
||||
|
||||
fun resumeExecution() {
|
||||
try {
|
||||
// Force re-establish connection and resume
|
||||
if (currentCommand != null || commandQueue.isNotEmpty()) {
|
||||
// Slight delay to ensure USB connection is stable
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
processNextCommand()
|
||||
}, 500)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("UsbTerminalFragment", "Error resuming execution: ${e.message}")
|
||||
appendFormattedMessage("Error resuming: ${e.localizedMessage}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun processNextCommand() {
|
||||
if (!isExecuting && currentCommand == null && commandQueue.isNotEmpty()) {
|
||||
currentCommand = commandQueue.removeAt(0)
|
||||
isExecuting = true
|
||||
saveCommandState()
|
||||
callCommand(currentCommand!!)
|
||||
}
|
||||
}
|
||||
|
||||
private fun callCommand(command: String) {
|
||||
try {
|
||||
val usbActivity = activity as? UsbTerminalActivity
|
||||
usbActivity?.mService?.let { service ->
|
||||
usbTerminalViewModel.progressBar.postValue(true)
|
||||
appendFormattedMessage("Sending command: $command \n")
|
||||
usbTerminalViewModel.progressBar.postValue(true)
|
||||
(activity as UsbTerminalActivity).mService.sendAndListenToHemoCubeTxt(
|
||||
command,
|
||||
object : UsbServiceListener {
|
||||
override fun onUsbRead(data: ByteArray?) {
|
||||
//nothing
|
||||
}
|
||||
|
||||
service.sendAndListenToHemoCubeTxt(
|
||||
command,
|
||||
object : UsbServiceListener {
|
||||
override fun onUsbRead(data: ByteArray?) {
|
||||
// Optional: Handle read if needed
|
||||
}
|
||||
|
||||
override fun onUsbError(e: Exception?) {
|
||||
activity?.runOnUiThread {
|
||||
handleCommandError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} ?: run {
|
||||
// If service is not available, log and handle error
|
||||
Log.e("UsbTerminalFragment", "USB Service not available")
|
||||
handleCommandError(Exception("USB Service not available"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
handleCommandError(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleCommandError(e: Exception?) {
|
||||
val errorMessage = e?.localizedMessage ?: "Unknown error"
|
||||
Log.e("UsbTerminalFragment", "Command error: $errorMessage")
|
||||
|
||||
appendFormattedMessage("Error: $errorMessage")
|
||||
|
||||
// Ensure we don't completely stop execution
|
||||
usbTerminalViewModel.progressBar.postValue(false)
|
||||
isExecuting = false
|
||||
|
||||
// Important: Do NOT clear the current command or queue
|
||||
saveCommandState()
|
||||
|
||||
// Try to process next command
|
||||
processNextCommand()
|
||||
override fun onUsbError(e: Exception?) {
|
||||
usbTerminalViewModel.progressBar.postValue(false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun listenToHemoCube() {
|
||||
|
||||
val fullReadOutput = StringBuilder()
|
||||
startListening.postValue(true)
|
||||
|
||||
try {
|
||||
(activity as? UsbTerminalActivity)?.mService?.listenToHemoCube(
|
||||
object : UsbServiceListener {
|
||||
override fun onUsbRead(data: ByteArray?) {
|
||||
data?.let { handleUsbData(String(it)) }
|
||||
}
|
||||
|
||||
override fun onUsbError(e: Exception?) {
|
||||
activity?.runOnUiThread {
|
||||
Log.e("UsbTerminalFragment", "USB Listen Error: ${e?.message}")
|
||||
// Do not completely stop execution
|
||||
appendFormattedMessage("USB Listen Error: ${e?.localizedMessage}")
|
||||
}
|
||||
(activity as UsbTerminalActivity).mService.listenToHemoCube(object : UsbServiceListener {
|
||||
override fun onUsbRead(data: ByteArray?) {
|
||||
data?.let {
|
||||
val stringData = String(it)
|
||||
fullReadOutput.append(stringData)
|
||||
resultData += stringData
|
||||
usbTerminalViewModel.messages.postValue(resultData)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
override fun onUsbError(e: Exception?) {
|
||||
usbTerminalViewModel.messages.postValue(e!!.localizedMessage)
|
||||
usbTerminalViewModel.progressBar.postValue(false)
|
||||
}
|
||||
})
|
||||
} catch (e: Exception) {
|
||||
Log.e("UsbTerminalFragment", "Error setting up USB listener: ${e.message}")
|
||||
appendFormattedMessage("Error setting up USB listener: ${e.localizedMessage}")
|
||||
usbTerminalViewModel.messages.postValue(e.localizedMessage)
|
||||
Firebase.crashlytics.recordException(e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun handleUsbData(stringData: String) {
|
||||
resultData.append(stringData)
|
||||
|
||||
activity?.runOnUiThread {
|
||||
usbTerminalViewModel.messages.postValue(resultData.toString())
|
||||
scrollToBottom()
|
||||
|
||||
if (currentCommand != null && stringData.contains("${currentCommand}C")) {
|
||||
isExecuting = false
|
||||
currentCommand = null
|
||||
|
||||
if (commandQueue.isEmpty()) {
|
||||
sharedPreferences.edit().clear().apply()
|
||||
appendFormattedMessage("\nAll commands completed")
|
||||
} else {
|
||||
processNextCommand()
|
||||
}
|
||||
saveCommandState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearQueue() {
|
||||
commandQueue.clear()
|
||||
currentCommand = null
|
||||
isExecuting = false
|
||||
saveCommandState()
|
||||
appendFormattedMessage("\nCommand queue cleared")
|
||||
}
|
||||
|
||||
private fun scrollToBottom() {
|
||||
binding.messageCommand.post {
|
||||
(binding.messageCommand.layout.getLineTop(binding.messageCommand.lineCount) -
|
||||
binding.messageCommand.height).takeIf { it > 0 }?.let {
|
||||
binding.messageCommand.scrollTo(0, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendFormattedMessage(message: String) {
|
||||
resultData.append("\n").append(message)
|
||||
usbTerminalViewModel.messages.postValue(resultData.toString())
|
||||
scrollToBottom()
|
||||
}
|
||||
private fun saveCommandState() {
|
||||
sharedPreferences.edit().apply {
|
||||
putStringSet(PREF_COMMAND_QUEUE, commandQueue.toSet())
|
||||
putString(PREF_CURRENT_COMMAND, currentCommand)
|
||||
putString(PREF_RESULT_DATA, resultData.toString())
|
||||
putBoolean(PREF_EXECUTION_STATE, isExecuting)
|
||||
apply()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
startListening.value = false
|
||||
clearQueue()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class UsbTerminalViewModel @Inject constructor(
|
||||
private val hemoCubeDao: HemoCubeDao,
|
||||
private val repository: Repository,
|
||||
) : ViewModel() {
|
||||
var isServiceConnected = false
|
||||
val progressBar = MutableLiveData(false)
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:autoMirrored="true" android:height="24dp" android:tint="#000000" android:viewportHeight="24" android:viewportWidth="24" android:width="24dp">
|
||||
|
||||
<path android:fillColor="@android:color/white" android:pathData="M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z"/>
|
||||
|
||||
</vector>
|
||||
@@ -11,51 +11,59 @@
|
||||
~ // from ShanMukha Innovations Pvt. Ltd.
|
||||
-->
|
||||
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
<RelativeLayout
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<Button
|
||||
android:id="@+id/clearQueueButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Clar All Commands" />
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/messageCommand"
|
||||
android:id="@+id/message_command"
|
||||
style="@style/title1_1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:background="@android:color/darker_gray"
|
||||
android:padding="8dp"
|
||||
android:scrollbars="vertical"
|
||||
android:textColor="@android:color/white" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginTop="10dp"
|
||||
android:gravity="start|bottom"
|
||||
android:text="Start"
|
||||
android:scrollbars = "vertical"
|
||||
android:layout_alignParentStart="true"
|
||||
android:layout_alignParentEnd="true"
|
||||
android:layout_above="@+id/ll_commands"
|
||||
android:visibility="visible"
|
||||
android:textColor="@color/black"
|
||||
android:textSize="18sp"
|
||||
/>
|
||||
<RelativeLayout
|
||||
android:id="@+id/ll_commands"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:layout_alignParentEnd="true"
|
||||
android:layout_alignParentStart="true"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<EditText
|
||||
android:id="@+id/etCommands"
|
||||
android:layout_width="0dp"
|
||||
android:id="@+id/et_commands"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:hint="Enter command"
|
||||
android:inputType="text"
|
||||
android:maxLines="1"
|
||||
android:minHeight="48dp" />
|
||||
android:layout_marginTop="10dp"
|
||||
android:hint="@string/commands"
|
||||
android:layout_alignParentStart="true"
|
||||
android:imeOptions="actionDone"
|
||||
android:textSize="18sp"
|
||||
android:layout_marginBottom="10dp"
|
||||
/>
|
||||
<ImageView
|
||||
android:id="@+id/send_command"
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="26dp"
|
||||
android:layout_alignParentEnd="true"
|
||||
android:layout_centerInParent="true"
|
||||
android:src="@drawable/ic_baseline_send_24"/>
|
||||
</RelativeLayout>
|
||||
|
||||
<Button
|
||||
android:id="@+id/sendCommand"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:text="Send" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
</RelativeLayout>
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
-->
|
||||
|
||||
<resources>
|
||||
<string name="app_name">HPOS ALPHA Testing</string>
|
||||
<string name="app_name">HPOS Testing</string>
|
||||
|
||||
<string-array name="instrument">
|
||||
<item>TestRight</item>
|
||||
|
||||
Reference in New Issue
Block a user