Skip to content
Draft
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
7 changes: 7 additions & 0 deletions app/src/main/java/com/geeksville/mesh/model/UIState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,13 @@ constructor(
serviceRepository.clearTracerouteResponse()
}

val neighborInfoResponse: LiveData<String?>
get() = serviceRepository.neighborInfoResponse.asLiveData()

fun clearNeighborInfoResponse() {
serviceRepository.clearNeighborInfoResponse()
}

val appIntroCompleted: StateFlow<Boolean> = uiPreferencesDataSource.appIntroCompleted

fun onAppIntroCompleted() {
Expand Down
150 changes: 150 additions & 0 deletions app/src/main/java/com/geeksville/mesh/service/MeshService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ class MeshService : Service() {
@Inject lateinit var analytics: PlatformAnalytics

private val tracerouteStartTimes = ConcurrentHashMap<Int, Long>()
private val neighborInfoStartTimes = ConcurrentHashMap<Int, Long>()

@Volatile private var lastNeighborInfo: MeshProtos.NeighborInfo? = null

companion object {

Expand Down Expand Up @@ -236,6 +239,8 @@ class MeshService : Service() {
private val batteryPercentCooldownSeconds = 1500
private val batteryPercentCooldowns: HashMap<Int, Long> = HashMap()

private val oneHour = 3600

private fun getSenderName(packet: DataPacket?): String {
val name = nodeDBbyID[packet?.from]?.user?.longName
return name ?: getString(Res.string.unknown_username)
Expand Down Expand Up @@ -867,6 +872,112 @@ class MeshService : Service() {
}
}

Portnums.PortNum.NEIGHBORINFO_APP_VALUE -> {
val requestId = packet.decoded.requestId
Timber.d("Processing NEIGHBORINFO_APP packet with requestId: $requestId")
val start = neighborInfoStartTimes.remove(requestId)
Timber.d("Found start time for requestId $requestId: $start")

val info =
runCatching { MeshProtos.NeighborInfo.parseFrom(data.payload.toByteArray()) }.getOrNull()

// Store the last neighbor info from our connected radio
if (info != null && packet.from == myInfo.myNodeNum) {
lastNeighborInfo = info
Timber.d("Stored last neighbor info from connected radio")
}

val formatted =
if (info != null) {
val fmtNode: (Int) -> String = { nodeNum ->
val user = nodeRepository.nodeDBbyNum.value[nodeNum]?.user
val shortName = user?.shortName?.takeIf { it.isNotEmpty() } ?: ""
val nodeId = "!%08x".format(nodeNum)
if (shortName.isNotEmpty()) "$nodeId ($shortName)" else nodeId
}
buildString {
appendLine("NeighborInfo:")
appendLine("node_id: ${fmtNode(info.nodeId)}")
appendLine("last_sent_by_id: ${fmtNode(info.lastSentById)}")
appendLine("node_broadcast_interval_secs: ${info.nodeBroadcastIntervalSecs}")
if (info.neighborsCount > 0) {
appendLine("neighbors:")
info.neighborsList.forEach { n ->
appendLine(" - node_id: ${fmtNode(n.nodeId)} snr: ${n.snr}")
}
}
}
} else {
// Fallback to raw string if parsing fails
String(data.payload.toByteArray())
}

val response =
if (start != null) {
val elapsedMs = System.currentTimeMillis() - start
val seconds = elapsedMs / 1000.0
Timber.i("Neighbor info $requestId complete in $seconds s")
"$formatted\n\nDuration: ${"%.1f".format(seconds)} s"
} else {
Timber.w("No start time found for neighbor info requestId: $requestId")
formatted
}
serviceRepository.setNeighborInfoResponse(response)
}

Portnums.PortNum.NEIGHBORINFO_APP_VALUE -> {
val requestId = packet.decoded.requestId
Timber.d("Processing NEIGHBORINFO_APP packet with requestId: $requestId")
val start = neighborInfoStartTimes.remove(requestId)
Timber.d("Found start time for requestId $requestId: $start")

val info =
runCatching { MeshProtos.NeighborInfo.parseFrom(data.payload.toByteArray()) }.getOrNull()

// Store the last neighbor info from our connected radio
if (info != null && packet.from == myInfo.myNodeNum) {
lastNeighborInfo = info
Timber.d("Stored last neighbor info from connected radio")
}

val formatted =
if (info != null) {
val fmtNode: (Int) -> String = { nodeNum ->
val user = nodeRepository.nodeDBbyNum.value[nodeNum]?.user
val shortName = user?.shortName?.takeIf { it.isNotEmpty() } ?: ""
val nodeId = "!%08x".format(nodeNum)
if (shortName.isNotEmpty()) "$nodeId ($shortName)" else nodeId
}
buildString {
appendLine("NeighborInfo:")
appendLine("node_id: ${fmtNode(info.nodeId)}")
appendLine("last_sent_by_id: ${fmtNode(info.lastSentById)}")
appendLine("node_broadcast_interval_secs: ${info.nodeBroadcastIntervalSecs}")
if (info.neighborsCount > 0) {
appendLine("neighbors:")
info.neighborsList.forEach { n ->
appendLine(" - node_id: ${fmtNode(n.nodeId)} snr: ${n.snr}")
}
}
}
} else {
// Fallback to raw string if parsing fails
String(data.payload.toByteArray())
}

val response =
if (start != null) {
val elapsedMs = System.currentTimeMillis() - start
val seconds = elapsedMs / 1000.0
Timber.i("Neighbor info $requestId complete in $seconds s")
"$formatted\n\nDuration: ${"%.1f".format(seconds)} s"
} else {
Timber.w("No start time found for neighbor info requestId: $requestId")
formatted
}
serviceRepository.setNeighborInfoResponse(response)
}

else -> Timber.d("No custom processing needed for ${data.portnumValue} from $fromId")
}

Expand Down Expand Up @@ -2260,6 +2371,45 @@ class MeshService : Service() {
}
}

override fun requestNeighbourInfo(requestId: Int, destNum: Int) = toRemoteExceptions {
if (destNum != myNodeNum) {
neighborInfoStartTimes[requestId] = System.currentTimeMillis()
// Always send the neighbor info from our connected radio (myNodeNum), not request from destNum
val neighborInfoToSend =
lastNeighborInfo
?: run {
// If we don't have it, send dummy/interceptable data
Timber.d("No stored neighbor info from connected radio, sending dummy data")
MeshProtos.NeighborInfo.newBuilder()
.setNodeId(myNodeNum)
.setLastSentById(myNodeNum)
.setNodeBroadcastIntervalSecs(oneHour)
.addNeighbors(
MeshProtos.Neighbor.newBuilder()
.setNodeId(0) // Dummy node ID that can be intercepted
.setSnr(0f)
.setLastRxTime(currentSecond())
.setNodeBroadcastIntervalSecs(oneHour)
.build(),
)
.build()
}

// Send the neighbor info from our connected radio to the destination
packetHandler.sendToRadio(
newMeshPacketTo(destNum).buildMeshPacket(
wantAck = true,
id = requestId,
channel = nodeDBbyNodeNum[destNum]?.channel ?: 0,
) {
portnumValue = Portnums.PortNum.NEIGHBORINFO_APP_VALUE
payload = neighborInfoToSend.toByteString()
wantResponse = true
},
)
}
}

override fun requestPosition(destNum: Int, position: Position) = toRemoteExceptions {
if (destNum != myNodeNum) {
val provideLocation = meshPrefs.shouldProvideNodeLocation(myNodeNum)
Expand Down
96 changes: 96 additions & 0 deletions app/src/main/java/com/geeksville/mesh/ui/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import androidx.compose.animation.scaleOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.recalculateWindowInsets
import androidx.compose.foundation.layout.safeDrawingPadding
Expand All @@ -44,6 +45,7 @@ import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.PlainTooltip
import androidx.compose.material3.Text
Expand All @@ -70,6 +72,8 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavDestination
Expand Down Expand Up @@ -245,6 +249,98 @@ fun MainScreen(uIViewModel: UIViewModel = hiltViewModel(), scanModel: BTScanMode
onDismiss = { uIViewModel.clearTracerouteResponse() },
)
}

val neighborInfoResponse by uIViewModel.neighborInfoResponse.observeAsState()
neighborInfoResponse?.let { response ->
SimpleAlertDialog(
title = R.string.neighbor_info,
text = {
Column(modifier = Modifier.fillMaxWidth()) {
fun tryParseNeighborInfo(input: String): MeshProtos.NeighborInfo? {
// First, try parsing directly from raw bytes of the string
var neighborInfo: MeshProtos.NeighborInfo? =
runCatching { MeshProtos.NeighborInfo.parseFrom(input.toByteArray()) }.getOrNull()

if (neighborInfo == null) {
// Next, try to decode a hex dump embedded as text (e.g., "AA BB CC ...")
val hexPairs = Regex("""\b[0-9A-Fa-f]{2}\b""").findAll(input).map { it.value }.toList()
@Suppress("detekt:MagicNumber") // byte offsets
if (hexPairs.size >= 4) {
val bytes = hexPairs.map { it.toInt(16).toByte() }.toByteArray()
neighborInfo = runCatching { MeshProtos.NeighborInfo.parseFrom(bytes) }.getOrNull()
}
}

return neighborInfo
}

val parsed = tryParseNeighborInfo(response)
if (parsed != null) {
fun fmtNode(nodeNum: Int): String = "!%08x".format(nodeNum)
Text(text = "NeighborInfo:", style = MaterialTheme.typography.bodyMedium)
Text(
text = "node_id: ${fmtNode(parsed.nodeId)}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 8.dp),
)
Text(
text = "last_sent_by_id: ${fmtNode(parsed.lastSentById)}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 2.dp),
)
Text(
text = "node_broadcast_interval_secs: ${parsed.nodeBroadcastIntervalSecs}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 2.dp),
)
if (parsed.neighborsCount > 0) {
Text(
text = "neighbors:",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp),
)
parsed.neighborsList.forEach { n ->
Text(
text = " - node_id: ${fmtNode(n.nodeId)} snr: ${n.snr}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(start = 8.dp),
)
}
}
} else {
val rawBytes = response.toByteArray()

@Suppress("detekt:MagicNumber") // byte offsets
val isBinary = response.any { it.code < 32 && it != '\n' && it != '\r' && it != '\t' }
if (isBinary) {
val hexString = rawBytes.joinToString(" ") { "%02X".format(it) }
Text(
text = "Binary data (hex view):",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(bottom = 4.dp),
)
Text(
text = hexString,
style =
MaterialTheme.typography.bodyMedium.copy(
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
),
modifier = Modifier.padding(bottom = 8.dp).fillMaxWidth(),
)
} else {
Text(
text = response,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(bottom = 8.dp).fillMaxWidth(),
)
}
}
}
},
dismissText = stringResource(id = R.string.okay),
onDismiss = { uIViewModel.clearNeighborInfoResponse() },
)
}
val navSuiteType = NavigationSuiteScaffoldDefaults.navigationSuiteType(currentWindowAdaptiveInfo())
val currentDestination = navController.currentBackStackEntryAsState().value?.destination
val topLevelDestination = TopLevelDestination.fromNavDestination(currentDestination)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ interface IMeshService {
/// Send traceroute packet with wantResponse to nodeNum
void requestTraceroute(in int requestId, in int destNum);

/// Send neighbor info packet with wantResponse to nodeNum
void requestNeighbourInfo(in int requestId, in int destNum);

/// Send Shutdown admin packet to nodeNum
void requestShutdown(in int requestId, in int destNum);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,18 @@ class ServiceRepository @Inject constructor() {
setTracerouteResponse(null)
}

private val _neighborInfoResponse = MutableStateFlow<String?>(null)
val neighborInfoResponse: StateFlow<String?>
get() = _neighborInfoResponse

fun setNeighborInfoResponse(value: String?) {
_neighborInfoResponse.value = value
}

fun clearNeighborInfoResponse() {
setNeighborInfoResponse(null)
}

private val _serviceAction = Channel<ServiceAction>()
val serviceAction = _serviceAction.receiveAsFlow()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,7 @@
<string name="import_known_shared_contact_text">Warning: This contact is known, importing will overwrite the previous contact information.</string>
<string name="public_key_changed">Public Key Changed</string>
<string name="import_label">Import</string>
<string name="request_neighbor_info">Request NeighborInfo</string>
<string name="request_metadata">Request Metadata</string>
<string name="actions">Actions</string>
<string name="firmware">Firmware</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ sealed class NodeMenuAction {

data class RequestUserInfo(val node: Node) : NodeMenuAction()

data class RequestNeighbourInfo(val node: Node) : NodeMenuAction()

data class RequestPosition(val node: Node) : NodeMenuAction()

data class TraceRoute(val node: Node) : NodeMenuAction()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package org.meshtastic.feature.node.component
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.twotone.Message
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.twotone.Mediation
import androidx.compose.runtime.Composable
import org.jetbrains.compose.resources.stringResource
import org.meshtastic.core.database.model.Node
Expand Down Expand Up @@ -57,4 +58,10 @@ internal fun RemoteDeviceActions(node: Node, lastTracerouteTime: Long?, onAction
lastTracerouteTime = lastTracerouteTime,
onClick = { onAction(NodeDetailAction.HandleNodeMenuAction(NodeMenuAction.TraceRoute(node))) },
)
ListItem(
text = stringResource(Res.string.request_neighbor_info),
leadingIcon = Icons.TwoTone.Mediation,
trailingIcon = null,
onClick = { onAction(NodeDetailAction.HandleNodeMenuAction(NodeMenuAction.RequestNeighbourInfo(node))) },
)
}
Loading
Loading