Compare commits

...
4 Commits
12 changed files with 86 additions and 115 deletions

No files matched your search

@@ -40,27 +40,21 @@ class DatabaseRepo(
private val settingsRepo: ISettingsRepo
) : IDatabaseRepo {
private companion object {
val tleTypes = setOf("Amsat", "R4UAB", "Other")
val zippedTleTypes = setOf("McCants", "Classified")
}
private val customSourceType = "Other"
override suspend fun updateTLEFromFile(uri: String) = withContext(dispatcher) {
remoteSource.getFileStream(uri)?.let { stream ->
val entries = dataParser.parseTLEStream(stream)
val entries = dataParser.parseTLEStream(unwrapIfZipped(uri, stream))
localSource.insertEntries(entries)
settingsRepo.setSatelliteTypeIds("Other", entries.map { it.catnum })
settingsRepo.setSatelliteTypeIds(customSourceType, entries.map { it.catnum })
}
setUpdateSuccessful(System.currentTimeMillis())
}
override suspend fun updateTransceiversFromFile(uri: String) = withContext(dispatcher) {
remoteSource.getFileStream(uri)
?.let { dataParser.parseJSONStream(it) }
?.takeIf { it.isNotEmpty() }
?.let {
localSource.deleteRadios()
localSource.insertRadios(it)
remoteSource.getFileStream(uri)?.let { stream ->
val transceivers = dataParser.parseJSONStream(unwrapIfZipped(uri, stream))
localSource.insertRadios(transceivers)
}
setUpdateSuccessful(System.currentTimeMillis())
}
@@ -69,28 +63,26 @@ class DatabaseRepo(
val dataSourcesSettings = settingsRepo.dataSourcesSettings.value
val tleUrls = buildMap {
putAll(Sources.satelliteDataUrls)
if (dataSourcesSettings.useCustomTLE) put("Other", dataSourcesSettings.tleUrl)
}.filterValues { it.isNotEmpty() }
val radioUrls = buildList {
add(Sources.RADIO_DATA_URL)
if (dataSourcesSettings.useCustomTransceivers) add(dataSourcesSettings.transceiversUrl)
}
if (dataSourcesSettings.useCustomTLE) put(customSourceType, dataSourcesSettings.tleUrl)
}.filterValues { it.isNotBlank() }
val radioUrls = buildMap {
putAll(Sources.transceiversDataUrls)
if (dataSourcesSettings.useCustomTransceivers) put(customSourceType, dataSourcesSettings.transceiversUrl)
}.filterValues { it.isNotBlank() }
// launch all network requests concurrently
val tleJobs = tleUrls.map { (type, url) -> async { type to remoteSource.getNetworkStream(url) } }
val radioJobs = radioUrls.map { url -> async { remoteSource.getNetworkStream(url) } }
// parse satellite data
val importedEntries = tleJobs.awaitAll().flatMap { (type, stream) ->
stream?.let { parseSatelliteStream(type, it) }.orEmpty().also { satellites ->
settingsRepo.setSatelliteTypeIds(type, satellites.map { it.catnum })
val tleJobs = tleUrls.values.map { url -> async { url to remoteSource.getNetworkStream(url) } }
val radioJobs = radioUrls.values.map { url -> async { url to remoteSource.getNetworkStream(url) } }
// parse fetched data concurrently and associate with types
val importedEntries = tleJobs.awaitAll().flatMap { (url, stream) ->
val type = tleUrls.entries.find { it.value == url }?.key ?: customSourceType
stream?.let { parseSatelliteStream(url, unwrapIfZipped(url, it)) }.orEmpty().also { entries ->
settingsRepo.setSatelliteTypeIds(type, entries.map { it.catnum })
}
}
// parse radio data
val importedRadios = radioJobs.awaitAll().filterNotNull().flatMap { dataParser.parseJSONStream(it) }
val importedRadios = radioJobs.awaitAll().flatMap { (url, stream) ->
stream?.let { dataParser.parseJSONStream(unwrapIfZipped(url, it)) }.orEmpty()
}
// insert parsed data into the database
localSource.insertEntries(importedEntries)
localSource.insertRadios(importedRadios)
setUpdateSuccessful(System.currentTimeMillis())
@@ -102,10 +94,9 @@ class DatabaseRepo(
setUpdateSuccessful(0L)
}
private suspend fun parseSatelliteStream(type: String, stream: InputStream): List<OrbitalData> = when (type) {
in tleTypes -> dataParser.parseTLEStream(stream)
in zippedTleTypes -> dataParser.parseTLEStream(ZipInputStream(stream).apply { nextEntry })
else -> dataParser.parseCSVStream(stream)
private suspend fun parseSatelliteStream(url: String, stream: InputStream): List<OrbitalData> = when {
url.contains("FORMAT=csv", ignoreCase = true) -> dataParser.parseCSVStream(stream)
else -> dataParser.parseTLEStream(stream)
}
private suspend fun setUpdateSuccessful(timestamp: Long) {
@@ -113,4 +104,7 @@ class DatabaseRepo(
DatabaseState(localSource.getRadiosTotal(), localSource.getEntriesTotal(), timestamp)
)
}
private fun unwrapIfZipped(url: String, stream: InputStream): InputStream =
if (url.endsWith(".zip", ignoreCase = true)) ZipInputStream(stream).apply { nextEntry } else stream
}
@@ -242,7 +242,8 @@ object CelestialComputer {
t = (jd - 2451545.0) / 36525.0
var teg = 280.46061837 + 360.98564736629 * (jd - 2451545.0) + (0.000387933 * t - t * t / 38710000.0) * t
while (teg > 360.0) teg -= 360.0
val th = fixAngle((teg - observer.longitude) * DEG2RAD)
// LST = GMST + east longitude (positive east convention)
val th = mod2PI((teg + observer.longitude) * DEG2RAD)
val h = th - ra
val azVal = atan2(sin(h), cos(h) * sin(n) - tan(dec) * cos(n)) + PI
val el = asin(sin(n) * sin(dec) + cos(n) * cos(dec) * cos(h))
@@ -563,9 +564,9 @@ object CelestialComputer {
// ── Internal helpers ──
private fun observerGeodetic(pos: GeoPos): DoubleArray {
// [lat_rad, lon_rad, alt_km] — longitude negated so that
// mod2PI(thetaGJD + obsGeo[1]) == mod2PI(thetaGJD + lon_rad)
return doubleArrayOf(pos.latitude * DEG2RAD, -pos.longitude * DEG2RAD, pos.altitude / 1000.0)
// [lat_rad, lon_rad, alt_km] — longitude positive east, matching OrbitalObject convention.
// LST = thetaGJD(julUtc) + obsGeo[1] = GMST + lon_rad (correct).
return doubleArrayOf(pos.latitude * DEG2RAD, pos.longitude * DEG2RAD, pos.altitude / 1000.0)
}
/**
@@ -18,7 +18,6 @@
package com.rtbishop.look4sat.core.domain.source
object Sources {
const val RADIO_DATA_URL = "https://db.satnogs.org/api/transmitters/?format=json&status=active"
val satelliteDataUrls = mapOf(
"All" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=active&FORMAT=csv",
"Amateur" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=amateur&FORMAT=csv",
@@ -49,4 +48,7 @@ object Sources {
"R4UAB" to "https://r4uab.ru/satonline.txt",
"Other" to "" // key for sats filter
)
val transceiversDataUrls = mapOf(
"SatNOGS" to "https://db.satnogs.org/api/transmitters/?format=json&status=active"
)
}
@@ -58,8 +58,6 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
}.getOrDefault(emptyList())
}
fun isLeapYear(year: Int): Boolean = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
private fun parseCSV(values: List<String>): OrbitalData? = runCatching {
val name = values[0]
val timestamp = values[2]
@@ -106,7 +104,8 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
}.onFailure { println("TLE parsing exception: $it") }.getOrNull()
private fun getDayOfYear(year: Int, month: Int, dayOfMonth: Int): Int {
val daysInMonth = intArrayOf(31, if (isLeapYear(year)) 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
val isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
val daysInMonth = intArrayOf(31, if (isLeapYear) 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
return daysInMonth.take(month - 1).sum() + dayOfMonth
}
}
@@ -95,11 +95,11 @@ class DataParserTest {
assert(dataParser.parseCSVStream(validCSVStream) == dataParser.parseTLEStream(validTLEStream))
}
@Test
fun `Function isLeapYear returns correct data`() = runTest(testDispatcher) {
val years = listOf(1900, 1984, 1994, 2016, 2022, 2024, 2042, 2048)
val answers = listOf(false, true, false, true, false, true, false, true)
val results = years.map { dataParser.isLeapYear(it) }
assert(results == answers)
}
// @Test
// fun `Function isLeapYear returns correct data`() = runTest(testDispatcher) {
// val years = listOf(1900, 1984, 1994, 2016, 2022, 2024, 2042, 2048)
// val answers = listOf(false, true, false, true, false, true, false, true)
// val results = years.map { dataParser.isLeapYear(it) }
// assert(results == answers)
// }
}
@@ -130,8 +130,16 @@
<string name="prefs_other_switch_update">启用卫星数据自动更新</string>
<string name="prefs_other_switch_sweep">启用雷达扫描动画</string>
<string name="prefs_other_switch_sensors">使用传感器旋转雷达视图</string>
<string name="prefs_other_switch_night_mode">启用红色夜间模式</string>
<string name="prefs_outro_title">我要感谢:</string>
<string name="prefs_outro_thanks" translatable="false">
• Look4Sat 所有用户及贡献者!
\n• David A. B. Johnson (predict4java)
\n• Dave Moten (predict4java)
\n• Alexandru Csete (Gpredict)
\n• Dr T.S. Kelso (Celestrak)
\n• Libre Space Foundation (SatNOGS)</string>
<string name="prefs_outro_license">该应用程序不提供任何保修.</string>
</resources>
@@ -49,12 +49,10 @@
\n\nPlease update the database at least weekly to get accurate predictions.</string>
<string name="pass_whatsnew_title" translatable="false">What\'s new in Look4Sat</string>
<string name="pass_whatsnew_message" translatable="false">
* Added fixes for Turkish translation, by Emre Can Akdaş (TA3ECR)
\n* Added passes sticky header with sunrise/sunset times
\n* Added current moon/sun positions to the Radar Screen
\n* Added current moon/sun positions to the Map Screen
\n* Added red night mode filter overlay for the whole app
* Added fixes for Chinese translation, by Mubi-Baihua (#216)
\n* Added zipped data sources handling to DatabaseRepo
\n* Tweaked Passes list to show DeepSpace ones at the top
\n* Tweaked RadarView to display sun/moon positions correctly
</string>
<!-- Radar screen -->
@@ -1,5 +1,4 @@
* Added fixes for Turkish translation, by Emre Can Akdaş (TA3ECR)
* Added passes sticky header with sunrise/sunset times
* Added current moon/sun positions to the Radar Screen
* Added current moon/sun positions to the Map Screen
* Added red night mode filter overlay for the whole app
* Added fixes for Chinese translation, by Mubi-Baihua (#216)
* Added zipped data sources handling to DatabaseRepo
* Tweaked Passes list to show DeepSpace ones at the top
* Tweaked RadarView to display sun/moon positions correctly
@@ -1,5 +1,4 @@
* Added fixes for Turkish translation, by Emre Can Akdaş (TA3ECR)
* Added passes sticky header with sunrise/sunset times
* Added current moon/sun positions to the Radar Screen
* Added current moon/sun positions to the Map Screen
* Added red night mode filter overlay for the whole app
* Added fixes for Chinese translation, by Mubi-Baihua (#216)
* Added zipped data sources handling to DatabaseRepo
* Tweaked Passes list to show DeepSpace ones at the top
* Tweaked RadarView to display sun/moon positions correctly
@@ -29,11 +29,8 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
@@ -45,8 +42,6 @@ import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -125,7 +120,6 @@ private fun PassesScreen(
onAction(PassesAction.DismissWhatsNew)
}
}
val gridState = rememberLazyGridState()
ScreenColumn(
topBar = { isVerticalLayout ->
TopBar(
@@ -151,7 +145,6 @@ private fun PassesScreen(
passes = uiState.itemsList,
navigateToRadar = navigateToRadar,
refreshPasses = { onAction(PassesAction.RefreshPasses) },
gridState = gridState,
sunTimes = uiState.sunTimes
)
}
@@ -165,7 +158,6 @@ private fun PassesList(
passes: List<OrbitalPass>,
navigateToRadar: (Int, Long) -> Unit,
refreshPasses: () -> Unit,
gridState: LazyGridState,
sunTimes: Map<String, Pair<String, String>>
) {
val isVerticalLayout = isVerticalLayout()
@@ -175,31 +167,15 @@ private fun PassesList(
SimpleDateFormat("EEE, dd MMM yyyy", Locale.ENGLISH).also { it.timeZone = timeZone }
}
// Group passes by calendar day so we know where headers go
// Deep Space first, then date-grouped timed passes
val groupedPasses = remember(passes, isUtc) {
passes.filter { !it.isDeepSpace }.groupBy { sdfDate.format(Date(it.aosTime)) } +
if (passes.any { it.isDeepSpace }) mapOf("Deep Space" to passes.filter { it.isDeepSpace }) else emptyMap()
}
// Derive the sticky header label from the first visible item index
val stickyHeader by remember(gridState, groupedPasses) {
derivedStateOf {
val firstVisible = gridState.firstVisibleItemIndex
var itemIndex = 0
var header = groupedPasses.keys.firstOrNull() ?: ""
for ((key, items) in groupedPasses) {
header = key
itemIndex += 1 + items.size
if (itemIndex > firstVisible) break
}
header
}
}
// The sticky overlay should only show when the first in-list header has scrolled out of view.
// firstVisibleItemIndex == 0 means the first header is still visible — hide the overlay.
val showStickyOverlay by remember(gridState) {
derivedStateOf { gridState.firstVisibleItemIndex > 0 || gridState.firstVisibleItemScrollOffset > 0 }
val ordered = LinkedHashMap<String, List<OrbitalPass>>()
val deepSpace = passes.filter { it.isDeepSpace }
if (deepSpace.isNotEmpty()) ordered["Deep Space"] = deepSpace
passes.filter { !it.isDeepSpace }
.groupByTo(LinkedHashMap()) { sdfDate.format(Date(it.aosTime)) }
.forEach { (k, v) -> ordered[k] = v }
ordered
}
ElevatedCard(modifier = Modifier.fillMaxSize()) {
@@ -220,20 +196,9 @@ private fun PassesList(
if (passes.isEmpty()) {
EmptyListCard(message = stringResource(R.string.pass_empty_list_message))
} else {
Column {
// Sticky header overlay — only visible once the in-list header scrolls away
if (showStickyOverlay) {
val (rise, set) = sunTimes[stickyHeader] ?: ("--:--" to "--:--")
StickyDateHeader(label = stickyHeader, sunriseTime = rise, sunsetTime = set)
}
LazyVerticalGrid(
state = gridState,
columns = GridCells.Adaptive(320.dp),
modifier = Modifier.fillMaxSize()
) {
LazyVerticalGrid(columns = GridCells.Adaptive(320.dp), modifier = Modifier.fillMaxSize()) {
for ((dateLabel, dayPasses) in groupedPasses) {
// In-list section header (scrolls away, drives the sticky overlay)
item(span = { GridItemSpan(maxLineSpan) }) {
stickyHeader(key = "header_$dateLabel") {
val (rise, set) = sunTimes[dateLabel] ?: ("--:--" to "--:--")
StickyDateHeader(label = dateLabel, sunriseTime = rise, sunsetTime = set)
}
@@ -251,7 +216,6 @@ private fun PassesList(
}
}
}
}
}
@Composable
@@ -124,13 +124,20 @@ class PassesViewModel(
}
}
/** Computes sunrise/sunset strings for each unique calendar day in the pass list. */
// Computes sunrise/sunset strings for each unique calendar day in the pass list, plus today for Deep Space
private fun computeSunTimes(passes: List<OrbitalPass>, isUtc: Boolean): Map<String, Pair<String, String>> {
val stationPos = settingsRepo.stationPosition.value
val tz = if (isUtc) TimeZone.getTimeZone("UTC") else TimeZone.getDefault()
val sdfDate = SimpleDateFormat("EEE, dd MMM yyyy", Locale.ENGLISH).also { it.timeZone = tz }
val sdfTime = SimpleDateFormat("HH:mm", Locale.ENGLISH).also { it.timeZone = tz }
val result = LinkedHashMap<String, Pair<String, String>>()
// Deep Space group always shows today's sun times
if (passes.any { it.isDeepSpace }) {
val riseSet = CelestialComputer.findSunRiseSet(stationPos, System.currentTimeMillis())
val rise = if (riseSet.riseTimeMillis > 0) sdfTime.format(Date(riseSet.riseTimeMillis)) else "--:--"
val set = if (riseSet.setTimeMillis > 0) sdfTime.format(Date(riseSet.setTimeMillis)) else "--:--"
result["Deep Space"] = rise to set
}
for (pass in passes) {
if (pass.isDeepSpace) continue
val label = sdfDate.format(Date(pass.aosTime))
+2 -2
View File
@@ -1,8 +1,8 @@
[versions]
#noinspection UnusedVersionCatalogEntry
appVersionCode = "430"
appVersionCode = "431"
#noinspection UnusedVersionCatalogEntry
appVersionName = "4.3.0"
appVersionName = "4.3.1"
#noinspection GradleDependency,UnusedVersionCatalogEntry
compileSdk = "36"
#noinspection UnusedVersionCatalogEntry