Implement Device Pairing and Config screens

This commit is contained in:
Hy4ri committed 2026-06-16 00:02:05 +03:00
1 parent d6ff3de594
commit a8cf79d91c
10 files changed
+773 -24

No files matched your search

@@ -0,0 +1,271 @@
package com.m57.hermescontrol.ui.pairing
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PairingScreen(
modifier: Modifier = Modifier,
onOpenDrawer: (() -> Unit)? = null,
viewModel: PairingViewModel = viewModel { PairingViewModel() },
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
LaunchedEffect(Unit) {
viewModel.loadPairing()
}
LaunchedEffect(state.toastMessage) {
state.toastMessage?.let { msg ->
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
viewModel.clearToast()
}
}
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
if (onOpenDrawer != null) {
IconButton(onClick = onOpenDrawer) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Open Drawer",
)
}
}
},
title = { Text("Device Pairing") },
actions = {
IconButton(onClick = { viewModel.loadPairing() }) {
Icon(imageVector = Icons.Filled.Refresh, contentDescription = "Refresh")
}
},
)
},
modifier = modifier,
) { paddingValues ->
Box(
modifier =
Modifier
.fillMaxSize()
.padding(paddingValues),
) {
if (state.isLoading && state.pairing == null) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
} else if (state.errorMessage != null && state.pairing == null) {
Column(
modifier =
Modifier
.align(Alignment.Center)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(text = state.errorMessage ?: "", color = MaterialTheme.colorScheme.error)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { viewModel.loadPairing() }) {
Text("Retry")
}
}
} else {
val pairing = state.pairing
val pending = pairing?.pending.orEmpty()
val approved = pairing?.approved.orEmpty()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
if (pending.isNotEmpty()) {
item {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = "Pending Approvals",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
OutlinedButton(
onClick = { viewModel.clearPending() },
colors =
ButtonDefaults.outlinedButtonColors(
contentColor = MaterialTheme.colorScheme.error,
),
) {
Text("Clear All")
}
}
}
items(pending) { item ->
Card(
modifier = Modifier.fillMaxWidth(),
colors =
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.2f),
),
) {
Row(
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Platform: ${item.platform.uppercase()}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
item.code?.let {
Text(
text = "Pairing Code: $it",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
)
}
}
Button(
onClick = {
viewModel.approvePairing(item.platform, item.code ?: "")
},
colors =
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
),
) {
Text("Approve")
}
}
}
}
}
item {
Text(
text = "Approved Devices",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
}
if (approved.isEmpty()) {
item {
Card(
modifier = Modifier.fillMaxWidth(),
) {
Box(
modifier =
Modifier
.fillMaxWidth()
.padding(24.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = "No approved devices paired yet.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
} else {
items(approved) { item ->
Card(
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Platform: ${item.platform.uppercase()}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
text = "User ID: ${item.user_id ?: "Unknown"}",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
item.username?.let {
Text(
text = "Username: @$it",
style = MaterialTheme.typography.bodySmall,
)
}
}
OutlinedButton(
onClick = {
viewModel.revokePairing(item.platform, item.user_id ?: "")
},
colors =
ButtonDefaults.outlinedButtonColors(
contentColor = MaterialTheme.colorScheme.error,
),
) {
Text("Revoke")
}
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,120 @@
package com.m57.hermescontrol.ui.pairing
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.m57.hermescontrol.data.model.PairingApproveRequest
import com.m57.hermescontrol.data.model.PairingResponse
import com.m57.hermescontrol.data.model.PairingRevokeRequest
import com.m57.hermescontrol.data.remote.ApiClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
data class PairingUiState(
val isLoading: Boolean = false,
val isActionRunning: Boolean = false,
val pairing: PairingResponse? = null,
val errorMessage: String? = null,
val toastMessage: String? = null,
)
class PairingViewModel : ViewModel() {
private val _uiState = MutableStateFlow(PairingUiState())
val uiState: StateFlow<PairingUiState> = _uiState.asStateFlow()
fun loadPairing() {
_uiState.update { it.copy(isLoading = true, errorMessage = null) }
viewModelScope.launch {
try {
val response =
withContext(Dispatchers.IO) {
ApiClient.hermesApi.getPairing()
}
if (response.isSuccessful) {
_uiState.update { it.copy(isLoading = false, pairing = response.body()) }
} else {
_uiState.update {
it.copy(
isLoading = false,
errorMessage = "Failed to load pairing info: HTTP ${response.code()}",
)
}
}
} catch (e: Exception) {
_uiState.update {
it.copy(
isLoading = false,
errorMessage = "Failed to load pairing info: ${e.message}",
)
}
}
}
}
fun approvePairing(
platform: String,
code: String,
) {
runAction("Approve") {
ApiClient.hermesApi.approvePairing(PairingApproveRequest(platform, code))
}
}
fun revokePairing(
platform: String,
userId: String,
) {
runAction("Revoke") {
ApiClient.hermesApi.revokePairing(PairingRevokeRequest(platform, userId))
}
}
fun clearPending() {
runAction("Clear Pending") {
ApiClient.hermesApi.clearPendingPairing()
}
}
private fun runAction(
actionName: String,
apiCall: suspend () -> retrofit2.Response<Unit>,
) {
_uiState.update { it.copy(isActionRunning = true) }
viewModelScope.launch {
try {
val response = withContext(Dispatchers.IO) { apiCall() }
if (response.isSuccessful) {
_uiState.update {
it.copy(
isActionRunning = false,
toastMessage = "Pairing action '$actionName' succeeded",
)
}
loadPairing()
} else {
_uiState.update {
it.copy(
isActionRunning = false,
toastMessage = "Action '$actionName' failed: HTTP ${response.code()}",
)
}
}
} catch (e: Exception) {
_uiState.update {
it.copy(
isActionRunning = false,
toastMessage = "Action '$actionName' failed: ${e.message}",
)
}
}
}
}
fun clearToast() {
_uiState.update { it.copy(toastMessage = null) }
}
}