mirror of
https://github.com/atsunatsu/Look4Sat.git
synced 2026-10-02 03:15:37 +00:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
317f6d877f | ||
|
|
865fa9c6f2 | ||
|
|
a082abb72c | ||
|
|
a2e41a0c1a | ||
|
|
e1daf70f11 | ||
|
|
ca9f93c1ed | ||
|
|
42bd55e180 | ||
|
|
7401e1451b | ||
|
|
fa51fb2b44 | ||
|
|
75a251eb98 | ||
|
|
91b5269740 | ||
|
|
522cac25e8 | ||
|
|
732412deb2 | ||
|
|
30000a913e | ||
|
|
e7754a4c9e | ||
|
|
cf1e2b99b4 | ||
|
|
b295500d14 | ||
|
|
0163c7b217 | ||
|
|
85a4b9cfa3 | ||
|
|
c4c4dd682d | ||
|
|
62ad995aeb | ||
|
|
c8fdd2e93e | ||
|
|
dc013f920d | ||
|
|
f36a426855 | ||
|
|
4da59bdd17 | ||
|
|
b8138c948b | ||
|
|
0e28231c4a | ||
|
|
d6bdf5ecb6 |
No files matched your search
@@ -177,6 +177,28 @@ fun MainScreen(
|
||||
factory = MapFilterViewModel.factory()
|
||||
)
|
||||
|
||||
// Map grid-QSO dialog "Match" button: pre-fill the match page for that
|
||||
// grid and run the query BEFORE navigating, so the page's first frame
|
||||
// already contains the results (time-range card at the top, pass curves
|
||||
// right below — no scroll flicker). Navigation happens once the query
|
||||
// finishes (see the collector below).
|
||||
val mutualState by mutualViewModel.uiState.collectAsStateWithLifecycle()
|
||||
val matchCalculating = mutualState.pendingNavigation && mutualState.isCalculating
|
||||
|
||||
LaunchedEffect(mutualViewModel) {
|
||||
mutualViewModel.uiState.collect { state ->
|
||||
if (state.pendingNavigation && !state.isCalculating) {
|
||||
mutualViewModel.consumePendingNavigation()
|
||||
// Push Mutual on top of the Map entry instead of replacing the
|
||||
// stack (bottom-nav style): the system back gesture then pops
|
||||
// back to the map page, which is the page the user came from.
|
||||
if (backStack.lastOrNull() !is Screen.Mutual) {
|
||||
backStack.add(Screen.Mutual)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(
|
||||
LocalElevationThresholds provides ElevationThresholds(
|
||||
low = otherSettings.lowElevation,
|
||||
@@ -246,17 +268,14 @@ fun MainScreen(
|
||||
entry<Screen.Map> {
|
||||
MapDestination(
|
||||
mapFilterViewModel = mapFilterViewModel,
|
||||
matchCalculating = matchCalculating,
|
||||
onMatchGrid = { grid ->
|
||||
// Grid-QSO dialog "Match" button: pre-fill the
|
||||
// match page for that grid and open it.
|
||||
// Grid-QSO dialog "Match" button: pre-fill
|
||||
// the match page for that grid and start the
|
||||
// query. Navigation to the match page is
|
||||
// handled by the uiState collector above,
|
||||
// once the query finishes.
|
||||
mutualViewModel.prefillMatchFromGrid(grid)
|
||||
// Push Mutual on top of the Map entry instead of
|
||||
// replacing the stack (bottom-nav style): the
|
||||
// system back gesture then pops back to the map
|
||||
// page, which is the page the user came from.
|
||||
if (backStack.lastOrNull() !is Screen.Mutual) {
|
||||
backStack.add(Screen.Mutual)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -45,9 +45,22 @@ interface Look4SatDao {
|
||||
@Query("DELETE FROM entries")
|
||||
suspend fun deleteEntries()
|
||||
|
||||
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes)")
|
||||
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND isAlive = 1")
|
||||
suspend fun getIdsWithModes(modes: List<String>): List<Int>
|
||||
|
||||
/** Like [getIdsWithModes] but only matches transponder records with an uplink,
|
||||
* excluding downlink-only beacons/telemetry that share the same mode label
|
||||
* (e.g. CW beacons, FM voice-synthesis beacons) from FM/Linear filter fallback. */
|
||||
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND uplinkLow IS NOT NULL AND isAlive = 1")
|
||||
suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int>
|
||||
|
||||
/** Like [getIdsWithModes] but only matches records whose service class is
|
||||
* "Amateur", so the SSTV filter never matches weather birds (TIROS),
|
||||
* launcher debris or other non-amateur transmitters that happen to carry
|
||||
* an SSTV-labelled downlink. */
|
||||
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND service = 'Amateur' AND isAlive = 1")
|
||||
suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM radios")
|
||||
suspend fun getRadiosTotal(): Int
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.rtbishop.look4sat.core.data.database.entity.SatEntry
|
||||
import com.rtbishop.look4sat.core.data.database.entity.SatRadio
|
||||
|
||||
@Database(entities = [SatEntry::class, SatRadio::class], version = 2, exportSchema = false)
|
||||
@Database(entities = [SatEntry::class, SatRadio::class], version = 3, exportSchema = false)
|
||||
abstract class Look4SatDb : RoomDatabase() {
|
||||
abstract fun look4SatDao(): Look4SatDao
|
||||
}
|
||||
@@ -37,3 +37,11 @@ val MIGRATION_1_2 = object : Migration(1, 2) {
|
||||
db.execSQL("ALTER TABLE radios ADD COLUMN isCustom INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the transceiver service class ("Amateur" etc.), used by the SSTV virtual
|
||||
* filter to tell amateur satellites apart from debris/weather/launcher stages. */
|
||||
val MIGRATION_2_3 = object : Migration(2, 3) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE radios ADD COLUMN service TEXT")
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ data class SatRadio(
|
||||
val uplinkMode: String?,
|
||||
val isInverted: Boolean,
|
||||
val catnum: Int?,
|
||||
/** Service class from the transceiver source ("Amateur"/"Unknown" etc.).
|
||||
* Used to tell amateur satellites apart from debris / weather birds
|
||||
* (TIROS) / launcher stages (Ariane 6 R/B) in the SSTV virtual filter. */
|
||||
val service: String? = null,
|
||||
/** Set for manually imported transceivers, which remote updates must not replace. */
|
||||
val isCustom: Boolean = false
|
||||
)
|
||||
@@ -25,6 +25,7 @@ import android.location.LocationManager
|
||||
import androidx.room.Room
|
||||
import com.rtbishop.look4sat.core.data.database.Look4SatDb
|
||||
import com.rtbishop.look4sat.core.data.database.MIGRATION_1_2
|
||||
import com.rtbishop.look4sat.core.data.database.MIGRATION_2_3
|
||||
import com.rtbishop.look4sat.core.data.framework.BluetoothReporter
|
||||
import com.rtbishop.look4sat.core.data.framework.Ft817Controller
|
||||
import com.rtbishop.look4sat.core.data.framework.Ic705Controller
|
||||
@@ -73,6 +74,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import okhttp3.OkHttpClient
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class MainContainer(private val context: Context) : IMainContainer {
|
||||
|
||||
@@ -169,14 +171,23 @@ class MainContainer(private val context: Context) : IMainContainer {
|
||||
private fun provideLocalSource(): ILocalSource {
|
||||
val builder = Room.databaseBuilder(context, Look4SatDb::class.java, "Look4SatDBv400")
|
||||
val database = builder
|
||||
.addMigrations(MIGRATION_1_2)
|
||||
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
|
||||
.fallbackToDestructiveMigration(false)
|
||||
.build()
|
||||
return LocalSource(database.look4SatDao())
|
||||
}
|
||||
|
||||
private fun provideRemoteSource(): IRemoteSource {
|
||||
return RemoteSource(Dispatchers.IO, context.contentResolver, OkHttpClient.Builder().build())
|
||||
// amsat.org live pages are slow (7-10s+ from some networks); the
|
||||
// OkHttp defaults (10s read timeout) made every AMSAT Live update
|
||||
// time out, silently keeping stale FM/Linear lists forever.
|
||||
val client = OkHttpClient.Builder()
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.writeTimeout(30, TimeUnit.SECONDS)
|
||||
.callTimeout(60, TimeUnit.SECONDS)
|
||||
.build()
|
||||
return RemoteSource(Dispatchers.IO, context.contentResolver, client)
|
||||
}
|
||||
|
||||
private fun provideSatelliteRepo(): ISatelliteRepo {
|
||||
|
||||
@@ -23,6 +23,7 @@ import com.rtbishop.look4sat.core.domain.repository.IDatabaseRepo
|
||||
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
|
||||
import com.rtbishop.look4sat.core.domain.source.ILocalSource
|
||||
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
|
||||
import com.rtbishop.look4sat.core.domain.source.NetworkResult
|
||||
import com.rtbishop.look4sat.core.domain.source.Sources
|
||||
import com.rtbishop.look4sat.core.domain.utility.DataParser
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -115,12 +116,107 @@ class DatabaseRepo(
|
||||
localSource.insertRadios(importedRadios)
|
||||
}
|
||||
if (importedEntries.isNotEmpty()) localSource.insertEntries(importedEntries)
|
||||
updateAmSatLiveLists()
|
||||
setUpdateSuccessful(System.currentTimeMillis())
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the AMSAT Live FM/Linear satellite lists (transponders currently
|
||||
* on the air). Best effort: any failure keeps the previous lists and never
|
||||
* blocks the rest of the data update, so the mutual-match filter simply
|
||||
* falls back to the last successful snapshot.
|
||||
*/
|
||||
private suspend fun updateAmSatLiveLists() = withContext(dispatcher) {
|
||||
runCatching {
|
||||
val entries = localSource.getEntriesList() // catnum -> name
|
||||
val jobs = Sources.amSatLiveUrls.map { (type, url) ->
|
||||
async { type to remoteSource.getNetworkStream(url) }
|
||||
} + async { "Active" to fetchAmSatActiveStream() }
|
||||
val results = jobs.awaitAll()
|
||||
val fmNames = results.firstOrNull { it.first == "FM" }?.second?.stream
|
||||
?.let { dataParser.parseAmSatLivePage(it) }.orEmpty()
|
||||
val linearNames = results.firstOrNull { it.first == "Linear" }?.second?.stream
|
||||
?.let { dataParser.parseAmSatLivePage(it) }.orEmpty()
|
||||
// Amateur whitelist: a failed fetch yields an empty result, which
|
||||
// must NOT wipe out the last good snapshot. Fall back to the
|
||||
// persisted whitelist, and only persist when this fetch actually
|
||||
// returned a stream.
|
||||
val activeStream = results.firstOrNull { it.first == "Active" }?.second?.stream
|
||||
val activeCatnums = activeStream
|
||||
?.let { dataParser.parseAmSatActiveCatnums(it) }
|
||||
.orEmpty()
|
||||
.ifEmpty { settingsRepo.getAmSatActiveCatnums() }
|
||||
if (activeStream != null) settingsRepo.setAmSatActiveCatnums(activeCatnums)
|
||||
val nameToCatnum = entries.associate { it.name.uppercase() to it.catnum }
|
||||
// Resolve every matching local entry per AMSAT name. A single match
|
||||
// is kept as-is (so satellites absent from the amateur whitelist,
|
||||
// e.g. JO-97/TO-108, are never dropped). Only when several local
|
||||
// entries share the name (ISS station modules ZARYA/UNITY/ZVEZDA/
|
||||
// DESTINY/NAUKA) is the whitelist used to pick the primary one.
|
||||
fun resolvePerName(name: String): Set<Int> {
|
||||
val keys = dataParser.normalizeAmSatName(name)
|
||||
val all = nameToCatnum.filter { (localName, _) ->
|
||||
dataParser.matchesAmSatName(localName, keys)
|
||||
}.values.toSet()
|
||||
// No local entry matches this AMSAT name (e.g. a brand-new
|
||||
// satellite not yet in the local TLE, like TEVEL2/RS95S):
|
||||
// skip it. Returning empty is correct — crashing here (via
|
||||
// all.first()) aborted the WHOLE list update and kept the
|
||||
// stale pre-whitelist FM list with all five ISS modules.
|
||||
if (all.isEmpty()) return emptySet()
|
||||
if (all.size <= 1) return all
|
||||
val preferred = all.intersect(activeCatnums)
|
||||
if (preferred.isNotEmpty()) return preferred
|
||||
// Whitelist unavailable: keep only the primary entry (smallest
|
||||
// catnum — ISS ZARYA=25544 is the smallest of its five module
|
||||
// entries) instead of admitting every alias (DESTINY etc.).
|
||||
return setOf(all.minOrNull() ?: all.first())
|
||||
}
|
||||
// A failed FM/Linear page fetch yields an empty list here; do NOT
|
||||
// keep the stale list verbatim (it may predate the whitelist and
|
||||
// still contain ISS module aliases like DESTINY). Instead re-run
|
||||
// the multi-match disambiguation on the previous catnums via their
|
||||
// local names, so the whitelist / smallest-catnum rules clean it.
|
||||
fun cleanStaleList(previous: Set<Int>): Set<Int> =
|
||||
previous.mapNotNull { catnum ->
|
||||
nameToCatnum.entries.firstOrNull { it.value == catnum }?.key
|
||||
}.flatMap { resolvePerName(it) }.toSet()
|
||||
// Last-resort fallback when the AMSAT page is down AND there is no
|
||||
// previous list to clean (e.g. right after clearing data): derive
|
||||
// the FM/Linear sets from the local transceivers intersected with
|
||||
// the amateur whitelist, so a network timeout never wipes the
|
||||
// filters to empty.
|
||||
val fmFallback = localSource.getIdsWithModes(listOf("FM")).toSet().intersect(activeCatnums)
|
||||
val linearFallback = localSource
|
||||
.getIdsWithModes(listOf("SSB", "CW", "USB", "LSB")).toSet().intersect(activeCatnums)
|
||||
val fmCatnums = fmNames.flatMap { resolvePerName(it) }.toSet()
|
||||
.ifEmpty { cleanStaleList(settingsRepo.getAmSatFmCatnums()) }
|
||||
.ifEmpty { fmFallback }
|
||||
val linearCatnums = linearNames.flatMap { resolvePerName(it) }.toSet()
|
||||
.ifEmpty { cleanStaleList(settingsRepo.getAmSatLinearCatnums()) }
|
||||
.ifEmpty { linearFallback }
|
||||
settingsRepo.setAmSatCatnums(fmCatnums, linearCatnums)
|
||||
println("AMSAT live lists updated: FM=${fmCatnums.size}, Linear=${linearCatnums.size}, Active=${activeCatnums.size}")
|
||||
}.onFailure {
|
||||
// Keep the previous lists; the mutual filter stays on the last good snapshot.
|
||||
println("AMSAT live lists update failed: $it")
|
||||
}
|
||||
}
|
||||
|
||||
/** Try the amateur-whitelist sources in order and return the first
|
||||
* NetworkResult that carried a stream (or null if all failed). */
|
||||
private suspend fun fetchAmSatActiveStream(): NetworkResult? {
|
||||
for (url in Sources.amSatActiveUrls) {
|
||||
val result = remoteSource.getNetworkStream(url)
|
||||
if (result.stream != null) return result
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override suspend fun clearAllData() = withContext(dispatcher) {
|
||||
localSource.deleteEntries()
|
||||
localSource.deleteRadios()
|
||||
settingsRepo.setAmSatCatnums(emptySet(), emptySet())
|
||||
setUpdateSuccessful(0L)
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,12 @@ class SatelliteRepo(
|
||||
|
||||
override suspend fun getRadiosWithId(id: Int) = localStorage.getRadiosWithId(id)
|
||||
|
||||
override suspend fun getSatelliteIdsWithModes(modes: List<String>) = localStorage.getIdsWithModes(modes)
|
||||
|
||||
override suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>) = localStorage.getIdsWithModesAndUplink(modes)
|
||||
|
||||
override suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>) = localStorage.getIdsWithModesAndAmateur(modes)
|
||||
|
||||
override suspend fun initRepository() = withContext(dispatcher) {
|
||||
combine(
|
||||
settingsRepo.selectedIds,
|
||||
|
||||
+55
-12
@@ -25,6 +25,7 @@ import com.rtbishop.look4sat.core.domain.source.Sources
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -43,17 +44,23 @@ class SelectionRepo(
|
||||
|
||||
// Resolve type IDs once when types change, then filter items reactively.
|
||||
// The HashSet gives O(1) catnum lookups instead of O(n) with a List.
|
||||
private val itemsWithTypes = currentTypes.flatMapLatest { types: List<String> ->
|
||||
val catnumSet: Set<Int>? = if (types.isEmpty()) {
|
||||
null // null = no filtering
|
||||
} else {
|
||||
val ids = settingsRepo.getSatelliteTypesIds(types)
|
||||
if (ids.isEmpty()) null else ids.toHashSet()
|
||||
// The three virtual types ("AMSAT Live FM", "AMSAT Live Linear", "Live SSTV")
|
||||
// are resolved from live transponder data instead of SharedPreferences.
|
||||
// The AMSAT list version counter re-triggers resolution when a background
|
||||
// data sync rewrites the FM/Linear lists, so the UI reflects the new list
|
||||
// without a restart or type toggle.
|
||||
private val itemsWithTypes = combine(currentTypes, settingsRepo.amSatListsVersion) { types, _ -> types }
|
||||
.flatMapLatest { types: List<String> ->
|
||||
val catnumSet: Set<Int>? = if (types.isEmpty()) {
|
||||
null // null = no filtering
|
||||
} else {
|
||||
val ids = resolveTypeIds(types)
|
||||
if (ids.isEmpty()) emptySet() else ids.toHashSet()
|
||||
}
|
||||
currentItems.map { items ->
|
||||
if (catnumSet == null) items else items.filter { it.catnum in catnumSet }
|
||||
}
|
||||
}
|
||||
currentItems.map { items ->
|
||||
if (catnumSet == null) items else items.filter { it.catnum in catnumSet }
|
||||
}
|
||||
}
|
||||
|
||||
private val itemsWithQuery = currentQuery.flatMapLatest { query ->
|
||||
itemsWithTypes.map { items -> filterByQuery(items, query) }
|
||||
@@ -61,8 +68,44 @@ class SelectionRepo(
|
||||
|
||||
override fun getCurrentTypes() = currentTypes.value
|
||||
|
||||
override fun getTypesList() = Sources.satelliteDataUrls.keys.sorted().toMutableList().apply {
|
||||
removeAt(0)
|
||||
/**
|
||||
* Resolves a list of type names to satellite catnums. The three virtual
|
||||
* transponder/activity types are resolved from live data; all other types
|
||||
* come from the per-type ID lists persisted by [ISettingsRepo].
|
||||
*/
|
||||
private suspend fun resolveTypeIds(types: List<String>): List<Int> {
|
||||
val idsSet = mutableSetOf<Int>()
|
||||
types.forEach { type ->
|
||||
when (type) {
|
||||
Sources.virtualTypeNames[0] -> idsSet.addAll(settingsRepo.getAmSatFmCatnums())
|
||||
Sources.virtualTypeNames[1] -> idsSet.addAll(settingsRepo.getAmSatLinearCatnums())
|
||||
// Live SSTV: mode=SSTV transponder records whose service class
|
||||
// is "Amateur", excluding launcher debris / rocket bodies
|
||||
// (names ending in "R/B" or "DEB" — e.g. Ariane 6 R/B) that
|
||||
// carry an amateur payload transponder but are not satellites.
|
||||
Sources.virtualTypeNames[2] -> {
|
||||
val sstvIds = localSource.getIdsWithModesAndAmateur(listOf("SSTV")).toSet()
|
||||
val inOrbitNames = currentItems.value.associate { it.catnum to it.name }
|
||||
val filtered = sstvIds.filter { catnum ->
|
||||
val name = inOrbitNames[catnum]?.uppercase().orEmpty()
|
||||
!name.endsWith(" R/B") && !name.endsWith(" DEB") &&
|
||||
!name.endsWith("R/B") && !name.endsWith("DEB")
|
||||
}
|
||||
idsSet.addAll(filtered)
|
||||
}
|
||||
else -> idsSet.addAll(settingsRepo.getSatelliteTypesIds(listOf(type)))
|
||||
}
|
||||
}
|
||||
return idsSet.toList()
|
||||
}
|
||||
|
||||
override fun getTypesList() = buildList {
|
||||
// 三个转发器/活动虚拟类型排在最前.
|
||||
addAll(Sources.virtualTypeNames)
|
||||
// 所有真实 TLE 源类型均可选(含 "All" = CelesTrak active);只排除
|
||||
// "Other"(空 URL 占位,无数据)。不要用 removeAt(0) —— 字母序第一个
|
||||
// 是 "All"/"ARISS" 这类真实源,删掉会让用户勾不到它们。
|
||||
addAll(Sources.satelliteDataUrls.keys.sorted().filterNot { it == "Other" })
|
||||
}
|
||||
|
||||
override suspend fun getEntriesFlow() = withContext(dispatcher) {
|
||||
|
||||
@@ -107,6 +107,9 @@ class SettingsRepo(
|
||||
private val keySatelliteEnabled = "satelliteEnabled"
|
||||
private val keyTransceiversEnabled = "transceiversEnabled"
|
||||
private val keySatnogsTleSourceMigration = "satnogsTleSourceMigration"
|
||||
private val keyAmSatFmCatnums = "amSatFmCatnums"
|
||||
private val keyAmSatLinearCatnums = "amSatLinearCatnums"
|
||||
private val keyAmSatActiveCatnums = "amSatActiveCatnums"
|
||||
private val separatorComma = ","
|
||||
private val separatorUrl = "\n"
|
||||
private val legacyCelestrakSatnogsUrl =
|
||||
@@ -269,6 +272,59 @@ class SettingsRepo(
|
||||
preferences.edit { putString(keyRoamedGrids, array.toString()) }
|
||||
}
|
||||
|
||||
// Marked stations in unworked gridsquares, persisted as a single JSON
|
||||
// object: {"OL62":[{"c":call,"t":epochMs}, ...]}. Each grid holds an
|
||||
// ordered list (first = pinned/top). v14.1 stored a single object per
|
||||
// grid; reads transparently migrate that old shape to a one-element list.
|
||||
private val keyMarkedGridStations = "markedGridStations"
|
||||
|
||||
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> {
|
||||
val json = preferences.getString(keyMarkedGridStations, null).orEmpty()
|
||||
if (json.isBlank()) return emptyMap()
|
||||
return try {
|
||||
val root = org.json.JSONObject(json)
|
||||
val result = mutableMapOf<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>()
|
||||
for (grid in root.keys()) {
|
||||
val value = root.opt(grid)
|
||||
val list = when (value) {
|
||||
// v14.2+ shape: JSON array of station objects.
|
||||
is org.json.JSONArray -> (0 until value.length()).mapNotNull { i ->
|
||||
val o = value.optJSONObject(i) ?: return@mapNotNull null
|
||||
val call = o.optString("c").ifBlank { return@mapNotNull null }
|
||||
com.rtbishop.look4sat.core.domain.model.MarkedStation(call = call, epochMs = o.optLong("t"))
|
||||
}
|
||||
// v14.1 legacy shape: a single station object per grid.
|
||||
is org.json.JSONObject -> {
|
||||
val call = value.optString("c").ifBlank { null }
|
||||
if (call == null) emptyList()
|
||||
else listOf(com.rtbishop.look4sat.core.domain.model.MarkedStation(call = call, epochMs = value.optLong("t")))
|
||||
}
|
||||
else -> emptyList()
|
||||
}
|
||||
if (list.isNotEmpty()) result[grid] = list
|
||||
}
|
||||
result
|
||||
} catch (_: Exception) {
|
||||
emptyMap()
|
||||
}
|
||||
}
|
||||
|
||||
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) {
|
||||
val root = org.json.JSONObject()
|
||||
for ((grid, list) in stations) {
|
||||
val array = org.json.JSONArray()
|
||||
for (station in list) {
|
||||
array.put(
|
||||
org.json.JSONObject()
|
||||
.put("c", station.call)
|
||||
.put("t", station.epochMs)
|
||||
)
|
||||
}
|
||||
root.put(grid, array)
|
||||
}
|
||||
preferences.edit { putString(keyMarkedGridStations, root.toString()) }
|
||||
}
|
||||
|
||||
// LoTW credentials (stored locally on the device only)
|
||||
private val keyLoTWCall = "lotwCallsign"
|
||||
private val keyLoTWPass = "lotwPassword"
|
||||
@@ -442,7 +498,9 @@ class SettingsRepo(
|
||||
}
|
||||
|
||||
override fun setSatelliteTypeIds(type: String, ids: List<Int>) {
|
||||
if (type == "All") return
|
||||
// "All" is a real TLE source type (CelesTrak active group) whose ids
|
||||
// must be persisted like any other type — skipping it made the "All"
|
||||
// filter resolve to an empty set and show nothing.
|
||||
val typesString = ids.joinToString(separatorComma)
|
||||
preferences.edit { putString("type$type", typesString) }
|
||||
}
|
||||
@@ -692,6 +750,40 @@ class SettingsRepo(
|
||||
}
|
||||
//endregion
|
||||
|
||||
//region # AMSAT live-transponder lists
|
||||
private val _amSatListsVersion = MutableStateFlow(0)
|
||||
override val amSatListsVersion: StateFlow<Int> = _amSatListsVersion
|
||||
|
||||
override fun getAmSatFmCatnums(): Set<Int> {
|
||||
val raw = preferences.getString(keyAmSatFmCatnums, null) ?: return emptySet()
|
||||
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
|
||||
}
|
||||
|
||||
override fun getAmSatLinearCatnums(): Set<Int> {
|
||||
val raw = preferences.getString(keyAmSatLinearCatnums, null) ?: return emptySet()
|
||||
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
|
||||
}
|
||||
|
||||
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
|
||||
preferences.edit {
|
||||
putString(keyAmSatFmCatnums, fmCatnums.sorted().joinToString(separatorComma))
|
||||
putString(keyAmSatLinearCatnums, linearCatnums.sorted().joinToString(separatorComma))
|
||||
}
|
||||
_amSatListsVersion.update { it + 1 }
|
||||
}
|
||||
|
||||
override fun getAmSatActiveCatnums(): Set<Int> {
|
||||
val raw = preferences.getString(keyAmSatActiveCatnums, null) ?: return emptySet()
|
||||
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
|
||||
}
|
||||
|
||||
override fun setAmSatActiveCatnums(catnums: Set<Int>) {
|
||||
preferences.edit {
|
||||
putString(keyAmSatActiveCatnums, catnums.sorted().joinToString(separatorComma))
|
||||
}
|
||||
}
|
||||
//endregion
|
||||
|
||||
//region # Radio control settings
|
||||
private val keyRadioControlEnabled = "radioControlEnabled"
|
||||
private val keyRadioModel = "radioModel"
|
||||
|
||||
@@ -48,6 +48,8 @@ class LocalSource(private val look4SatDao: Look4SatDao) : ILocalSource {
|
||||
override suspend fun deleteEntries() = look4SatDao.deleteEntries()
|
||||
|
||||
override suspend fun getIdsWithModes(modes: List<String>) = look4SatDao.getIdsWithModes(modes)
|
||||
override suspend fun getIdsWithModesAndUplink(modes: List<String>) = look4SatDao.getIdsWithModesAndUplink(modes)
|
||||
override suspend fun getIdsWithModesAndAmateur(modes: List<String>) = look4SatDao.getIdsWithModesAndAmateur(modes)
|
||||
|
||||
private fun FrameworkEntry.toDomain() = OrbitalData(
|
||||
this.name, this.epoch, this.meanmo, this.eccn, this.incl,
|
||||
@@ -83,12 +85,14 @@ class LocalSource(private val look4SatDao: Look4SatDao) : ILocalSource {
|
||||
|
||||
private fun DomainRadio.toFramework() = FrameworkRadio(
|
||||
this.uuid, this.info, this.isAlive, this.downlinkLow, this.downlinkHigh, this.downlinkMode,
|
||||
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum, this.isCustom
|
||||
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum,
|
||||
this.service, this.isCustom
|
||||
)
|
||||
|
||||
private fun FrameworkRadio.toDomain() = DomainRadio(
|
||||
this.uuid, this.info, this.isAlive, this.downlinkLow, this.downlinkHigh, this.downlinkMode,
|
||||
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum, this.isCustom
|
||||
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum,
|
||||
this.service, this.isCustom
|
||||
)
|
||||
|
||||
private fun List<DomainRadio>.toFrameworkRadios() = this.map { radio -> radio.toFramework() }
|
||||
|
||||
+211
-2
@@ -127,6 +127,29 @@ class DatabaseRepoTest {
|
||||
assertEquals(listOf(98248), settingsRepo.satelliteTypeIdsByType["SatNOGS"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `remote update persists All source type ids`() = runTest(dispatcher) {
|
||||
// Regression: "All" (CelesTrak active) is a real TLE source type whose
|
||||
// ids must be persisted on sync — the old `if (type == "All") return`
|
||||
// silently dropped them, making the "All" filter resolve to nothing.
|
||||
val allUrl = Sources.satelliteDataUrls.getValue("All")
|
||||
val localSource = FakeLocalSource()
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[allUrl] = { validCsvStream() }
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(allUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
)
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
assertEquals(listOf(25544), settingsRepo.satelliteTypeIdsByType["All"])
|
||||
}
|
||||
|
||||
private fun validCsvStream(): InputStream = """
|
||||
OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
|
||||
ISS (ZARYA),1998-067A,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25544,999,31220,.31985E-4,.1288E-4,0
|
||||
@@ -143,6 +166,168 @@ class DatabaseRepoTest {
|
||||
1 98248U 26237.16675926 .00015724 00000-0 97477-3 0 00013
|
||||
2 98248 097.5373 310.9694 0011309 278.1232 340.7230 15.09766181000012
|
||||
""".trimIndent().byteInputStream()
|
||||
|
||||
@Test
|
||||
fun `amsat fm list disambiguates ISS modules via persisted whitelist when active csv fetch fails`() =
|
||||
runTest(dispatcher) {
|
||||
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
|
||||
val localSource = FakeLocalSource()
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[satnogsUrl] = { issModulesCsvStream() }
|
||||
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageStream() }
|
||||
// Amateur-whitelist URLs intentionally NOT registered -> fetch fails.
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(satnogsUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
).apply { amSatActive = setOf(25544) } // whitelist persisted by an earlier good sync
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
// Whitelist fetch fails on both sources, but the persisted whitelist
|
||||
// still disambiguates: only primary ISS (ZARYA) survives,
|
||||
// ISS (DESTINY) = 26700 must NOT enter the FM list.
|
||||
assertTrue(25544 in settingsRepo.amSatFm)
|
||||
assertTrue(26700 !in settingsRepo.amSatFm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `amsat fm list keeps only smallest catnum when whitelist never available`() = runTest(dispatcher) {
|
||||
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
|
||||
val localSource = FakeLocalSource()
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[satnogsUrl] = { issModulesCsvStream() }
|
||||
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageStream() }
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(satnogsUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
) // no persisted whitelist at all
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
// Without any whitelist, the multi-match collapse keeps the primary
|
||||
// entry (smallest catnum = ISS ZARYA 25544), never every module alias.
|
||||
assertEquals(setOf(25544), settingsRepo.amSatFm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `amsat fm list cleans stale ISS module aliases when fm page fetch fails`() = runTest(dispatcher) {
|
||||
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
|
||||
val localSource = FakeLocalSource()
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[satnogsUrl] = { issModulesCsvStream() }
|
||||
// FM page NOT registered -> 404 -> empty parse.
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(satnogsUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
).apply {
|
||||
// Pre-whitelist era stale list: ALL five ISS module entries.
|
||||
amSatFm = setOf(25544, 25575, 26400, 26700, 49044)
|
||||
}
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
// The stale list is not kept verbatim: with the FM page down, the
|
||||
// previous catnums are re-disambiguated via local names, collapsing
|
||||
// the five ISS modules to the primary ZARYA (25544).
|
||||
assertEquals(setOf(25544), settingsRepo.amSatFm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `amsat fm list survives unknown satellite names and still disambiguates ISS`() = runTest(dispatcher) {
|
||||
// Regression: AMSAT pages list satellites absent from the local TLE
|
||||
// (TEVEL2-1..9, RS95S). resolvePerName used to crash on the empty
|
||||
// match set (all.first()), aborting the WHOLE list update and keeping
|
||||
// the stale pre-whitelist FM list with all five ISS modules.
|
||||
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
|
||||
val localSource = FakeLocalSource()
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[satnogsUrl] = { issModulesCsvStream() }
|
||||
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageWithUnknownStream() }
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(satnogsUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
).apply { amSatActive = setOf(25544) }
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
// No crash; ISS still collapses to the primary ZARYA (25544).
|
||||
assertEquals(setOf(25544), settingsRepo.amSatFm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `amsat fm list falls back to local FM transceivers when page fails and no previous list`() =
|
||||
runTest(dispatcher) {
|
||||
// After clearing data, the previous FM list is empty AND the AMSAT
|
||||
// page is down (timeout) -> the filter must fall back to local FM
|
||||
// transceivers intersected with the whitelist, never stay empty.
|
||||
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
|
||||
val localSource = FakeLocalSource().apply {
|
||||
idsWithModes = listOf(25544, 26700, 39444) // local FM-transceiver sats
|
||||
}
|
||||
val remoteSource = FakeRemoteSource().apply {
|
||||
networkStreams[satnogsUrl] = { issModulesCsvStream() }
|
||||
// FM/Linear pages NOT registered -> 404 -> fetch fails.
|
||||
}
|
||||
val settingsRepo = FakeSettingsRepo(
|
||||
dataSources = DataSourcesSettings(
|
||||
satelliteUrls = listOf(satnogsUrl),
|
||||
transceiversUrls = emptyList()
|
||||
)
|
||||
).apply { amSatActive = setOf(25544) } // whitelist has only ZARYA
|
||||
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
|
||||
|
||||
repository.updateFromRemote()
|
||||
|
||||
// Fallback = local FM ids ∩ whitelist = {25544}; ISS module aliases
|
||||
// (26700) are excluded by the whitelist.
|
||||
assertEquals(setOf(25544), settingsRepo.amSatFm)
|
||||
}
|
||||
|
||||
private fun amsatFmPageWithUnknownStream(): InputStream = """
|
||||
<table>
|
||||
<thead><tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>ISS</td><td>145.990 MHz</td><td>437.800 MHz</td><td></td></tr>
|
||||
<tr><td>TEVEL2-1 thru TEVEL2-9</td><td>145.970 MHz</td><td>436.400 MHz</td><td></td></tr>
|
||||
<tr><td>RS95S(QMR-KWT-2)</td><td>145.920 MHz</td><td>436.950 MHz</td><td></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
""".trimIndent().byteInputStream()
|
||||
|
||||
private fun issModulesCsvStream(): InputStream = """
|
||||
OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
|
||||
ISS (ZARYA),1998-067A,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25544,999,31220,.31985E-4,.1288E-4,0
|
||||
ISS (UNITY),1998-067B,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25575,999,31220,.31985E-4,.1288E-4,0
|
||||
ISS (ZVEZDA),1998-067C,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,26400,999,31220,.31985E-4,.1288E-4,0
|
||||
ISS (DESTINY),1998-067D,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,26700,999,31220,.31985E-4,.1288E-4,0
|
||||
ISS (NAUKA),1998-067E,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,49044,999,31220,.31985E-4,.1288E-4,0
|
||||
""".trimIndent().byteInputStream()
|
||||
|
||||
private fun amsatFmPageStream(): InputStream = """
|
||||
<table class="has-background">
|
||||
<thead><tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>ISS</td><td>145.990 MHz</td><td>437.800 MHz</td><td></td></tr>
|
||||
<tr><td>AO-91(RadFxSat / Fox-1B)</td><td>435.250 MHz</td><td>145.960 MHz</td><td></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
""".trimIndent().byteInputStream()
|
||||
}
|
||||
|
||||
private class FakeRemoteSource : IRemoteSource {
|
||||
@@ -164,10 +349,12 @@ private class FakeRemoteSource : IRemoteSource {
|
||||
private class FakeLocalSource : ILocalSource {
|
||||
val insertedEntries = mutableListOf<OrbitalData>()
|
||||
private val insertedRadios = mutableListOf<SatRadio>()
|
||||
var idsWithModes: List<Int> = emptyList()
|
||||
|
||||
override suspend fun getEntriesTotal(): Int = insertedEntries.size
|
||||
|
||||
override suspend fun getEntriesList(): List<SatItem> = emptyList()
|
||||
override suspend fun getEntriesList(): List<SatItem> =
|
||||
insertedEntries.map { SatItem(it.catnum, it.name) }
|
||||
|
||||
override suspend fun getEntriesWithIds(ids: List<Int>): List<OrbitalObject> = emptyList()
|
||||
|
||||
@@ -179,7 +366,9 @@ private class FakeLocalSource : ILocalSource {
|
||||
insertedEntries.clear()
|
||||
}
|
||||
|
||||
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = emptyList()
|
||||
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = idsWithModes
|
||||
override suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int> = idsWithModes
|
||||
override suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int> = emptyList()
|
||||
|
||||
override suspend fun getRadiosTotal(): Int = insertedRadios.size
|
||||
|
||||
@@ -269,6 +458,22 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
|
||||
(dataSourcesStatus as? MutableStateFlow)?.value = status
|
||||
}
|
||||
|
||||
var amSatFm: Set<Int> = emptySet()
|
||||
var amSatLinear: Set<Int> = emptySet()
|
||||
var amSatActive: Set<Int> = emptySet()
|
||||
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
|
||||
|
||||
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
|
||||
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
|
||||
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
|
||||
amSatFm = fmCatnums
|
||||
amSatLinear = linearCatnums
|
||||
}
|
||||
override fun getAmSatActiveCatnums(): Set<Int> = amSatActive
|
||||
override fun setAmSatActiveCatnums(catnums: Set<Int>) {
|
||||
amSatActive = catnums
|
||||
}
|
||||
|
||||
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
|
||||
|
||||
override fun getSatelliteOffset(catnum: Int): String = ""
|
||||
@@ -312,6 +517,10 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
|
||||
override fun setRoamedGrids(grids: Set<String>) {
|
||||
roamedGrids.value = grids
|
||||
}
|
||||
|
||||
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
|
||||
|
||||
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
|
||||
}
|
||||
|
||||
private fun defaultDataSourcesSettings(): DataSourcesSettings {
|
||||
|
||||
+207
-8
@@ -112,22 +112,200 @@ class SelectionRepoSearchTest {
|
||||
assertTrue(repo.getEntriesFlow().first().isEmpty())
|
||||
}
|
||||
|
||||
private fun createRepo(items: List<SatItem>): ISelectionRepo {
|
||||
return SelectionRepo(
|
||||
@Test
|
||||
fun `FM virtual type shows only AMSAT FM list satellites`() = runTest {
|
||||
val repo = createRepo(
|
||||
items = sampleItems,
|
||||
amSatFm = setOf(25544, 39444)
|
||||
)
|
||||
repo.setTypes(listOf("AMSAT Live FM"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(listOf(25544, 39444), results.map { it.catnum })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `SSTV virtual type shows only satellites with SSTV radios`() = runTest {
|
||||
val repo = createRepo(
|
||||
items = sampleItems,
|
||||
sstvIds = listOf(43803)
|
||||
)
|
||||
repo.setTypes(listOf("Live SSTV"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(listOf(43803), results.map { it.catnum })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `SSTV virtual type uses the amateur-only radio query`() = runTest {
|
||||
// The repo delegates to getIdsWithModesAndAmateur: the fake returns
|
||||
// only catnums the DAO would have filtered to Amateur service (43803).
|
||||
val repo = createRepo(
|
||||
items = sampleItems,
|
||||
sstvIds = listOf(43803),
|
||||
amSatActive = setOf(43803)
|
||||
)
|
||||
repo.setTypes(listOf("Live SSTV"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(listOf(43803), results.map { it.catnum })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `SSTV virtual type excludes rocket-body debris by name`() = runTest {
|
||||
// 60239 is "ARIANE 6 R/B" (launcher debris carrying an amateur SSTV
|
||||
// payload); it must be dropped even though its radio is Amateur.
|
||||
val items = sampleItems + SatItem(catnum = 60239, name = "ARIANE 6 R/B")
|
||||
val repo = createRepo(
|
||||
items = items,
|
||||
sstvIds = listOf(43803, 60239),
|
||||
amSatActive = setOf(43803, 60239)
|
||||
)
|
||||
repo.setTypes(listOf("Live SSTV"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(listOf(43803), results.map { it.catnum })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multiple virtual types union their satellites`() = runTest {
|
||||
val repo = createRepo(
|
||||
items = sampleItems,
|
||||
amSatFm = setOf(25544),
|
||||
amSatLinear = setOf(7530),
|
||||
sstvIds = listOf(43803)
|
||||
)
|
||||
repo.setTypes(listOf("AMSAT Live FM", "Live SSTV"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(setOf(25544, 43803), results.map { it.catnum }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clearing types restores full list`() = runTest {
|
||||
val repo = createRepo(items = sampleItems, amSatFm = setOf(25544))
|
||||
repo.setTypes(listOf("AMSAT Live FM"))
|
||||
assertTrue(repo.getEntriesFlow().first().isNotEmpty())
|
||||
repo.setTypes(emptyList())
|
||||
assertEquals(sampleItems.size, repo.getEntriesFlow().first().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `virtual type with empty AMSAT list shows empty not everything`() = runTest {
|
||||
// 根因2回归: AMSAT 清单未同步(空)时, 选虚拟类型应显示空列表, 而非全部卫星.
|
||||
val repo = createRepo(items = sampleItems, amSatFm = emptySet())
|
||||
repo.setTypes(listOf("AMSAT Live FM"))
|
||||
assertTrue(repo.getEntriesFlow().first().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `virtual type combined with regular type unions both lists`() = runTest {
|
||||
val repo = createRepo(
|
||||
items = sampleItems,
|
||||
amSatFm = setOf(25544),
|
||||
amSatLinear = setOf(7530)
|
||||
)
|
||||
repo.setTypes(listOf("AMSAT Live FM", "AMSAT Live Linear"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(setOf(25544, 7530), results.map { it.catnum }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `types list has virtual transponder types first and keeps All`() {
|
||||
val repo = createRepo(sampleItems)
|
||||
val types = repo.getTypesList()
|
||||
assertTrue(types.size >= 4)
|
||||
assertEquals("AMSAT Live FM", types[0])
|
||||
assertEquals("AMSAT Live Linear", types[1])
|
||||
assertEquals("Live SSTV", types[2])
|
||||
// "All" must be kept in the list (first original type shown after virtual ones).
|
||||
assertTrue("All" in types)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `All type resolves to persisted CelesTrak active ids`() = runTest {
|
||||
// Regression: "All" is a real TLE source type (CelesTrak active). Its
|
||||
// ids are persisted on sync like any other type; selecting it must
|
||||
// show the synced satellites, NOT an empty list.
|
||||
val fake = FakeSettingsRepoForSearch()
|
||||
fake.setSatelliteTypeIds("All", sampleItems.map { it.catnum })
|
||||
val repo = SelectionRepo(
|
||||
dispatcher = Dispatchers.Unconfined,
|
||||
localSource = FakeLocalSourceForSearch(sampleItems),
|
||||
settingsRepo = fake
|
||||
)
|
||||
repo.setTypes(listOf("All"))
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(sampleItems.map { it.catnum }.toSet(), results.map { it.catnum }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getTypesList excludes only the Other placeholder`() = runTest {
|
||||
val repo = createRepo(sampleItems)
|
||||
val types = repo.getTypesList()
|
||||
// All real TLE source types must be selectable, including "All"
|
||||
// (CelesTrak active) and "ARISS" (removed by the old removeAt(0)).
|
||||
assertTrue("All" in types)
|
||||
assertTrue("ARISS" in types)
|
||||
assertTrue("R4UAB" in types)
|
||||
assertTrue("SatNOGS" in types)
|
||||
assertTrue("Other" !in types)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `all types shows all items`() = runTest {
|
||||
val repo = createRepo(sampleItems)
|
||||
repo.setTypes(emptyList()) // "All" = no type filtering
|
||||
val results = repo.getEntriesFlow().first()
|
||||
assertEquals(sampleItems.size, results.size)
|
||||
assertEquals(sampleItems.map { it.catnum }.toSet(), results.map { it.catnum }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `amsat list version bump re-resolves FM filter after data sync`() = runTest {
|
||||
// ISS module aliases: dirty pre-sync FM list contains both ZARYA and DESTINY.
|
||||
val items = listOf(
|
||||
SatItem(25544, "ISS (ZARYA)"),
|
||||
SatItem(26700, "ISS (DESTINY)")
|
||||
)
|
||||
val fake = FakeSettingsRepoForSearch(amSatFm = setOf(25544, 26700))
|
||||
val repo = SelectionRepo(
|
||||
dispatcher = Dispatchers.Unconfined,
|
||||
localSource = FakeLocalSourceForSearch(items),
|
||||
settingsRepo = FakeSettingsRepoForSearch()
|
||||
settingsRepo = fake
|
||||
)
|
||||
repo.setTypes(listOf("AMSAT Live FM"))
|
||||
assertEquals(setOf(25544, 26700), repo.getEntriesFlow().first().map { it.catnum }.toSet())
|
||||
|
||||
// Simulate a background data sync: lists rewritten + version bumped.
|
||||
fake.setAmSatCatnums(fmCatnums = setOf(25544), linearCatnums = emptySet())
|
||||
|
||||
// The FM filter must reflect the new list WITHOUT a type toggle or restart.
|
||||
assertEquals(listOf(25544), repo.getEntriesFlow().first().map { it.catnum })
|
||||
}
|
||||
|
||||
private fun createRepo(
|
||||
items: List<SatItem>,
|
||||
amSatFm: Set<Int> = emptySet(),
|
||||
amSatLinear: Set<Int> = emptySet(),
|
||||
sstvIds: List<Int> = emptyList(),
|
||||
amSatActive: Set<Int> = emptySet()
|
||||
): ISelectionRepo {
|
||||
return SelectionRepo(
|
||||
dispatcher = Dispatchers.Unconfined,
|
||||
localSource = FakeLocalSourceForSearch(items, sstvIds),
|
||||
settingsRepo = FakeSettingsRepoForSearch(amSatFm, amSatLinear, amSatActive)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private class FakeLocalSourceForSearch(private val items: List<SatItem>) : ILocalSource {
|
||||
private class FakeLocalSourceForSearch(
|
||||
private val items: List<SatItem>,
|
||||
private val sstvIds: List<Int> = emptyList()
|
||||
) : ILocalSource {
|
||||
override suspend fun getEntriesTotal(): Int = items.size
|
||||
override suspend fun getEntriesList(): List<SatItem> = items
|
||||
override suspend fun getEntriesWithIds(ids: List<Int>): List<OrbitalObject> = emptyList()
|
||||
override suspend fun insertEntries(entries: List<OrbitalData>) = Unit
|
||||
override suspend fun deleteEntries() = Unit
|
||||
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = emptyList()
|
||||
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = sstvIds
|
||||
override suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int> = sstvIds
|
||||
override suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int> = sstvIds
|
||||
override suspend fun getRadiosTotal(): Int = 0
|
||||
override suspend fun getRadiosWithId(id: Int): List<SatRadio> = emptyList()
|
||||
override suspend fun insertRadios(radios: List<SatRadio>, isCustom: Boolean) = Unit
|
||||
@@ -135,7 +313,12 @@ private class FakeLocalSourceForSearch(private val items: List<SatItem>) : ILoca
|
||||
override suspend fun deleteRadios() = Unit
|
||||
}
|
||||
|
||||
private class FakeSettingsRepoForSearch : ISettingsRepo {
|
||||
private class FakeSettingsRepoForSearch(
|
||||
var amSatFm: Set<Int> = emptySet(),
|
||||
var amSatLinear: Set<Int> = emptySet(),
|
||||
private var amSatActive: Set<Int> = emptySet()
|
||||
) : ISettingsRepo {
|
||||
private val typeIds = mutableMapOf<String, List<Int>>()
|
||||
override val appVersionName: String = "test"
|
||||
override val selectedIds: StateFlow<List<Int>> = MutableStateFlow(emptyList())
|
||||
override val selectedTypes: StateFlow<List<String>> = MutableStateFlow(emptyList())
|
||||
@@ -170,13 +353,27 @@ private class FakeSettingsRepoForSearch : ISettingsRepo {
|
||||
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
|
||||
override fun setStationPosition(): Boolean = true
|
||||
override fun setStationPosition(locator: String): Boolean = true
|
||||
override fun getSatelliteTypesIds(types: List<String>): List<Int> = emptyList()
|
||||
override fun setSatelliteTypeIds(type: String, ids: List<Int>) = Unit
|
||||
override fun getSatelliteTypesIds(types: List<String>): List<Int> =
|
||||
types.flatMap { typeIds[it].orEmpty() }.distinct()
|
||||
|
||||
override fun setSatelliteTypeIds(type: String, ids: List<Int>) {
|
||||
typeIds[type] = ids
|
||||
}
|
||||
override fun updateDatabaseState(state: DatabaseState) = Unit
|
||||
override fun updateRCSettings(settings: RCSettings) = Unit
|
||||
override fun updateOtherSettings(transform: (OtherSettings) -> OtherSettings) = Unit
|
||||
override fun updateDataSourcesSettings(settings: DataSourcesSettings) = Unit
|
||||
override fun updateDataSourcesStatus(status: Map<String, Int>) = Unit
|
||||
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
|
||||
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
|
||||
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
|
||||
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
|
||||
amSatFm = fmCatnums
|
||||
amSatLinear = linearCatnums
|
||||
(amSatListsVersion as MutableStateFlow<Int>).value++
|
||||
}
|
||||
override fun getAmSatActiveCatnums(): Set<Int> = amSatActive
|
||||
override fun setAmSatActiveCatnums(catnums: Set<Int>) { amSatActive = catnums }
|
||||
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
|
||||
override fun getSatelliteOffset(catnum: Int): String = ""
|
||||
override fun setSatelliteOffset(catnum: Int, offset: String) = Unit
|
||||
@@ -189,6 +386,8 @@ private class FakeSettingsRepoForSearch : ISettingsRepo {
|
||||
override fun setWorkedGridQsos(qsos: Map<String, List<com.rtbishop.look4sat.core.domain.model.GridQso>>) = Unit
|
||||
override fun getRoamedGrids(): Set<String> = emptySet()
|
||||
override fun setRoamedGrids(grids: Set<String>) = Unit
|
||||
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
|
||||
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
|
||||
override fun updateLoTWSettings(settings: com.rtbishop.look4sat.core.domain.model.LoTWSettings) = Unit
|
||||
override fun getLastLotwSyncDate(): String = ""
|
||||
override fun setLastLotwSyncDate(date: String) = Unit
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Look4Sat. Amateur radio satellite tracker and pass predictor.
|
||||
* Copyright (C) 2019-2026 Arty Bishop and contributors.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.rtbishop.look4sat.core.domain.model
|
||||
|
||||
/**
|
||||
* A station the user marked in a gridsquare they have NOT yet worked — a
|
||||
* reminder to try to contact that callsign. Stored per 4-char grid (one mark
|
||||
* per grid).
|
||||
*
|
||||
* @param call the callsign the user wants to work (uppercase)
|
||||
* @param epochMs the moment the mark was created, UTC milliseconds
|
||||
*/
|
||||
data class MarkedStation(
|
||||
val call: String,
|
||||
val epochMs: Long
|
||||
)
|
||||
@@ -33,6 +33,10 @@ data class SatRadio(
|
||||
@SerialName("uplink_mode") val uplinkMode: String?,
|
||||
@SerialName("invert") val isInverted: Boolean,
|
||||
@SerialName("norad_cat_id") val catnum: Int?,
|
||||
/** Service class from the transceiver source ("Amateur"/"Unknown" etc.).
|
||||
* Used by the SSTV virtual filter to tell amateur satellites apart from
|
||||
* debris / weather birds (TIROS) / launcher stages (Ariane 6 R/B). */
|
||||
@SerialName("service") val service: String? = null,
|
||||
/** Set for manually imported transceivers, which remote updates must not replace. */
|
||||
val isCustom: Boolean = false
|
||||
)
|
||||
+15
@@ -65,4 +65,19 @@ interface ISatelliteRepo {
|
||||
|
||||
/** Fetch radio transceivers for a satellite by its catalog number. */
|
||||
suspend fun getRadiosWithId(id: Int): List<SatRadio>
|
||||
|
||||
/** Satellite catnums whose radios carry any of the given downlink modes.
|
||||
* Empty modes -> empty result; used to filter the mutual-match satellite
|
||||
* set to transponder satellites (FM voice / linear). */
|
||||
suspend fun getSatelliteIdsWithModes(modes: List<String>): List<Int>
|
||||
|
||||
/** Like [getSatelliteIdsWithModes] but only matches records with an uplink
|
||||
* (real transponders), excluding downlink-only beacons/telemetry that share
|
||||
* the same mode label. Used by the FM/Linear fallback filter. */
|
||||
suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>): List<Int>
|
||||
|
||||
/** Like [getSatelliteIdsWithModes] but only matches records whose service
|
||||
* class is "Amateur", so SSTV never matches weather birds (TIROS),
|
||||
* launcher debris or other non-amateur transmitters. */
|
||||
suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>): List<Int>
|
||||
}
|
||||
+22
@@ -79,6 +79,23 @@ interface ISettingsRepo {
|
||||
fun updateDataSourcesStatus(status: Map<String, Int>)
|
||||
//endregion
|
||||
|
||||
//region # AMSAT live-transponder lists
|
||||
/** Catalog numbers of satellites listed on AMSAT's "Live FM Satellites" page. */
|
||||
fun getAmSatFmCatnums(): Set<Int>
|
||||
/** Catalog numbers of satellites listed on AMSAT's "Live Linear Satellites" page. */
|
||||
fun getAmSatLinearCatnums(): Set<Int>
|
||||
fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>)
|
||||
/** Catalog numbers of active *amateur* satellites from AMSAT's
|
||||
* active-transponder table (whitelist for the virtual type filters). */
|
||||
fun getAmSatActiveCatnums(): Set<Int>
|
||||
fun setAmSatActiveCatnums(catnums: Set<Int>)
|
||||
/** Monotonic version counter, incremented every time the AMSAT live
|
||||
* FM/Linear lists are rewritten. Consumers that resolve the virtual
|
||||
* types (SelectionRepo) should re-resolve on change so a background
|
||||
* data sync is reflected in the UI without a restart. */
|
||||
val amSatListsVersion: StateFlow<Int>
|
||||
//endregion
|
||||
|
||||
//region # Radio control settings
|
||||
val radioControlSettings: StateFlow<RadioControlSettings>
|
||||
fun updateRadioControlSettings(settings: RadioControlSettings)
|
||||
@@ -105,6 +122,11 @@ interface ISettingsRepo {
|
||||
/** Distinct 4-char gridsquares the account operated from (LoTW <MY_GRIDSQUARE>). */
|
||||
fun getRoamedGrids(): Set<String>
|
||||
fun setRoamedGrids(grids: Set<String>)
|
||||
/** Stations the user marked as "want to contact" in unworked gridsquares
|
||||
* (grid -> ordered list of marks; the first is the pinned/top one). The
|
||||
* whole grid clears automatically once it becomes worked. */
|
||||
fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>
|
||||
fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>)
|
||||
//endregion
|
||||
|
||||
//region # LoTW confirmed-grids settings
|
||||
|
||||
@@ -29,6 +29,8 @@ interface ILocalSource {
|
||||
suspend fun insertEntries(entries: List<OrbitalData>)
|
||||
suspend fun deleteEntries()
|
||||
suspend fun getIdsWithModes(modes: List<String>): List<Int>
|
||||
suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int>
|
||||
suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int>
|
||||
suspend fun getRadiosTotal(): Int
|
||||
suspend fun getRadiosWithId(id: Int): List<SatRadio>
|
||||
suspend fun insertRadios(radios: List<SatRadio>, isCustom: Boolean = false)
|
||||
|
||||
@@ -55,4 +55,31 @@ object Sources {
|
||||
"SatNOGS" to "https://db.satnogs.org/api/transmitters/?format=json&status=active",
|
||||
"R4UAB" to "https://r4uab.ru/transmitters.json"
|
||||
)
|
||||
/** AMSAT "Live FM/Linear Satellites" pages: human-maintained lists of
|
||||
* transponders currently on the air. Parsed into the mutual-match filter
|
||||
* (satellites that actually carry a working FM-voice / linear repeater). */
|
||||
val amSatLiveUrls = mapOf(
|
||||
"FM" to "https://www.amsat.org/live-fm-satellites/",
|
||||
"Linear" to "https://www.amsat.org/live-linear-satellites/"
|
||||
)
|
||||
|
||||
/** Machine-readable AMSAT active-transponder table (palewire mirror of
|
||||
* amsat.org's active-frequency pages): one CSV row per active amateur
|
||||
* transponder with its NORAD catnum. Used as the authoritative whitelist
|
||||
* of *amateur* satellites, so the virtual filters never match
|
||||
* non-amateur debris (Ariane 6 R/B), retired weather sats (TIROS), or
|
||||
* ISS station-module aliases (ISS (DESTINY) etc.). Primary source plus
|
||||
* a jsDelivr CDN mirror: raw.githubusercontent.com is unreachable on
|
||||
* some networks (e.g. mainland China mobile), and a failed whitelist
|
||||
* fetch would silently disable the module disambiguation. */
|
||||
val amSatActiveUrls = listOf(
|
||||
"https://raw.githubusercontent.com/palewire/amateur-satellite-database/main/data/amsat-active-frequencies.csv",
|
||||
"https://cdn.jsdelivr.net/gh/palewire/amateur-satellite-database@main/data/amsat-active-frequencies.csv"
|
||||
)
|
||||
|
||||
/** Virtual satellite-selection types: transponder/activity filters shown
|
||||
* at the top of the type picker. They resolve to live lists (AMSAT pages
|
||||
* or mode=SSTV radios) instead of persisted per-type IDs, and are
|
||||
* mutually exclusive with the regular TLE-source types in the picker. */
|
||||
val virtualTypeNames = listOf("AMSAT Live FM", "AMSAT Live Linear", "Live SSTV")
|
||||
}
|
||||
@@ -40,6 +40,21 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse AMSAT's active-transponder CSV (palewire mirror) and return the
|
||||
* set of NORAD catnums of active *amateur* satellites. Header row has a
|
||||
* norad_id column; some rows carry alphanumeric IDs (Bluebird A0241 etc.)
|
||||
* which are skipped. */
|
||||
suspend fun parseAmSatActiveCatnums(stream: InputStream): Set<Int> = withContext(dispatcher) {
|
||||
stream.bufferedReader().useLines { lines ->
|
||||
val header = lines.firstOrNull() ?: return@useLines emptySet()
|
||||
val noradIdx = header.split(",").indexOfFirst { it.trim().equals("norad_id", true) }
|
||||
if (noradIdx < 0) return@useLines emptySet()
|
||||
lines.mapNotNull { line ->
|
||||
line.split(",").getOrNull(noradIdx)?.trim()?.toIntOrNull()
|
||||
}.toSet()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun parseTLEStream(stream: InputStream): List<OrbitalData> = withContext(dispatcher) {
|
||||
stream.bufferedReader().readLines()
|
||||
.chunked(3)
|
||||
@@ -58,6 +73,101 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an AMSAT "Live FM/Linear Satellites" page into satellite names.
|
||||
* The page is an HTML table whose first column is the satellite name,
|
||||
* sometimes written as an alias list ("AO-91(RadFxSat / Fox-1B)") or a
|
||||
* range ("TEVEL2-1 thru TEVEL2-9"). Returns the distinct expanded names.
|
||||
*/
|
||||
suspend fun parseAmSatLivePage(stream: InputStream): List<String> = withContext(dispatcher) {
|
||||
runCatching {
|
||||
val html = stream.bufferedReader().readText()
|
||||
// Grab table rows, take the first cell of each row, keep rows that
|
||||
// look like satellite names (start with letters/digits, not a header).
|
||||
val rows = Regex("<tr[^>]*>(.*?)</tr>", RegexOption.IGNORE_CASE)
|
||||
.findAll(html)
|
||||
.mapNotNull { match ->
|
||||
val cells = Regex("<t[dh][^>]*>(.*?)</t[dh]>", RegexOption.IGNORE_CASE)
|
||||
.findAll(match.groupValues[1])
|
||||
.map { cell -> stripHtml(cell.groupValues[1]).trim() }
|
||||
.toList()
|
||||
cells.firstOrNull()?.takeIf { it.isNotBlank() && !it.equals("Satellite", ignoreCase = true) }
|
||||
}
|
||||
.toList()
|
||||
rows.flatMap { expandNameRange(it) }.distinct()
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
private fun stripHtml(raw: String): String =
|
||||
raw.replace(Regex("<[^>]+>"), " ").replace(Regex("\\s+"), " ").trim()
|
||||
|
||||
/** Expand "NAME1 thru NAME9" ranges (e.g. TEVEL2-1 thru TEVEL2-9). */
|
||||
private fun expandNameRange(name: String): List<String> {
|
||||
val m = Regex("^(.*?)(\\d+)\\s+thru\\s+(.*?)(\\d+)$", RegexOption.IGNORE_CASE).find(name)
|
||||
if (m == null) return listOf(name)
|
||||
val prefix1 = m.groupValues[1].trim()
|
||||
val startNum = m.groupValues[2].toIntOrNull() ?: return listOf(name)
|
||||
val endNum = m.groupValues[4].toIntOrNull() ?: return listOf(name)
|
||||
val prefix2 = m.groupValues[3].trim()
|
||||
if (startNum > endNum) return listOf(name)
|
||||
// Suffix after the end number, if any (e.g. "TEVEL2-1 thru TEVEL2-9 ").
|
||||
val suffix = name.substringAfterLast(m.groupValues[4]).trim()
|
||||
return (startNum..endNum).map { "$prefix1$it$suffix" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a satellite name from the AMSAT live pages into lookup keys
|
||||
* used to match against the local entries table:
|
||||
* - primary key: the leading designator ("AO-91" from "AO-91 (RadFxSat / Fox-1B)")
|
||||
* - alias keys: every bracketed alias, uppercased, digits preserved
|
||||
* The local entry names are normalized the same way in [matchesAmSatName].
|
||||
*/
|
||||
fun normalizeAmSatName(name: String): List<String> {
|
||||
val keys = mutableListOf<String>()
|
||||
// Primary: everything before the first '(' (or '['), then the first token.
|
||||
val primary = name.substringBefore('(').substringBefore('[').trim()
|
||||
primary.split(Regex("\\s+")).firstOrNull()?.takeIf { it.isNotBlank() }?.let {
|
||||
keys += it.uppercase()
|
||||
}
|
||||
// Aliases inside parentheses / brackets: "RadFxSat / Fox-1B" -> two keys.
|
||||
Regex("\\(([^)]*)\\)").findAll(name).forEach { m ->
|
||||
m.groupValues[1].split('/', '|').forEach { alias ->
|
||||
alias.trim().takeIf { it.isNotBlank() }?.let { keys += it.uppercase() }
|
||||
}
|
||||
}
|
||||
Regex("\\[([^]]*)]").findAll(name).forEach { m ->
|
||||
m.groupValues[1].split('/', '|').forEach { alias ->
|
||||
alias.trim().takeIf { it.isNotBlank() }?.let { keys += it.uppercase() }
|
||||
}
|
||||
}
|
||||
return keys.distinct()
|
||||
}
|
||||
|
||||
/** True if a local entry name matches any of the AMSAT normalized keys.
|
||||
* Token-based exact match (split on spaces/brackets/slashes), so a key
|
||||
* like "ISS" does not substring-match "AISSAT-1" — the key must equal a
|
||||
* whole name token (case-insensitive). OSCAR designators are expanded so
|
||||
* that "AO-7" also matches local names spelled "OSCAR 7" / "AMSAT-OSCAR 7"
|
||||
* (the form used by CelesTrak/SatNOGS TLE sources). */
|
||||
fun matchesAmSatName(localName: String, amSatKeys: List<String>): Boolean {
|
||||
val localUpper = localName.uppercase()
|
||||
val localTokens = localUpper
|
||||
.split(Regex("[\\s()\\[\\]/]+"))
|
||||
.filter { it.isNotBlank() }
|
||||
.toSet()
|
||||
return amSatKeys.any { key ->
|
||||
val k = key.uppercase()
|
||||
if (k in localTokens) return@any true
|
||||
// "AO-7" -> also match local "OSCAR 7" or "AMSAT-OSCAR 7".
|
||||
val oscar = Regex("^([A-Z]{1,3})-(\\d+)$").find(k)
|
||||
if (oscar != null) {
|
||||
val num = oscar.groupValues[2]
|
||||
if ("OSCAR $num" in localUpper || "AMSAT-OSCAR $num" in localUpper) return@any true
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseCSV(values: List<String>): OrbitalData? = runCatching {
|
||||
val name = values[0]
|
||||
val timestamp = values[2]
|
||||
|
||||
@@ -239,4 +239,60 @@ class DataParserTest {
|
||||
// Matches the CSV test data epoch: 2021-11-16 → day 320
|
||||
assert(dataParser.getDayOfYear(2021, 11, 16) == 320)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT FM page parses satellite names and expands thru ranges`() = runTest(testDispatcher) {
|
||||
val html = """
|
||||
<html><body><table>
|
||||
<tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr>
|
||||
<tr><td>AO-91(RadFxSat / Fox-1B)</td><td>435.250</td><td>145.960</td></tr>
|
||||
<tr><td>SO-50(SaudiSat-1C)</td><td>145.850</td><td>436.795</td></tr>
|
||||
<tr><td>TEVEL2-1 thru TEVEL2-9</td><td>145.970</td><td>436.400</td></tr>
|
||||
</table></body></html>
|
||||
""".trimIndent().byteInputStream()
|
||||
val names = dataParser.parseAmSatLivePage(html)
|
||||
assert(names.contains("AO-91(RadFxSat / Fox-1B)"))
|
||||
assert(names.contains("SO-50(SaudiSat-1C)"))
|
||||
assert(names.contains("TEVEL2-1"))
|
||||
assert(names.contains("TEVEL2-9"))
|
||||
assert(names.size == 11) // 2 singles + 9 expanded TEVEL2
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT linear page keeps mode-suffixed names`() = runTest(testDispatcher) {
|
||||
val html = """
|
||||
<table>
|
||||
<tr><th>Satellite</th><th>Frequencies</th><th>Comment</th></tr>
|
||||
<tr><td>AO-7 Mode B U/v Inverting Analog</td><td>Uplink LSB</td></tr>
|
||||
<tr><td>FO-29 (JAS-2)V/u Inverting Analog</td><td>Uplink LSB</td></tr>
|
||||
</table>
|
||||
""".trimIndent().byteInputStream()
|
||||
val names = dataParser.parseAmSatLivePage(html)
|
||||
assert(names.contains("AO-7 Mode B U/v Inverting Analog"))
|
||||
assert(names.contains("FO-29 (JAS-2)V/u Inverting Analog"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT name normalization produces primary and alias keys`() {
|
||||
assert(dataParser.normalizeAmSatName("AO-91(RadFxSat / Fox-1B)") == listOf("AO-91", "RADFXSAT", "FOX-1B"))
|
||||
assert(dataParser.normalizeAmSatName("QO-100 (Es'hail-2/P4A) S/x") == listOf("QO-100", "ES'HAIL-2", "P4A"))
|
||||
assert(dataParser.normalizeAmSatName("ISS") == listOf("ISS"))
|
||||
assert(dataParser.matchesAmSatName("AO-91 (RADFXSAT)", listOf("AO-91", "RADFXSAT")))
|
||||
assert(!dataParser.matchesAmSatName("SO-50", listOf("AO-91")))
|
||||
// Regression: "ISS" must not substring-match "AISSAT-1" (token match only).
|
||||
assert(dataParser.matchesAmSatName("ISS (ZARYA)", listOf("ISS")))
|
||||
assert(!dataParser.matchesAmSatName("AISSAT-1", listOf("ISS")))
|
||||
assert(!dataParser.matchesAmSatName("TESS", listOf("ISS")))
|
||||
// OSCAR designators match local names spelled "OSCAR N"/"AMSAT-OSCAR N".
|
||||
assert(dataParser.matchesAmSatName("OSCAR 7", listOf("AO-7")))
|
||||
assert(dataParser.matchesAmSatName("AMSAT-OSCAR 7", listOf("AO-7")))
|
||||
assert(dataParser.matchesAmSatName("CATSAT", listOf("CATSAT")))
|
||||
assert(dataParser.matchesAmSatName("RS-44 & BREEZE-KM R/B", listOf("RS-44")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT live page with no table returns empty`() = runTest(testDispatcher) {
|
||||
val html = "<html><body>No data</body></html>".byteInputStream()
|
||||
assert(dataParser.parseAmSatLivePage(html).isEmpty())
|
||||
}
|
||||
}
|
||||
+10
@@ -21,6 +21,7 @@ import com.rtbishop.look4sat.core.domain.model.DatabaseState
|
||||
import com.rtbishop.look4sat.core.domain.model.DataSourcesSettings
|
||||
import com.rtbishop.look4sat.core.domain.model.GridQso
|
||||
import com.rtbishop.look4sat.core.domain.model.LoTWSettings
|
||||
import com.rtbishop.look4sat.core.domain.model.MarkedStation
|
||||
import com.rtbishop.look4sat.core.domain.model.OtherSettings
|
||||
import com.rtbishop.look4sat.core.domain.model.PassesSettings
|
||||
import com.rtbishop.look4sat.core.domain.model.RCSettings
|
||||
@@ -261,6 +262,9 @@ class LoTWGridSyncTest {
|
||||
override fun setWorkedGridQsos(qsos: Map<String, List<GridQso>>) { workedGridQsos = qsos }
|
||||
override fun getRoamedGrids(): Set<String> = roamedGrids
|
||||
override fun setRoamedGrids(grids: Set<String>) { roamedGrids = grids }
|
||||
private var markedGridStations: Map<String, List<MarkedStation>> = emptyMap()
|
||||
override fun getMarkedGridStations(): Map<String, List<MarkedStation>> = markedGridStations
|
||||
override fun setMarkedGridStations(stations: Map<String, List<MarkedStation>>) { markedGridStations = stations }
|
||||
override fun getLastLotwSyncDate(): String = lastSyncDate
|
||||
override fun setLastLotwSyncDate(date: String) { lastSyncDate = date }
|
||||
override fun getLastLotwSyncCallsign(): String = lastSyncCallsign
|
||||
@@ -279,6 +283,12 @@ class LoTWGridSyncTest {
|
||||
override fun updateOtherSettings(transform: (OtherSettings) -> OtherSettings) = TODO()
|
||||
override fun updateDataSourcesSettings(settings: DataSourcesSettings) = TODO()
|
||||
override fun updateDataSourcesStatus(status: Map<String, Int>) = TODO()
|
||||
override fun getAmSatFmCatnums(): Set<Int> = emptySet()
|
||||
override fun getAmSatLinearCatnums(): Set<Int> = emptySet()
|
||||
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
|
||||
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) = Unit
|
||||
override fun getAmSatActiveCatnums(): Set<Int> = emptySet()
|
||||
override fun setAmSatActiveCatnums(catnums: Set<Int>) = Unit
|
||||
override fun updateRadioControlSettings(settings: RadioControlSettings) = TODO()
|
||||
override fun getSatelliteOffset(catnum: Int): String = ""
|
||||
override fun setSatelliteOffset(catnum: Int, offset: String) = TODO()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<!-- 冖 (秃宝盖): 顶横 + 两侧短竖, 笔画型 -->
|
||||
<path
|
||||
android:pathData="M5,4 L19,4 M5,4 L5,8.5 M19,4 L19,8.5"
|
||||
android:strokeColor="@android:color/white"
|
||||
android:strokeWidth="2"
|
||||
android:strokeLineCap="round"
|
||||
android:fillColor="#00000000" />
|
||||
<!-- 笔画型向上箭头 ↑: 竖杆 + 两斜线箭头头 -->
|
||||
<path
|
||||
android:pathData="M12,9 L12,20 M12,9 L7.5,14 M12,9 L16.5,14"
|
||||
android:strokeColor="@android:color/white"
|
||||
android:strokeWidth="2"
|
||||
android:strokeLineCap="round"
|
||||
android:fillColor="#00000000" />
|
||||
</vector>
|
||||
@@ -131,6 +131,13 @@
|
||||
<string name="grid_qso_first">首通</string>
|
||||
<string name="grid_qso_no_sat">卫星未知</string>
|
||||
<string name="grid_qso_match">匹配</string>
|
||||
<!-- 未通联网格中的“标记想通联的电台”提醒 -->
|
||||
<string name="grid_mark_station">标记你想通联的电台</string>
|
||||
<string name="grid_mark_callsign">呼号</string>
|
||||
<string name="grid_mark_confirm">标记</string>
|
||||
<string name="grid_mark_label">标记</string>
|
||||
<string name="grid_mark_delete">删除标记</string>
|
||||
<string name="grid_mark_pin">置顶</string>
|
||||
<string name="map_visible">日照中</string>
|
||||
|
||||
<!-- Settings screen -->
|
||||
@@ -301,6 +308,9 @@
|
||||
<string name="mutual_grid_hint">支持 4/6/8 位 Maidenhead 网格;也可直接输入经纬度</string>
|
||||
<string name="mutual_min_elevation">最小仰角:%d°</string>
|
||||
<string name="mutual_time_range">时间范围</string>
|
||||
<string name="mutual_filter_transponder">转发器</string>
|
||||
<string name="mutual_filter_fm">FM</string>
|
||||
<string name="mutual_filter_linear">线性</string>
|
||||
<string name="mutual_calculating">计算中…</string>
|
||||
<string name="mutual_query">查询匹配</string>
|
||||
<string name="mutual_elevation_you">你:%d°</string>
|
||||
|
||||
@@ -151,6 +151,13 @@
|
||||
<string name="grid_qso_first">First</string>
|
||||
<string name="grid_qso_no_sat">satellite unknown</string>
|
||||
<string name="grid_qso_match">Match</string>
|
||||
<!-- Mark-a-station reminder in unworked grids -->
|
||||
<string name="grid_mark_station">Mark a station you want to contact</string>
|
||||
<string name="grid_mark_callsign">Callsign</string>
|
||||
<string name="grid_mark_confirm">Mark</string>
|
||||
<string name="grid_mark_label">Marked</string>
|
||||
<string name="grid_mark_delete">Remove mark</string>
|
||||
<string name="grid_mark_pin">Pin to top</string>
|
||||
<string name="map_visible">Visible</string>
|
||||
|
||||
<!-- Settings screen -->
|
||||
@@ -331,6 +338,9 @@
|
||||
<string name="mutual_grid_hint">Supports 4/6/8-char Maidenhead grid; or enter lat/lon directly</string>
|
||||
<string name="mutual_min_elevation">Min elevation: %d°</string>
|
||||
<string name="mutual_time_range">Time range</string>
|
||||
<string name="mutual_filter_transponder">Transponders</string>
|
||||
<string name="mutual_filter_fm">FM</string>
|
||||
<string name="mutual_filter_linear">Linear</string>
|
||||
<string name="mutual_calculating">Calculating…</string>
|
||||
<string name="mutual_query">Query Match</string>
|
||||
<string name="mutual_elevation_you">You: %d°</string>
|
||||
|
||||
+37
-4
@@ -64,6 +64,11 @@ class MaidenheadGridOverlay : Overlay() {
|
||||
style = android.graphics.Paint.Style.FILL
|
||||
color = Color.argb(90, 76, 217, 100)
|
||||
}
|
||||
// 标记(想通联)网格填充: 红色, 透明度与绿色 workedPaint 一致(alpha 90).
|
||||
private val markedPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = android.graphics.Paint.Style.FILL
|
||||
color = Color.argb(90, 255, 59, 48)
|
||||
}
|
||||
private val roamStripePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = 14f
|
||||
@@ -87,6 +92,12 @@ class MaidenheadGridOverlay : Overlay() {
|
||||
/** Worked gridsquares (4-char, uppercase) to highlight, e.g. {"OL62", "PM95"}. */
|
||||
var workedGrids: Set<String> = emptySet()
|
||||
|
||||
/** Marked gridsquares (4-char, uppercase) — unworked grids the user has
|
||||
* marked stations they want to contact in; drawn red, same alpha as the
|
||||
* green worked fill. Value is the ordered mark list (first = pinned);
|
||||
* label mode shows the FIRST marked callsign. */
|
||||
var markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
|
||||
|
||||
/** Grid-mode first-call labels: label worked (green) cells with the first
|
||||
* callsign worked in that grid instead of the Maidenhead code; non-worked
|
||||
* cells get no label at all. Only meaningful at sub-square zoom. */
|
||||
@@ -189,6 +200,9 @@ class MaidenheadGridOverlay : Overlay() {
|
||||
if (cellLabel(lat, lon, zoom) in workedGrids) {
|
||||
canvas.drawRect(xLeft, yTop, xRight, yBottom, workedPaint)
|
||||
}
|
||||
if (cellLabel(lat, lon, zoom) in markedGrids) {
|
||||
canvas.drawRect(xLeft, yTop, xRight, yBottom, markedPaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -215,6 +229,22 @@ class MaidenheadGridOverlay : Overlay() {
|
||||
canvas.drawRect(xLeft, yTop, xRight, yBottom, workedPaint)
|
||||
}
|
||||
}
|
||||
for (grid in markedGrids.keys) {
|
||||
val cell = gridCellBounds(grid) ?: continue
|
||||
for (turn in -colRepeats..colRepeats) {
|
||||
val dLon = turn * 360.0
|
||||
if (cell.lonRight + dLon <= leftLon || cell.lonLeft + dLon >= rightLon) continue
|
||||
val yTop = projectionToY(projection, cell.latTop) ?: continue
|
||||
val yBottom = projectionToY(projection, cell.latBottom) ?: continue
|
||||
val xLeftBase = projectionToX(projection, cell.lonLeft, centerLon, worldWidthPx) ?: continue
|
||||
val xRightBase = projectionToX(projection, cell.lonRight, centerLon, worldWidthPx) ?: continue
|
||||
val xLeft = xLeftBase + turn * worldWidthPx.toFloat()
|
||||
val xRight = xRightBase + turn * worldWidthPx.toFloat()
|
||||
if (xRight < 0f || xLeft > canvas.width) continue
|
||||
if (yBottom < 0f || yTop > canvas.height) continue
|
||||
canvas.drawRect(xLeft, yTop, xRight, yBottom, markedPaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,12 +444,15 @@ class MaidenheadGridOverlay : Overlay() {
|
||||
if (xRight < 0f || xLeft > canvas.width) continue
|
||||
val label = cellLabel(lat, lon, zoom)
|
||||
if (showFirstCallLabels) {
|
||||
// 首通呼号模式: 只有绿格(worked)标注该格第一个通联的呼号,
|
||||
// 非绿格空着不写网格字符.
|
||||
if (label in workedGrids) {
|
||||
firstCallsByGrid[label]?.let { call ->
|
||||
// 首通呼号模式: 绿格(worked)标注该格第一个通联的呼号, 红格(marked)
|
||||
// 标注用户标记想通联的呼号, 均淡黄文字; 其它格空着不写网格字符.
|
||||
when {
|
||||
label in workedGrids -> firstCallsByGrid[label]?.let { call ->
|
||||
canvas.drawText(call, (xLeft + xRight) / 2f, yCenter, firstCallPaint)
|
||||
}
|
||||
label in markedGrids -> markedGrids[label]?.firstOrNull()?.let { station ->
|
||||
canvas.drawText(station.call, (xLeft + xRight) / 2f, yCenter, firstCallPaint)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
canvas.drawText(label, (xLeft + xRight) / 2f, yCenter, labelPaint)
|
||||
|
||||
@@ -54,6 +54,7 @@ import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -153,7 +154,10 @@ fun MapDestination(
|
||||
mapFilterViewModel: MapFilterViewModel,
|
||||
// Invoked with the tapped grid when the QSO dialog's "Match" button is
|
||||
// pressed: navigate to the match page pre-filled for that grid.
|
||||
onMatchGrid: (String) -> Unit = {}
|
||||
onMatchGrid: (String) -> Unit = {},
|
||||
// True while the map "Match" query is running (the page only navigates
|
||||
// once the query finished, so the match page opens with results ready).
|
||||
matchCalculating: Boolean = false
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val container = (context.applicationContext as IContainerProvider).getMainContainer()
|
||||
@@ -190,7 +194,7 @@ fun MapDestination(
|
||||
viewModel.onAction(MapAction.SetVisible(false))
|
||||
}
|
||||
}
|
||||
MapScreen(uiState, viewModel::onAction, mapView, mapFilterViewModel, onMatchGrid)
|
||||
MapScreen(uiState, viewModel::onAction, mapView, mapFilterViewModel, onMatchGrid, matchCalculating)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -199,7 +203,8 @@ private fun MapScreen(
|
||||
onAction: (MapAction) -> Unit,
|
||||
mapView: MapView,
|
||||
mapFilterViewModel: MapFilterViewModel,
|
||||
onMatchGrid: (String) -> Unit
|
||||
onMatchGrid: (String) -> Unit,
|
||||
matchCalculating: Boolean
|
||||
) {
|
||||
val rotateMod = Modifier.rotate(180f)
|
||||
val timeString = uiState.mapData?.aosTime ?: "00:00:00"
|
||||
@@ -357,7 +362,8 @@ private fun MapScreen(
|
||||
centerOnStation = shouldCenter,
|
||||
// 首通呼号标签只作用于 VUCC 视图(用户要求); "All"/其他奖状不过滤.
|
||||
showFirstCallLabels = uiState.showFirstCallLabels && selectedAward == AwardType.VUCC,
|
||||
firstCallsByGrid = firstCallsByGrid
|
||||
firstCallsByGrid = firstCallsByGrid,
|
||||
markedGrids = uiState.markedGrids
|
||||
)
|
||||
if (!shouldCenter || uiState.stationPosition != null) {
|
||||
prevGridMode = uiState.isGridMode
|
||||
@@ -417,14 +423,20 @@ private fun MapScreen(
|
||||
}
|
||||
}
|
||||
// Centered dialog listing the tapped worked grid's confirmed satellite QSOs.
|
||||
// Dismissed by tapping outside (no explicit close button).
|
||||
// Dismissed by tapping outside (no explicit close button). Unworked grids
|
||||
// open the same dialog with an empty list plus a mark-a-station reminder.
|
||||
selectedGrid?.let { grid ->
|
||||
WorkedGridQsoDialog(
|
||||
grid = grid,
|
||||
qsos = uiState.workedGridQsos[grid].orEmpty().sortedBy { it.epochMs },
|
||||
marked = uiState.markedGrids[grid].orEmpty(),
|
||||
isUtc = uiState.isUtc,
|
||||
matchCalculating = matchCalculating,
|
||||
onDismiss = { selectedGrid = null },
|
||||
onMatch = { onMatchGrid(grid) }
|
||||
onMatch = { onMatchGrid(grid) },
|
||||
onMark = { call -> onAction(MapAction.SetMarkedStation(grid, call)) },
|
||||
onRemoveMark = { call -> onAction(MapAction.RemoveMarkedStation(grid, call)) },
|
||||
onPinMark = { call -> onAction(MapAction.PinMarkedStation(grid, call)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -435,10 +447,17 @@ private fun MapScreen(
|
||||
private fun WorkedGridQsoDialog(
|
||||
grid: String,
|
||||
qsos: List<com.rtbishop.look4sat.core.domain.model.GridQso>,
|
||||
marked: List<com.rtbishop.look4sat.core.domain.model.MarkedStation>,
|
||||
isUtc: Boolean,
|
||||
matchCalculating: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onMatch: () -> Unit
|
||||
onMatch: () -> Unit,
|
||||
onMark: (String) -> Unit,
|
||||
onRemoveMark: (String) -> Unit,
|
||||
onPinMark: (String) -> Unit
|
||||
) {
|
||||
var showMarkInput by remember { mutableStateOf(false) }
|
||||
var callInput by remember { mutableStateOf("") }
|
||||
androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) {
|
||||
// Centered card, ~85% width, internal scroll for long lists.
|
||||
Card(
|
||||
@@ -467,41 +486,181 @@ private fun WorkedGridQsoDialog(
|
||||
)
|
||||
}
|
||||
TextButton(
|
||||
enabled = !matchCalculating,
|
||||
onClick = {
|
||||
onDismiss()
|
||||
onMatch()
|
||||
}
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_radio_tower),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
if (matchCalculating) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_radio_tower),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(stringResource(R.string.grid_qso_match))
|
||||
}
|
||||
}
|
||||
androidx.compose.material3.HorizontalDivider()
|
||||
if (qsos.isNotEmpty()) {
|
||||
// Group by callsign preserving first-contact order (list is
|
||||
// already sorted oldest-first); expandable rows.
|
||||
val grouped = remember(qsos) {
|
||||
qsos.groupBy { it.call }.entries.sortedBy { it.value.first().epochMs }
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 380.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
) {
|
||||
// Marked stations show first as red reminder rows: pale-yellow
|
||||
// callsign, "标记" in the count column, the marking date in the
|
||||
// date column, a small pin icon (first = pinned, grey; others
|
||||
// pale yellow) and a delete icon to remove the mark.
|
||||
val showPin = marked.size > 1
|
||||
marked.forEachIndexed { index, station ->
|
||||
MarkedStationRow(
|
||||
marked = station,
|
||||
isPinned = index == 0,
|
||||
showPin = showPin,
|
||||
isUtc = isUtc,
|
||||
onRemoveMark = { onRemoveMark(station.call) },
|
||||
onPinMark = { onPinMark(station.call) }
|
||||
)
|
||||
androidx.compose.material3.HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 380.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
) {
|
||||
if (qsos.isNotEmpty()) {
|
||||
// Group by callsign preserving first-contact order (list is
|
||||
// already sorted oldest-first); expandable rows.
|
||||
val grouped = remember(qsos) {
|
||||
qsos.groupBy { it.call }.entries.sortedBy { it.value.first().epochMs }
|
||||
}
|
||||
grouped.forEach { (call, callQsos) ->
|
||||
WorkedGridCallRow(call, callQsos = callQsos, isUtc = isUtc)
|
||||
androidx.compose.material3.HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
|
||||
}
|
||||
}
|
||||
// Unworked grids: offer to mark a station the user wants to
|
||||
// contact in this grid (a reminder, cleared when worked).
|
||||
if (qsos.isEmpty()) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
callInput = ""
|
||||
showMarkInput = true
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_add),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(stringResource(R.string.grid_mark_station))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mark-a-station input dialog: enter a callsign as a reminder.
|
||||
if (showMarkInput) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { showMarkInput = false },
|
||||
title = { Text(stringResource(R.string.grid_mark_station)) },
|
||||
text = {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = callInput,
|
||||
onValueChange = { callInput = it.uppercase() },
|
||||
label = { Text(stringResource(R.string.grid_mark_callsign)) },
|
||||
singleLine = true
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
enabled = callInput.isNotBlank(),
|
||||
onClick = {
|
||||
onMark(callInput)
|
||||
showMarkInput = false
|
||||
}
|
||||
) { Text(stringResource(R.string.grid_mark_confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showMarkInput = false }) { Text(stringResource(R.string.btn_cancel)) }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkedStationRow(
|
||||
marked: com.rtbishop.look4sat.core.domain.model.MarkedStation,
|
||||
isPinned: Boolean,
|
||||
showPin: Boolean,
|
||||
isUtc: Boolean,
|
||||
onRemoveMark: () -> Unit,
|
||||
onPinMark: () -> Unit
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
) {
|
||||
Text(
|
||||
text = marked.call,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
|
||||
color = ComposeColor(0xFFFFE082),
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
// "标记" column: pin icon (only when the grid has multiple marks) sits
|
||||
// left of the label; pinned (first) row's icon is grey, others pale
|
||||
// yellow — tapping moves that mark to the top.
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
if (showPin) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_pin),
|
||||
contentDescription = stringResource(R.string.grid_mark_pin),
|
||||
tint = if (isPinned) ComposeColor(0xFF9E9E9E) else ComposeColor(0xFFFFE082),
|
||||
modifier = Modifier
|
||||
.size(18.dp)
|
||||
.clickable(onClick = onPinMark)
|
||||
)
|
||||
Spacer(Modifier.width(2.dp))
|
||||
}
|
||||
Text(
|
||||
text = stringResource(R.string.grid_mark_label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center
|
||||
)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.End,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = formatDate(marked.epochMs, isUtc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_delete),
|
||||
contentDescription = stringResource(R.string.grid_mark_delete),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier
|
||||
.size(18.dp)
|
||||
.clickable(onClick = onRemoveMark)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -929,7 +1088,8 @@ private fun setGridMode(
|
||||
stationPosition: GeoPos?,
|
||||
centerOnStation: Boolean = false,
|
||||
showFirstCallLabels: Boolean = false,
|
||||
firstCallsByGrid: Map<String, String> = emptyMap()
|
||||
firstCallsByGrid: Map<String, String> = emptyMap(),
|
||||
markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
|
||||
) {
|
||||
try {
|
||||
val gridOverlay = mapView.overlays[OVERLAY_GRID]
|
||||
@@ -940,6 +1100,7 @@ private fun setGridMode(
|
||||
// 首通呼号模式: 绿格标注第一个通联的呼号, 非绿格不显示标签.
|
||||
gridOverlay.showFirstCallLabels = showFirstCallLabels
|
||||
gridOverlay.firstCallsByGrid = firstCallsByGrid
|
||||
gridOverlay.markedGrids = markedGrids
|
||||
// ownGrid must be set on EVERY update — the position is available
|
||||
// regardless of whether this frame centers (centering happens only
|
||||
// on entry, but passing null here would wipe the bold outline).
|
||||
@@ -951,6 +1112,7 @@ private fun setGridMode(
|
||||
this.roamedGrids = roamedGrids
|
||||
this.showFirstCallLabels = showFirstCallLabels
|
||||
this.firstCallsByGrid = firstCallsByGrid
|
||||
this.markedGrids = markedGrids
|
||||
this.ownGrid = ownGridOf(stationPosition)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@ data class MapState(
|
||||
val workedGridQsos: Map<String, List<com.rtbishop.look4sat.core.domain.model.GridQso>> = emptyMap(),
|
||||
/** 4-char gridsquares the station operated from (LoTW MY_GRIDSQUARE) — blue stripes. */
|
||||
val roamedGrids: Set<String> = emptySet(),
|
||||
/** Stations the user marked in unworked gridsquares (grid -> ordered list;
|
||||
* first = pinned/top) — red fill. */
|
||||
val markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap(),
|
||||
val stationPosition: GeoPos? = null,
|
||||
val orbitalPass: OrbitalPass,
|
||||
val track: List<List<GeoPos>>? = null,
|
||||
@@ -52,6 +55,9 @@ sealed interface MapAction {
|
||||
data class SelectDefaultItem(val catnum: Int) : MapAction
|
||||
data class ToggleGridMode(val value: Boolean) : MapAction
|
||||
data class ToggleFirstCallLabels(val value: Boolean) : MapAction
|
||||
data class SetMarkedStation(val grid: String, val call: String) : MapAction
|
||||
data class RemoveMarkedStation(val grid: String, val call: String) : MapAction
|
||||
data class PinMarkedStation(val grid: String, val call: String) : MapAction
|
||||
data class SetVisible(val isVisible: Boolean) : MapAction
|
||||
}
|
||||
|
||||
|
||||
@@ -90,11 +90,19 @@ class MapViewModel(
|
||||
}
|
||||
viewModelScope.launch {
|
||||
settingsRepo.wavelogSettings.collectLatest { _ ->
|
||||
val workedGrids = settingsRepo.getWorkedGrids()
|
||||
val markedGrids = settingsRepo.getMarkedGridStations()
|
||||
// Marked stations auto-clear once their grid becomes worked:
|
||||
// the reminder has served its purpose (user req: 网格变绿后标记自动清除).
|
||||
val stale = markedGrids.keys.filter { it in workedGrids }
|
||||
val activeMarks = if (stale.isEmpty()) markedGrids else markedGrids - stale.toSet()
|
||||
if (stale.isNotEmpty()) settingsRepo.setMarkedGridStations(activeMarks)
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
workedGrids = settingsRepo.getWorkedGrids(),
|
||||
workedGrids = workedGrids,
|
||||
workedGridQsos = settingsRepo.getWorkedGridQsos(),
|
||||
roamedGrids = settingsRepo.getRoamedGrids()
|
||||
roamedGrids = settingsRepo.getRoamedGrids(),
|
||||
markedGrids = activeMarks
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -112,6 +120,38 @@ class MapViewModel(
|
||||
is MapAction.SelectDefaultItem -> selectDefaultSatellite(action.catnum)
|
||||
is MapAction.ToggleGridMode -> settingsRepo.updateOtherSettings { it.copy(stateOfMapGrid = action.value) }
|
||||
is MapAction.ToggleFirstCallLabels -> settingsRepo.updateOtherSettings { it.copy(stateOfMapFirstCall = action.value) }
|
||||
is MapAction.SetMarkedStation -> {
|
||||
val call = action.call.trim().uppercase()
|
||||
val existing = settingsRepo.getMarkedGridStations()
|
||||
val current = existing[action.grid].orEmpty()
|
||||
// 重复呼号忽略: 同一网格已标记过的呼号不再重复添加.
|
||||
val updated = if (current.any { it.call == call }) existing
|
||||
else existing + (action.grid to current + com.rtbishop.look4sat.core.domain.model.MarkedStation(
|
||||
call = call,
|
||||
epochMs = System.currentTimeMillis()
|
||||
))
|
||||
settingsRepo.setMarkedGridStations(updated)
|
||||
_uiState.update { it.copy(markedGrids = updated) }
|
||||
}
|
||||
is MapAction.RemoveMarkedStation -> {
|
||||
val existing = settingsRepo.getMarkedGridStations()
|
||||
val current = existing[action.grid].orEmpty()
|
||||
val remaining = current.filterNot { it.call == action.call }
|
||||
val updated = if (remaining.isEmpty()) existing - action.grid
|
||||
else existing + (action.grid to remaining)
|
||||
settingsRepo.setMarkedGridStations(updated)
|
||||
_uiState.update { it.copy(markedGrids = updated) }
|
||||
}
|
||||
is MapAction.PinMarkedStation -> {
|
||||
val existing = settingsRepo.getMarkedGridStations()
|
||||
val current = existing[action.grid].orEmpty()
|
||||
val target = current.firstOrNull { it.call == action.call }
|
||||
if (target != null) {
|
||||
val updated = existing + (action.grid to listOf(target) + current.filterNot { it.call == action.call })
|
||||
settingsRepo.setMarkedGridStations(updated)
|
||||
_uiState.update { it.copy(markedGrids = updated) }
|
||||
}
|
||||
}
|
||||
is MapAction.SetVisible -> isScreenVisible.value = action.isVisible
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ fun MutualScreen(
|
||||
viewModel = viewModel,
|
||||
state = state,
|
||||
isVertical = isVertical,
|
||||
onQuery = viewModel::queryMutualPasses,
|
||||
onQuery = { viewModel.queryMutualPasses() },
|
||||
onSelectPass = viewModel::onSelectPass,
|
||||
onNavigateToRadar = navigateToRadar,
|
||||
onStationALat = viewModel::onStationALat,
|
||||
@@ -174,6 +174,8 @@ fun MutualScreen(
|
||||
onStationBMinElev = viewModel::onStationBMinElev,
|
||||
onUseCurrentPosition = viewModel::onUseCurrentPosition,
|
||||
onHoursAhead = viewModel::onHoursAhead,
|
||||
onFilterFM = viewModel::onFilterFM,
|
||||
onFilterLinear = viewModel::onFilterLinear,
|
||||
onClearError = viewModel::clearError
|
||||
)
|
||||
}
|
||||
@@ -197,6 +199,8 @@ private fun MutualContent(
|
||||
onStationBMinElev: (Double) -> Unit,
|
||||
onUseCurrentPosition: () -> Unit,
|
||||
onHoursAhead: (Int) -> Unit,
|
||||
onFilterFM: (Boolean) -> Unit,
|
||||
onFilterLinear: (Boolean) -> Unit,
|
||||
onClearError: () -> Unit
|
||||
) {
|
||||
val timeFormat = remember(state.isUtc) {
|
||||
@@ -353,6 +357,10 @@ private fun MutualContent(
|
||||
MatchSearchCard(
|
||||
hoursAhead = state.hoursAhead,
|
||||
isCalculating = state.isCalculating,
|
||||
filterFM = state.filterFM,
|
||||
filterLinear = state.filterLinear,
|
||||
onFilterFM = onFilterFM,
|
||||
onFilterLinear = onFilterLinear,
|
||||
onHoursAhead = onHoursAhead,
|
||||
onQuery = onQuery
|
||||
)
|
||||
@@ -570,6 +578,10 @@ private fun StationInputCard(
|
||||
private fun MatchSearchCard(
|
||||
hoursAhead: Int,
|
||||
isCalculating: Boolean,
|
||||
filterFM: Boolean,
|
||||
filterLinear: Boolean,
|
||||
onFilterFM: (Boolean) -> Unit,
|
||||
onFilterLinear: (Boolean) -> Unit,
|
||||
onHoursAhead: (Int) -> Unit,
|
||||
onQuery: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
@@ -596,6 +608,28 @@ private fun MatchSearchCard(
|
||||
)
|
||||
}
|
||||
}
|
||||
// 转发器类型筛选: 只匹配 AMSAT Live 清单里的 FM 话音 / 线性转发器卫星,
|
||||
// 防止选入大量无转发器卫星占用匹配页.
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.mutual_filter_transponder),
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
FilterChip(
|
||||
selected = filterFM,
|
||||
onClick = { onFilterFM(!filterFM) },
|
||||
label = { Text(stringResource(R.string.mutual_filter_fm)) }
|
||||
)
|
||||
FilterChip(
|
||||
selected = filterLinear,
|
||||
onClick = { onFilterLinear(!filterLinear) },
|
||||
label = { Text(stringResource(R.string.mutual_filter_linear)) }
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = onQuery,
|
||||
enabled = !isCalculating,
|
||||
|
||||
+101
-16
@@ -52,6 +52,13 @@ data class MutualUiState(
|
||||
val stationBGrid: String = "",
|
||||
val stationBMinElev: Double = 10.0,
|
||||
val hoursAhead: Int = 24,
|
||||
/** 历史过境回看窗口(小时), 跟随主页面 Passes 设置; 匹配查询从
|
||||
* now-hoursBefore 开始, 使设置过历史回看时匹配页也包含历史过境. */
|
||||
val hoursBefore: Int = 0,
|
||||
/** 转发器类型筛选: 只匹配搭载 FM 话音转发器的卫星. 默认开启. */
|
||||
val filterFM: Boolean = true,
|
||||
/** 转发器类型筛选: 只匹配搭载线性(USB/LSB/CW/SSB)转发器的卫星. 默认开启. */
|
||||
val filterLinear: Boolean = true,
|
||||
val mutualPasses: List<MutualPass> = emptyList(),
|
||||
val isCalculating: Boolean = false,
|
||||
val hasSearched: Boolean = false,
|
||||
@@ -61,7 +68,12 @@ data class MutualUiState(
|
||||
// One-shot flag set by prefillMatchFromGrid() (map grid → Match button):
|
||||
// the page scrolls to the time-range card after the first layout, then
|
||||
// consumeScrollToTimeRange() clears it.
|
||||
val scrollToTimeRange: Boolean = false
|
||||
val scrollToTimeRange: Boolean = false,
|
||||
// One-shot flag set by prefillMatchFromGrid(): the map page waits for the
|
||||
// pre-filled query to finish, then navigates to the match page so the very
|
||||
// first frame already contains the results (time-range card + pass curves,
|
||||
// no scroll flicker). consumePendingNavigation() clears it.
|
||||
val pendingNavigation: Boolean = false
|
||||
)
|
||||
|
||||
class MutualViewModel(
|
||||
@@ -103,6 +115,12 @@ class MutualViewModel(
|
||||
_uiState.update { it.copy(isUtc = settings.stateOfUtc) }
|
||||
}
|
||||
}
|
||||
// 历史过境回看窗口跟随主页面 Passes 设置 (设置里改小时数, 匹配页同步生效)
|
||||
viewModelScope.launch {
|
||||
settingsRepo.passesSettings.collectLatest { settings ->
|
||||
_uiState.update { it.copy(hoursBefore = settings.hoursBefore) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onStationALat(value: String) {
|
||||
@@ -187,6 +205,8 @@ class MutualViewModel(
|
||||
) }
|
||||
}
|
||||
fun onHoursAhead(value: Int) = _uiState.update { it.copy(hoursAhead = value) }
|
||||
fun onFilterFM(value: Boolean) = _uiState.update { it.copy(filterFM = value) }
|
||||
fun onFilterLinear(value: Boolean) = _uiState.update { it.copy(filterLinear = value) }
|
||||
fun onSelectPass(index: Int) = _uiState.update { it.copy(selectedPassIndex = index) }
|
||||
|
||||
/**
|
||||
@@ -206,18 +226,33 @@ class MutualViewModel(
|
||||
stationBLat = pos?.let { p -> "%.4f".format(p.latitude) } ?: it.stationBLat,
|
||||
stationBLon = pos?.let { p -> "%.4f".format(p.longitude) } ?: it.stationBLon,
|
||||
hoursAhead = 24,
|
||||
scrollToTimeRange = true
|
||||
scrollToTimeRange = true,
|
||||
pendingNavigation = true
|
||||
)
|
||||
}
|
||||
queryMutualPasses()
|
||||
}
|
||||
|
||||
fun consumePendingNavigation() {
|
||||
android.util.Log.d(TAG, "consumePendingNavigation")
|
||||
_uiState.update { it.copy(pendingNavigation = false) }
|
||||
}
|
||||
|
||||
fun consumeScrollToTimeRange() {
|
||||
android.util.Log.d(TAG, "consumeScrollToTimeRange")
|
||||
_uiState.update { it.copy(scrollToTimeRange = false) }
|
||||
}
|
||||
|
||||
fun queryMutualPasses(initialScrollIndex: Int = 0) {
|
||||
/**
|
||||
* Run a mutual-pass query. `initialScrollIndex` non-null forces the list
|
||||
* to rebuild at that position (legacy callers); null keeps the current
|
||||
* scroll position, so re-running a query from the match page does not
|
||||
* jump back to the top. The previous results stay on screen while the
|
||||
* query runs (the list keeps its height, so the scroll position is not
|
||||
* clamped away); they are replaced — possibly with empty — when the new
|
||||
* results arrive.
|
||||
*/
|
||||
fun queryMutualPasses(initialScrollIndex: Int? = null) {
|
||||
val state = _uiState.value
|
||||
|
||||
// Resolve positions from lat/lon or grid
|
||||
@@ -235,31 +270,76 @@ class MutualViewModel(
|
||||
return
|
||||
}
|
||||
|
||||
// 转发器类型筛选: 至少勾选一种(默认 FM + Linear 都开), 否则提示不查询.
|
||||
// 防止用户选入大量无转发器卫星占用匹配页.
|
||||
if (!state.filterFM && !state.filterLinear) {
|
||||
_uiState.update { it.copy(errorMessage = "Select at least one transponder type (FM / Linear) to run the match.") }
|
||||
return
|
||||
}
|
||||
// AMSAT Live 清单(同步自 AMSAT "Live FM/Linear Satellites" 页面)是本过滤的
|
||||
// 权威来源: 只匹配当前在轨且话音/线性转发器实际工作的卫星. 清单为空
|
||||
// (从未成功同步过)时回退到数据库 downlinkMode 过滤, 避免首启匹配页空结果.
|
||||
// 过滤本身在下面的协程里执行 (getSatelliteIdsWithModes 是 suspend).
|
||||
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
isCalculating = true,
|
||||
hasSearched = true,
|
||||
errorMessage = null,
|
||||
mutualPasses = emptyList(),
|
||||
// Deliberately keep mutualPasses: clearing it would shrink the
|
||||
// list below one screen and clamp the scroll position away.
|
||||
// The stale results are replaced when the new ones arrive.
|
||||
selectedPassIndex = -1
|
||||
)
|
||||
}
|
||||
// The results list is about to be replaced, so the scroll position must
|
||||
// not leak from the previous query's list. A prefill from the map
|
||||
// (grid-QSO dialog "Match" button) instead starts at the time-range
|
||||
// card so the page opens with it at the top.
|
||||
listScrollIndex = initialScrollIndex
|
||||
listScrollOffset = 0
|
||||
// Scroll position: an explicit initialScrollIndex overrides (legacy
|
||||
// callers start at a fixed spot); null keeps the current position so
|
||||
// re-querying does not jump back to the top.
|
||||
if (initialScrollIndex != null) {
|
||||
listScrollIndex = initialScrollIndex
|
||||
listScrollOffset = 0
|
||||
}
|
||||
queryGeneration += 1
|
||||
|
||||
viewModelScope.launch {
|
||||
val time = System.currentTimeMillis()
|
||||
val now = System.currentTimeMillis()
|
||||
// 转发器类型过滤(协程上下文): AMSAT Live 清单优先, 为空时回退数据库.
|
||||
val amSatFm = settingsRepo.getAmSatFmCatnums()
|
||||
val amSatLinear = settingsRepo.getAmSatLinearCatnums()
|
||||
val filteredSatellites = if (amSatFm.isEmpty() && amSatLinear.isEmpty()) {
|
||||
// 回退到数据库模式过滤: 只用带上行频率的转发器记录, 排除纯下行
|
||||
// 信标/遥测(如 CW 信标、FM 语音合成信标), 避免 ISS/IO-86/FO-29 等
|
||||
// 因共享模式标签(CW/FM)被误判进错误类别.
|
||||
val filterModes = buildList {
|
||||
if (state.filterFM) add("FM")
|
||||
if (state.filterLinear) addAll(listOf("USB", "LSB", "CW", "SSB"))
|
||||
}
|
||||
val idsWithModes = satelliteRepo.getSatelliteIdsWithModesAndUplink(filterModes)
|
||||
if (idsWithModes.isEmpty()) satellites
|
||||
else satellites.filter { it.data.catnum in idsWithModes }
|
||||
} else {
|
||||
val allowed = buildSet {
|
||||
if (state.filterFM) addAll(amSatFm)
|
||||
if (state.filterLinear) addAll(amSatLinear)
|
||||
}
|
||||
satellites.filter { it.data.catnum in allowed }
|
||||
}
|
||||
// 历史回看: 查询窗口起点 = now - hoursBefore (跟随主页面 Passes 设置),
|
||||
// 终点 = now + hoursAhead 不变.
|
||||
val time = now - state.hoursBefore * 60L * 60L * 1000L
|
||||
val minElevA = state.stationAMinElev
|
||||
val minElevB = state.stationBMinElev
|
||||
val hours = state.hoursAhead
|
||||
|
||||
val results = withContext(computeDispatcher) {
|
||||
findMutualPasses(satellites, posA, posB, minElevA, minElevB, time, hours)
|
||||
val results = try {
|
||||
withContext(computeDispatcher) {
|
||||
findMutualPasses(filteredSatellites, posA, posB, minElevA, minElevB, time, hours, state.hoursBefore)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
// Never leave the query stuck in "calculating" (which would also
|
||||
// block the pending map→match navigation forever).
|
||||
android.util.Log.e(TAG, "findMutualPasses threw", t)
|
||||
emptyList()
|
||||
}
|
||||
|
||||
val errorMsg = if (results.isEmpty()) {
|
||||
@@ -298,15 +378,20 @@ class MutualViewModel(
|
||||
satellites: List<OrbitalObject>,
|
||||
posA: GeoPos, posB: GeoPos,
|
||||
minElevADeg: Double, minElevBDeg: Double,
|
||||
time: Long, hours: Int
|
||||
time: Long, hours: Int, hoursBefore: Int
|
||||
): List<MutualPass> {
|
||||
val endTime = time + hours * 60L * 60L * 1000L
|
||||
// 终点始终是 now + hoursAhead; 起点已由调用方下移 hoursBefore 小时,
|
||||
// 因此这里的 endTime 要在起点之上补回 hoursBefore, 保证窗口 = [now-hb, now+h].
|
||||
val endTime = time + (hoursBefore + hours) * 60L * 60L * 1000L
|
||||
val sampleInterval = 5_000L
|
||||
|
||||
// Use the main page's pass list for AOS/LOS times, then sample the curves
|
||||
// using the actual positions. The passes list is already computed by getLeoPass
|
||||
// and its AOS/LOS times match the Passes page exactly.
|
||||
val existingPasses = satelliteRepo.passes.value
|
||||
// The satellites argument may be a subset (transponder-type filter), so
|
||||
// only passes belonging to the filtered satellites are reused.
|
||||
val allowedCatnums = satellites.map { it.data.catnum }.toSet()
|
||||
val existingPasses = satelliteRepo.passes.value.filter { it.catNum in allowedCatnums }
|
||||
val results = findMutualPassesFromList(existingPasses, satellites, posA, posB,
|
||||
minElevADeg, minElevBDeg, time, endTime, sampleInterval)
|
||||
if (results.isNotEmpty()) return results
|
||||
|
||||
@@ -44,13 +44,20 @@ class FakeSatelliteRepo(
|
||||
override suspend fun getTrack(sat: OrbitalObject, pos: GeoPos, start: Long, end: Long): List<OrbitalPos> = TODO()
|
||||
override suspend fun getRadios(sat: OrbitalObject, pos: GeoPos, radios: List<SatRadio>, time: Long): List<SatRadio> = TODO()
|
||||
override suspend fun getRadiosWithId(id: Int): List<SatRadio> = TODO()
|
||||
override suspend fun getSatelliteIdsWithModes(modes: List<String>): List<Int> = emptyList()
|
||||
override suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>): List<Int> = emptyList()
|
||||
override suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>): List<Int> = emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Test fake for ISettingsRepo. Only [stationPosition] is backed by mutable
|
||||
* state; everything else the ViewModel never touches fails loudly.
|
||||
*/
|
||||
class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISettingsRepo {
|
||||
class FakeSettingsRepo(
|
||||
initialPosition: GeoPos = GeoPos(23.13, 113.26),
|
||||
val amSatFm: Set<Int> = emptySet(),
|
||||
val amSatLinear: Set<Int> = emptySet()
|
||||
) : ISettingsRepo {
|
||||
|
||||
override val stationPosition = MutableStateFlow(initialPosition)
|
||||
|
||||
@@ -103,6 +110,13 @@ class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISetti
|
||||
|
||||
override fun updateDataSourcesStatus(status: Map<String, Int>) = TODO()
|
||||
|
||||
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
|
||||
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
|
||||
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
|
||||
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) = TODO()
|
||||
override fun getAmSatActiveCatnums(): Set<Int> = emptySet()
|
||||
override fun setAmSatActiveCatnums(catnums: Set<Int>) = TODO()
|
||||
|
||||
override fun updateRadioControlSettings(settings: RadioControlSettings) = TODO()
|
||||
override fun getSatelliteOffset(catnum: Int): String = ""
|
||||
override fun setSatelliteOffset(catnum: Int, offset: String) = TODO()
|
||||
@@ -115,6 +129,8 @@ class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISetti
|
||||
override fun setWorkedGridQsos(qsos: Map<String, List<GridQso>>) = TODO()
|
||||
override fun getRoamedGrids(): Set<String> = TODO()
|
||||
override fun setRoamedGrids(grids: Set<String>) = TODO()
|
||||
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
|
||||
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
|
||||
override fun updateLoTWSettings(settings: LoTWSettings) = TODO()
|
||||
override fun getLastLotwSyncDate(): String = ""
|
||||
override fun setLastLotwSyncDate(date: String) = Unit
|
||||
|
||||
+7
@@ -146,6 +146,13 @@ class MutualMatchPrefillScrollTest {
|
||||
// ...and the target grid + 24h range pre-filled.
|
||||
org.junit.Assert.assertEquals("OL62", s.stationBGrid)
|
||||
org.junit.Assert.assertEquals(24, s.hoursAhead)
|
||||
// ...and navigation to the match page is pending until the query done.
|
||||
assertTrue("navigation should be pending", s.pendingNavigation)
|
||||
// The early-return guard means the query finished immediately (no
|
||||
// satellites): the map page must now be free to navigate.
|
||||
org.junit.Assert.assertFalse("query finished -> not calculating", s.isCalculating)
|
||||
vm.consumePendingNavigation()
|
||||
org.junit.Assert.assertFalse("consume clears pending navigation", vm.uiState.value.pendingNavigation)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+102
-2
@@ -31,10 +31,12 @@ class MutualViewModelTest {
|
||||
private fun TestScope.createVm(
|
||||
satellites: List<OrbitalObject> = emptyList(),
|
||||
passes: List<OrbitalPass> = emptyList(),
|
||||
position: GeoPos = TestOrbits.GUANGZHOU
|
||||
position: GeoPos = TestOrbits.GUANGZHOU,
|
||||
amSatFm: Set<Int> = emptySet(),
|
||||
amSatLinear: Set<Int> = emptySet()
|
||||
): MutualViewModel = MutualViewModel(
|
||||
satelliteRepo = FakeSatelliteRepo(satellites, passes),
|
||||
settingsRepo = FakeSettingsRepo(position),
|
||||
settingsRepo = FakeSettingsRepo(position, amSatFm, amSatLinear),
|
||||
computeDispatcher = StandardTestDispatcher(mainDispatcherRule.dispatcher.scheduler)
|
||||
)
|
||||
|
||||
@@ -285,4 +287,102 @@ class MutualViewModelTest {
|
||||
|
||||
assertNull(vm.uiState.value.errorMessage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `requery keeps scroll position and stale results while running`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
|
||||
val windows = TestOrbits.findPassWindows()
|
||||
assertTrue("fixture must produce ISS windows", windows.isNotEmpty())
|
||||
val vm = createVm(
|
||||
satellites = listOf(TestOrbits.ISS),
|
||||
passes = windows
|
||||
)
|
||||
vm.onStationBGrid("OL62")
|
||||
queryAndSettle(vm)
|
||||
assertTrue("fixture must yield passes", vm.uiState.value.mutualPasses.isNotEmpty())
|
||||
|
||||
// The user scrolled into the results; the snapshotFlow write-back has
|
||||
// stored this position in the VM.
|
||||
vm.listScrollIndex = 4
|
||||
vm.listScrollOffset = 137
|
||||
|
||||
// Re-run the query from the match page ("query" button).
|
||||
vm.queryMutualPasses()
|
||||
|
||||
// While the query runs, the old results stay on screen (the list keeps
|
||||
// its height, so the scroll position is not clamped away)...
|
||||
assertTrue("stale results kept while calculating", vm.uiState.value.mutualPasses.isNotEmpty())
|
||||
// ...and the scroll position must not be reset to the top.
|
||||
assertEquals(4, vm.listScrollIndex)
|
||||
assertEquals(137, vm.listScrollOffset)
|
||||
|
||||
advanceUntilIdle()
|
||||
assertFalse(vm.uiState.value.isCalculating)
|
||||
assertTrue("fresh results replace the stale ones", vm.uiState.value.mutualPasses.isNotEmpty())
|
||||
// Position intact after the query settled.
|
||||
assertEquals(4, vm.listScrollIndex)
|
||||
assertEquals(137, vm.listScrollOffset)
|
||||
}
|
||||
|
||||
// --------------------------------------------- transponder filters (AMSAT)
|
||||
|
||||
@Test
|
||||
fun `both filters off sets an error and does not search`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
|
||||
val windows = TestOrbits.findPassWindows()
|
||||
val vm = createVm(satellites = listOf(TestOrbits.ISS), passes = windows)
|
||||
vm.onStationBGrid("OL62")
|
||||
vm.onFilterFM(false)
|
||||
vm.onFilterLinear(false)
|
||||
|
||||
queryAndSettle(vm)
|
||||
|
||||
assertEquals(
|
||||
"Select at least one transponder type (FM / Linear) to run the match.",
|
||||
vm.uiState.value.errorMessage
|
||||
)
|
||||
assertFalse(vm.uiState.value.hasSearched)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT filter restricts results to listed catnums`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
|
||||
val windows = TestOrbits.findPassWindows(hoursAhead = 24) +
|
||||
TestOrbits.findPassWindows(sat = TestOrbits.ISS_VARIANT, hoursAhead = 24)
|
||||
assertTrue("fixture must produce windows", windows.isNotEmpty())
|
||||
// Only ISS (25544) is on the AMSAT live FM list; ISS_VARIANT (25545) is not.
|
||||
val vm = createVm(
|
||||
satellites = listOf(TestOrbits.ISS, TestOrbits.ISS_VARIANT),
|
||||
passes = windows,
|
||||
amSatFm = setOf(25544)
|
||||
)
|
||||
vm.onStationBGrid("OL62")
|
||||
vm.onHoursAhead(24)
|
||||
|
||||
queryAndSettle(vm)
|
||||
|
||||
val state = vm.uiState.value
|
||||
assertNull(state.errorMessage)
|
||||
assertTrue(state.mutualPasses.isNotEmpty())
|
||||
assertTrue("only AMSAT-listed satellites should appear", state.mutualPasses.all { it.catNum == 25544 })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `AMSAT filter off for one type excludes its satellites`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
|
||||
val windows = TestOrbits.findPassWindows(hoursAhead = 24) +
|
||||
TestOrbits.findPassWindows(sat = TestOrbits.ISS_VARIANT, hoursAhead = 24)
|
||||
// FM filter off, Linear on: neither sat is linear-listed -> nothing matches.
|
||||
val vm = createVm(
|
||||
satellites = listOf(TestOrbits.ISS, TestOrbits.ISS_VARIANT),
|
||||
passes = windows,
|
||||
amSatFm = setOf(25544),
|
||||
amSatLinear = setOf(25545)
|
||||
)
|
||||
vm.onStationBGrid("OL62")
|
||||
vm.onHoursAhead(24)
|
||||
vm.onFilterFM(false)
|
||||
|
||||
queryAndSettle(vm)
|
||||
|
||||
val state = vm.uiState.value
|
||||
assertNull(state.errorMessage)
|
||||
assertTrue("only linear-listed satellites should appear", state.mutualPasses.all { it.catNum == 25545 })
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -42,6 +42,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.rtbishop.look4sat.core.presentation.MainTheme
|
||||
import com.rtbishop.look4sat.core.presentation.R
|
||||
import com.rtbishop.look4sat.core.presentation.SharedDialog
|
||||
import com.rtbishop.look4sat.core.domain.source.Sources
|
||||
|
||||
@Preview(showBackground = true)
|
||||
@Composable
|
||||
@@ -54,9 +55,20 @@ private fun MultiTypesDialogPreview() {
|
||||
internal fun MultiTypesDialog(
|
||||
allTypes: List<String>, types: List<String>, cancel: () -> Unit, accept: (List<String>) -> Unit
|
||||
) {
|
||||
// 虚拟类型(转发器/活动筛选)与普通 TLE 源类型互斥: 勾虚拟类型时取消普通类型,
|
||||
// 勾普通类型时取消虚拟类型. 虚拟类型之间可多选组合.
|
||||
val virtualTypes = Sources.virtualTypeNames
|
||||
val selected = remember { mutableStateOf(types.toSet()) }
|
||||
val toggle = { type: String ->
|
||||
selected.value = if (type in selected.value) selected.value - type else selected.value + type
|
||||
selected.value = if (type in selected.value) {
|
||||
selected.value - type
|
||||
} else if (type in virtualTypes) {
|
||||
// 勾选虚拟类型: 移除所有普通类型, 保留已勾的虚拟类型.
|
||||
(selected.value.filterTo(mutableSetOf()) { it in virtualTypes }) + type
|
||||
} else {
|
||||
// 勾选普通类型: 移除所有虚拟类型, 保留已勾的普通类型.
|
||||
(selected.value.filterTo(mutableSetOf()) { it !in virtualTypes }) + type
|
||||
}
|
||||
}
|
||||
val onAccept = { accept(selected.value.toList()) }
|
||||
SharedDialog(title = stringResource(R.string.sat_type_title), onCancel = cancel, onAccept = onAccept) {
|
||||
|
||||
+1
@@ -177,6 +177,7 @@ private fun SatellitesScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
// 转发器/活动筛选已在"卫星类型"对话框前三个选项中体现(AMSAT Live FM/Linear, Live SSTV).
|
||||
ElevatedCard(modifier = Modifier.fillMaxSize()) {
|
||||
val emptyMessage = stringResource(R.string.sat_empty_list_message)
|
||||
when {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
[versions]
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
appVersionCode = "492"
|
||||
appVersionCode = "505"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
appVersionName = "4.4.7-ba7opf.12.6"
|
||||
appVersionName = "4.4.7-ba7opf.15.8"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
compileSdk = "37"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
|
||||
Reference in new issue
Block a user