Refactor NsdManager and improve service display (#2292)

Signed-off-by: James Rich <2199651+jamesarich@users.noreply.github.com>
This commit is contained in:
James Rich 2025-06-29 14:18:14 +00:00 committed by GitHub
parent ec74bbfe19
commit 8b095aba09
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 30 additions and 23 deletions

View file

@ -41,16 +41,13 @@ class NetworkRepository @Inject constructor(
.conflate()
val resolvedList: Flow<List<NsdServiceInfo>>
get() = nsdManagerLazy.get().serviceList(SERVICE_TYPES, SERVICE_NAME)
get() = nsdManagerLazy.get().serviceList(SERVICE_TYPE)
.flowOn(dispatchers.io)
.conflate()
companion object {
// To find all available services use SERVICE_TYPE = "_services._dns-sd._udp"
internal const val SERVICE_NAME = "Meshtastic"
internal const val SERVICE_PORT = 4403
private const val SERVICE_TYPE = "_meshtastic._tcp"
internal val SERVICE_TYPES = setOf("_http._tcp", SERVICE_TYPE)
fun NsdServiceInfo.toAddressString() = buildString {
append(@Suppress("DEPRECATION") host.toString().substring(1))

View file

@ -24,27 +24,16 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.coroutines.resume
internal fun NsdManager.serviceList(
serviceTypes: Set<String>,
serviceName: String,
): Flow<List<NsdServiceInfo>> {
val flows = serviceTypes.map { serviceType -> serviceList(serviceType, serviceName) }
return combine(flows) { lists -> lists.flatMap { it } }
}
@OptIn(ExperimentalCoroutinesApi::class)
internal fun NsdManager.serviceList(
serviceType: String,
serviceName: String,
): Flow<List<NsdServiceInfo>> = discoverServices(serviceType).mapLatest { serviceList ->
serviceList
.filter { it.serviceName.contains(serviceName) }
.mapNotNull { resolveService(it) }
}