Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config reading #252

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 41 additions & 23 deletions zeapp/android/src/main/java/de/berlindroid/zeapp/ZeMainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.rounded.Lock
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.Button
Expand All @@ -47,6 +48,7 @@ import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
Expand Down Expand Up @@ -655,13 +657,13 @@ private fun InfoBar(
@Composable
@Preview
private fun BadgeConfigEditor(
config: Map<String, String> = mapOf(
config: Map<String, Any?> = mapOf(
"sample configuration" to "sample value",
"sample int" to "23",
"another configuration" to "true",
"sample int" to 23,
"another configuration" to true,
),
onDismissRequest: () -> Unit = {},
onConfirmed: (updateConfig: Map<String, String>) -> Unit = {},
onConfirmed: (updateConfig: Map<String, Any?>) -> Unit = {},
) {
var configState by remember { mutableStateOf(config) }
var error by remember { mutableStateOf(mapOf<String, String>()) }
Expand Down Expand Up @@ -695,26 +697,42 @@ private fun BadgeConfigEditor(
text = {
LazyColumn {
items(config.keys.toList()) { key ->
val value = configState[key]

AutoSizeTextField(
value = "$value",
isError = !error[key].isNullOrEmpty(),
onValueChange = { updated ->
if (updated != value) {
error = error.copy(key to "")
configState = configState.copy(
key to updated,
when (val value = configState[key]) {
is Boolean -> AutoSizeTextField(
value = value.toString(),
label = { Text("$key (read only)") },
onValueChange = { },
placeholder = {},
trailingIcon = {
Icon(
Icons.Rounded.Lock,
tint = ZeBlack,
contentDescription = null,
)
}
},
label = { Text(text = key) },
supportingText = {
Text(text = error.getOrDefault(key, ""))
},
trailingIcon = {},
placeholder = {},
)
},
supportingText = { },
)

else -> AutoSizeTextField(
value = "$value",
isError = !error[key].isNullOrEmpty(),
onValueChange = { updated ->
if (updated != value) {
error = error.copy(key to "")
configState = configState.copy(
key to updated,
)
}
},
label = { Text(text = key) },
supportingText = {
Text(text = error.getOrDefault(key, ""))
},
trailingIcon = {},
placeholder = {},
)

}
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ import de.berlindroid.zekompanion.base64
import de.berlindroid.zekompanion.buildBadgeManager
import de.berlindroid.zekompanion.toBinary
import de.berlindroid.zekompanion.zipit
import timber.log.Timber
import javax.inject.Inject

private const val SPACE_REPLACEMENT = "\$SPACE#"

class ZeBadgeManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
Expand Down Expand Up @@ -81,55 +84,103 @@ class ZeBadgeManager @Inject constructor(
/**
* Return the current active configuration.
*/
suspend fun listConfiguration(): Result<Map<String, String>> {
suspend fun listConfiguration(): Result<Map<String, Any?>> {
val payload = BadgePayload(
type = "config_list",
meta = "",
payload = "",
)

if (badgeManager.sendPayload(payload).isSuccess) {
val responses = mutableListOf<Result<String>>()
while (true) {
val response = badgeManager.readResponse()
if (response.isSuccess) {
responses += response
} else {
break
}
}

val successful = responses.filter { it.isSuccess }.joinToString(separator = "\n") {
it.getOrDefault("")
val response = badgeManager.readResponse()
if (response.isSuccess) {
val config = response.getOrDefault("")
Timber.v("Badge sent response: successfully received configuration: '${config.replace("\n", "\\n")}'.")

val kv = mapOf(
*config.split(" ").mapNotNull {
if ("=" in it) {
val (key, value) = it.split("=")
val typedValue = pythonToKotlin(value)
key to typedValue
} else {
Timber.v("Config '$it' is malformed, ignoring it.")
null
}
}.toTypedArray(),
)
return Result.success(kv)
}

print("message: '$successful'")
val kv = mapOf(
*successful.split(",").map {
val (k, v) = it.split(" = ")
k to v
}.toTypedArray(),
)
return Result.success(kv)
return Result.failure(IllegalStateException("Could not read response."))
} else {
return Result.failure(NoSuchElementException())
return Result.failure(NoSuchElementException("Sending command failed."))
}
}

/**
* Update configuration on badge..
*/
suspend fun updateConfiguration(configuration: Map<String, String>): Result<Int> {
val config = configuration.entries.joinToString(separator = ",")
suspend fun updateConfiguration(configuration: Map<String, Any?>): Result<Any> {

val detypedConfig: Map<String, String> = configuration.map { e ->
val (k, v) = e
k to kotlinToPython(v)
}.toMap()

val config = detypedConfig.entries.joinToString(separator = " ")

val payload = BadgePayload(
type = "config_update",
meta = "",
payload = config,
)

return badgeManager.sendPayload(payload)
if (badgeManager.sendPayload(payload).isSuccess) {

if (badgeManager.sendPayload(
BadgePayload(
type = "config_save",
meta = "",
payload = "",
),
).isSuccess
) {
return Result.success(true)
} else {
return Result.failure(IllegalStateException("Could not save the config to ZeBadge."))
}
} else {
return Result.failure(NoSuchElementException("Could not update the runtime configuration on ZeBadge."))
}
}

fun isConnected(): Boolean = badgeManager.isConnected()
}

private fun pythonToKotlin(value: String): Any? = when {
value.startsWith("\"") ->
value
.replace("\"", "")
.replace(SPACE_REPLACEMENT, " ")


value.startsWith("\'") ->
value
.replace("\'", "")
.replace(SPACE_REPLACEMENT, " ")


value == "None" -> null
value.toIntOrNull() != null -> value.toInt()
value.toFloatOrNull() != null -> value.toFloat()
value == "True" -> true
value == "False" -> false
else -> value
}

private fun kotlinToPython(value: Any?): String = when (value) {
null -> "None"
is String -> "\"${value.replace(" ", SPACE_REPLACEMENT)}\""
is Boolean -> if (value) "True" else "False"
else -> "$value"
}
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ class ZeBadgeViewModel @Inject constructor(
}
}

fun updateConfiguration(configuration: Map<String, String>) {
fun updateConfiguration(configuration: Map<String, Any?>) {
_uiState.update {
it.copy(currentBadgeConfig = null)
}
Expand Down Expand Up @@ -501,5 +501,5 @@ data class ZeBadgeUiState(
val currentTemplateChooser: ZeTemplateChooser?, // if that is not null, we are currently configuring which editor / template to use
val currentSimulatorSlot: ZeSlot, // which page should be displayed in the simulator?
val slots: Map<ZeSlot, ZeConfiguration>,
val currentBadgeConfig: Map<String, String>?,
val currentBadgeConfig: Map<String, Any?>?,
)
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,6 @@ class AndroidBadgeManager(
}
} else {
Timber.e("USB Permission", "Could not request permission to access to badge.")
continuation.resumeWithException(
RuntimeException("Could not request permission to access to badge."),
)
}
}
}
Expand Down
Loading
Loading