Compare commits

..
Author SHA1 Message Date
mckero 691c5f5bb1 feat(status): add AMSAT satellite status tracking
New feature: displays recent AMSAT satellite activity from amsat.org API.
Shows 6-day status grid (Heard/Telemetry/Not Heard) + detailed reports.

Addresses PR #233 feedback:
- Uses Material3 colorScheme (tertiary/tertiaryContainer) for theme support
- HTTP in data layer via RemoteSource (Clean Architecture)
- SimpleDateFormat instead of manual date math
- Edge-to-edge support

Implementation:
- feature:status module (AMSAT status screen + legend)
- core:data AmSatRepository (API client using RemoteSource)
- core:domain models (SatStatus/SatReport/SatSlot/SatDay)
- MainTheme.kt: AMSAT colors mapped to colorScheme slots

Navigation intentionally not included - you mentioned potential UI
restructuring (Navigation Drawer). The screen is ready to integrate
wherever it fits your roadmap.

Ref: https://github.com/rt-bishop/Look4Sat/pull/233
2026-08-05 17:43:17 +00:00
241 changed files with 1246 additions and 24239 deletions

No files matched your search

-58
View File
@@ -1,58 +0,0 @@
# First step of the Kotlin Multiplatform port: core:domain becomes shareable code that compiles
# and runs on iOS as well as Android. This workflow is the evidence for that claim - the same
# orbital math (SGP4/SDP4), models and repository contracts are compiled by the Kotlin/Native
# compiler for iOS and their unit tests run on an iOS simulator. It deliberately does not touch
# the Android build rules: the second job only proves the existing app still builds.
name: ios-kmp
on:
workflow_dispatch:
push:
branches:
- feat/ios-kmp
- ios-kmp
jobs:
ios:
name: iOS shared module
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
- name: Compile shared module for iOS
run: ./gradlew :core:domain:compileKotlinIosSimulatorArm64 --console=plain
- name: Unit tests on the iOS simulator
run: ./gradlew :core:domain:iosSimulatorArm64Test --console=plain
- name: Upload iOS test reports
if: always()
uses: actions/upload-artifact@v4
with:
name: ios-domain-test-report
path: core/domain/build/reports/tests/
android:
name: Android regression
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
- name: JVM unit tests (domain and data)
run: ./gradlew :core:domain:jvmTest :core:data:testDebugUnitTest --console=plain
- name: Assemble debug APK
run: ./gradlew :app:assembleDebug --console=plain
- name: Upload test reports
if: always()
uses: actions/upload-artifact@v4
with:
name: android-reports
path: |
core/domain/build/reports/tests/
core/data/build/reports/tests/
+40 -19
View File
@@ -4,15 +4,10 @@ on:
push:
tags:
- v**
workflow_dispatch:
inputs:
tag_name:
description: 'Release tag name (e.g. v4.4.3)'
required: false
default: ''
env:
TAG_NAME: ${{ github.event.inputs.tag_name || github.ref_name }}
TAG_NAME: ${{ github.ref_name }}
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
jobs:
release:
@@ -21,40 +16,66 @@ jobs:
contents: write
steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: '21'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
uses: gradle/actions/setup-gradle@v6
- name: Assemble APK
run: ./gradlew assembleRelease
- name: Assemble Artifacts
run: ./gradlew assembleRelease bundleRelease
- name: Sign APK
run: |
echo "${{ secrets.KEY_STORE }}" | base64 -d > keystore.jks
APK=$(find app/build/outputs/apk/release -name "*.apk" | head -1)
VERSION=${TAG_NAME#v}
SIGNED_APK="app/build/outputs/apk/release/Look4Sat-Pro-${VERSION}.apk"
BUILD_TOOLS=$(ls -d ${ANDROID_HOME}/build-tools/*/ | sort -V | tail -1)
${BUILD_TOOLS}apksigner sign \
--ks keystore.jks \
--ks-pass pass:${{ secrets.KEY_STORE_PASSWORD }} \
--ks-key-alias ${{ secrets.KEY_ALIAS }} \
--key-pass pass:${{ secrets.KEY_PASSWORD }} \
--out "$SIGNED_APK" \
--out app/build/outputs/apk/release/look4sat.apk \
"$APK"
rm keystore.jks
echo "SIGNED_APK=$SIGNED_APK" >> "$GITHUB_ENV"
- name: Sign Bundle
run: |
echo "${{ secrets.KEY_STORE }}" | base64 -d > keystore.jks
AAB=$(find app/build/outputs/bundle/release -name "*.aab" | head -1)
jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 \
-keystore keystore.jks \
-storepass ${{ secrets.KEY_STORE_PASSWORD }} \
-keypass ${{ secrets.KEY_PASSWORD }} \
"$AAB" ${{ secrets.KEY_ALIAS }}
rm keystore.jks
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4'
- name: Deploy Bundle to Google Play
run: |
gem install multi_json
gem install fastlane --no-document
AAB=$(find app/build/outputs/bundle/release -name "*.aab" | head -1)
echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
fastlane supply \
--aab "$AAB" \
--json_key service_account.json \
--package_name com.rtbishop.look4sat \
--track production \
--skip_upload_images true \
--skip_upload_screenshots true \
rm service_account.json
- name: Create Release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create $TAG_NAME --title=$TAG_NAME --generate-notes
gh release upload $TAG_NAME "$SIGNED_APK"
gh release upload $TAG_NAME app/build/outputs/apk/release/look4sat.apk
+2 -11
View File
@@ -1,9 +1,6 @@
# Built application files
*.ap_
# Hermes AI plans and metadata
.hermes/
# Files for the ART/Dalvik VM
*.dex
@@ -39,15 +36,12 @@ captures/
.idea/
# Keystore files
*.jks
*.keystore
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
/*.properties
/keystore.properties
/app/keystore.jks
# Hermes agent workspace (plans, local notes)
.hermes/
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
@@ -70,6 +64,3 @@ fastlane/readme.md
/app/release/output-metadata.json
/app/release/
/.kotlin/sessions/
# Kotlin build caches in any module, not only the root - build-logic produces one too.
.kotlin/
.hermes/
+4 -28
View File
@@ -25,7 +25,7 @@ no tracking, no network required after initial data download.
|----------------------|---------------------------------------------------------------------|
| `app` | Entry point. Aggregates all modules |
| `core:data` | Android library. Room DB, OkHttp networking, repo implementations |
| `core:domain` | Multiplatform: JVM + iOS. Orbital math (SGP4/SDP4), models, contracts |
| `core:domain` | Pure Kotlin (JVM). Orbital math (SGP4/SDP4), models, repo contracts |
| `core:presentation` | Android library. Compose theme, shared UI components, NavKeys |
| `feature:map` | OSMDroid map with ground tracks |
| `feature:passes` | Pass predictions and upcoming events |
@@ -50,7 +50,7 @@ no tracking, no network required after initial data download.
./gradlew test
```
- **Min SDK**: 24 | **Target SDK**: 36 | **JDK**: 21 (`jdkVersion` in the version catalog)
- **Min SDK**: 24 | **Target SDK**: 36 | **JDK**: 17
- **Gradle**: Version catalog in `gradle/libs.versions.toml` + convention plugins in `build-logic/`
## Tech Stack
@@ -71,7 +71,7 @@ Look4Sat supports both TLE and OMM (Orbit Mean-Elements Message) CSV formats:
- **TLE format**: Legacy 3-line element format limited by 5-digit NORAD IDs
- **OMM/CSV format**: Successor format with ISO 8601 timestamps and larger NORAD ID support
- New 5-digit NORAD IDs are exhausted; TLE is officially deprecated and OMM/CSV is the clear default
- `DataParser.kt` supports both via `parseTLE()` and `parseCSV()`, each taking the file text
- `DataParser.kt` supports both via `parseTLEStream()` and `parseCSVStream()`
- Downloads auto-detect format; both produce identical `OrbitalData` objects
- Existing code already supports transparent source transition without feature changes
- Refresh orbital data weekly for accurate pass prediction (orbital decay)
@@ -103,37 +103,13 @@ Look4Sat supports both TLE and OMM (Orbit Mean-Elements Message) CSV formats:
## Roadmap
- **KMP migration**: `core:domain` is now a Kotlin Multiplatform module (jvm + iosArm64/iosSimulatorArm64),
so the orbital math, models and repository contracts are compiled once and shared with the iOS app; Android
modules consume its jvm target. `commonMain` must stay free of JVM-only APIs (no `java.*`, `org.json`,
`String.format`, `Locale`, `InputStream`) - `formatString` in `utility/CommonFormat.kt` covers printf.
- **iOS app**: next step - an iOS shell that consumes the `Look4SatCore` framework plus the `expect`/`actual`
platform pieces (map, location, sensors, notifications).
- **KMP migration**: `core:domain` is to become a fully shareable KMM module. Keep it pure Kotlin/JVM.
## Gotchas
- Orbital math lives in `core:domain/predict/` — dense vector math (SGP4/SDP4). Tread carefully.
- `core:domain` is compiled for iOS too: anything added to its `commonMain` must exist in Kotlin/Native.
`.github/workflows/ios-kmp.yml` compiles it for iOS and runs the shared tests on an iOS simulator.
- Kotlin/JVM-only declarations still *resolve* in `commonMain` and only fail when the iOS target compiles:
`@Synchronized` and `@Volatile` (the `kotlin.jvm` ones) are errors in common code since Kotlin 2.1, as are
`toUpperCase`/`toLowerCase`/`capitalize` and `BigDecimal`. Use `kotlin.concurrent.Volatile`, and
`utility/SynchronizedOn.kt` (a platform actual) when a monitor is needed. `check-multiplatform.sh` in the
working copy's parent directory flags the rest.
- Source sets: `commonTest` runs on both jvm and iOS, so no JUnit4, no `javaClass.classLoader` and no bare
`assert()` there - a build without `-ea` skips those silently, and `-ea` is a JVM flag. Use `kotlin.test`.
JVM-only tests (classpath resources, `Locale.setDefault`) belong in `jvmTest`; platform code in
`jvmMain`/`iosMain`.
- `formatString` has to match `java.lang.String.format` exactly, and that rounds the *shortest decimal
representation* of a double half-up: `"%.3f"` of 0.5005 is `"0.501"`, even though the stored double is
0.50049999999999994493. `CommonFormatOracleTest` (jvmTest) compares against real `String.format` over
sampled doubles; `CommonFormatRoundingTest` (commonTest) pins literals so iOS checks the same digits.
- SSTV decoding in `feature:radar` is experimental; image quality depends on signal strength during satellite pass.
- `build-logic/convention/` contains shared Gradle configuration — edit there, not in individual modules.
- AMSAT status colours are ARGB literals in `core:data` (`AmSatRepository.statusColorOf`) and duplicated in
`core:presentation/MainTheme.kt`, so the data layer currently decides how the UI looks. Known debt, left as
upstream shipped it: the fix is a status enum in `core:domain` with the colour mapping in `core:presentation`.
Anything needing themeable, dark-mode-aware or colour-blind-safe status colours has to do that first.
## Copilot Working Mode: Code-Only
+77 -64
View File
@@ -1,5 +1,5 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@@ -7,15 +7,17 @@
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -24,34 +26,44 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -60,7 +72,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -537,45 +549,35 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@@ -633,29 +635,40 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
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 Affero General Public License for more details.
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-24
View File
@@ -1,24 +0,0 @@
LOOK4SAT (MCKERO6423 FORK) — LICENSING NOTICE
This repository combines two separately-licensed components:
1. Look4Sat application code (all modules except the DeepCW model)
— Copyright (C) 2019-2026 Arty Bishop (rt-bishop) and contributors
— Licensed under the GNU General Public License v3.0 (GPL-3.0)
2. The DeepCW neural decoding model in feature/cw/src/main/assets/deepcw/
— Copyright (C) e04 (https://github.com/e04/deepcw-engine)
— Licensed under the GNU Affero General Public License v3.0 only
(AGPL-3.0-only)
Because this combined work incorporates an AGPL-3.0 component, it is
distributed under the GNU Affero General Public License v3.0. GPL-3.0
Section 13 permits this combination; AGPL-3.0 Section 13 applies to the
combined work as a whole.
See feature/cw/licenses/NOTICE.md for model provenance, attribution, and
the applied int8 quantization. The original GPL-3.0 text for the Look4Sat
application code is preserved at feature/cw/licenses/Look4Sat-GPL-3.0.txt.
--------------------------------------------------------------------------------
+4 -19
View File
@@ -34,27 +34,12 @@ It is now and always will be completely ad-free and open-source.
* Custom TLE satellite data import is available via Three Line Element .txt files
* Offline first: calculations are made offline. Weekly TLE data update is recommended.
## License
The Look4Sat application code is licensed under the GNU General Public License v3.0.
The CW decoder in `feature/cw` bundles the [DeepCW](https://github.com/e04/deepcw-engine)
neural decoding model, licensed under the GNU Affero General Public License v3.0 only
(AGPL-3.0-only). Because the combined work incorporates an AGPL-3.0 component, the
combined work is distributed under the
[GNU Affero General Public License v3.0](LICENSE) — GPL-3.0 Section 13 permits the
combination, and AGPL-3.0 Section 13 applies to the combined work as a whole.
Model provenance and attribution are documented in
[`feature/cw/licenses/NOTICE.md`](feature/cw/licenses/NOTICE.md); the original GPL-3.0
text is preserved at `feature/cw/licenses/Look4Sat-GPL-3.0.txt`. The CW model runs
locally on-device and does not provide services over a network.
## Star History
<a href="https://star-history.dera.page/#rt-bishop/Look4Sat&type=timeline&legend=top-left">
<a href="https://www.star-history.com/?repos=rt-bishop%2FLook4Sat&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://star-history.dera.page/svg?repos=rt-bishop/Look4Sat&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://star-history.dera.page/svg?repos=rt-bishop/Look4Sat&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://star-history.dera.page/svg?repos=rt-bishop/Look4Sat&type=timeline&legend=top-left" />
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=rt-bishop/Look4Sat&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=rt-bishop/Look4Sat&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=rt-bishop/Look4Sat&type=timeline&legend=top-left" />
</picture>
</a>
-47
View File
@@ -1,50 +1,3 @@
import java.util.Properties
plugins {
alias(libs.plugins.convention.applicationPlugin)
}
// Load signing config from keystore.properties (gitignored, never commit credentials)
val keystoreProperties = Properties().apply {
val propsFile = rootProject.file("keystore.properties")
if (propsFile.exists()) propsFile.inputStream().use { load(it) }
}
android {
defaultConfig {
// ONNX Runtime 的 AAR 自带 4 个架构共 115MB 原生库(arm64 28M / armv7 20M /
// x86 33M / x86_64 34M)。x86 系列只有模拟器用得到, 全打包会让 APK 从 8MB
// 涨到 135MB。仅保留真机需要的两个 ABI。
ndk {
abiFilters += listOf("arm64-v8a", "armeabi-v7a")
}
}
androidResources {
// 显式保留全部语言(防 shrinkResources 丢弃 in/id 印尼语配置); AGP 9 用 localeFilters
localeFilters += listOf(
"en", "zh", "tr", "in", "id", "es", "ru", "si", "uk"
)
// DeepCW 模型必须以未压缩形式打包: ONNX Runtime 通过 mmap 直接读取
// assets, 压缩后无法映射会导致 createSession 失败。noCompress 只在
// 打包 APK 的 app 模块生效, 在 feature 库模块声明无效。
noCompress += "onnx"
}
signingConfigs {
if (keystoreProperties["storeFile"] != null) {
create("release") {
storeFile = rootProject.file(keystoreProperties["storeFile"] as String)
storePassword = keystoreProperties["storePassword"] as String
keyAlias = keystoreProperties["keyAlias"] as String
keyPassword = keystoreProperties["keyPassword"] as String
}
}
}
buildTypes {
release {
signingConfig = signingConfigs.findByName("release")
// ONNX Runtime 走 JNI, R8 混淆会重命名 ai.onnxruntime.* 类导致 native
// 崩溃。convention 插件已开启 isMinifyEnabled, 必须补 keep 规则。
proguardFiles("proguard-rules.pro")
}
}
}
-13
View File
@@ -1,13 +0,0 @@
# ProGuard / R8 rules for the Look4Sat application module.
#
# NOTE: release builds enable minification (isMinifyEnabled=true in the
# convention plugin), so anything whose classes are resolved reflectively or
# through JNI by name MUST be kept here.
# ONNX Runtime (ai.onnxruntime): the Java binding is backed by JNI. Native code
# resolves Java methods/classes by their original names; R8 renaming or
# stripping them causes a hard crash at runtime with no Java stack trace.
# This rule is required by the ONNX Runtime docs for minified Android builds.
# https://onnxruntime.ai/docs/get-started/with-java.html
-keep class ai.onnxruntime.** { *; }
-dontwarn ai.onnxruntime.**
+1 -24
View File
@@ -14,24 +14,6 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!--
dataSync rather than location. The location type is refused outright unless a location
runtime permission has already been granted - startForeground throws SecurityException -
and this service reads the station position the operator typed into settings, so demanding
location access to beacon a fixed QTH is both wrong and a way to fail silently for anyone
who declined it. The dataSync six-hour cap that prompted the earlier switch applies only
when targetSdk is 35 or higher, which this project does not declare.
-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!--
Doze suspends network access and ignores wake locks even for a foreground service, so a
coroutine delay wakes up on time and then cannot reach the network. An exact alarm with
setExactAndAllowWhileIdle is the only scheduling that survives Doze, and at a five-minute
floor the system's one-alarm-per-nine-minutes throttle is not a problem.
-->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:name=".MainApplication"
android:allowBackup="false"
@@ -43,7 +25,6 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait"
android:theme="@style/Theme.Look4Sat.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -61,11 +42,7 @@
<meta-data
android:name="android.telephony.PROPERTY_SATELLITE_DATA_OPTIMIZED"
android:value="com.rtbishop.look4sat.bg7nta" />
android:value="com.rtbishop.look4sat" />
<service
android:name="com.rtbishop.look4sat.app.AprsForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -1,287 +0,0 @@
package com.rtbishop.look4sat.app
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.widget.Toast
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.IBinder
import com.rtbishop.look4sat.BuildConfig
import com.rtbishop.look4sat.MainApplication
import com.rtbishop.look4sat.core.presentation.R
import com.rtbishop.look4sat.core.data.aprs.AprsConfig
import com.rtbishop.look4sat.core.data.aprs.AprsStore
import com.rtbishop.look4sat.core.data.aprs.AprsReporter
import com.rtbishop.look4sat.core.data.aprs.AprsState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* APRS foreground service: kept alive by a system notification; keeps working across pages.
* START_STICKY: auto-restarted after being killed by the system (same strategy as APRSdroid).
*/
class AprsForegroundService : Service() {
companion object {
const val ACTION_START = AprsStore.ACTION_START
const val ACTION_STOP = AprsStore.ACTION_STOP
const val ACTION_REPORT_NOW = AprsStore.ACTION_REPORT_NOW
const val CHANNEL_ID = "aprs_service"
const val NOTIF_ID = 101
/** Alarm-driven tick, kept separate so a manual report stays distinguishable. */
const val ACTION_ALARM_TICK = "com.rtbishop.look4sat.APRS_ALARM_TICK"
private const val ALARM_REQUEST = 4101
}
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var reporter: AprsReporter? = null
/**
* Handler on the main looper, for anything that must not run on the reporter's IO thread.
*
* onReport is invoked from AprsReporter's Dispatchers.IO scope, and Toast construction there
* throws because that thread has no Looper - an exception the surrounding runCatching then
* swallowed, so every report notice was silently discarded. The messages existed and no
* operator ever saw one.
*/
private val mainHandler = Handler(Looper.getMainLooper())
private var lastState: AprsState = AprsState.Idle
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
createChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_STOP -> stopReporting()
ACTION_ALARM_TICK -> {
// Woken by the exact alarm. Reporting once and then booking the next tick, rather
// than using a repeating alarm, means a changed interval takes effect at once.
if (reporter == null) startReporting() else reporter?.reportNow()
scheduleNextTick()
}
ACTION_REPORT_NOW -> {
if (reporter == null) {
// Service not running: start it first (Toast hint when not configured)
startReporting()
}
reporter?.reportNow()
}
else -> startReporting()
}
return START_STICKY
}
private fun startReporting() {
// onStartCommand reaches here for every ACTION_START and for the null
// intent that START_STICKY delivers on restart. Without this guard each
// call built a fresh AprsReporter and overwrote the field, leaving the
// previous one running with its own scope and timer: the server then
// received one duplicate position report per leaked instance per cycle,
// and ACTION_STOP could only ever stop the newest one.
reporter?.let { existing ->
if (existing.isRunning) return
existing.stop()
}
val cfg = AprsStore.loadConfig(this)
if (!cfg.enabled || cfg.callsign.isBlank()) {
runCatching {
Toast.makeText(this, getString(R.string.aprs_toast_not_configured), Toast.LENGTH_SHORT).show()
}
stopSelf()
return
}
startForegroundWithNotification(cfg)
val rep = AprsReporter(
configProvider = { AprsStore.loadConfig(this) },
// The real version, so the login line cannot drift from the build again.
appVersion = BuildConfig.VERSION_NAME,
positionProvider = { stationPosition() },
onState = { lastState = it },
onReport = { report ->
AprsStore.saveLastReport(this, report.ok, report.detail)
// Derived from this report rather than read from lastState: onState fires AFTER
// onReport, so the notification was being rebuilt from the previous cycle's
// verdict. For an alarm-driven report at 03:00 the notification is the only
// surface that survives, and it was showing the wrong one.
lastState = if (report.ok) AprsState.Connected else AprsState.Error
updateNotification(cfg)
// Report result always surfaces: success = short Toast, failure = long Toast + reason
// An unverified login needs its own message: the write succeeded, so a bare
// failure notice would send the operator looking at their network when the
// problem is the passcode - and APRS-IS is dropping every packet meanwhile.
// No receive-only notice. APRS-IS lets an unverified station connect and then
// discards its packets, but this app only reports its own position - there is no
// receiving side to it - so telling the operator they are "in receive-only mode"
// named a state that does not exist here. Without a passcode the packet does not
// arrive, and that is what the failure notice says.
val msg = when {
report.ok -> getString(R.string.aprs_toast_ok)
!report.verified -> getString(R.string.aprs_toast_unverified)
else -> getString(R.string.aprs_toast_fail, report.detail)
}
mainHandler.post {
Toast.makeText(this, msg,
if (report.ok) Toast.LENGTH_SHORT else Toast.LENGTH_LONG).show()
}
}
)
reporter = rep
rep.start()
// The reporter beacons once on start; the alarm carries every one after that.
scheduleNextTick()
}
private fun stopReporting() {
cancelTicks()
reporter?.stop()
reporter = null
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun startForegroundWithNotification(cfg: AprsConfig) {
try {
val notif = buildNotification(cfg)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Must match the manifest attribute exactly: AOSP checks the passed type is a
// subset of the declared one and throws otherwise, which the catch below turns
// into a silent stopSelf(). Declaring location instead would additionally require
// a granted location permission before this call, and the settings card asks only
// for notifications - so that combination fails silently too.
startForeground(NOTIF_ID, notif, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(NOTIF_ID, notif)
}
} catch (e: Exception) {
// Vendor ROM / old-system safety net: foreground-start failure only stops the service, never crashes the app
stopSelf()
}
}
private fun buildNotification(cfg: AprsConfig): Notification {
val pi = PendingIntent.getActivity(
this, 0, packageManager.getLaunchIntentForPackage(packageName),
PendingIntent.FLAG_IMMUTABLE
)
val stopPi = PendingIntent.getService(
this, 1, Intent(this, AprsForegroundService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE
)
val stateText = when (lastState) {
AprsState.Connected -> getString(R.string.aprs_notif_connected)
AprsState.Error -> getString(R.string.aprs_notif_error)
else -> getString(R.string.aprs_notif_running)
}
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_radios)
.setContentTitle(getString(R.string.aprs_notif_title, cfg.callsign))
.setContentText(stateText)
.setContentIntent(pi)
.setOngoing(true)
.addAction(0, getString(R.string.aprs_notif_stop), stopPi)
.build()
}
private fun updateNotification(cfg: AprsConfig) {
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.notify(NOTIF_ID, buildNotification(cfg))
}
/** Report position: station QTH from settings first (per user); live GPS as fallback when invalid */
private fun stationPosition(): Pair<Double, Double>? {
// 1. Station QTH (position set in settings)
val station = runCatching {
val container = (application as MainApplication).getMainContainer()
container.settingsRepo.stationPosition.value
}.getOrNull()
if (station != null && (station.latitude != 0.0 || station.longitude != 0.0)) {
return Pair(station.latitude, station.longitude)
}
// 2. Fallback: last live GPS position
return runCatching {
val lm = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager
val providers = listOf(
android.location.LocationManager.GPS_PROVIDER,
android.location.LocationManager.NETWORK_PROVIDER
)
for (p in providers) {
val loc = lm.getLastKnownLocation(p) ?: continue
if (loc.latitude != 0.0 || loc.longitude != 0.0) {
return Pair(loc.latitude, loc.longitude)
}
}
null
}.getOrNull()
}
private fun createChannel() {
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
CHANNEL_ID, getString(R.string.aprs_notif_channel),
NotificationManager.IMPORTANCE_LOW
)
nm.createNotificationChannel(channel)
}
override fun onDestroy() {
reporter?.stop()
reporter = null
super.onDestroy()
}
/**
* Book the next beacon with an exact alarm.
*
* A coroutine delay was used before, which Doze defeats: the timer fires but network access is
* suspended and wake locks are ignored, even inside a foreground service. Only
* setExactAndAllowWhileIdle survives that, and the five-minute floor keeps this well clear of
* the system's throttle on how often such an alarm may repeat.
*/
private fun scheduleNextTick() {
val cfg = AprsStore.loadConfig(this)
if (!cfg.enabled) return
val alarms = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val minutes = cfg.intervalMin.coerceAtLeast(AprsReporter.MIN_INTERVAL_MIN)
val at = System.currentTimeMillis() + minutes * 60_000L
runCatching {
val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarms.canScheduleExactAlarms()
if (exact) {
alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, tickIntent())
} else {
// The operator revoked exact alarms. An inexact one still beacons, just whenever
// the system decides, which beats not beaconing at all.
alarms.set(AlarmManager.RTC_WAKEUP, at, tickIntent())
}
}
}
private fun cancelTicks() {
val alarms = getSystemService(Context.ALARM_SERVICE) as AlarmManager
runCatching { alarms.cancel(tickIntent()) }
}
private fun tickIntent(): PendingIntent = PendingIntent.getService(
this,
ALARM_REQUEST,
Intent(this, AprsForegroundService::class.java).setAction(ACTION_ALARM_TICK),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
@@ -49,7 +49,7 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
observeNightFilterState()
setContent {
MainTheme(isDarkTheme = true) { NavRoot() }
MainTheme(isDarkTheme = true) { MainScreen() }
}
}
@@ -30,29 +30,10 @@ class MainApplication : Application(), IContainerProvider {
private lateinit var container: IMainContainer
/** Global crash capture: stack written to files/crash_log.txt, viewable after restart (user asked for error reports) */
private fun installCrashHandler() {
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
runCatching {
val log = StringBuilder()
log.append("=== Crash ${System.currentTimeMillis()} ===\n")
log.append("Thread: ").append(thread.name).append("\n")
val sw = java.io.StringWriter()
throwable.printStackTrace(java.io.PrintWriter(sw))
log.append(sw.toString()).append("\n")
val file = java.io.File(filesDir, "crash_log.txt")
file.appendText(log.toString())
}
defaultHandler?.uncaughtException(thread, throwable)
}
}
override fun getMainContainer(): IMainContainer = container
override fun onCreate() {
super.onCreate()
installCrashHandler()
container = MainContainer(this)
// trigger automatic update every 48 hours
container.appScope.launch { checkAutoUpdate() }
@@ -17,13 +17,6 @@
*/
package com.rtbishop.look4sat
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -32,6 +25,8 @@ import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
@@ -49,7 +44,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteDefaults
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold
@@ -58,31 +53,23 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator
import androidx.navigation3.ui.NavDisplay
import com.rtbishop.look4sat.core.domain.repository.IContainerProvider
import com.rtbishop.look4sat.core.domain.repository.MutualPassData
import com.rtbishop.look4sat.core.domain.navigation.MenuLayout
import com.rtbishop.look4sat.core.presentation.DeeplinkResolver
import com.rtbishop.look4sat.core.presentation.ElevationThresholds
import com.rtbishop.look4sat.core.presentation.LocalElevationThresholds
@@ -90,52 +77,42 @@ import com.rtbishop.look4sat.core.presentation.RadarDestination
import com.rtbishop.look4sat.core.presentation.Screen
import com.rtbishop.look4sat.core.presentation.hasEnoughHeight
import com.rtbishop.look4sat.core.presentation.hasEnoughWidth
import com.rtbishop.look4sat.feature.cw.CwDecodeScreen
import com.rtbishop.look4sat.feature.map.MapDestination
import com.rtbishop.look4sat.feature.mutual.MutualScreen
import com.rtbishop.look4sat.feature.mutual.MutualViewModel
import com.rtbishop.look4sat.feature.passes.PassesDestination
import com.rtbishop.look4sat.feature.radar.RadarDestination
import com.rtbishop.look4sat.feature.radar.WavelogLogScreen
import com.rtbishop.look4sat.feature.roaming.RoamingScreen
import com.rtbishop.look4sat.feature.satellites.SatellitesDestination
import com.rtbishop.look4sat.feature.settings.SettingsDestination
import com.rtbishop.look4sat.feature.status.SatStatusDestination
@Composable
fun NavRoot(deeplink: String? = null) {
val rootBackStack = rememberNavBackStack(Screen.Passes)
val deeplinkResolver = DeeplinkResolver()
LaunchedEffect(deeplink) {
deeplink?.let { rootBackStack.add(deeplinkResolver.resolve(it)) }
deeplink?.let {
val destination = deeplinkResolver.resolve(it) // rootBackStack.clear()
rootBackStack.add(destination)
}
}
val navigateBack: () -> Unit = { rootBackStack.removeLastOrNull() }
val navigateToRadar: () -> Unit = { rootBackStack.add(RadarDestination) }
// Incoming screen slides in from the right, outgoing drifts left at 1/3 speed (API35+ style)
val pushTransition = slideInHorizontally(tween(300)) { it } togetherWith
slideOutHorizontally(tween(300)) { -it / 3 }
// Reverse: outgoing slides out to the right, incoming drifts in from the left
val popTransition = slideInHorizontally(tween(300)) { -it / 3 } togetherWith
slideOutHorizontally(tween(300)) { it }
val slideInTransition = slideInHorizontally(initialOffsetX = { it }) togetherWith scaleOut(targetScale = 0.9f)
val slideOutTransition = scaleIn(initialScale = 0.9f) togetherWith slideOutHorizontally(targetOffsetX = { it })
NavDisplay(
modifier = Modifier.fillMaxSize(),
backStack = rootBackStack,
onBack = navigateBack,
transitionSpec = { pushTransition },
popTransitionSpec = { popTransition },
predictivePopTransitionSpec = { popTransition },
transitionSpec = { slideInTransition },
popTransitionSpec = { slideOutTransition },
predictivePopTransitionSpec = { slideOutTransition },
entryDecorators = listOf(
rememberSaveableStateHolderNavEntryDecorator(),
rememberViewModelStoreNavEntryDecorator()
rememberSaveableStateHolderNavEntryDecorator(), // Required for saving Compose state per entry
rememberViewModelStoreNavEntryDecorator() // Required for ViewModel scoping per entry
),
entryProvider = entryProvider {
entry<Screen.Passes> { MainScreen() }
entry<Screen.Passes> { MainScreen(navigateToRadar = { rootBackStack.add(RadarDestination) }) }
entry<RadarDestination> {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Scaffold { innerPadding ->
RadarDestination(navigateUp = navigateBack)
innerPadding.calculateTopPadding()
}
}
}
@@ -143,45 +120,17 @@ fun NavRoot(deeplink: String? = null) {
}
@Composable
fun MainScreen() {
fun MainScreen(navigateToRadar: () -> Unit = {}) {
val backStack = rememberNavBackStack(Screen.Passes)
val currentKey = backStack.lastOrNull()
val navigateBack: () -> Unit = { backStack.removeLastOrNull() }
val fadeTransition = fadeIn(animationSpec = tween(350)) togetherWith fadeOut(animationSpec = tween(350))
val navItems = listOf(Screen.Satellites, Screen.Passes, Screen.Radar, Screen.Map, Screen.Settings)
val context = LocalContext.current
val container = (context.applicationContext as IContainerProvider).getMainContainer()
val trackingState by container.radioTrackingService.state.collectAsStateWithLifecycle()
val otherSettings by container.settingsRepo.otherSettings.collectAsStateWithLifecycle()
// Menu layout is resolved in core:domain so the bar and the settings editor
// cannot disagree, and so Settings can never be pushed out of both menus.
val allNavItems = listOf(
Screen.Satellites, Screen.Passes, Screen.Radar, Screen.Mutual, Screen.Roaming,
Screen.CwDecode, Screen.WavelogLog, Screen.AmSat, Screen.Map, Screen.Settings
)
val menuLayout = remember(
otherSettings.screenOrder, otherSettings.subMenuOrder, otherSettings.hiddenScreens
) {
MenuLayout.resolve(
allScreenIds = allNavItems.map { it.screenId },
screenOrder = otherSettings.screenOrder,
subMenuOrder = otherSettings.subMenuOrder,
hiddenScreenIds = otherSettings.hiddenScreens
)
}
val mainNavItems = remember(menuLayout) {
menuLayout.mainIds.mapNotNull { id -> allNavItems.find { it.screenId == id } }
}
val moreNavItems = remember(menuLayout) {
menuLayout.moreIds.mapNotNull { id -> allNavItems.find { it.screenId == id } }
}
var moreExpanded by remember { mutableStateOf(false) }
// Intercept Back while the More menu is open: close the menu first
BackHandler(enabled = moreExpanded) { moreExpanded = false }
// Activity-scoped so the mutual query results survive navigation to Radar and back
val mutualViewModel: MutualViewModel = viewModel(
viewModelStoreOwner = context as ViewModelStoreOwner,
factory = MutualViewModel.factory(container)
)
CompositionLocalProvider(
LocalElevationThresholds provides ElevationThresholds(
@@ -191,41 +140,26 @@ fun MainScreen() {
) {
NavigationSuiteScaffold(
navigationSuiteItems = {
mainNavItems.forEach { screen ->
// Screen subclasses are data objects, so identity is enough and
// newly added pages highlight without touching this call site.
val isSelected = currentKey == screen
navItems.forEach { screen ->
val isSelected = when (currentKey) {
is Screen.Satellites -> screen is Screen.Satellites
is Screen.Passes -> screen is Screen.Passes
is Screen.Radar -> screen is Screen.Radar
is Screen.Map -> screen is Screen.Map
is Screen.Settings -> screen is Screen.Settings
else -> false
}
item(
icon = {
Icon(
painter = painterResource(screen.iconResId),
contentDescription = stringResource(screen.titleResId)
)
},
icon = { Icon(painterResource(screen.iconResId), stringResource(screen.titleResId)) },
label = { Text(stringResource(screen.titleResId)) },
selected = isSelected,
onClick = {
if (isSelected) return@item
moreExpanded = false
while (backStack.size > 1) backStack.removeAt(backStack.size - 1)
if (screen !is Screen.Passes) backStack.add(screen)
}
)
}
// More-menu button (fixed slot 6; shown only when the sub-menu is non-empty)
if (moreNavItems.isNotEmpty()) {
item(
icon = {
Icon(
painterResource(com.rtbishop.look4sat.R.drawable.ic_more),
stringResource(com.rtbishop.look4sat.core.presentation.R.string.nav_more)
)
},
label = { Text(stringResource(com.rtbishop.look4sat.core.presentation.R.string.nav_more)) },
selected = moreExpanded,
onClick = { moreExpanded = !moreExpanded }
)
}
},
navigationSuiteColors = NavigationSuiteDefaults.colors(
navigationRailContainerColor = MaterialTheme.colorScheme.surfaceContainer
@@ -236,11 +170,10 @@ fun MainScreen() {
else -> NavigationSuiteType.ShortNavigationBarMedium
}
) {
Box {
Column(modifier = Modifier.fillMaxSize()) {
Column {
NavDisplay(
backStack = backStack,
modifier = Modifier.weight(1f).fillMaxWidth(),
modifier = Modifier.weight(1f),
onBack = navigateBack,
transitionSpec = { fadeTransition },
popTransitionSpec = { fadeTransition },
@@ -257,9 +190,9 @@ fun MainScreen() {
}
entry<Screen.Passes> {
PassesDestination { catNum, aosTime ->
container.setMutualPassData(MutualPassData())
container.satelliteRepo.selectPass(catNum, aosTime)
backStack.add(Screen.Radar)
// navigateToRadar()
}
}
entry<Screen.Radar> {
@@ -268,29 +201,6 @@ fun MainScreen() {
entry<Screen.Map> {
MapDestination()
}
entry<Screen.Mutual> {
MutualScreen(
viewModel = mutualViewModel,
navigateUp = navigateBack,
navigateToRadar = { catNum, aosTime, pass ->
container.setMutualPassData(pass ?: MutualPassData())
container.satelliteRepo.selectPass(catNum, aosTime)
backStack.add(Screen.Radar)
}
)
}
entry<Screen.Roaming> {
RoamingScreen()
}
entry<Screen.CwDecode> {
CwDecodeScreen()
}
entry<Screen.AmSat> {
SatStatusDestination()
}
entry<Screen.WavelogLog> {
WavelogLogScreen(queue = container.wavelogQueue)
}
entry<Screen.Settings> {
SettingsDestination()
}
@@ -314,7 +224,6 @@ fun MainScreen() {
.clickable {
val pass = trackingState.currentPass
if (pass != null) {
container.setMutualPassData(MutualPassData())
container.satelliteRepo.selectPass(pass.catNum, pass.aosTime)
backStack.add(Screen.Radar)
}
@@ -329,7 +238,7 @@ fun MainScreen() {
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(com.rtbishop.look4sat.core.presentation.R.string.tracking_status, trackingState.currentPass?.name ?: ""),
text = "Tracking: ${trackingState.currentPass?.name ?: ""}",
fontSize = 13.sp,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onPrimaryContainer,
@@ -345,31 +254,6 @@ fun MainScreen() {
}
}
}
// More-menu popup panel (slim strip anchored to the bottom-right corner)
AnimatedVisibility(
visible = moreExpanded,
modifier = Modifier.fillMaxSize(),
enter = scaleIn(
animationSpec = tween(150),
transformOrigin = TransformOrigin(1f, 1f)
) + fadeIn(animationSpec = tween(150)),
exit = scaleOut(
animationSpec = tween(120),
transformOrigin = TransformOrigin(1f, 1f)
) + fadeOut(animationSpec = tween(120))
) {
MoreMenuPopup(
items = moreNavItems,
currentKey = currentKey,
onDismiss = { moreExpanded = false },
onSelect = { screen ->
moreExpanded = false
while (backStack.size > 1) backStack.removeAt(backStack.size - 1)
if (screen !is Screen.Passes) backStack.add(screen)
}
)
}
}
}
}
}
@@ -1,106 +0,0 @@
/*
* MoreMenuPopup.kt - bottom-nav "More" second-level menu popup panel (4.5.1).
*
* A slim right-aligned strip above the bottom bar, vertical menu items (icon+text+arrow),
* current page highlighted; tap outside to close, tap an item to navigate. No dimming scrim, so the
* page stays readable. Open/close animation is driven by the caller (MainScreen's AnimatedVisibility).
*/
package com.rtbishop.look4sat
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation3.runtime.NavKey
import com.rtbishop.look4sat.core.presentation.Screen
@Composable
fun MoreMenuPopup(
items: List<Screen>,
currentKey: NavKey?,
onDismiss: () -> Unit,
onSelect: (Screen) -> Unit
) {
Box(
modifier = Modifier
.fillMaxSize()
// Transparent catcher: taps outside the card dismiss the menu without
// dimming the page behind it.
.clickable(onClick = onDismiss)
) {
Card(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(12.dp)
.widthIn(max = 232.dp)
// Swallow taps on the card so they do not reach the dismiss
// catcher underneath.
.clickable(enabled = false) {},
shape = RoundedCornerShape(12.dp),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.6f)),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainer
)
) {
Column(modifier = Modifier.padding(vertical = 4.dp)) {
items.forEach { screen ->
// Screen subclasses are data objects, so identity is enough. The
// old per-type when was missing AmSat and Roaming, leaving those
// pages unhighlighted while open.
val isSelected = currentKey == screen
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable { onSelect(screen) }
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
Icon(
painter = painterResource(screen.iconResId),
contentDescription = stringResource(screen.titleResId),
tint = if (isSelected) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = stringResource(screen.titleResId),
fontSize = 14.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
Text(
text = "›",
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
}
-9
View File
@@ -1,9 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" />
</vector>
@@ -31,15 +31,11 @@ internal class ApplicationPlugin : Plugin<Project> {
implementation(project(":core:data"))
implementation(project(":core:domain"))
implementation(project(":core:presentation"))
implementation(project(":feature:cw"))
implementation(project(":feature:map"))
implementation(project(":feature:mutual"))
implementation(project(":feature:passes"))
implementation(project(":feature:radar"))
implementation(project(":feature:roaming"))
implementation(project(":feature:satellites"))
implementation(project(":feature:settings"))
implementation(project(":feature:status"))
implementation(libs.androidx.core.splashscreen)
implementation(libs.compose.material3.adaptive)
implementation(libs.compose.navigation3)
@@ -19,50 +19,17 @@ package com.rtbishop.look4sat.convention
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.gradle.kotlin.dsl.dependencies
/**
* core:domain is the one module shared by every platform: it holds the orbital math, the data
* models and the repository contracts, and none of it touches Android APIs. It is a Kotlin
* Multiplatform module (JVM for Android, Kotlin/Native for iOS) rather than a JVM one so the
* same compiled logic runs on both platforms instead of being reimplemented.
*
* Android modules consume the jvm target; the iOS app consumes the framework built from the
* ios targets. Anything JVM-only - org.json, java.net, java.io, java.util.Locale,
* String.format - cannot live in commonMain, because Kotlin/Native has none of them.
*/
@Suppress("Unused")
internal class CoreDomainPlugin : Plugin<Project> {
override fun apply(target: Project) = with(target) {
applyPlugin(libs.plugins.kotlin.multiplatform)
applyPlugin(libs.plugins.kotlin.jvm)
applyPlugin(libs.plugins.kotlin.serialization)
extensions.configure<KotlinMultiplatformExtension> {
jvmToolchain(libs.versions.jdkVersion.get().toInt())
jvm()
listOf(iosArm64(), iosSimulatorArm64()).forEach { iosTarget ->
iosTarget.binaries.framework {
baseName = "Look4SatCore"
isStatic = true
}
}
// The bare name accessors (commonMain, jvmTest, ...) are script-only syntax;
// plugin source has to resolve through the container members, so configure each
// source set by name. getByName is safe here: jvm() above has just created the
// jvm source sets, the same pattern the local probe build script relies on.
sourceSets.getByName("commonMain").dependencies {
setupKotlin()
dependencies {
implementation(libs.kotlin.coroutines)
implementation(libs.kotlin.serialization)
}
sourceSets.getByName("commonTest").dependencies {
implementation(libs.kotlin.test)
implementation(libs.test.coroutines)
}
// JVM-only tests live here: the AndroidManifest check reads the file system, and
// the formatter oracle tests compare against java.lang.String.format.
sourceSets.getByName("jvmTest").dependencies {
implementation(libs.test.junit4)
}
}
}
}
@@ -57,17 +57,11 @@ internal fun Project.setupAndroidApp() {
namespace = libs.versions.packageName.get()
compileSdk = libs.versions.compileSdk.get().toInt()
defaultConfig {
applicationId = libs.versions.applicationId.get()
applicationId = libs.versions.packageName.get()
minSdk = libs.versions.minSdk.get().toInt()
versionCode = libs.versions.appVersionCode.get().toInt()
versionName = libs.versions.appVersionName.get()
}
// The APRS login line reports the app version to every station on the network. It used
// to be a literal in core:data and drifted twice, so the app module now reads
// BuildConfig.VERSION_NAME - which AGP 8 only generates when asked.
buildFeatures {
buildConfig = true
}
buildTypes {
debug {
applicationIdSuffix = ".debug"
-6
View File
@@ -5,9 +5,3 @@ plugins {
android {
namespace = "com.rtbishop.look4sat.core.data"
}
dependencies {
// DeepCW 神经网络 CW 解码推理。ONNX 推理属 Android 平台依赖, 放此处而非
// core:domain —— 后者须保持纯 Kotlin/JVM 以留 KMP 迁移余地 (见 AGENTS.md)。
implementation(libs.other.onnxruntime)
}
@@ -1,244 +0,0 @@
package com.rtbishop.look4sat.core.data.aprs
import com.rtbishop.look4sat.core.domain.aprs.AprsLogin
import com.rtbishop.look4sat.core.domain.aprs.AprsPacket
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketTimeoutException
/**
* APRS-IS TCP client. Plain text: the server greets, the client logs in, then one packet per line.
*
* Two things here decide whether the operator can trust the app at all. A packet sent on a dead
* socket must not report success, and a login the server refused to verify must not look like a
* working connection - an unverified client stays connected while the server silently drops
* everything it sends.
*/
class AprsIsClient(
private val host: String,
private val port: Int,
private val callsign: String,
private val ssid: String,
private val passcode: Int,
private val softwareName: String,
private val version: String,
private val filter: String = "",
private val timeoutSec: Int = 120
) {
private var socket: Socket? = null
private var writer: PrintWriter? = null
private var reader: BufferedReader? = null
private val lock = Any()
/**
* What the server said about this login, or null before a login has been attempted.
*
* Kept as state rather than only thrown, because [AprsLogin.Outcome.Unverified] is not a
* connection error: the socket is up and writes succeed. The operator has to be told, or
* they will watch reports "succeed" for hours while nothing reaches the network.
*/
@Volatile
var loginOutcome: AprsLogin.Outcome? = null
private set
val isConnected: Boolean
get() = synchronized(lock) { socket?.isConnected == true && socket?.isClosed == false }
/** True when the server verified the passcode, so packets from this client are accepted. */
val isVerified: Boolean get() = loginOutcome is AprsLogin.Outcome.Verified
/**
* True only when the server told us it did NOT verify the login.
*
* Distinct from `!isVerified` on purpose. [AprsLogin.Outcome.Unverified] means the server
* said so and really is discarding our packets. [AprsLogin.Outcome.Unknown] means we could
* not recognise its answer - the packets may well be landing - so blaming the operator's
* passcode for that would send them to fix something that is not broken.
*/
val isRefusedByServer: Boolean get() = loginOutcome is AprsLogin.Outcome.Unverified
/**
* Connect and log in. Blocking; call from a background thread.
*
* Throws when the connection cannot be made or the server rejected the login outright.
* A login the server accepted but did not verify returns normally and leaves
* [loginOutcome] as [AprsLogin.Outcome.Unverified] for the caller to surface.
*/
@Throws(Exception::class)
fun connect() {
disconnect()
loginOutcome = null
val s = Socket()
try {
s.connect(InetSocketAddress(host, port), CONNECT_MS)
s.tcpNoDelay = true
synchronized(lock) {
socket = s
writer = PrintWriter(OutputStreamWriter(s.getOutputStream(), Charsets.ISO_8859_1), true)
reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.ISO_8859_1), 256)
}
s.soTimeout = LOGIN_MS
// The spec has the client log in AFTER the server's identification line, so read the
// greeting first. Anything starting with # is a comment and may be skipped.
readGreeting(s)?.let { refusal ->
// The server refused before we even logged in. Previously this verdict was
// computed and then overwritten by readLoginResponse, so the branch was a lie.
loginOutcome = refusal
throw IllegalArgumentException(refusal.detail)
}
val login = AprsLogin.line(callsign, ssid, passcode, softwareName, version, filter)
writer?.print(login)
writer?.print(CRLF)
writer?.flush()
loginOutcome = readLoginResponse()
s.soTimeout = timeoutSec * 1000
val outcome = loginOutcome
if (outcome is AprsLogin.Outcome.Rejected) throw IllegalArgumentException(outcome.detail)
} catch (e: Exception) {
// Close the local socket before re-throwing so it does not leak when the failure
// lands after connect() but before the field assignment - otherwise periodic
// reconnects accumulate file descriptors until no more can be opened.
runCatching { s.close() }
synchronized(lock) {
writer = null
reader = null
socket = null
}
throw e
}
}
/**
* Consume the server's greeting comment, returning a refusal when it is not one.
*
* Absence is tolerated because some servers send none, but on a short probe window rather
* than the full login timeout: waiting LOGIN_MS for a greeting that will never come cost
* eight seconds on every single connect to such a server.
*/
private fun readGreeting(socket: Socket): AprsLogin.Outcome.Rejected? {
val previous = socket.soTimeout
return try {
socket.soTimeout = GREETING_MS
val line = reader?.readLine() ?: return null
// A server that opens with anything but a comment is refusing us.
if (line.startsWith("#")) null else AprsLogin.Outcome.Rejected(line.trim())
} catch (ignored: IOException) {
null
} finally {
runCatching { socket.soTimeout = previous }
}
}
/**
* Read lines until the login verdict arrives, skipping keepalive comments.
*
* Bounded by the read timeout, so an unresponsive server cannot hang the caller.
*/
private fun readLoginResponse(): AprsLogin.Outcome {
// Bounded by a deadline, not a line count: comments are free to skip, and a chatty
// server that sent six of them before its verdict used to exhaust a fixed budget and
// turn an accepted login into Unknown - telling the operator their passcode was wrong
// when it had just been accepted.
val deadline = System.currentTimeMillis() + LOGIN_MS
while (System.currentTimeMillis() < deadline) {
val line = try {
reader?.readLine()
} catch (timeout: SocketTimeoutException) {
return AprsLogin.Outcome.Unknown("no response within ${LOGIN_MS}ms")
} catch (failure: IOException) {
return AprsLogin.Outcome.Rejected(failure.message ?: "login read failed")
} ?: return AprsLogin.Outcome.Rejected("connection closed during login")
AprsLogin.parse(line)?.let { return it }
}
return AprsLogin.Outcome.Unknown("no login response recognised")
}
/**
* Send one packet and report what happened.
*
* Returns null when there is no connection to write to. Otherwise a pair of whether the
* packet went out and a detail string for the operator.
*/
fun sendPacket(packetLine: String): Pair<Boolean, String>? {
synchronized(lock) {
val w = writer ?: return null
// Reading the response inside the same lock: disconnect() may run concurrently and
// null these fields, and reading outside the lock raced with that - the read could
// hit a just-closed socket and be reported as a successful send.
// CRLF explicitly rather than println: the spec requires "TNC2 format terminated by
// a carriage return, line feed sequence", and println emits the platform separator,
// a bare LF on Android. An earlier draft of this method sent no terminator at all,
// which leaves the server's line reader waiting forever while every send reports
// success - exactly the failure this class exists to prevent.
w.print(packetLine)
w.print(CRLF)
w.flush()
if (w.checkError()) return Pair(false, "write failed")
val s = socket ?: return Pair(false, "not connected")
val previousTimeout = s.soTimeout
return try {
s.soTimeout = ACK_MS
classifyAck(reader?.readLine())
} catch (timeout: SocketTimeoutException) {
// Silence is the normal case: APRS-IS does not acknowledge a position report, so
// nothing arriving means the line went out and the server had nothing to say.
// Telling this apart from a broken connection is the point of this method - the
// previous version treated EVERY exception as success, so a dead socket reported
// "sent OK" and made every real failure invisible, including a rejected login.
Pair(true, "sent")
} catch (failure: IOException) {
Pair(false, failure.message ?: "read failed")
} finally {
runCatching { s.soTimeout = previousTimeout }
}
}
}
/**
* Interpret whatever the server sent back after a packet.
*
* Shares AprsLogin's judgement rather than keeping its own, because the two disagreed in a way
* that mattered: treating any leading `#` as harmless meant `# Port full` and `# Login by user
* not allowed` - both of which mean the server is about to drop us - were reported as a
* successful send. APRS-IS does not acknowledge position reports, so a harmless comment still
* counts as sent; anything the server says that is not harmless does not.
*/
private fun classifyAck(response: String?): Pair<Boolean, String> {
if (response == null) return Pair(false, "connection closed by server")
return when (val verdict = AprsLogin.parse(response)) {
// A keepalive or identification comment: no verdict, so the write stands.
null -> Pair(true, "sent")
is AprsLogin.Outcome.Rejected -> Pair(false, verdict.detail)
// A late login verdict is not about this packet, and loginOutcome already carries it.
else -> Pair(true, "sent")
}
}
fun disconnect() {
synchronized(lock) {
runCatching { writer?.close() }
runCatching { reader?.close() }
runCatching { socket?.close() }
writer = null
reader = null
socket = null
}
}
private companion object {
/** Line terminator the protocol requires, independent of the platform's own. */
const val CRLF = "\r\n"
const val CONNECT_MS = 30_000
const val LOGIN_MS = 8_000
const val ACK_MS = 3_000
/** Probe window for the greeting, short because its absence is legitimate. */
const val GREETING_MS = 2_000
}
}
@@ -1,202 +0,0 @@
package com.rtbishop.look4sat.core.data.aprs
import com.rtbishop.look4sat.core.domain.aprs.AprsBeacon
import com.rtbishop.look4sat.core.domain.aprs.AprsPasscode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
/** APRS connection state */
enum class AprsState { Idle, Connecting, Connected, Disconnected, Error }
/** APRS config (persisted in SharedPreferences, saved as filled) */
data class AprsConfig(
val enabled: Boolean = false,
val server: String = "euro.aprs2.net",
val port: Int = 14580,
val callsign: String = "",
val ssid: String = "",
val passcode: String = "",
val intervalMin: Int = 5,
val statusText: String = "Look4Sat APRS",
val symbolTable: String = "/",
val symbolCode: String = ">",
val includeCourseSpeed: Boolean = true,
val includeAltitude: Boolean = true
)
/** APRS report result */
data class AprsReport(
val timestamp: Long,
val packet: String,
val ok: Boolean,
val detail: String,
/**
* False only when the server told us it did not verify the login.
*
* Carried separately from [ok] because the two are independent: a refused client's writes
* still succeed, so the packet leaves the phone and looks sent, while aprsc discards every
* one of them. Without surfacing it the operator can watch reports succeed for hours with
* nothing reaching the network. A login whose response we simply could not parse leaves this
* true, since the packets may be landing and the passcode is not at fault.
*/
val verified: Boolean = true,
/**
* True when the operator asked for a receive-only connection.
*
* Distinguished from a refused login because both log in with -1 and the server answers
* "unverified" to each: without this, deliberately choosing receive-only - the one way to
* test a setup without putting anything on the network - was reported as a wrong passcode
* and sent the operator to fix something they had set on purpose.
*/
)
/** Report scheduler (periodic + manual trigger); connection management lives in the foreground service */
class AprsReporter(
private val configProvider: () -> AprsConfig,
/**
* The app's own version, reported to APRS-IS in the login line.
*
* Passed in because core:data has no BuildConfig. It used to be a literal here and drifted
* exactly as predicted: it still read 4.6.0 two releases later, so every station on the
* network was told the wrong version. A caller in the app module can read the real one.
*/
private val appVersion: String,
private val positionProvider: () -> Pair<Double, Double>? = { null },
private val onState: (AprsState) -> Unit = {},
private val onReport: (AprsReport) -> Unit = {}
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var client: AprsIsClient? = null
private var job: Job? = null
private var manualJob: Job? = null
val isRunning: Boolean get() = job?.isActive == true
/** Start periodic reporting (called by the foreground service) */
fun start() {
stop()
val cfg = configProvider()
if (!cfg.enabled || cfg.callsign.isBlank()) {
onState(AprsState.Error)
return
}
// One report now; the service's exact alarm drives every one after this. The loop that
// used to live here relied on a coroutine delay, which Doze defeats - the timer fires on
// schedule and then finds network access suspended, so the beacon stopped whenever the
// screen locked while the notification still claimed it was running.
job = scope.launch { reportOnce() }
}
fun stop() {
job?.cancel()
job = null
runCatching { client?.disconnect() }
client = null
onState(AprsState.Idle)
}
/** Trigger one report manually (immediately, without waiting for the cycle) */
fun reportNow() {
manualJob?.cancel()
manualJob = scope.launch { reportOnce() }
}
private suspend fun reportOnce() {
val cfg = configProvider()
if (!cfg.enabled || cfg.callsign.isBlank()) return
onState(AprsState.Connecting)
try {
// The packet is built BEFORE connecting: there is no reason to open a session and log
// in only to discover there is nothing to send, which happened every five minutes for
// an operator whose QTH was unset.
val pos = positionProvider()
val beacon = AprsBeacon.build(
callsign = cfg.callsign,
ssid = cfg.ssid,
latitude = pos?.first,
longitude = pos?.second,
symbolTable = cfg.symbolTable,
symbolCode = cfg.symbolCode,
comment = cfg.statusText
)
// Nothing goes out without a position. Substituting 0,0 put this station in the Gulf
// of Guinea on the global network, under the operator's own callsign.
if (beacon is AprsBeacon.Result.Blocked) {
onState(AprsState.Error)
onReport(
AprsReport(System.currentTimeMillis(), "", false, refusalDetail(beacon.refusal))
)
return
}
val packetLine = (beacon as AprsBeacon.Result.Line).text
val c = client ?: AprsIsClient(
host = cfg.server,
port = cfg.port,
callsign = cfg.callsign,
ssid = cfg.ssid,
// Never derives one: a blank or wrong entry logs in receive-only rather than
// transmitting under a passcode the app invented for an unchecked licence.
passcode = AprsPasscode.loginValue(cfg.callsign, cfg.passcode),
// Two fields, because APRS-IS wants `vers <name> <version>` as separate tokens.
softwareName = "Look4Sat",
version = appVersion
).also { client = it }
if (!c.isConnected) c.connect()
onState(AprsState.Connected)
val result = c.sendPacket(packetLine)
val sent = result?.first == true
val detail = result?.second ?: "no connection"
// A write that succeeded on a login the server refused to verify is not a delivered
// packet: aprsc takes it and drops it, which is what let every real failure hide.
// Only an explicit refusal counts against us though - a login whose response we
// could not parse may be working fine, and blaming the passcode for that would send
// the operator to fix something that is not broken.
val refused = c.isRefusedByServer
val ok = sent && !refused
// "sent" is the write's own verdict and reads as nonsense next to a failure - the card
// showed "failed - sent" for a refused login. When the refusal is what failed the
// report, say that instead.
val reported = when {
ok -> detail
refused -> "login not verified"
else -> detail
}
onReport(
AprsReport(
System.currentTimeMillis(), packetLine, ok, reported,
verified = !refused
)
)
if (ok) onState(AprsState.Connected) else onState(AprsState.Error)
} catch (e: Exception) {
runCatching { client?.disconnect() }
client = null
onState(AprsState.Error)
onReport(AprsReport(System.currentTimeMillis(), "", false, e.message ?: "error", false))
}
}
/** A short reason for a refusal, for the operator's last-report line. */
private fun refusalDetail(refusal: AprsBeacon.Refusal): String = when (refusal) {
AprsBeacon.Refusal.NoPosition -> "no position yet"
AprsBeacon.Refusal.NoCallsign -> "no callsign set"
is AprsBeacon.Refusal.ImpossiblePosition -> "position out of range"
}
companion object {
/** Floor for the reporting interval, in minutes. */
const val MIN_INTERVAL_MIN = 5
}
}
@@ -1,92 +0,0 @@
package com.rtbishop.look4sat.core.data.aprs
import android.content.Context
/**
* APRS config storage + service action constants (shared by feature/settings and the app service,
* so feature never depends on app).
*/
object AprsStore {
const val ACTION_START = "com.rtbishop.look4sat.aprs.START"
const val ACTION_STOP = "com.rtbishop.look4sat.aprs.STOP"
const val ACTION_REPORT_NOW = "com.rtbishop.look4sat.aprs.REPORT_NOW"
const val SERVICE_CLASS = "com.rtbishop.look4sat.app.AprsForegroundService"
private const val PREFS = "aprs_config"
private const val KEY_ENABLED = "enabled"
private const val KEY_SERVER = "server"
private const val KEY_PORT = "port"
private const val KEY_CALLSIGN = "callsign"
private const val KEY_SSID = "ssid"
private const val KEY_PASSCODE = "passcode"
private const val KEY_INTERVAL = "interval"
private const val KEY_STATUS = "status"
private const val KEY_SYMBOL_TABLE = "symbol_table"
private const val KEY_SYMBOL_CODE = "symbol_code"
/**
* A house, not a car.
*
* Only fresh installs see this: saveConfig writes every key unconditionally and the enable
* switch calls it, so anyone who has ever turned APRS on has both symbol keys on disk and this
* fallback cannot reach them.
*/
private const val DEFAULT_SYMBOL_CODE = "-"
private const val KEY_LAST_TIME = "last_report_time"
private const val KEY_LAST_OK = "last_report_ok"
private const val KEY_LAST_DETAIL = "last_report_detail"
/** Read config (saved as filled; no need to re-enter each time) */
fun loadConfig(context: Context): AprsConfig {
val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return AprsConfig(
enabled = p.getBoolean(KEY_ENABLED, false),
server = p.getString(KEY_SERVER, "euro.aprs2.net") ?: "euro.aprs2.net",
port = p.getInt(KEY_PORT, 14580),
callsign = p.getString(KEY_CALLSIGN, "") ?: "",
ssid = p.getString(KEY_SSID, "") ?: "",
passcode = p.getString(KEY_PASSCODE, "") ?: "",
intervalMin = p.getInt(KEY_INTERVAL, 5),
statusText = p.getString(KEY_STATUS, "Look4Sat APRS") ?: "Look4Sat APRS",
symbolTable = p.getString(KEY_SYMBOL_TABLE, "/") ?: "/",
symbolCode = p.getString(KEY_SYMBOL_CODE, DEFAULT_SYMBOL_CODE) ?: DEFAULT_SYMBOL_CODE
)
}
/** Last report result (shown on the settings card) */
data class LastReport(val time: Long = 0L, val ok: Boolean = false, val detail: String = "")
fun loadLastReport(context: Context): LastReport {
val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return LastReport(
time = p.getLong(KEY_LAST_TIME, 0L),
ok = p.getBoolean(KEY_LAST_OK, false),
detail = p.getString(KEY_LAST_DETAIL, "") ?: ""
)
}
fun saveLastReport(context: Context, ok: Boolean, detail: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putLong(KEY_LAST_TIME, System.currentTimeMillis())
.putBoolean(KEY_LAST_OK, ok)
.putString(KEY_LAST_DETAIL, detail)
.apply()
}
/** Save config */
fun saveConfig(context: Context, cfg: AprsConfig) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_ENABLED, cfg.enabled)
.putString(KEY_SERVER, cfg.server)
.putInt(KEY_PORT, cfg.port)
.putString(KEY_CALLSIGN, cfg.callsign)
.putString(KEY_SSID, cfg.ssid)
.putString(KEY_PASSCODE, cfg.passcode)
.putInt(KEY_INTERVAL, cfg.intervalMin)
.putString(KEY_STATUS, cfg.statusText)
.putString(KEY_SYMBOL_TABLE, cfg.symbolTable)
.putString(KEY_SYMBOL_CODE, cfg.symbolCode)
.apply()
}
}
@@ -1,771 +0,0 @@
/*
* 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.data.cw
import ai.onnxruntime.OnnxTensor
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import android.content.Context
import android.util.Log
import com.rtbishop.look4sat.core.domain.cw.CwCtcDecoder
import com.rtbishop.look4sat.core.domain.cw.CwDeepBuffer
import com.rtbishop.look4sat.core.domain.cw.CwAntiAlias
import com.rtbishop.look4sat.core.domain.cw.CwDeepSpectrogram
import com.rtbishop.look4sat.core.domain.cw.CwDetectionPool
import com.rtbishop.look4sat.core.domain.cw.CwShiftDecider
import com.rtbishop.look4sat.core.domain.cw.CwToneShifter
import com.rtbishop.look4sat.core.domain.cw.ICwDecoder
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.nio.FloatBuffer
/**
* CW decoder backed by the DeepCW neural network (AGPL-3.0, see
* `feature/cw/licenses/NOTICE.md`).
*
* The model classifies a whole audio segment at once rather than streaming
* sample by sample, and it revises earlier characters once more context
* arrives. Incremental stitching therefore produces duplicated callsigns —
* measured character error rates of 67-294% against 0% for whole-segment
* decoding. Instead a [CwDeepBuffer] holds the last 20 seconds and the whole
* window is re-decoded every 1.5 seconds, replacing [decodedText] outright.
*
* The model's fixed 400-1200 Hz analysis window means pitch detection is built
* in; no spectral peak tracking or squelch gating is needed. A tone outside that
* window is invisible to the model, so [CwToneShifter] can optionally move it in —
* see [isToneShiftEnabled].
*
* @param isToneShiftEnabled read on every chunk so toggling the setting takes effect
* without rebuilding the decoder. Defaults to disabled: with it off the audio path
* is byte-for-byte what it was before the feature existed.
*/
class CwDeepDecoder(
context: Context,
private val isToneShiftEnabled: () -> Boolean = { false }
) : ICwDecoder {
// internal, not private: the archive timing is user-visible behaviour and its test asserts
// against these constants directly rather than a copy that could silently drift.
internal companion object {
const val TAG = "CwDeepDecoder"
const val MODEL_ASSET = "deepcw/model.onnx"
const val METADATA_ASSET = "deepcw/model.onnx.json"
/**
* Evicted audio is decoded into permanent history once this much accumulates.
*
* This is the delay before decoded text reaches the record, and it is additive with
* the 20 s live window: at the old 15 s the record showed nothing for the first 35 s
* of a session, and thereafter text that had scrolled out of the live window sat
* invisible for up to 15 s before landing - the record appeared to stall and, when
* it was still concatenating the live window, to delete what it had just shown.
*
* Each batch is one full inference, so this trades CPU for latency. 4 s holds the gap
* under the ~4.7 s a seven-character call sign takes at 18 WPM - the record must not
* stall for longer than the one thing an operator most needs to read back - while the
* archive path still fires less than half as often as the 1.5 s live redecode cycle.
*/
const val ARCHIVE_SECONDS = 4.0
val ARCHIVE_THRESHOLD: Int = (CwDeepSpectrogram.SAMPLE_RATE * ARCHIVE_SECONDS).toInt()
/**
* Samples the detector needs for a usable estimate: 0.4 s at 3200 Hz, giving
* ~12.5 Hz resolution.
*
* A capture chunk is ~100 ms, which is 4410 samples at the 44.1 kHz capture
* rate but only 320 after resampling to 3200 Hz. Gating on a single chunk
* reaching this size would therefore never fire, so chunks are accumulated in
* [detectionPool] until enough audio is available.
*/
const val DETECT_MIN_SAMPLES = 1280
/** Detection cadence; re-running it on every 100 ms chunk would be wasteful. */
const val DETECT_INTERVAL_MS = 2000
/** Silence after which a tone reading is treated as stale. See runDetection. */
const val TONE_EXPIRY_MS = 10_000L
/**
* Minimum change in the required shift before the window is re-shifted.
*
* Two scan bins (12.5 Hz each) plus margin. Re-shifting drops the 20 s decode
* window, so a tone drifting slightly - or the estimate hopping to an adjacent
* bin - must not keep wiping context that is still perfectly decodable.
*/
const val SHIFT_HYSTERESIS_HZ = 40f
}
private val _decodedText = MutableStateFlow("")
override val decodedText: StateFlow<String> = _decodedText.asStateFlow()
/**
* Archived text: only appended to, so a pane bound to it never loses what it showed.
*
* This once carried a provisional tail meant to cover the gap while audio waited to be
* archived, but the decode feeding that tail was never wired up, so the tail was always
* empty and the gap stayed. It is closed instead by archiving in [ARCHIVE_SECONDS]
* batches, which no longer concatenate anything that gets rewritten.
*/
private val _historyText = MutableStateFlow("")
override val historyText: StateFlow<String> = _historyText.asStateFlow()
/** Permanently archived text; the provisional tail is appended to this for display. */
private var committedText = ""
private val _estimatedPitch = MutableStateFlow<Float?>(null)
override val estimatedPitch: StateFlow<Float?> = _estimatedPitch.asStateFlow()
private val _detectedToneHz = MutableStateFlow<Float?>(null)
override val detectedToneHz: StateFlow<Float?> = _detectedToneHz.asStateFlow()
private val _activeShiftHz = MutableStateFlow(0f)
override val activeShiftHz: StateFlow<Float> = _activeShiftHz.asStateFlow()
private val _signalStrength = MutableStateFlow(0f)
override val signalStrength: StateFlow<Float> = _signalStrength.asStateFlow()
private val _lastInferenceMs = MutableStateFlow(0)
override val lastInferenceMs: StateFlow<Int> = _lastInferenceMs.asStateFlow()
private val _errorMessage = MutableStateFlow<String?>(null)
override val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
private val buffer = CwDeepBuffer()
/**
* Evicted audio accumulates here until it reaches [ARCHIVE_SECONDS], then is decoded
* once and appended to [historyText]. The batch stays short enough that the record does
* not visibly stall, and accuracy barely suffers: this content has already been through
* the 20 s window many times, so the archive decode is a confirmation, not a first look.
*
* Sized to the full window rather than the batch: [flush] hands over whatever the live
* window holds, which can be the whole 20 s.
*/
private val archiveBuffer = FloatArray(CwDeepBuffer.DEFAULT_MAX_SECONDS.toInt() * CwDeepSpectrogram.SAMPLE_RATE)
private var archiveSize = 0
/**
* Window contents retired by a change of shift, waiting to be archived.
*
* The live window is the only route into the archive - audio gets there by being pushed
* out - so clearing the window used to mean its audio was never decoded at all. When the
* shift changed more often than the window took to fill, that was every sample: modelled
* at 18 WPM with a drift every 20 s, five minutes of listening archived nothing whatever.
* Synchronised on itself: written from the capture path and drained from both there and
* [flush], which run on different coroutines. Capped, because a signal drifting on every
* detection scan would otherwise queue windows faster than they can be decoded and grow
* without bound; past the cap the oldest goes, since newer audio is what is being read.
*/
private val retiredAudio = ArrayDeque<FloatArray>()
/** Windows held awaiting archival before the oldest is dropped. */
private val retiredAudioLimit = 4
/** Held while inference runs so slow devices skip work instead of queuing it. */
private val inferenceLock = Mutex()
/**
* Serialises the archive path, which mutates state the capture coroutine also touches.
*
* [flush] runs on a different coroutine from [processBuffer] - on pause, and from the app
* scope as the screen leaves - and both append to [committedText], which is a read, an
* inference lasting hundreds of milliseconds, and only then a write. Interleaved, the
* later write wins and a whole batch of text is lost, precisely at the moment the
* operator stops listening and starts reading. They also both touch [archiveBuffer] and
* [archiveSize]: a reset of the index under a snapshot that already covered those slots
* makes the same audio decode twice.
*
* Not [inferenceLock]: that one is a tryLock, dropping work when contended, which is
* right for the live window (another decode is 1.5 s away) and wrong here (dropping an
* archive batch discards the audio for good).
*/
private val archiveLock = Mutex()
/** Decides what shift to apply from successive tone estimates. */
private val shiftDecider = CwShiftDecider(SHIFT_HYSTERESIS_HZ)
/** Wall clock of the last scan that actually found a tone, for [TONE_EXPIRY_MS]. */
private var lastToneAtMs = 0L
/** Wall clock of the last detection scan, throttling it to [DETECT_INTERVAL_MS]. */
private var lastDetectAtMs = 0L
/**
* Pools resampled chunks until [DETECT_MIN_SAMPLES] is reached. A single capture
* chunk is only 320 samples once resampled, so detection has to pool several.
*/
private val detectionPool = CwDetectionPool(DETECT_MIN_SAMPLES)
/** Carries Hilbert filter history and mixer phase across capture chunks. */
private val streamingShifter = CwToneShifter.Streaming()
/**
* Anti-alias filter for the decimation to [CwDeepSpectrogram.SAMPLE_RATE].
*
* Built on the first chunk because the capture rate is not known until then. Without
* it everything above 1600 Hz folds into the window: a 3000 Hz tone reappeared at
* 200 Hz at 119 times the spectral mean, and the whole 1600-22050 Hz band of hiss
* folded down on top of the signal.
*/
private var antiAlias: CwAntiAlias.Streaming? = null
private var antiAliasRate = 0
/**
* Previous value of the setting, so a toggle can invalidate buffered audio.
* Null until the first chunk: a decoder created while the setting is already on
* must not treat that as a change and wipe an empty buffer.
*/
private var toneShiftWasEnabled: Boolean? = null
private var environment: OrtEnvironment? = null
private var session: OrtSession? = null
private var chars: List<String> = emptyList()
private var blankIndex = 41
private var inputName = "spectrogram"
private var outputName = "log_probs"
private val appContext = context.applicationContext
private var loadAttempted = false
init {
CwProbe.init(appContext)
CwProbe.step("decoder_constructed")
}
/**
* Loads metadata and the ONNX session on first use.
*
* Deliberately not done in `init`: loading pulls in ONNX Runtime's native
* library, and a failure there surfaces as [UnsatisfiedLinkError]. Thrown
* from a constructor it would take down the whole composable that created
* the decoder, so the work happens here where it can be reported through
* [errorMessage] instead.
*
* @return true when the session is ready to run.
*/
private fun ensureLoaded(): Boolean {
if (session != null) return true
if (loadAttempted) return false
loadAttempted = true
CwProbe.step("load_begin")
try {
val metadata = JSONObject(
appContext.assets.open(METADATA_ASSET).bufferedReader().use { it.readText() }
)
val charArray = metadata.getJSONArray("chars")
chars = List(charArray.length()) { charArray.getString(it) }
blankIndex = metadata.getInt("blank_index")
inputName = metadata.getString("onnx_input_name")
outputName = metadata.getString("onnx_output_name")
val modelBytes = appContext.assets.open(MODEL_ASSET).use { it.readBytes() }
val env = OrtEnvironment.getEnvironment()
environment = env
val options = OrtSession.SessionOptions().apply {
// Keep a core free for audio capture and the UI; the default
// would spread inference across every core on the device.
val threads = (Runtime.getRuntime().availableProcessors() - 1).coerceIn(1, 4)
setIntraOpNumThreads(threads)
}
session = env.createSession(modelBytes, options)
CwProbe.step("load_session_ok")
Log.i(TAG, "DeepCW ready: ${modelBytes.size} bytes, ${chars.size} classes")
return true
} catch (t: Throwable) {
// Catches UnsatisfiedLinkError (missing/mismatched .so) as well as
// asset and session failures.
CwProbe.step("load_failed:${t.javaClass.simpleName}")
Log.e(TAG, "DeepCW model failed to load", t)
_errorMessage.value =
"CW model failed to load: ${t.message ?: t.javaClass.simpleName}"
// Persist the failure for devices without logcat access.
runCatching {
val sw = java.io.StringWriter()
t.printStackTrace(java.io.PrintWriter(sw))
java.io.File(appContext.filesDir, "deepcw_load_error.txt")
.writeText("${t.javaClass.name}: ${t.message}\n${sw}\n")
}
return false
}
}
override suspend fun processBuffer(samples: FloatArray, sampleRate: Int) {
if (samples.isEmpty()) return
if (!ensureLoaded()) return
// Filter before decimating. resampleLinear interpolates without removing anything
// above the new Nyquist, so this has to happen first or the fold is already baked in.
if (antiAlias == null || antiAliasRate != sampleRate) {
antiAlias = CwAntiAlias.Streaming(sampleRate, CwDeepSpectrogram.SAMPLE_RATE)
antiAliasRate = sampleRate
}
val bandLimited = antiAlias?.process(samples) ?: samples
// The filter holds back its group delay, so the first call returns nothing.
if (bandLimited.isEmpty()) return
val resampled = CwDeepSpectrogram.resampleLinear(
bandLimited, sampleRate, CwDeepSpectrogram.SAMPLE_RATE
)
val prepared = applyToneShift(resampled)
// Anything applyToneShift just retired from the window is older than what follows, so
// it is archived before the new audio is buffered - otherwise the record comes out
// with its text transposed. Archived whole rather than accumulated: it is already a
// full window's worth, and holding it back would only expose it to the next retirement.
val retired = drainRetiredAudio()
for (batch in retired) {
try {
archiveDecode(batch)
} catch (t: Throwable) {
if (t is CancellationException) throw t
Log.e(TAG, "retired audio decode failed", t)
}
}
val shouldRedecode = buffer.append(prepared)
// Archive audio that scrolled out of the live window. It is decoded once
// when a full archive chunk has accumulated, so old text does not vanish.
val overflow = buffer.drainOverflow()
if (overflow.isNotEmpty()) {
for (v in overflow) {
// Flush before appending when the buffer is full, so large batches
// (e.g. 47999 samples already accumulated + 64000 new overflow)
// do not silently drop audio that scrolled out of the live window.
if (archiveSize >= archiveBuffer.size) {
val audio = archiveBuffer.copyOf(archiveSize)
archiveSize = 0
try {
archiveDecode(audio)
} catch (t: Throwable) {
if (t is CancellationException) throw t
Log.e(TAG, "archive decode failed", t)
}
}
archiveBuffer[archiveSize++] = v
}
// Final flush when threshold is reached (e.g. exactly 48000 accumulated).
if (archiveSize >= ARCHIVE_THRESHOLD) {
val audio = archiveBuffer.copyOf(archiveSize)
archiveSize = 0
try {
archiveDecode(audio)
} catch (t: Throwable) {
if (t is CancellationException) throw t
Log.e(TAG, "archive decode failed", t)
}
}
}
if (!shouldRedecode || !buffer.hasEnoughAudio) return
// Drop this cycle rather than queue when the previous run is still going.
if (!inferenceLock.tryLock()) {
Log.d(TAG, "inference still running, skipping this interval")
return
}
try {
decodeWindow(buffer.snapshot())
} catch (t: Throwable) {
// Cancellation is normal when the user pauses: the capture coroutine
// is cancelled while an inference is in flight. Never swallow it as
// a decode error — rethrow so the coroutine machinery works, and do
// not flash a spurious "decode failed" banner.
if (t is CancellationException) throw t
Log.e(TAG, "inference failed", t)
_errorMessage.value = "CW decode failed: ${t.message ?: t.javaClass.simpleName}"
runCatching {
val sw = java.io.StringWriter()
t.printStackTrace(java.io.PrintWriter(sw))
java.io.File(appContext.filesDir, "deepcw_infer_error.txt")
.writeText("${t.javaClass.name}: ${t.message}\n${sw}\n")
}
} finally {
inferenceLock.unlock()
}
}
/**
* Move an out-of-window tone into the model's analysis window when the user has
* enabled it.
*
* The detection scan is a bin-by-bin DFT, so it runs at most every
* [DETECT_INTERVAL_MS] rather than on every ~100 ms capture chunk; the decision it
* produces is cached in [_activeShiftHz] and applied to the chunks in between. A
* tone already inside the window yields a zero shift, and then this returns the
* caller's array untouched.
*
* @return the audio to buffer: [resampled] itself whenever no shift applies.
*/
private fun applyToneShift(resampled: FloatArray): FloatArray {
val enabled = isToneShiftEnabled()
// A toggle invalidates whatever is already buffered: those samples were moved by
// the old setting and cannot be un-shifted, so the 20 s window would keep
// decoding them - and the pitch readout would correct them by the wrong amount -
// for up to 20 s after the user acted. Seeded from the current setting on the
// first chunk so starting up with it already on is not treated as a change.
val previousEnabled = toneShiftWasEnabled ?: enabled
toneShiftWasEnabled = enabled
if (enabled != previousEnabled) {
Log.i(TAG, "toneShift: setting changed to $enabled, dropping buffered audio")
dropBufferedAudio()
_activeShiftHz.value = 0f
_detectedToneHz.value = null
lastToneAtMs = 0L
shiftDecider.reset()
lastDetectAtMs = 0L
detectionPool.clear()
streamingShifter.reset()
}
// Detection runs whether or not shifting is enabled. It is the only measurement
// that can see past the model's window, so with it skipped an out-of-window tone
// left the UI with nothing truthful to show: the spectrogram's own pitch readout
// is arithmetically confined to the window and reports the leakage piled against
// the nearest edge, so a 1500 Hz tone published "1200 Hz" and a healthy signal
// level while decoding nothing at all.
detectionPool.add(resampled)
val now = System.currentTimeMillis()
val elapsed = now - lastDetectAtMs
if (detectionPool.isReady && elapsed >= DETECT_INTERVAL_MS) {
lastDetectAtMs = now
runDetection(detectionPool.drain(), shiftEnabled = enabled)
}
if (!enabled) return resampled
// Streaming keeps the Hilbert filter history and mixer phase across chunks;
// shifting each chunk in isolation distorted the 62 samples at its edges.
return streamingShifter.process(resampled, _activeShiftHz.value, CwDeepSpectrogram.SAMPLE_RATE)
}
/**
* Discard buffered audio that was shifted by a now-stale amount.
*
* The live window and the pending archive chunk both hold shifted samples that
* cannot be un-shifted, so they are dropped rather than decoded against the new
* shift. Text already committed to [historyText] stays: it was correct when decoded.
*/
/**
* Drop audio that was shifted by a setting no longer in force - but keep what can be kept.
*
* The live window has to go: it holds samples moved by two different amounts, and one
* spectrogram over both smears the tone. The pending archive batch does not. Those samples
* already left the window, they were shifted consistently, and they are complete, so
* discarding them threw away decodable audio for no reason. They are left in place here to
* be archived by the normal path, which keeps this function non-suspending: its two
* callers sit on the synchronous capture path, and making them suspend to run an inference
* here would put a decode inside the tone-detection scan.
*
* It mattered because this runs on every change of shift, which tracks the detected tone,
* which drifts across a pass. Modelled at 18 WPM, a drift every 20 s left the record
* permanently empty however long the operator listened: the window was wiped before any
* batch could complete, so nothing was ever committed. With the record still concatenating
* the live decode at the time, each wipe visibly cut the transcript short as well - text
* going backwards, then never accumulating at all.
*/
/** Take every retired window, oldest first, leaving the queue empty. */
private fun drainRetiredAudio(): List<FloatArray> = synchronized(retiredAudio) {
if (retiredAudio.isEmpty()) {
emptyList()
} else {
retiredAudio.toList().also { retiredAudio.clear() }
}
}
private fun dropBufferedAudio() {
// Retired, not discarded. The samples cannot stay in the window - mixing two shifts
// in one spectrogram smears the tone - but they are internally consistent and
// complete, so they decode fine on their own. Handed to the archive path rather than
// decoded here, because both callers sit on the synchronous capture path.
val retiring = buffer.snapshot()
if (retiring.isNotEmpty()) {
synchronized(retiredAudio) {
while (retiredAudio.size >= retiredAudioLimit) {
Log.w(TAG, "retired audio queue full, dropping the oldest window")
retiredAudio.removeFirst()
}
retiredAudio.addLast(retiring)
}
}
buffer.reset()
// Committed text stays: it was correct for audio that really was archived.
_historyText.value = committedText
}
/**
* Feed one detection to [shiftDecider] and log what it decided.
*
* The rule itself lives in core:domain so it can be tested directly; keeping it here
* meant tests could only restate it, and a restated rule cannot fail when the real
* one is wrong - four injected defects once left the whole suite green.
*/
private fun runDetection(sample: FloatArray, shiftEnabled: Boolean) {
val analysis = CwToneShifter.analyse(sample, CwDeepSpectrogram.SAMPLE_RATE)
// Published either way: the UI needs the real pitch to say why nothing decodes
// when shifting is off and the tone is out of range. Held through silences for
// the same reason the shift is - CW is gaps, and a gap is not a retune - but not
// indefinitely: without an expiry the last out-of-band reading survived every
// silent scan, so after retuning into the band the hint kept naming a frequency
// the operator had left. Ten seconds clears comfortably any real gap, the longest
// being about 1.7 s at 5 WPM between words plus a few seconds of thinking.
val tone = analysis.toneHz
if (tone != null) {
_detectedToneHz.value = tone
lastToneAtMs = System.currentTimeMillis()
} else if (System.currentTimeMillis() - lastToneAtMs > TONE_EXPIRY_MS) {
_detectedToneHz.value = null
}
if (!shiftEnabled) return
val decision = shiftDecider.accept(analysis)
_activeShiftHz.value = decision.shiftHz
when (decision.outcome) {
CwShiftDecider.Outcome.NO_TONE -> Log.d(
TAG,
"toneShift: no tone in ${sample.size} samples, keeping shift=${decision.shiftHz}Hz"
)
CwShiftDecider.Outcome.WITHIN_HYSTERESIS -> Log.d(
TAG,
"toneShift: tone=${decision.toneHz}Hz within ${CwShiftDecider.DEFAULT_HYSTERESIS_HZ}Hz " +
"of anchor ${shiftDecider.anchorToneHz}Hz, keeping shift=${decision.shiftHz}Hz"
)
CwShiftDecider.Outcome.NO_SHIFT_NEEDED -> Log.d(
TAG,
"toneShift: tone=${decision.toneHz}Hz inside " +
"${CwDeepSpectrogram.MIN_FREQ_HZ}-${CwDeepSpectrogram.MAX_FREQ_HZ}Hz, no shift"
)
CwShiftDecider.Outcome.SHIFTED -> Log.i(
TAG,
"toneShift: tone=${decision.toneHz}Hz outside window, " +
"shifting ${decision.shiftHz}Hz to ${CwToneShifter.TARGET_HZ}Hz"
)
}
if (decision.changed) {
// The window still holds audio moved by the old amount. Mixing two shifts in
// one spectrogram smears the tone, and the pitch readout could only be right
// for one of them, so rebuild the window from the new shift.
Log.i(TAG, "toneShift: shift changed, dropping buffered audio")
dropBufferedAudio()
streamingShifter.reset()
CwProbe.step("tone_shift tone=${decision.toneHz} shift=${decision.shiftHz}")
}
}
private suspend fun decodeWindow(window: FloatArray) = withContext(Dispatchers.Default) {
val activeSession = session ?: return@withContext
val activeEnvironment = environment ?: return@withContext
CwProbe.step("infer_begin frames=${window.size}")
val spectrogram = CwDeepSpectrogram.compute(window)
val text = runInference(activeSession, activeEnvironment, spectrogram)
// Replace, never append: the model rewrites earlier characters as more
// context arrives, so appending would leave stale guesses on screen.
_decodedText.value = text
updateSignalMetrics(spectrogram)
}
/**
* Archive whatever audio is still in the pipeline, so stopping does not discard it.
*
* Two places hold audio that would otherwise never be decoded into the record: the
* batch accumulating towards [ARCHIVE_THRESHOLD], and the live window itself, whose
* contents only ever reach the archive by being pushed out by newer audio. Together
* that is the last [CwDeepBuffer.DEFAULT_MAX_SECONDS] + [ARCHIVE_SECONDS] of a session
* - which includes the end of every transmission, the part with the call sign in it.
*
* Order matters: the pending batch left the window before anything still in it, so it
* has to be archived first or the record comes out with its text transposed.
*/
override suspend fun flush() = archiveLock.withLock {
// Oldest first, all the way down: retired window contents, then the batch accumulating
// towards the threshold, then what is still live.
for (batch in drainRetiredAudio()) {
runCatching { archiveDecodeLocked(batch) }
.onFailure { if (it is CancellationException) throw it }
}
if (archiveSize > 0) {
val pending = archiveBuffer.copyOf(archiveSize)
archiveSize = 0
runCatching { archiveDecodeLocked(pending) }
.onFailure { if (it is CancellationException) throw it }
}
// Draining the window empties it, so a second flush cannot double-archive the tail.
val window = buffer.snapshot()
if (window.isNotEmpty()) {
buffer.reset()
runCatching { archiveDecodeLocked(window) }
.onFailure { if (it is CancellationException) throw it }
}
// The live line described audio that is now in the record; leaving it would show the
// same characters twice, in two places, one of them stale.
_decodedText.value = ""
}
/**
* Decode a chunk of audio that has scrolled out of the live window and
* append it to [historyText]. Unlike the live window this never replaces —
* the archived audio is final, so its text is permanent.
*/
private suspend fun archiveDecode(audio: FloatArray) = archiveLock.withLock {
archiveDecodeLocked(audio)
}
/** [archiveDecode] without the lock, for callers already holding [archiveLock]. */
private suspend fun archiveDecodeLocked(audio: FloatArray) = withContext(Dispatchers.Default) {
val activeSession = session ?: return@withContext
val activeEnvironment = environment ?: return@withContext
if (audio.size < CwDeepSpectrogram.FFT_LENGTH) return@withContext
val spectrogram = CwDeepSpectrogram.compute(audio)
val text = runInference(activeSession, activeEnvironment, spectrogram)
committedText += text
_historyText.value = committedText
}
/** Run the ONNX model over a pre-computed spectrogram and return the decoded text. */
private fun runInference(
activeSession: OrtSession,
activeEnvironment: OrtEnvironment,
spectrogram: Array<FloatArray>
): String {
val frames = spectrogram.size
val bins = CwDeepSpectrogram.FREQUENCY_BINS
val flat = FloatBuffer.allocate(frames * bins)
for (frame in spectrogram) flat.put(frame)
flat.rewind()
val shape = longArrayOf(1, 1, frames.toLong(), bins.toLong())
val startedAt = System.currentTimeMillis()
val text: String
OnnxTensor.createTensor(activeEnvironment, flat, shape).use { input ->
activeSession.run(mapOf(inputName to input)).use { result ->
@Suppress("UNCHECKED_CAST")
val logits = result[outputName].get().value as Array<Array<FloatArray>>
text = CwCtcDecoder.greedy(logits, chars, blankIndex)
}
}
_lastInferenceMs.value = (System.currentTimeMillis() - startedAt).toInt()
CwProbe.step("infer_done ms=${_lastInferenceMs.value}")
return text
}
/**
* Report the loudest bin as the tone pitch and its prominence over the
* window mean as a 0..1 strength, purely for the UI readout.
*/
private fun updateSignalMetrics(spectrogram: Array<FloatArray>) {
if (spectrogram.isEmpty()) return
var bestBin = 0
var bestValue = 0f
var total = 0f
var count = 0
for (frame in spectrogram) {
for (bin in frame.indices) {
val value = frame[bin]
total += value
count++
if (value > bestValue) {
bestValue = value
bestBin = bin
}
}
}
if (count == 0 || bestValue <= 0f) return
val binHz = CwDeepSpectrogram.SAMPLE_RATE.toDouble() / CwDeepSpectrogram.FFT_LENGTH
// Relative bin 0 is 400 Hz; absolute bin index is 32 + bestBin.
val absoluteBin = 32 + bestBin
// Undo the shift before reporting: the spectrogram sees the moved tone, but
// the readout must show the pitch the operator actually hears on the radio.
_estimatedPitch.value = (absoluteBin * binHz - _activeShiftHz.value).toFloat()
val mean = total / count
val prominence = ((bestValue - mean) / bestValue).coerceIn(0f, 1f)
// The meter claims something decodable is present, so it needs a tone the scan has
// actually confirmed inside the window - not merely the absence of a confirmed
// out-of-window one. Requiring the confirmation is what covers the intermittent
// case: a slow fist out of band at 15% duty scores 2.5 against MIN_PROMINENCE 4.5,
// so no tone is reported, and a condition keyed on "confirmed outside" stayed false
// and let the meter read half scale on window-edge leakage beside an empty
// transcript - the exact reading this gate exists to suppress.
val confirmed = _detectedToneHz.value
val decodable = confirmed != null &&
(_activeShiftHz.value != 0f || CwToneShifter.isInsideWindow(confirmed))
_signalStrength.value = if (decodable) prominence else 0f
}
/**
* Clear everything. Not serialised against [archiveLock]: an archive decode already in
* flight can land its batch after this returns, leaving a few characters behind. The
* operator asked to clear and can ask again; making this suspend to close that window
* would push it onto every caller, including a synchronous button handler.
*/
override fun reset() {
antiAlias?.reset()
buffer.reset()
synchronized(retiredAudio) { retiredAudio.clear() }
_decodedText.value = ""
_historyText.value = ""
committedText = ""
archiveSize = 0
_estimatedPitch.value = null
_detectedToneHz.value = null
lastToneAtMs = 0L
_signalStrength.value = 0f
_lastInferenceMs.value = 0
// Re-detect from scratch: the operator may have retuned before resetting.
_activeShiftHz.value = 0f
shiftDecider.reset()
lastDetectAtMs = 0L
detectionPool.clear()
streamingShifter.reset()
// Leave toneShiftWasEnabled unset so the next chunk re-seeds it from the
// current setting instead of reporting a spurious change.
toneShiftWasEnabled = null
}
override fun close() {
try {
session?.close()
} catch (t: Throwable) {
Log.w(TAG, "session close failed", t)
}
session = null
environment = null
}
}
@@ -1,53 +0,0 @@
/*
* 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.data.cw
import android.content.Context
import android.util.Log
/**
* Minimal crash-probe logger for diagnosing crashes that produce no Java
* stack trace (native faults, low-memory kills). Each step appends one line
* to `files/probe_cw.txt`; if the process dies mid-way the last line shows
* exactly where. No adb or logcat required.
*/
internal object CwProbe {
/** Keep the diagnostic file bounded: the decoder writes two lines per
* 1.5 s inference tick (~170 KB/hour), so without a cap it grows without
* limit on every release build. Truncate instead of deleting so the
* probe keeps the last diagnostics before a crash. */
private const val MAX_FILE_BYTES = 1_048_576L // 1 MiB
private var dir: java.io.File? = null
fun init(context: Context) {
dir = context.filesDir
}
fun step(label: String) {
val target = dir ?: return
runCatching {
val line = "${System.currentTimeMillis()} $label"
val file = java.io.File(target, "probe_cw.txt")
if (file.length() > MAX_FILE_BYTES) file.delete()
file.appendText("$line\n")
Log.i("CwProbe", line)
}
}
}
@@ -76,12 +76,10 @@ class BluetoothReporter(
private fun ensureRotatorConnected() {
if (rotatorConnected || rotatorConnecting || rotatorDeviceId.isBlank()) return
reporterScope.launch {
var opened: android.bluetooth.BluetoothSocket? = null
try {
rotatorConnecting = true
val device = bluetoothManager.adapter.getRemoteDevice(rotatorDeviceId)
val socket = device.createInsecureRfcommSocketToServiceRecord(sppId)
opened = socket
socket.connect()
rotatorSocket = socket
rotatorStream = socket.outputStream
@@ -89,11 +87,6 @@ class BluetoothReporter(
Log.i(tag, "Rotator connected to $rotatorDeviceId")
} catch (e: Exception) {
Log.e(tag, "Rotator connect error: ${e.message}")
// Close the socket we opened, otherwise a failure after connect()
// leaks it: nothing else holds a reference once this returns.
runCatching { opened?.close() }
rotatorSocket = null
rotatorStream = null
rotatorConnected = false
} finally {
rotatorConnecting = false
@@ -104,12 +97,10 @@ class BluetoothReporter(
private fun ensureFrequencyConnected() {
if (frequencyConnected || frequencyConnecting || frequencyDeviceId.isBlank()) return
reporterScope.launch {
var opened: android.bluetooth.BluetoothSocket? = null
try {
frequencyConnecting = true
val device = bluetoothManager.adapter.getRemoteDevice(frequencyDeviceId)
val socket = device.createInsecureRfcommSocketToServiceRecord(sppId)
opened = socket
socket.connect()
frequencySocket = socket
frequencyStream = socket.outputStream
@@ -117,11 +108,6 @@ class BluetoothReporter(
Log.i(tag, "Frequency connected to $frequencyDeviceId")
} catch (e: Exception) {
Log.e(tag, "Frequency connect error: ${e.message}")
// Close the socket we opened, otherwise a failure after connect()
// leaks it: nothing else holds a reference once this returns.
runCatching { opened?.close() }
frequencySocket = null
frequencyStream = null
frequencyConnected = false
} finally {
frequencyConnecting = false
@@ -42,9 +42,6 @@ class Ft817Controller(
private val commandDelayMs = 200L
private val maxAckReadFailures = 3
/** Largest frequency the 4-byte BCD / 10 Hz CAT field can represent. */
private val maxFrequencyHz = 999_999_990L
private var socket: BluetoothSocket? = null
private var outputStream: OutputStream? = null
private var inputStream: InputStream? = null
@@ -56,11 +53,9 @@ class Ft817Controller(
override suspend fun connect(): Boolean = withContext(Dispatchers.IO) {
if (isConnected) return@withContext true
if (deviceAddress.isBlank()) return@withContext false
var opened: android.bluetooth.BluetoothSocket? = null
try {
val device = bluetoothManager.adapter.getRemoteDevice(deviceAddress)
val btSocket = device.createInsecureRfcommSocketToServiceRecord(sppId)
opened = btSocket
btSocket.connect()
socket = btSocket
outputStream = btSocket.outputStream
@@ -71,13 +66,6 @@ class Ft817Controller(
true
} catch (e: Exception) {
Log.e(tag, "Connect error: ${e.message}")
// Close the socket we opened. Without this a failure after connect()
// (e.g. outputStream throwing) leaks the Bluetooth socket, because
// disconnect() only closes what already reached the fields.
runCatching { opened?.close() }
socket = null
outputStream = null
inputStream = null
isConnected = false
false
}
@@ -103,16 +91,6 @@ class Ft817Controller(
}
override suspend fun setFrequency(frequencyHz: Long): Boolean = withContext(Dispatchers.IO) {
// The FT-817 CAT frequency field is 4 BCD bytes at 10 Hz resolution,
// so the protocol cannot express anything above 999,999,990 Hz. Below
// that the encoder is exact; above it, the %08d formatting silently
// drops the leading digit and the radio receives a frequency ten
// times lower (e.g. 1267.6 MHz becomes 126.76 MHz), and the tracking
// loop's read-back then locks onto the wrong band. Reject instead.
if (frequencyHz > maxFrequencyHz) {
Log.e(tag, "setFrequency rejected: $frequencyHz Hz exceeds FT-817 CAT limit $maxFrequencyHz")
return@withContext false
}
ioMutex.withLock {
sendCommandWithAck(Ft817CatProtocol.buildSetFreqCommand(frequencyHz))
}
@@ -67,11 +67,9 @@ class Ic705Controller(
override suspend fun connect(): Boolean = withContext(Dispatchers.IO) {
if (isConnected) return@withContext true
if (deviceAddress.isBlank()) return@withContext false
var opened: android.bluetooth.BluetoothSocket? = null
try {
val device = bluetoothManager.adapter.getRemoteDevice(deviceAddress)
val btSocket = device.createInsecureRfcommSocketToServiceRecord(sppId)
opened = btSocket
btSocket.connect()
socket = btSocket
outputStream = btSocket.outputStream
@@ -86,13 +84,6 @@ class Ic705Controller(
true
} catch (e: Exception) {
Log.e(tag, "Connect error: ${e.message}")
// Close the socket we opened. Without this a failure after connect()
// (e.g. outputStream throwing) leaks the Bluetooth socket, because
// disconnect() only closes what already reached the fields.
runCatching { opened?.close() }
socket = null
outputStream = null
inputStream = null
isConnected = false
false
}
@@ -71,19 +71,14 @@ class NetworkReporter(
private fun ensureRotatorConnected() {
if (rotatorConnected || rotatorConnecting || rotatorServer.isBlank()) return
reporterScope.launch {
var opened: SocketChannel? = null
try {
rotatorConnecting = true
opened = SocketChannel.open(InetSocketAddress(rotatorServer, rotatorPort))
rotatorSocket = opened
rotatorSocket = SocketChannel.open(InetSocketAddress(rotatorServer, rotatorPort))
rotatorConnected = true
println("NetworkReporter: Rotator connected to $rotatorServer:$rotatorPort")
} catch (e: Exception) {
println("NetworkReporter rotator connect error: ${e.message}")
rotatorConnected = false
// Close a socket that connected but failed during setup, so a
// broken channel is never left referenced without a closer.
opened?.close()
} finally {
rotatorConnecting = false
}
@@ -93,17 +88,14 @@ class NetworkReporter(
private fun ensureFrequencyConnected() {
if (frequencyConnected || frequencyConnecting || frequencyServer.isBlank()) return
reporterScope.launch {
var opened: SocketChannel? = null
try {
frequencyConnecting = true
opened = SocketChannel.open(InetSocketAddress(frequencyServer, frequencyPort))
frequencySocket = opened
frequencySocket = SocketChannel.open(InetSocketAddress(frequencyServer, frequencyPort))
frequencyConnected = true
println("NetworkReporter: Frequency connected to $frequencyServer:$frequencyPort")
} catch (e: Exception) {
println("NetworkReporter frequency connect error: ${e.message}")
frequencyConnected = false
opened?.close()
} finally {
frequencyConnecting = false
}
@@ -119,17 +111,6 @@ class NetworkReporter(
} catch (e: Exception) {
println("NetworkReporter write error: ${e.message}")
onError()
// The channel failed a write: drop it and its closure obligation.
// Leaving it referenced lets the next connect overwrite the field
// and leak the old channel. Only the field the caller passed is
// cleared, matching the connected=false the onError sets.
if (socket === rotatorSocket) {
rotatorSocket?.close()
rotatorSocket = null
} else if (socket === frequencySocket) {
frequencySocket?.close()
frequencySocket = null
}
}
}
@@ -267,20 +267,14 @@ class RadioTrackingService(
if (tuningRadio.isEmpty()) {
if (txNow != null && txNow.isConnected && txRadioFreq != null) {
// Only remember the frequency we actually wrote: if the radio
// rejects it (FT-817 CAT limit) or the link dropped, keeping
// lastSetTxFreq updated would make the manual-tuning detector
// see a phantom dial change on the next read-back.
if (txNow.setFrequency(txRadioFreq)) {
txNow.setFrequency(txRadioFreq)
lastSetTxFreq = txRadioFreq.toDouble()
}
}
if (rxNow != null && rxNow.isConnected && rxRadioFreq != null) {
if (rxNow.setFrequency(rxRadioFreq)) {
rxNow.setFrequency(rxRadioFreq)
lastSetRxFreq = rxRadioFreq.toDouble()
}
}
}
_state.update {
it.copy(
@@ -456,17 +450,15 @@ class RadioTrackingService(
// 0x25/00 = active (RX) VFO, 0x25/01 = inactive (TX) VFO.
if (rxRadioFreq != null) {
Log.d(tag, "Split loop RX (0x25/00): ${rxRadioFreq}Hz")
if (radio.setWorkingFrequency(rxRadioFreq)) {
radio.setWorkingFrequency(rxRadioFreq)
lastSetRxFreq = rxRadioFreq.toDouble()
}
}
if (txRadioFreq != null) {
Log.d(tag, "Split loop TX (0x25/01): ${txRadioFreq}Hz")
if (radio.setTxVfoFrequency(txRadioFreq)) {
radio.setTxVfoFrequency(txRadioFreq)
lastSetTxFreq = txRadioFreq.toDouble()
}
}
}
_state.update {
it.copy(
@@ -36,15 +36,11 @@ import com.rtbishop.look4sat.core.data.repository.SelectionRepo
import com.rtbishop.look4sat.core.data.repository.SensorsRepo
import com.rtbishop.look4sat.core.data.repository.SettingsRepo
import com.rtbishop.look4sat.core.data.source.LocalSource
import com.rtbishop.look4sat.core.data.source.OkHttpHttpClient
import com.rtbishop.look4sat.core.data.source.RemoteSource
import com.rtbishop.look4sat.core.data.usecase.AddToCalendar
import com.rtbishop.look4sat.core.data.usecase.AudioCapture
import com.rtbishop.look4sat.core.data.usecase.SaveImage
import com.rtbishop.look4sat.core.data.usecase.ShowToast
import com.rtbishop.look4sat.core.domain.wavelog.IWavelogQueueStore
import com.rtbishop.look4sat.core.domain.wavelog.WavelogQueue
import com.rtbishop.look4sat.core.domain.wavelog.WavelogUploader
import com.rtbishop.look4sat.core.domain.model.RadioControlSettings
import com.rtbishop.look4sat.core.domain.repository.IDatabaseRepo
import com.rtbishop.look4sat.core.domain.repository.IMainContainer
@@ -55,7 +51,6 @@ import com.rtbishop.look4sat.core.domain.repository.ISatelliteRepo
import com.rtbishop.look4sat.core.domain.repository.ISelectionRepo
import com.rtbishop.look4sat.core.domain.repository.ISensorsRepo
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import com.rtbishop.look4sat.core.domain.repository.MutualPassData
import com.rtbishop.look4sat.core.domain.source.ILocalSource
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import com.rtbishop.look4sat.core.domain.usecase.IAddToCalendar
@@ -67,28 +62,12 @@ import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.rtbishop.look4sat.core.data.qrz.QrzGridLookup
import com.rtbishop.look4sat.core.domain.qrz.IQrzGridLookup
import okhttp3.OkHttpClient
import com.rtbishop.look4sat.core.data.wavelog.LotwSatellitesRepo
import com.rtbishop.look4sat.core.domain.wavelog.WaveLogApi
class MainContainer(private val context: Context) : IMainContainer {
private val localSource = provideLocalSource()
private val remoteSource by lazy { provideRemoteSource() }
/**
* WaveLogApi is a plain object in core:domain, and shared code has no socket API of its own on
* iOS, so the container hands it the platform client. Its requests used to be made by an
* HttpURLConnection built inside WaveLogApi, which only ever existed on the JVM.
*/
init {
WaveLogApi.installHttpClient(OkHttpHttpClient(OkHttpClient.Builder().build()))
}
private val remoteSource = provideRemoteSource()
private val mainHandler = CoroutineExceptionHandler { _, error -> println("MainHandler: $error") }
override val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + mainHandler)
override val settingsRepo = provideSettingsRepo()
@@ -101,68 +80,14 @@ class MainContainer(private val context: Context) : IMainContainer {
RadioTrackingService(appScope, manager, satelliteRepo, settingsRepo)
}
private val _mutualPassData = MutableStateFlow(MutualPassData())
override val mutualPassData: StateFlow<MutualPassData> = _mutualPassData.asStateFlow()
override fun setMutualPassData(data: MutualPassData) {
_mutualPassData.value = data
}
override fun provideAddToCalendar(): IAddToCalendar = AddToCalendar(context)
override fun providePairedBluetoothDevices(): List<Pair<String, String>> = buildList {
try {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
manager.adapter?.bondedDevices?.forEach { add(Pair(it.name ?: "Unknown", it.address ?: "")) }
} catch (_: SecurityException) {}
}
override fun provideShowToast(): IShowToast = ShowToast(context)
override fun provideAudioCapture(): IAudioCapture = AudioCapture()
// 每次调用返回新实例: 调用方负责 close() 释放 OrtSession, 且 Radar 内嵌
// 面板与独立 CW 页各自持有自己的解码器
override fun provideCwDecoder(): com.rtbishop.look4sat.core.domain.cw.ICwDecoder =
com.rtbishop.look4sat.core.data.cw.CwDeepDecoder(context) {
// Read per chunk so toggling the setting applies without restarting capture.
settingsRepo.otherSettings.value.cwToneShiftEnabled
}
override fun provideSaveImage(): ISaveImage = SaveImage(context)
// WaveLog logging (4.5.2): local queue + uploader (shared instance)
override val wavelogQueue: WavelogQueue by lazy {
val prefs = context.getSharedPreferences("wavelog", Context.MODE_PRIVATE)
WavelogQueue(object : IWavelogQueueStore {
override fun load(): String = prefs.getString("wavelog_queue", "[]") ?: "[]"
override fun save(json: String) = prefs.edit().putString("wavelog_queue", json).apply()
})
}
override fun provideWavelogUploader(): WavelogUploader = WavelogUploader(settingsRepo, wavelogQueue)
private val lotwRepo: LotwSatellitesRepo by lazy {
LotwSatellitesRepo(context).also { it.restore() }
}
override fun provideLotwSatellitesRepo(): com.rtbishop.look4sat.core.domain.wavelog.ILotwSatellitesRepo = lotwRepo
/**
* QRZ grid lookup. Holds the cookie read so no composable has to: the log screen used to pull
* it out of SharedPreferences through LocalContext, putting disk access inside composition.
*/
private val qrzGridLookup: QrzGridLookup by lazy {
QrzGridLookup(
context.getSharedPreferences(QrzGridLookup.PREFS_NAME, Context.MODE_PRIVATE),
OkHttpClient.Builder()
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(20, java.util.concurrent.TimeUnit.SECONDS)
.build()
)
}
override fun provideQrzGridLookup(): IQrzGridLookup = qrzGridLookup
override fun provideBluetoothReporter(): IReporter {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val rc = settingsRepo.rcSettings.value
@@ -213,9 +138,17 @@ class MainContainer(private val context: Context) : IMainContainer {
return SensorsRepo(manager, displayManager)
}
override fun providePairedBluetoothDevices(): List<Pair<String, String>> = buildList {
try {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
manager.adapter?.bondedDevices?.forEach { add(Pair(it.name ?: "Unknown", it.address ?: "")) }
} catch (_: SecurityException) {}
}
private fun provideDatabaseRepo(): IDatabaseRepo {
val dbDispatcher = Dispatchers.Default
val dataParser = DataParser(dbDispatcher)
val remoteSource = provideRemoteSource()
return DatabaseRepo(dbDispatcher, dataParser, localSource, remoteSource, settingsRepo)
}
@@ -226,14 +159,7 @@ class MainContainer(private val context: Context) : IMainContainer {
}
private fun provideRemoteSource(): IRemoteSource {
return RemoteSource(
Dispatchers.IO, context.contentResolver,
OkHttpClient.Builder()
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(20, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(20, java.util.concurrent.TimeUnit.SECONDS)
.build()
)
return RemoteSource(Dispatchers.IO, context.contentResolver, OkHttpClient.Builder().build())
}
private fun provideSatelliteRepo(): ISatelliteRepo {
@@ -249,6 +175,6 @@ class MainContainer(private val context: Context) : IMainContainer {
val appPrefsFileName = "${context.packageName}_preferences"
val appPreferences = context.getSharedPreferences(appPrefsFileName, Context.MODE_PRIVATE)
val appVersionName = context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "4.0.4"
return SettingsRepo(context, manager, appPreferences, appVersionName)
return SettingsRepo(manager, appPreferences, appVersionName)
}
}
@@ -1,61 +0,0 @@
/*
* 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.data.qrz
import android.content.SharedPreferences
import com.rtbishop.look4sat.core.domain.qrz.IQrzGridLookup
import com.rtbishop.look4sat.core.domain.qrz.QrzGrid
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import okhttp3.OkHttpClient
/**
* Grid lookup backed by the cookie the operator pasted into settings.
*
* Owns the cookie read so the log screen does not: a composable used to pull it out of
* SharedPreferences through LocalContext on every submission, which put disk access inside
* composition and went around the repository layer.
*/
class QrzGridLookup(
private val preferences: SharedPreferences,
httpClient: OkHttpClient,
dispatcher: CoroutineDispatcher = Dispatchers.IO
) : IQrzGridLookup {
private val source = QrzGridSource(httpClient, dispatcher)
override suspend fun lookup(callsign: String): QrzGrid {
val cookie = preferences.getString(COOKIE_KEY, "").orEmpty()
// No cookie and an expired one call for the same thing from the operator, so they report
// the same way rather than adding a fourth outcome nobody could act on differently.
if (cookie.isBlank()) return QrzGrid.SignedOut
return source.lookupGrid(callsign, cookie)
}
override suspend fun signedInAs(): String? {
val cookie = preferences.getString(COOKIE_KEY, "").orEmpty()
if (cookie.isBlank()) return null
return source.lookupOwnCallsign(cookie)
}
companion object {
/** Where the settings screen stores what the operator pasted. */
const val PREFS_NAME = "qrz_cookie"
const val COOKIE_KEY = "cookie"
}
}
@@ -1,112 +0,0 @@
/*
* 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.data.qrz
import com.rtbishop.look4sat.core.domain.qrz.QrzGrid
import com.rtbishop.look4sat.core.domain.qrz.QrzGridParser
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
/**
* Reads a station's Maidenhead locator off its QRZ.com page.
*
* QRZ has no free lookup API for this, so the page is fetched with the operator's own session
* cookie and parsed. The cookie is pasted by the operator in settings and never built into the
* app. Parsing lives in [QrzGridParser] so it can be tested without a network; this class only
* fetches and retries.
*/
class QrzGridSource(
private val httpClient: OkHttpClient,
private val dispatcher: CoroutineDispatcher
) {
/**
* Look up [callsign]'s locator.
*
* Retried because this runs on a phone, mid-pass, often on mobile data - a single timeout
* used to mean the QSO was logged without a grid and the operator was never told. Retries
* are bounded and backed off so a genuinely unreachable QRZ costs at most a few seconds:
* only transport failures are retried, since a page that loaded and parsed will not parse
* differently on a second attempt.
*/
suspend fun lookupGrid(callsign: String, cookieHeader: String): QrzGrid =
withContext(dispatcher) {
if (callsign.isBlank() || cookieHeader.isBlank()) return@withContext QrzGrid.SignedOut
val url = "$DB_URL${callsign.trim().uppercase()}"
fetchWithRetry(url, cookieHeader)?.let(QrzGridParser::parseGrid)
?: QrzGrid.Unreachable(MAX_ATTEMPTS)
}
/**
* The callsign the pasted cookie is signed in as, so settings can show the operator whose
* account it belongs to rather than just claiming success.
*/
suspend fun lookupOwnCallsign(cookieHeader: String): String? = withContext(dispatcher) {
if (cookieHeader.isBlank()) return@withContext null
fetchWithRetry(DB_URL, cookieHeader)?.let(QrzGridParser::parseOwnCallsign)
}
/** Fetch [url], retrying transport failures with backoff. Null when every attempt failed. */
/**
* Normalise whatever the operator pasted into a Cookie header value.
*
* They paste either a raw `k=v; k=v` header or the JSON array a cookie-export extension
* produces. The old client normalised this and the rewrite dropped it, so a JSON export that
* used to work went out as a literal JSON blob, QRZ served its signed-out page, and the app
* told the operator their cookie had expired when it was perfectly good.
*/
private fun normalise(raw: String): String = QrzGridParser.cookieHeader(raw)
private suspend fun fetchWithRetry(url: String, rawCookie: String): String? {
val cookieHeader = normalise(rawCookie)
if (cookieHeader.isBlank()) return null
repeat(MAX_ATTEMPTS) { attempt ->
try {
val request = Request.Builder().url(url)
.header("User-Agent", USER_AGENT)
.header("Cookie", cookieHeader)
.build()
httpClient.newCall(request).execute().use { response ->
if (response.isSuccessful) return response.body.string()
// A 4xx will repeat identically, so only server-side faults are worth retrying.
if (response.code < 500) return null
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("QrzGridSource attempt ${attempt + 1} failed: $exception")
}
if (attempt < MAX_ATTEMPTS - 1) delay(BACKOFF_MS[attempt])
}
return null
}
private companion object {
/** Bare form is the signed-in home page; a callsign appended is that station's page. */
const val DB_URL = "https://www.qrz.com/db/"
const val USER_AGENT = "Mozilla/5.0 (Linux; Android 13) Look4Sat"
const val MAX_ATTEMPTS = 3
/** Waits before the second and third attempt. Short enough to finish inside a pass. */
val BACKOFF_MS = longArrayOf(700L, 2_000L)
}
}
@@ -15,13 +15,8 @@ import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
/**
* One report from the AMSAT API (data layer model).
*
* Internal rather than private so [AmSatRepository.buildStatuses] can be unit-tested:
* the JSON parsing around it needs Android's JSONObject, which is a stub on the JVM.
*/
internal data class ApiReport(
/** One report from the AMSAT API (data layer model). */
private data class ApiReport(
val id: String,
val name: String,
val callsign: String,
@@ -40,10 +35,8 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
override suspend fun fetchStatus(): SatStatusPage? = withContext(Dispatchers.IO) {
val nowSec = System.currentTimeMillis() / 1000
val catalogJson = remoteSource.getAmSatCatalog() ?: return@withContext null
// 72h = 3 days; API hard cap is limit=500 regardless of what we send.
// 500 records across ~100 catalog satellites ≈ ~1-5 reports/satellite/day — enough for 3 days.
// Upgrade path: paginate or request AMSAT to raise the cap if catalog grows beyond ~200 sats.
val reportsJson = remoteSource.getAmSatReports(hours = 72, limit = 500) ?: return@withContext null
val reportsJson = remoteSource.getAmSatReports(hours = 168, limit = 500) ?: return@withContext null
val names = parseCatalog(catalogJson)
val reports = parseReports(reportsJson)
@@ -51,20 +44,7 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
val statuses = buildStatuses(names, reports, nowSec)
val reportMap = reports.associate { it.id to toSatReport(it) }
// The summary endpoint tells us how many reports each satellite actually has,
// independent of the 500-record cap. Mark any satellite whose global pull is
// incomplete so the UI can show a data-coverage note.
val summaryJson = remoteSource.getAmSatSummary(hours = 72)
val expectedCounts = parseSummary(summaryJson)
val marked = statuses.map { status ->
val expected = expectedCounts[status.name]
val actual = status.days.sumOf { day -> day.slots.sumOf { it.count } }
if (expected != null && expected > actual) status.copy(summaryCount = expected)
else status
}
SatStatusPage(System.currentTimeMillis(), marked, reportMap)
SatStatusPage(System.currentTimeMillis(), statuses, reportMap)
}
/** Parse catalog JSON to list of satellite names */
@@ -72,7 +52,7 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).map { arr.getJSONObject(it).getString("name") }
} catch (_: Exception) {
} catch (e: Exception) {
emptyList()
}
}
@@ -93,104 +73,36 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
reportedTimeUtcSec = parseIsoUtcSec(iso)
)
}
} catch (_: Exception) {
} catch (e: Exception) {
emptyList()
}
}
/**
* Parse summary JSON to per-satellite report counts.
*
* The summary aggregates across all statuses, so a satellite with both "heard" and
* "not heard" entries appears once; we sum its report_count across all its rows.
* Returns an empty map (not null) on failure so the caller can just check for
* missing keys — a failed summary call degrades gracefully to "no coverage marker".
*/
private fun parseSummary(json: String?): Map<String, Int> {
if (json == null) return emptyMap()
return try {
val arr = JSONObject(json).getJSONArray("data")
val out = mutableMapOf<String, Int>()
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i)
val name = o.optString("name", "")
val count = o.optInt("report_count", 0)
if (name.isNotEmpty() && count > 0) {
out[name] = (out[name] ?: 0) + count
}
}
out
} catch (_: Exception) {
emptyMap()
}
}
/** Parse ISO 8601 UTC timestamp to epoch seconds (e.g., "2026-08-05T07:30:00Z") */
private fun parseIsoUtcSec(iso: String): Long {
return try {
(isoUtcFormat.parse(iso)?.time ?: 0L) / 1000
} catch (_: Exception) {
} catch (e: Exception) {
0L
}
}
/**
* Build one SatStatus (3 days x 12 two-hour slots) per catalog satellite.
*
* Days are UTC calendar days and slots are fixed UTC bands, matching amsat.org: day 0
* is today, its slot 0 covers 22:00-24:00 UTC and slot 11 covers 00:00-02:00, so both
* the day list and the slots inside it read newest-first.
*
* A rolling window anchored on "now" was wrong: fetching at 06:07 UTC put 17.9 hours
* of yesterday into the cell labelled today. Checked against a live amsat.org page of
* 1021 reports, 73% landed in the wrong day column.
*/
internal fun buildStatuses(names: List<String>, reports: List<ApiReport>, nowSec: Long): List<SatStatus> {
/** Build one SatStatus (6 days x 12 slots) per catalog satellite, slotting reports by age. */
private fun buildStatuses(names: List<String>, reports: List<ApiReport>, nowSec: Long): List<SatStatus> {
val byName = reports.groupBy { it.name }
val monthAbbr = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
// Midnight UTC today, the anchor every slot boundary is derived from.
utc.timeInMillis = nowSec * 1000
utc.set(Calendar.HOUR_OF_DAY, 0)
utc.set(Calendar.MINUTE, 0)
utc.set(Calendar.SECOND, 0)
utc.set(Calendar.MILLISECOND, 0)
val todayMidnightSec = utc.timeInMillis / 1000
// Reuses the same Calendar, which is safe only because each pass assigns
// timeInMillis outright rather than adjusting fields. After this loop it points at
// the oldest day, so anything added below must set the time again before reading.
val labels = (0 until 3).map { d ->
utc.timeInMillis = (todayMidnightSec - d * 86400L) * 1000
val labels = (0 until 6).map { d ->
utc.timeInMillis = (nowSec - d * 86400L) * 1000
"${monthAbbr[utc.get(Calendar.MONTH)]} ${utc.get(Calendar.DAY_OF_MONTH)}"
}
// Oldest report across the whole response, marking how far back the data reaches.
// Taken globally rather than per satellite: a quiet satellite has no reports of its
// own, but the slots it shares with the rest of the response were still covered.
//
// Timestamps of zero are excluded: parseIsoUtcSec returns 0 when a reported_time
// fails to parse, and a single such record would drag this back to 1970 and mark
// nothing as uncovered, silently reverting the distinction.
val dataFromSec = reports.asSequence()
.map { it.reportedTimeUtcSec }
.filter { it > 0L }
.minOrNull()
?: todayMidnightSec
return names.map { name ->
val satReports = byName[name].orEmpty()
val days = (0 until 3).map { dayIdx ->
val dayStart = todayMidnightSec - dayIdx * 86400L
val slots = (0 until 12).map { slotIdx ->
// Slot 0 is the last band of the day, so the day reads newest-first.
val slotStart = dayStart + (11 - slotIdx) * 7200L
val slotEnd = slotStart + 7200L
val inSlot = satReports.filter { it.reportedTimeUtcSec in slotStart until slotEnd }
val slots = (0 until 72).map { slotIdx ->
val slotStart = nowSec - (slotIdx + 1) * 7200L
val slotEnd = nowSec - slotIdx * 7200L
val inSlot = byName[name].orEmpty().filter { it.reportedTimeUtcSec in slotStart until slotEnd }
if (inSlot.isEmpty()) {
// A slot entirely before the data starts is unknown, not silent.
val colour = if (slotEnd <= dataFromSec) NO_DATA_GRAY else NO_REPORT_GRAY
SatSlot(statusColor = colour, count = 0)
SatSlot(statusColor = NO_REPORT_GRAY, count = 0)
} else {
val newest = inSlot.maxByOrNull { it.reportedTimeUtcSec }!!
SatSlot(
@@ -200,7 +112,8 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
)
}
}
SatDay(dateLabel = labels[dayIdx], slots = slots)
val days = (0 until 6).map { d ->
SatDay(dateLabel = labels[d], slots = slots.subList(d * 12, (d + 1) * 12))
}
SatStatus(name = name, days = days)
}
@@ -239,15 +152,5 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
private const val NOT_HEARD_PINK = 0xFFDC267F
private const val CONFLICT_DEEP_ORANGE = 0xFFFE6100
private const val NO_REPORT_GRAY = 0xFFC0C0C0
/**
* Slots older than the data we actually received.
*
* The API caps at 500 records however many hours are requested. Measured live: a
* 72-hour request returned 500 reports spanning only 49 hours, leaving the oldest
* 9.5 hours of the third day with no data at all. Painting those the same grey as
* "nobody reported" claimed knowledge we do not have, so they get a lighter shade.
*/
private const val NO_DATA_GRAY = 0xFFE8E8E8
}
}
@@ -29,7 +29,7 @@ import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.util.zip.ZipInputStream
class DatabaseRepo(
@@ -42,23 +42,11 @@ class DatabaseRepo(
private val customSourceType = "Other"
/**
* Type key for satellites fetched from a custom URL.
*
* Separate from customSourceType because setSatelliteTypeIds overwrites rather than merges, so
* sharing "Other" with manual file import meant each wiped the other's type index. The
* satellites stayed in the database and stayed selectable either way - only their grouping in
* the type filter was lost - but the two sources are different things and deserve different
* keys.
*/
private val customUrlType = "Custom"
override suspend fun updateTLEFromFile(uri: String): Int = withContext(dispatcher) {
var importedCount = 0
remoteSource.getFileBytes(uri)?.let { data ->
val entries = parseSatelliteData(uri, unwrapIfZipped(uri, data))
remoteSource.getFileStream(uri)?.let { stream ->
val entries = parseSatelliteStream(uri, unwrapIfZipped(uri, stream))
localSource.insertEntries(entries)
settingsRepo.setSatelliteTypeIds(customSourceType, entries.map { it.catnum })
importedCount = entries.size
}
setUpdateSuccessful(System.currentTimeMillis())
@@ -67,8 +55,8 @@ class DatabaseRepo(
override suspend fun updateTransceiversFromFile(uri: String): Int = withContext(dispatcher) {
var importedCount = 0
remoteSource.getFileBytes(uri)?.let { data ->
val transceivers = dataParser.parseJSON(unwrapIfZipped(uri, data).decodeToString())
remoteSource.getFileStream(uri)?.let { stream ->
val transceivers = dataParser.parseJSONStream(unwrapIfZipped(uri, stream))
localSource.insertRadios(transceivers)
importedCount = transceivers.size
}
@@ -78,56 +66,23 @@ class DatabaseRepo(
override suspend fun updateFromRemote() = withContext(dispatcher) {
val dataSourcesSettings = settingsRepo.dataSourcesSettings.value
// A custom URL REPLACES the built-in sources rather than joining them. The previous map
// overwrote only the "All" value and still fetched the other 26, so switching this on meant
// "my source AND yours" - which defeats the reasons for setting one: a mirror, a filtered
// subset, an offline server, or a network where Celestrak is unreachable. On a blocked link
// the real behaviour was 26 failing requests.
//
// Satellites already stored do not disappear: insertEntries is OnConflictStrategy.REPLACE
// and nothing is deleted before the insert, so rows the new source does not mention survive.
// The type index for the skipped keys goes stale rather than empty, which is the honest
// outcome - it is the last known membership, not a claim about this fetch.
//
// The key is customUrlType, not "All": setSatelliteTypeIds early-returns on "All", so
// indexing under it was always a no-op and satellites from a custom URL were never
// reachable by the type filter at all. They now are.
val tleUrls = if (dataSourcesSettings.useCustomTLE && dataSourcesSettings.tleUrl.isNotBlank()) {
mapOf(customUrlType to dataSourcesSettings.tleUrl)
} else {
Sources.satelliteDataUrls.filterValues { it.isNotBlank() }
}
val radioUrls = if (dataSourcesSettings.useCustomTransceivers &&
dataSourcesSettings.transceiversUrl.isNotBlank()
) {
mapOf("SatNOGS" to dataSourcesSettings.transceiversUrl)
} else {
Sources.transceiversDataUrls.filterValues { it.isNotBlank() }
}
val tleUrls = buildMap {
putAll(Sources.satelliteDataUrls)
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.values.map { url -> async { url to remoteSource.getNetworkBytes(url) } }
val radioJobs = radioUrls.values.map { url -> async { url to remoteSource.getNetworkBytes(url) } }
val tleResults = tleJobs.awaitAll()
val radioResults = radioJobs.awaitAll()
// Orbital elements are counted on their own. A combined count let a successful transceivers
// fetch stand in for a failed orbital one: with a custom TLE URL there are two requests
// rather than 28, so if that URL was down and SatNOGS answered, the total was 1, no
// exception was raised, and setUpdateSuccessful stamped a fresh timestamp for an update
// that refreshed no orbital data at all - which also suppressed the 48-hour auto-update
// retry that keys off that timestamp. The failure existed before but 26 other sources hid
// it; replacing them made it easy to hit.
if (tleResults.none { it.second != null }) {
throw java.io.IOException("No orbital data source could be downloaded")
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
val importedEntries = tleJobs.awaitAll().flatMap { (url, stream) ->
stream?.let { parseSatelliteStream(url, unwrapIfZipped(url, it)) }.orEmpty()
}
// parse fetched data concurrently and associate with types
val importedEntries = tleResults.flatMap { (url, data) ->
val type = tleUrls.entries.find { it.value == url }?.key ?: customSourceType
data?.let { parseSatelliteData(url, unwrapIfZipped(url, it)) }.orEmpty().also { entries ->
settingsRepo.setSatelliteTypeIds(type, entries.map { it.catnum })
}
}
val importedRadios = radioResults.flatMap { (url, data) ->
data?.let { dataParser.parseJSON(unwrapIfZipped(url, it).decodeToString()) }.orEmpty()
val importedRadios = radioJobs.awaitAll().flatMap { (url, stream) ->
stream?.let { dataParser.parseJSONStream(unwrapIfZipped(url, it)) }.orEmpty()
}
// insert parsed data into the database
localSource.insertEntries(importedEntries)
@@ -141,11 +96,11 @@ class DatabaseRepo(
setUpdateSuccessful(0L)
}
private suspend fun parseSatelliteData(url: String, data: ByteArray): List<OrbitalData> {
val text = data.decodeToString()
private suspend fun parseSatelliteStream(url: String, stream: InputStream): List<OrbitalData> {
val bufferedStream = stream.buffered()
return when {
hasCsvHint(url) || looksLikeCsv(text) -> dataParser.parseCSV(text)
else -> dataParser.parseTLE(text)
hasCsvHint(url) || looksLikeCsv(bufferedStream) -> dataParser.parseCSVStream(bufferedStream)
else -> dataParser.parseTLEStream(bufferedStream)
}
}
@@ -155,9 +110,14 @@ class DatabaseRepo(
url.endsWith(".csv.zip", ignoreCase = true)
}
private fun looksLikeCsv(text: String): Boolean {
val line = text.lineSequence().firstOrNull()?.trim().orEmpty()
if (line.isEmpty()) return false
private fun looksLikeCsv(stream: InputStream): Boolean {
if (!stream.markSupported()) return false
stream.mark(4096)
val preview = ByteArray(4096)
val length = stream.read(preview)
stream.reset()
if (length <= 0) return false
val line = preview.decodeToString(0, length).lineSequence().firstOrNull()?.trim().orEmpty()
return line.contains("OBJECT_NAME", ignoreCase = true) ||
line.contains("NORAD_CAT_ID", ignoreCase = true) ||
line.count { it == ',' } >= 4
@@ -169,10 +129,6 @@ class DatabaseRepo(
)
}
private fun unwrapIfZipped(url: String, data: ByteArray): ByteArray =
if (url.endsWith(".zip", ignoreCase = true)) {
ZipInputStream(ByteArrayInputStream(data)).apply { nextEntry }.readBytes()
} else {
data
}
private fun unwrapIfZipped(url: String, stream: InputStream): InputStream =
if (url.endsWith(".zip", ignoreCase = true)) ZipInputStream(stream).apply { nextEntry } else stream
}
@@ -34,10 +34,7 @@ import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.util.TimeZone
import kotlin.time.Duration.Companion.milliseconds
@@ -54,10 +51,6 @@ class SatelliteRepo(
private val _isCalculating = MutableStateFlow(false)
override val isCalculating: StateFlow<Boolean> = _isCalculating
// Serializes pass calculation. Callers queue instead of being dropped: a
// dropped call would silently discard the filter the user just applied.
private val calculationMutex = Mutex()
private val _satellites = MutableStateFlow<List<OrbitalObject>>(emptyList())
override val satellites: StateFlow<List<OrbitalObject>> = _satellites
@@ -71,11 +64,7 @@ class SatelliteRepo(
override suspend fun getRadiosWithId(id: Int) = localStorage.getRadiosWithId(id)
override suspend fun initRepository() = withContext(dispatcher) {
combine(
settingsRepo.selectedIds,
settingsRepo.stationPosition
) { selectedIds, _ -> selectedIds }
.collect { selectedIds ->
settingsRepo.selectedIds.collect { selectedIds ->
_satellites.update { localStorage.getEntriesWithIds(selectedIds) }
val settings = settingsRepo.passesSettings.value
calculatePasses(
@@ -107,8 +96,14 @@ class SatelliteRepo(
}
}
override suspend fun getRadios(satPos: OrbitalPos, radios: List<SatRadio>): List<SatRadio> {
override suspend fun getRadios(
sat: OrbitalObject,
pos: GeoPos,
radios: List<SatRadio>,
time: Long
): List<SatRadio> {
return withContext(dispatcher) {
val satPos = sat.getPosition(pos, time)
radios.map { transmitter ->
transmitter.copy(
downlinkLow = transmitter.downlinkLow?.let { satPos.getDownlinkFreq(it) },
@@ -129,12 +124,7 @@ class SatelliteRepo(
invertAosTimeWindow: Boolean,
modes: List<String>
) {
// Queue behind any in-flight calculation rather than dropping this call:
// every invocation carries filter settings the user just chose, so a
// dropped one leaves the list showing results for the previous filter.
calculationMutex.withLock {
_isCalculating.value = true
try {
// Normalize to the start of the current minute so that coarse 60-second stepping
// in getLeoPass always begins from the same phase, producing stable AOS/LOS times
val normalizedTime = time / 60_000L * 60_000L
@@ -169,16 +159,11 @@ class SatelliteRepo(
}
}
newPasses.sortBy { it.aosTime }
delay(1000) // Simulate loading time for better UX
delay(1000.milliseconds) // Simulate loading time for better UX
_passes.update { newPasses }
}
} finally {
// finally: a thrown/cancelled calculation must not leave the
// progress indicator spinning forever.
_isCalculating.value = false
}
}
}
private fun isAosInRange(
aosTime: Long,
@@ -258,16 +243,13 @@ class SatelliteRepo(
if (elevation > maxElevation) maxElevation = elevation
} while (elevation < 0.0)
// refine AOS to ~500ms precision via binary search.
// Elevation is monotonic across the horizon crossing, so binary search
// finds the crossing in ~8 SGP4 calls instead of up to 120 linear steps.
var aosLo = calendarTimeMillis - 60L * 1000L // elevation < 0 (below horizon)
var aosHi = calendarTimeMillis // elevation >= 0 (above horizon)
while (aosHi - aosLo > 500L) {
val mid = (aosLo + aosHi) / 2
if (sat.getElevation(pos, mid) < 0.0) aosLo = mid else aosHi = mid
}
calendarTimeMillis = aosHi
// refine AOS to ~500ms precision
calendarTimeMillis -= 60L * 1000L
do {
calendarTimeMillis += 500L
elevation = sat.getElevation(pos, calendarTimeMillis)
if (elevation > maxElevation) maxElevation = elevation
} while (elevation < 0.0)
// Get full position for AOS data (azimuth, altitude)
val aosPos = sat.getFullPosition(pos, calendarTimeMillis)
@@ -281,14 +263,13 @@ class SatelliteRepo(
if (elevation > maxElevation) maxElevation = elevation
} while (elevation > 0.0)
// refine LOS to ~500ms precision via binary search (same monotonic argument)
var losLo = calendarTimeMillis - 30L * 1000L // elevation > 0 (above horizon)
var losHi = calendarTimeMillis // elevation <= 0 (below horizon)
while (losHi - losLo > 500L) {
val mid = (losLo + losHi) / 2
if (sat.getElevation(pos, mid) > 0.0) losLo = mid else losHi = mid
}
calendarTimeMillis = losHi
// refine LOS to ~500ms precision
calendarTimeMillis -= 30L * 1000L
do {
calendarTimeMillis += 500L
elevation = sat.getElevation(pos, calendarTimeMillis)
if (elevation > maxElevation) maxElevation = elevation
} while (elevation > 0.0)
// Get full position for LOS data (azimuth, altitude)
val losPos = sat.getFullPosition(pos, calendarTimeMillis)
@@ -29,21 +29,16 @@ import com.rtbishop.look4sat.core.domain.model.OtherSettings
import com.rtbishop.look4sat.core.domain.model.PassesSettings
import com.rtbishop.look4sat.core.domain.model.RCSettings
import com.rtbishop.look4sat.core.domain.model.RadioControlSettings
import com.rtbishop.look4sat.core.domain.model.Constants
import com.rtbishop.look4sat.core.domain.predict.GeoPos
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import com.rtbishop.look4sat.core.domain.source.Sources
import com.rtbishop.look4sat.core.domain.utility.positionToQth
import com.rtbishop.look4sat.core.domain.utility.qthToPosition
import com.rtbishop.look4sat.core.domain.utility.round
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import org.json.JSONObject
class SettingsRepo(
private val context: android.content.Context,
private val locationManager: LocationManager,
private val preferences: SharedPreferences,
override val appVersionName: String
@@ -72,7 +67,6 @@ class SettingsRepo(
private val keyFrequencyAddress = "frequencyAddress"
private val keyFrequencyPort = "frequencyPort"
private val keyFrequencyFormat = "frequencyFormat"
private val keyFrequencyOffsetHz = "frequencyOffsetHz"
private val keySelectedIds = "selectedIds"
private val keySelectedSatModes = "selectedSatModes"
private val keyStateOfAutoUpdate = "stateOfAutoUpdate"
@@ -81,8 +75,6 @@ class SettingsRepo(
private val keyStateOfUtc = "stateOfUtc"
private val keyStateOfLightTheme = "stateOfLightTheme"
private val keyStateOfNightMode = "stateOfNightMode"
private val keyHiddenScreens = "hiddenScreens"
private val keyScreenOrder = "screenOrder"
private val keyStationAltitude = "stationAltitude"
private val keyStationLatitude = "stationLatitude"
private val keyStationLongitude = "stationLongitude"
@@ -94,20 +86,12 @@ class SettingsRepo(
private val keySstvMode = "sstvMode"
private val keyLowElevation = "lowElevation"
private val keyHighElevation = "highElevation"
private val keyRadarCompassOffset = "radarCompassOffset"
private val keyRadarCompassOffsetElev = "radarCompassOffsetElev"
private val keyUseCustomTle = "useCustomTle"
private val keyUseCustomTransceivers = "useCustomTransceivers"
private val keyTleUrl = "tleUrl"
private val keyTransceiversUrl = "transceiversUrl"
private val keySubMenuOrder = "subMenuOrder"
private val keyWavelogUrl = "wavelogUrl"
private val keyWavelogApiKey = "wavelogApiKey"
private val keyWavelogStationId = "wavelogStationId"
private val keyWavelogAutoUpload = "wavelogAutoUpload"
private val keyRadarCompassOffset = "radarCompassOffset"
private val keyRadarCompassOffsetElev = "radarCompassOffsetElev"
private val keyCwToneShiftEnabled = "cwToneShiftEnabled"
private val keyAmsatDayStripes = "amsatDayStripes"
private val separatorComma = ","
//region # Satellites selection settings
@@ -185,50 +169,29 @@ class SettingsRepo(
}
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean {
// Wrap an out-of-range longitude into -180..180. Subtracting 180 (the
// previous behaviour) mapped 270 to +90 instead of -90, i.e. the wrong
// hemisphere, and 360 to +180 instead of 0.
val newLongitude = ((longitude + 180.0).mod(360.0)) - 180.0
val newLongitude = if (longitude > 180.0) longitude - 180 else longitude
val locator = positionToQth(latitude, newLongitude) ?: return false
setStationPosition(latitude, newLongitude, altitude, locator)
return true
}
/** GPS fix: one-shot getCurrentLocation (GPS first, 15 s timeout); returns true only with a fix */
override suspend fun setStationPosition(): Boolean {
// Permission gate: fail fast without location permission (no swallowed exceptions)
if (androidx.core.content.ContextCompat.checkSelfPermission(
context, android.Manifest.permission.ACCESS_FINE_LOCATION
) != android.content.pm.PackageManager.PERMISSION_GRANTED
) {
println("GPS: no fine location permission")
return false
}
override fun setStationPosition(): Boolean {
if (!LocationManagerCompat.isLocationEnabled(locationManager)) return false
return kotlinx.coroutines.suspendCancellableCoroutine { cont ->
val signal = android.os.CancellationSignal()
val handler = android.os.Handler(android.os.Looper.getMainLooper())
val executor = java.util.concurrent.Executor { handler.post(it) }
// 15 s timeout
val timeout = handler.postDelayed({
signal.cancel()
if (cont.isActive) cont.resume(false) { }
}, 15_000L)
val listener = androidx.core.util.Consumer<Location> { location ->
handler.removeCallbacksAndMessages(null)
setStationPosition(location.latitude, location.longitude, location.altitude)
if (cont.isActive) cont.resume(true) { }
}
val hasGps = LocationManagerCompat.hasProvider(locationManager, providerGps)
val provider = if (hasGps) providerGps else providerNet
try {
LocationManagerCompat.getCurrentLocation(locationManager, provider, signal, executor, listener)
val hasGps = LocationManagerCompat.hasProvider(locationManager, providerGps)
val hasNet = LocationManagerCompat.hasProvider(locationManager, providerNet)
val provider = if (hasGps) providerGps else if (hasNet) providerNet else providerDef
val location = locationManager.getLastKnownLocation(providerDef)
if (location == null || System.currentTimeMillis() - location.time > 600_000L) {
println("Requesting location for $provider provider")
locationManager.requestLocationUpdates(provider, 0L, 0f, this)
} else {
setStationPosition(location.latitude, location.longitude, location.altitude)
}
} catch (exception: SecurityException) {
handler.removeCallbacksAndMessages(null)
if (cont.isActive) cont.resume(false) { }
}
cont.invokeOnCancellation { signal.cancel(); handler.removeCallbacksAndMessages(null) }
println("No permissions were given - $exception")
}
return true
}
override fun setStationPosition(locator: String): Boolean {
@@ -247,8 +210,8 @@ class SettingsRepo(
}
private fun setStationPosition(latitude: Double, longitude: Double, altitude: Double, locator: String) {
val newLat = latitude.round(5)
val newLon = longitude.round(5)
val newLat = latitude.round(4)
val newLon = longitude.round(4)
val newAlt = altitude.round(1)
val timestamp = System.currentTimeMillis()
println("Received new Position($newLat, $newLon, $newAlt) & Locator $locator")
@@ -270,26 +233,6 @@ class SettingsRepo(
override val databaseState: StateFlow<DatabaseState> = _databaseState
override fun getSatelliteTypesIds(types: List<String>): List<Int> {
val idsSet = mutableSetOf<Int>()
types.forEach { type ->
val typeString = preferences.getString("type$type", null)
val typeIds = if (typeString.isNullOrBlank()) {
emptyList()
} else {
typeString.split(separatorComma).map { it.toInt() }
}
idsSet.addAll(typeIds)
}
return idsSet.toList()
}
override fun setSatelliteTypeIds(type: String, ids: List<Int>) {
if (type == "All") return
val typesString = ids.joinToString(separatorComma)
preferences.edit { putString("type$type", typesString) }
}
override fun updateDatabaseState(state: DatabaseState) = preferences.edit {
putInt(keyNumberOfSatellites, state.numberOfSatellites)
putInt(keyNumberOfRadios, state.numberOfRadios)
@@ -333,10 +276,6 @@ class SettingsRepo(
override val rcSettings: StateFlow<RCSettings> = _rcSettings
override fun updateRCSettings(settings: RCSettings) {
val clampedFreqOffsetHz = settings.frequencyOffsetHz.coerceIn(
Constants.FREQ_OFFSET_MIN_HZ,
Constants.FREQ_OFFSET_MAX_HZ
)
preferences.edit {
putBoolean(keyRotatorState, settings.rotatorState)
putString(keyRotatorAddress, settings.rotatorAddress)
@@ -346,7 +285,6 @@ class SettingsRepo(
putString(keyFrequencyAddress, settings.frequencyAddress)
putString(keyFrequencyPort, settings.frequencyPort)
putString(keyFrequencyFormat, settings.frequencyFormat)
putLong(keyFrequencyOffsetHz, clampedFreqOffsetHz)
putBoolean(keyBluetoothRotatorState, settings.bluetoothRotatorState)
putString(keyBluetoothRotatorFormat, settings.bluetoothRotatorFormat)
putString(keyBluetoothRotatorName, settings.bluetoothRotatorName)
@@ -355,7 +293,7 @@ class SettingsRepo(
putString(keyBluetoothFrequencyFormat, settings.bluetoothFrequencyFormat)
putString(keyBluetoothFrequencyAddress, settings.bluetoothFrequencyAddress)
}
_rcSettings.value = settings.copy(frequencyOffsetHz = clampedFreqOffsetHz)
_rcSettings.value = settings
}
private fun getRCSettings(): RCSettings = RCSettings(
@@ -367,8 +305,6 @@ class SettingsRepo(
frequencyAddress = preferences.getString(keyFrequencyAddress, null) ?: "127.0.0.1",
frequencyPort = preferences.getString(keyFrequencyPort, null) ?: "4532",
frequencyFormat = preferences.getString(keyFrequencyFormat, null) ?: $$"F $FREQ",
frequencyOffsetHz = preferences.getLong(keyFrequencyOffsetHz, 0L)
.coerceIn(Constants.FREQ_OFFSET_MIN_HZ, Constants.FREQ_OFFSET_MAX_HZ),
bluetoothRotatorState = preferences.getBoolean(keyBluetoothRotatorState, false),
bluetoothRotatorFormat = preferences.getString(keyBluetoothRotatorFormat, null) ?: $$"P $AZ $EL",
bluetoothRotatorName = preferences.getString(keyBluetoothRotatorName, null) ?: "Default",
@@ -398,18 +334,8 @@ class SettingsRepo(
putString(keySstvMode, new.sstvMode)
putLong(keyLowElevation, new.lowElevation.toRawBits())
putLong(keyHighElevation, new.highElevation.toRawBits())
putStringSet(keyHiddenScreens, new.hiddenScreens.toSet())
putString(keyScreenOrder, new.screenOrder.joinToString(","))
putString(keySubMenuOrder, new.subMenuOrder.joinToString(","))
putString(keyWavelogUrl, new.wavelogUrl)
putString(keyWavelogApiKey, new.wavelogApiKey)
putString(keyWavelogStationId, new.wavelogStationId)
putBoolean(keyWavelogAutoUpload, new.wavelogAutoUpload)
putFloat(keyRadarCompassOffset, new.radarCompassOffset)
putFloat(keyRadarCompassOffsetElev, new.radarCompassOffsetElev)
putBoolean(keyCwToneShiftEnabled, new.cwToneShiftEnabled)
putBoolean(keyAmsatDayStripes, new.amsatDayStripes)
}
new
}
@@ -425,19 +351,10 @@ class SettingsRepo(
shouldSeeWarning = preferences.getBoolean(keyShouldSeeWarning, true),
shouldSeeWhatsNew = preferences.getBoolean(keyShouldSeeWhatsNew, true),
sstvMode = preferences.getString(keySstvMode, null) ?: "Auto",
hiddenScreens = preferences.getStringSet(keyHiddenScreens, emptySet())?.toList() ?: emptyList(),
screenOrder = preferences.getString(keyScreenOrder, null)?.split(",")?.filter { it.isNotBlank() } ?: emptyList(),
subMenuOrder = preferences.getString(keySubMenuOrder, null)?.split(",")?.filter { it.isNotBlank() } ?: emptyList(),
lowElevation = Double.fromBits(preferences.getLong(keyLowElevation, 15.0.toRawBits())),
highElevation = Double.fromBits(preferences.getLong(keyHighElevation, 45.0.toRawBits())),
wavelogUrl = preferences.getString(keyWavelogUrl, null) ?: "",
wavelogApiKey = preferences.getString(keyWavelogApiKey, null) ?: "",
wavelogStationId = preferences.getString(keyWavelogStationId, null) ?: "",
wavelogAutoUpload = preferences.getBoolean(keyWavelogAutoUpload, false),
radarCompassOffset = preferences.getFloat(keyRadarCompassOffset, 0f),
radarCompassOffsetElev = preferences.getFloat(keyRadarCompassOffsetElev, 0f),
cwToneShiftEnabled = preferences.getBoolean(keyCwToneShiftEnabled, false),
amsatDayStripes = preferences.getBoolean(keyAmsatDayStripes, true)
radarCompassOffsetElev = preferences.getFloat(keyRadarCompassOffsetElev, 0f)
)
//endregion
@@ -455,47 +372,12 @@ class SettingsRepo(
_dataSourcesSettings.value = settings
}
/** Placeholders a 4.4.7-era build could persist. Neither is a reachable address. */
private val placeholderTleUrl = "https://example.com/tle.txt"
private val placeholderRadioUrl = "https://example.com/radio.json"
private val keyPlaceholderUrlsMigrated = "placeholderUrlsMigrated"
/**
* Replace the example.com placeholders an old build could store.
*
* Runs once, following the pattern of migrateRCFormats. This used to be a rewrite applied on
* every read, so the stored value and the returned value disagreed indefinitely and nothing
* ever settled the difference.
*/
private fun migratePlaceholderUrls() {
if (preferences.getBoolean(keyPlaceholderUrlsMigrated, false)) return
preferences.edit {
if (preferences.getString(keyTleUrl, null) == placeholderTleUrl) {
putString(keyTleUrl, Sources.defaultTleUrl)
putBoolean(keyUseCustomTle, false)
}
if (preferences.getString(keyTransceiversUrl, null) == placeholderRadioUrl) {
putString(keyTransceiversUrl, Sources.defaultTransceiversUrl)
putBoolean(keyUseCustomTransceivers, false)
}
putBoolean(keyPlaceholderUrlsMigrated, true)
}
}
private fun getDataSourcesSettings(): DataSourcesSettings {
migratePlaceholderUrls()
// The switch is reported as the operator set it. It used to be ANDed with
// `url != default`, so typing the default URL by hand switched custom sources off by
// itself and the settings screen showed a state nobody had chosen.
return DataSourcesSettings(
private fun getDataSourcesSettings(): DataSourcesSettings = DataSourcesSettings(
useCustomTLE = preferences.getBoolean(keyUseCustomTle, false),
useCustomTransceivers = preferences.getBoolean(keyUseCustomTransceivers, false),
tleUrl = preferences.getString(keyTleUrl, Sources.defaultTleUrl) ?: Sources.defaultTleUrl,
transceiversUrl = preferences.getString(keyTransceiversUrl, Sources.defaultTransceiversUrl)
?: Sources.defaultTransceiversUrl
tleUrl = preferences.getString(keyTleUrl, "https://example.com/tle.txt") ?: "",
transceiversUrl = preferences.getString(keyTransceiversUrl, "https://example.com/radio.json") ?: ""
)
}
//endregion
//region # Radio control settings
@@ -535,27 +417,5 @@ class SettingsRepo(
baudRate = preferences.getInt(keyRadioBaudRate, 4800),
splitMode = preferences.getBoolean(keyRadioSplitMode, false)
)
private val keySatelliteOffsets = "satelliteOffsets"
override fun getSatelliteOffset(catnum: Int): String {
val json = preferences.getString(keySatelliteOffsets, "{}") ?: "{}"
return try {
JSONObject(json).optString(catnum.toString(), "")
} catch (_: Exception) {
""
}
}
override fun setSatelliteOffset(catnum: Int, offset: String) {
val json = preferences.getString(keySatelliteOffsets, "{}") ?: "{}"
val updated = try {
val obj = JSONObject(json)
if (offset.isEmpty()) obj.remove(catnum.toString()) else obj.put(catnum.toString(), offset)
obj.toString()
} catch (_: Exception) {
"""{"$catnum": "$offset"}"""
}
preferences.edit { putString(keySatelliteOffsets, updated) }
}
//endregion
}
@@ -1,89 +0,0 @@
/*
* 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.data.source
import com.rtbishop.look4sat.core.domain.source.HttpResult
import com.rtbishop.look4sat.core.domain.source.IHttpClient
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit
/**
* Android [IHttpClient] for the shared Wavelog/QRZ code, which cannot reach java.net on iOS.
*
* Connect and read timeouts are the 15 s the previous HttpURLConnection client used, applied to
* the passed client so the caller keeps one connection pool. The response body is returned for
* error codes as well, which is what reading errorStream did.
*/
class OkHttpHttpClient(
baseClient: OkHttpClient,
dispatcher: CoroutineDispatcher = Dispatchers.IO
) : IHttpClient {
private val dispatcher = dispatcher
private val client = baseClient.newBuilder()
.connectTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS)
.readTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS)
.build()
override suspend fun post(url: String, headers: Map<String, String>, body: String): HttpResult =
execute {
Request.Builder().url(url).post(body.toRequestBody(JSON_MEDIA_TYPE)).withHeaders(headers).build()
}
override suspend fun get(url: String, headers: Map<String, String>): HttpResult =
execute { Request.Builder().url(url).withHeaders(headers).build() }
private suspend fun execute(buildRequest: () -> Request): HttpResult = withContext(dispatcher) {
try {
// Built in here, not by the caller: a URL OkHttp refuses to parse has to come back as
// the HTTP -1 the old client reported, not as an exception thrown at the caller.
val request = buildRequest()
client.newCall(request).execute().use { response ->
HttpResult(response.code, response.body.string())
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
HttpResult(NO_RESPONSE, "", exception.message ?: exception.javaClass.simpleName)
}
}
private fun Request.Builder.withHeaders(headers: Map<String, String>): Request.Builder {
headers.forEach { (name, value) -> header(name, value) }
return this
}
private companion object {
/** Matches HttpURLConnection's connect/read timeout in the original WaveLog client. */
const val TIMEOUT_MS = 15_000L
/** What HttpURLConnection's responseCode() reported when a request never got a response. */
const val NO_RESPONSE = -1
/** WaveLog's v2 and v1 endpoints take application/json in both directions. */
val JSON_MEDIA_TYPE = "application/json".toMediaType()
}
}
@@ -20,11 +20,11 @@ package com.rtbishop.look4sat.core.data.source
import android.content.ContentResolver
import androidx.core.net.toUri
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.InputStream
class RemoteSource(
private val dispatcher: CoroutineDispatcher,
@@ -32,28 +32,27 @@ class RemoteSource(
private val httpClient: OkHttpClient
) : IRemoteSource {
override suspend fun getFileBytes(uri: String): ByteArray? = withContext(dispatcher) {
override suspend fun getFileStream(uri: String): InputStream? = withContext(dispatcher) {
try {
val fileUri = uri.toUri()
contentResolver.openInputStream(fileUri)?.use { it.readBytes() }
} catch (exception: CancellationException) {
throw exception
contentResolver.openInputStream(fileUri)?.buffered()
} catch (exception: Exception) {
println("RemoteSource file stream exception: $exception")
null
}
}
override suspend fun getNetworkBytes(url: String): ByteArray? = withContext(dispatcher) {
override suspend fun getNetworkStream(url: String): InputStream? = withContext(dispatcher) {
try {
val networkRequest = Request.Builder().url(url).build()
// The whole body is read here, which also returns the connection to OkHttp's pool
httpClient.newCall(networkRequest).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body.bytes()
val response = httpClient.newCall(networkRequest).execute()
if (!response.isSuccessful) {
response.close()
return@withContext null
}
} catch (exception: CancellationException) {
throw exception
// Return the body stream directly as the caller is responsible for closing it
// That returns the connection to OkHttp's pool
response.body.byteStream().buffered()
} catch (exception: Exception) {
println("RemoteSource network stream exception: $exception")
null
@@ -64,17 +63,14 @@ class RemoteSource(
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/catalog.php")
.header("User-Agent", "Look4Sat/4.5.7")
.header("User-Agent", "Look4Sat")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
response.body.string()
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("RemoteSource amsat catalog exception: $exception")
println("RemoteSource getAmSatCatalog exception: $exception")
null
}
}
@@ -83,35 +79,14 @@ class RemoteSource(
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/reports.php?hours=$hours&limit=$limit")
.header("User-Agent", "Look4Sat/4.5.7")
.header("User-Agent", "Look4Sat")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
response.body.string()
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("RemoteSource amsat reports exception: $exception")
null
}
}
override suspend fun getAmSatSummary(hours: Int): String? = withContext(dispatcher) {
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/summary.php?hours=$hours")
.header("User-Agent", "Look4Sat/4.5.7")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("RemoteSource amsat summary exception: $exception")
println("RemoteSource getAmSatReports exception: $exception")
null
}
}
@@ -56,14 +56,8 @@ class AudioCapture : IAudioCapture {
if (read > 0) emit(if (read == chunkSize) buffer.copyOf() else buffer.copyOfRange(0, read))
}
} finally {
// stop() on a recorder that never started throws
// IllegalStateException; wrapping each cleanup step separately
// keeps the original error (e.g. a permission denial during
// startRecording) intact and guarantees release() still runs.
// Without this, a start failure masked the real cause AND leaked
// the recorder because release() was skipped.
runCatching { recorder.stop() }
runCatching { recorder.release() }
recorder.stop()
recorder.release()
}
}.flowOn(Dispatchers.IO)
}
@@ -25,12 +25,4 @@ class ShowToast(private val context: Context) : IShowToast {
override fun invoke(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
override fun invoke(resId: Int) {
invoke(context.getString(resId))
}
override fun invoke(resId: Int, vararg formatArgs: Any) {
invoke(context.getString(resId, *formatArgs))
}
}
@@ -1,62 +0,0 @@
/* LotwSatellitesRepo.kt - runtime refresh of the LoTW satellite list (4.5.5).
* Downloads ARRL's official config.tq6 (gzip XML), parses <satellite name="...">,
* updates the LotwSatellites dynamic set + persists to SharedPreferences (survives restarts).
* Trigger: the "Update sats" button in the settings WaveLog section (user decided: manual).
*/
package com.rtbishop.look4sat.core.data.wavelog
import android.content.Context
import com.rtbishop.look4sat.core.domain.wavelog.ILotwSatellitesRepo
import com.rtbishop.look4sat.core.domain.wavelog.LotwSatellites
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
import java.util.zip.GZIPInputStream
import kotlin.random.Random
class LotwSatellitesRepo(private val context: Context) : ILotwSatellitesRepo {
private val prefs = context.getSharedPreferences("lotw_satellites", Context.MODE_PRIVATE)
/** Restore the last downloaded list from SharedPreferences (call at process start) */
override fun restore() {
val saved = prefs.getString(KEY_NAMES, null)
if (!saved.isNullOrBlank()) {
LotwSatellites.updateNames(saved.split(",").filter { it.isNotBlank() }.toSet())
}
}
/** Download config.tq6 -> parse -> update memory + persist. Result is surfaced in the UI */
override suspend fun refresh(): ILotwSatellitesRepo.RefreshResult = withContext(Dispatchers.IO) {
try {
val url = URL("https://lotw.arrl.org/lotw/config.tq6")
val conn = url.openConnection()
conn.connectTimeout = 10_000
conn.readTimeout = 20_000
conn.setRequestProperty("User-Agent", "Look4Sat-Pro/4.5.5")
val raw = conn.getInputStream()
val reader = BufferedReader(InputStreamReader(GZIPInputStream(raw), Charsets.UTF_8))
val text = reader.use { it.readText() }
// Parse <satellite name="XXX" ...> - fixed format (official ARRL XML)
val names = Regex("""<satellite name="([^"]+)""").findAll(text)
.map { it.groupValues[1].uppercase() }
.toSet()
if (names.isEmpty()) return@withContext ILotwSatellitesRepo.RefreshResult.Error("列表为空(响应异常)")
LotwSatellites.updateNames(names)
prefs.edit()
.putString(KEY_NAMES, names.joinToString(","))
.putLong(KEY_UPDATED, System.currentTimeMillis())
.apply()
ILotwSatellitesRepo.RefreshResult.Ok(names.size)
} catch (e: Exception) {
ILotwSatellitesRepo.RefreshResult.Error(e.message ?: "未知错误")
}
}
companion object {
private const val KEY_NAMES = "names"
private const val KEY_UPDATED = "updated"
}
}
@@ -1,307 +0,0 @@
package com.rtbishop.look4sat.core.data.aprs
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Socket-level tests against a stand-in APRS-IS server.
*
* These exist because the pure-logic tests could not catch the failures that matter here. A draft
* of [AprsIsClient.sendPacket] once wrote the packet with no line terminator at all: every send
* reported success, the server received a single unterminated stream, and nothing anywhere went
* red. APRS-IS is a line protocol and does not acknowledge position reports, so silence is the
* normal case - which means only a test that reads the bytes off a real socket can tell a
* delivered packet from a lost one.
*/
class AprsIsClientSocketTest {
/**
* A minimal APRS-IS server. Greets, answers the login as instructed, then records whatever
* lines arrive without acknowledging them, which is what the real network does.
*/
private class FakeServer(
private val greeting: String? = "# aprsc 2.1.19-g730c5c0",
private val loginResponse: String? = "# logresp TEST verified, server FAKE",
private val chatter: List<String> = emptyList(),
/** Sent right after the first packet arrives, to exercise the ack read. */
private val afterPacket: String? = null
) : AutoCloseable {
private val server = ServerSocket(0)
private val ready = CountDownLatch(1)
/**
* The accepted connection. Held because closing the ServerSocket only stops it listening
* - an established connection survives, so a test that wants a dead peer has to close
* this one. Getting that wrong made a correct implementation look broken.
*/
@Volatile
private var peer: Socket? = null
val port: Int get() = server.localPort
/** Every complete line the client sent after logging in. */
val received = mutableListOf<String>()
/** Raw bytes of the client's traffic, so a missing terminator is visible. */
val rawAfterLogin = StringBuilder()
@Volatile
var loginLine: String? = null
fun start() {
thread(isDaemon = true) {
runCatching {
server.accept().use { client ->
peer = client
val out = PrintWriter(client.getOutputStream(), true)
val input = BufferedReader(InputStreamReader(client.getInputStream()))
greeting?.let { out.print(it + "\r\n"); out.flush() }
loginLine = input.readLine()
chatter.forEach { out.print(it + "\r\n"); out.flush() }
loginResponse?.let { out.print(it + "\r\n"); out.flush() }
ready.countDown()
// Read lines but never acknowledge, exactly as APRS-IS treats positions.
var firstPacket = true
while (true) {
val line = input.readLine() ?: break
synchronized(received) {
received += line
rawAfterLogin.append(line)
}
if (firstPacket) {
firstPacket = false
afterPacket?.let { out.print(it + "\r\n"); out.flush() }
}
}
}
}
ready.countDown()
}
}
fun awaitLogin(): Boolean = ready.await(5, TimeUnit.SECONDS)
fun lines(): List<String> = synchronized(received) { received.toList() }
/** Close the established connection, so the client is talking to a dead peer. */
fun dropClient() {
runCatching { peer?.close() }
}
override fun close() {
runCatching { server.close() }
}
}
private fun client(port: Int, passcode: Int = 12345) = AprsIsClient(
host = "127.0.0.1",
port = port,
callsign = "TEST",
ssid = "",
passcode = passcode,
softwareName = "Look4Sat",
version = "test"
)
/**
* The regression that motivated this file. Two packets must arrive as two lines; without a
* terminator they concatenate into one stream the server can never parse, while both sends
* report success.
*/
@Test
fun `each packet arrives as its own line`() {
FakeServer().use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
val first = c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>one")
val second = c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>two")
Thread.sleep(300)
c.disconnect()
assertEquals(true, first?.first)
assertEquals(true, second?.first)
val lines = server.lines()
assertEquals("both packets must reach the server as separate lines", 2, lines.size)
assertTrue(lines[0].endsWith(">one"))
assertTrue(lines[1].endsWith(">two"))
}
}
/** The login line has to be terminated too, or the server never reads it. */
@Test
fun `the server receives a complete login line`() {
FakeServer().use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
c.disconnect()
assertEquals("user TEST pass 12345 vers Look4Sat test", server.loginLine)
}
}
/** A verified login is recognised and lets reports count as delivered. */
@Test
fun `a verified login is not reported as refused`() {
FakeServer().use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
assertTrue(c.isVerified)
assertFalse(c.isRefusedByServer)
c.disconnect()
}
}
/**
* The case the rewrite exists for: the server accepts the connection, the write succeeds,
* and every packet is discarded. The client must say so rather than report success.
*/
@Test
fun `an unverified login is flagged while the connection stays up`() {
FakeServer(loginResponse = "# logresp TEST unverified, server FAKE").use { server ->
server.start()
val c = client(server.port, passcode = -1)
c.connect()
assertTrue(server.awaitLogin())
assertFalse("unverified must not read as verified", c.isVerified)
assertTrue("the server explicitly refused", c.isRefusedByServer)
// Not a connection error: a receive-only login is legitimate and stays connected.
assertTrue(c.isConnected)
c.disconnect()
}
}
/**
* A chatty server used to exhaust a fixed line budget, turning an accepted login into
* Unknown and telling the operator their passcode was wrong when it had been accepted.
*/
@Test
fun `keepalive chatter before the verdict does not hide it`() {
// The real keepalive repeats the server identification with a timestamp, captured from
// euro.aprs2.net. A made-up "# keepalive N" would now read as a refusal, correctly - only
// greetings and verdicts are treated as harmless.
val chatter = List(8) { "# aprsc 2.1.21-gbfc2090 25 Aug 2026 16:41:0$it GMT T2UK 1.2.3.4:14580" }
FakeServer(chatter = chatter).use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
assertTrue("the verdict must be found past the comments", c.isVerified)
c.disconnect()
}
}
/**
* A server that sends no greeting is legitimate, and must not cost the full login window on
* every connect - that was eight seconds per attempt.
*/
@Test
fun `a server without a greeting connects promptly`() {
FakeServer(greeting = null).use { server ->
server.start()
val c = client(server.port)
val started = System.currentTimeMillis()
c.connect()
assertTrue(server.awaitLogin())
val elapsed = System.currentTimeMillis() - started
c.disconnect()
assertTrue("connect took ${elapsed}ms, expected well under the login window",
elapsed < 6_000)
}
}
/**
* The failure a live server actually produced, and the one that mattered most.
*
* aprsc answers `# Invalid login: ...` and closes. That is a comment but not a logresp, so it
* was skipped as chatter, the login timed out into Unknown - treated as "may be working" - and
* every send afterwards reported success. Measured against euro.aprs2.net before the fix:
* loginOutcome=Unknown, isRefusedByServer=false, sendPacket=(true, "sent").
*/
@Test
fun `a refused login is not reported as a successful send`() {
FakeServer(loginResponse = "# Invalid login: bad software version").use { server ->
server.start()
val c = client(server.port)
// An outright refusal throws from connect(), which is the correct outcome.
val threw = runCatching { c.connect() }.exceptionOrNull()
assertTrue(server.awaitLogin())
assertFalse("a refused login must not read as verified", c.isVerified)
val sentOk = runCatching {
c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>x")?.first
}.getOrNull()
assertTrue(
"the refusal must surface: threw=$threw sentOk=$sentOk",
threw != null || sentOk != true
)
c.disconnect()
}
}
/**
* A server saying it is about to drop us must not read as a successful send.
*
* The ack read used to treat any leading `#` as harmless chatter, so `# Port full` - which
* means the server is closing the connection - was reported as sent. It now shares the login
* parser's judgement, so only a greeting or keepalive counts as harmless.
*/
@Test
fun `a server refusal after the write is not reported as sent`() {
FakeServer(afterPacket = "# Port full").use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
val result = c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>x")
c.disconnect()
assertEquals("a server refusal must fail the report", false, result?.first)
}
}
/** The real keepalive must still count as sent, since APRS-IS never acknowledges a position. */
@Test
fun `a keepalive after the write still counts as sent`() {
val keepalive = "# aprsc 2.1.21-gbfc2090 25 Aug 2026 16:41:07 GMT T2UK 1.2.3.4:14580"
FakeServer(afterPacket = keepalive).use { server ->
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
val result = c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>x")
c.disconnect()
assertEquals("a keepalive must not fail the report", true, result?.first)
}
}
/** Sending after the server has gone must report failure, not success. */
@Test
fun `a send after the server closes is reported as failed`() {
val server = FakeServer()
server.start()
val c = client(server.port)
c.connect()
assertTrue(server.awaitLogin())
// Closing the ServerSocket alone would leave this connection alive.
server.dropClient()
Thread.sleep(200)
// The first write may still land in the socket buffer; by the second the loss is certain.
c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>one")
val second = c.sendPacket("TEST>APRS,TCPIP*:=0000.00N/00000.00E>two")
c.disconnect()
assertEquals("a send on a dead connection must not report success", false, second?.first)
}
}
@@ -1,150 +0,0 @@
/*
* 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.data.cw
import com.rtbishop.look4sat.core.domain.cw.CwDeepBuffer
import com.rtbishop.look4sat.core.domain.cw.CwDeepSpectrogram
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.floor
/**
* How long audio waits before its text can reach the record pane.
*
* The record binds to archived text only. The live decode is rewritten from scratch every
* cycle, so a pane that concatenated it lost characters the operator had already read - the
* decoder appeared to delete its own output while still running. Binding to archived text
* makes the pane monotonic, and the cost is latency, which is additive: audio must first be
* pushed out of the live window, then accumulate into a full archive batch.
*
* [CwDeepDecoder] needs a Context and a loaded ONNX model, so it cannot be constructed here.
* These tests read its real constants rather than copies, so retuning one without
* reconsidering the user-visible delay fails here.
*/
class CwArchiveTimingTest {
/** Sending speed for the character counts, typical for satellite CW. */
private val wpm = 18.0
/** PARIS standard: one word is five characters. */
private val charsPerSecond = wpm * 5 / 60.0
private val window = CwDeepBuffer.DEFAULT_MAX_SECONDS
private val batch = CwDeepDecoder.ARCHIVE_SECONDS
/** Seconds of audio that have reached the archive after listening for [elapsed]. */
private fun archivedSeconds(elapsed: Double): Double {
val evicted = elapsed - window
if (evicted <= 0.0) return 0.0
return floor(evicted / batch) * batch
}
@Test
fun thresholdMatchesTheDeclaredBatchLength() {
assertEquals(
"threshold must be the batch length in samples",
(CwDeepSpectrogram.SAMPLE_RATE * batch).toInt(),
CwDeepDecoder.ARCHIVE_THRESHOLD
)
}
@Test
fun archiveBatchIsShorterThanACallSign() {
// A seven-character call sign at 18 WPM takes about 4.7 s. A batch longer than that
// means the record can stall for longer than the single most important thing being
// sent, which is what made the stall read as deletion.
val callSignSeconds = 7 / charsPerSecond
assertTrue(
"batch $batch s must not exceed a call sign at $wpm WPM " +
"(${"%.1f".format(callSignSeconds)} s)",
batch <= callSignSeconds
)
}
@Test
fun firstTextReachesTheRecordWithinHalfAMinute() {
// At the previous 15 s batch this was 35 s, so a short exchange ended with the record
// still completely empty: every decoded character had only ever been in the live line,
// which shows 64 characters and overwrites them.
val firstArchive = window + batch
assertTrue("first archived text must appear within 30 s, got $firstArchive s", firstArchive <= 30.0)
}
@Test
fun aThirtySecondSessionStillProducesARecord() {
val archived = archivedSeconds(30.0)
assertTrue("30 s of listening must archive something, got $archived s", archived > 0.0)
}
@Test
fun theRecordNeverStallsForLongerThanOneBatch() {
var longestStall = 0.0
var lastGrowthAt = window
var previous = 0.0
var t = window
while (t <= 600.0) {
val archived = archivedSeconds(t)
if (archived > previous) {
longestStall = maxOf(longestStall, t - lastGrowthAt)
lastGrowthAt = t
previous = archived
}
t += 0.1
}
assertTrue(
"record stalled ${"%.1f".format(longestStall)} s, one batch is $batch s",
longestStall <= batch + 0.11
)
}
@Test
fun audioInFlightWhenCaptureStopsWouldLoseTheEndOfTheTransmission() {
// Why flush() exists. Neither holding place drains on its own: the live window only
// reaches the archive by being pushed out by newer audio, and the pending batch only
// by filling up. Both hold the end of the transmission, where the call sign is.
val worstCase = window + batch
val lostCharacters = worstCase * charsPerSecond
assertTrue(
"flush() must exist: ${"%.0f".format(lostCharacters)} characters would be lost",
lostCharacters > 20
)
}
@Test
fun archivingStaysRarerThanTheLiveDecode() {
// Each batch is one inference. Shortening the batch trades CPU for latency, so it must
// stay rarer than the live redecode or the archive path becomes the dominant cost.
val liveIntervalSeconds = CwDeepBuffer.DEFAULT_REDECODE_INTERVAL_MS / 1000.0
assertTrue(
"batch $batch s must stay longer than the live cycle $liveIntervalSeconds s",
batch > liveIntervalSeconds
)
}
@Test
fun aBatchIsLongEnoughToDecode() {
// compute() rejects audio shorter than one FFT frame, so a batch below that would be
// silently dropped by archiveDecode's size guard and its text lost outright.
assertTrue(
"batch of ${CwDeepDecoder.ARCHIVE_THRESHOLD} samples must exceed " +
"FFT_LENGTH ${CwDeepSpectrogram.FFT_LENGTH}",
CwDeepDecoder.ARCHIVE_THRESHOLD > CwDeepSpectrogram.FFT_LENGTH
)
}
}
@@ -1,130 +0,0 @@
package com.rtbishop.look4sat.core.data.cw
import com.rtbishop.look4sat.core.domain.cw.CwDeepSpectrogram
import com.rtbishop.look4sat.core.domain.cw.CwToneShifter
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
/**
* The gating contract the decoder relies on: shift only when the user opted in AND the
* tone is outside the model window.
*
* [CwDeepDecoder] needs a Context and a loaded ONNX model, so it cannot be constructed
* here. What these tests do exercise is the real decision function the decoder calls -
* [CwToneShifter.analyse] - rather than a copy of it, so a wrong verdict fails here.
* The decoder's own sample accumulation and throttling are covered by the streaming
* tests in core:domain.
*/
class CwToneShiftGateTest {
private val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
private fun tone(hz: Double, samples: Int = 1600): FloatArray = FloatArray(samples) { i ->
sin(2.0 * PI * hz * i / sampleRate).toFloat()
}
/**
* The enabled/disabled gate as [CwDeepDecoder.applyToneShift] applies it: when off
* the audio is returned as-is, when on the verdict comes from the real analyser.
*/
private fun gate(audio: FloatArray, enabled: Boolean): FloatArray {
if (!enabled) return audio
val analysis = CwToneShifter.analyse(audio, sampleRate)
if (!analysis.needsShift) return audio
return CwToneShifter.shift(audio, analysis.shiftHz, sampleRate)
}
@Test
fun `disabled leaves every tone untouched`() {
for (hz in listOf(150.0, 300.0, 800.0, 1200.0, 1500.0)) {
val audio = tone(hz)
assertSame(
"$hz Hz must pass through unchanged while the setting is off",
audio, gate(audio, enabled = false)
)
}
}
@Test
fun `enabled still leaves in-window tones untouched`() {
for (hz in listOf(400.0, 600.0, 800.0, 1000.0, 1200.0)) {
val audio = tone(hz)
assertSame(
"$hz Hz is inside the window; enabling the setting must not alter it",
audio, gate(audio, enabled = true)
)
}
}
@Test
fun `enabled shifts only out-of-window tones`() {
for (hz in listOf(200.0, 300.0, 1300.0, 1500.0)) {
val audio = tone(hz)
val result = gate(audio, enabled = true)
assertFalse("$hz Hz should have been shifted", result === audio)
assertEquals("shift must preserve length", audio.size, result.size)
}
}
@Test
fun `window edges count as inside`() {
val analysisLow = CwToneShifter.analyse(tone(CwDeepSpectrogram.MIN_FREQ_HZ), sampleRate)
val analysisHigh = CwToneShifter.analyse(tone(CwDeepSpectrogram.MAX_FREQ_HZ), sampleRate)
assertFalse("400 Hz is the lower edge, inside", analysisLow.needsShift)
assertFalse("1200 Hz is the upper edge, inside", analysisHigh.needsShift)
}
@Test
fun `shift target is inside the window`() {
assertTrue(
"the target must be a pitch the model can see",
CwToneShifter.isInsideWindow(CwToneShifter.TARGET_HZ.toFloat())
)
}
/**
* Regression guard for the defect that made the whole feature dead on arrival:
* the decoder gated detection on a single chunk reaching DETECT_MIN_SAMPLES, but
* AudioCapture delivers 4410 samples at 44.1 kHz, which is only 320 after
* resampling to 3200 Hz. Detection could never run.
*
* The decoder now pools chunks, so what matters is that the pooled size is
* reachable: a handful of real-sized chunks must add up to enough audio.
*/
@Test
fun `pooled capture chunks reach the detection threshold`() {
val captureRate = 44100
val captureChunk = captureRate / 10 // AudioCapture's ~100 ms read
val resampledChunk = captureChunk * CwDeepSpectrogram.SAMPLE_RATE / captureRate
assertEquals(
"a capture chunk resamples to 320 samples; if this changes revisit pooling",
320, resampledChunk
)
val threshold = 1280 // CwDeepDecoder.DETECT_MIN_SAMPLES
val chunksNeeded = (threshold + resampledChunk - 1) / resampledChunk
assertTrue(
"a single chunk ($resampledChunk) must not be expected to reach $threshold",
resampledChunk < threshold
)
assertTrue(
"pooling must reach the threshold within a second of audio, needs $chunksNeeded chunks",
chunksNeeded in 2..10
)
// And that much audio must actually be enough for the detector to work.
val pooled = tone(1500.0, samples = threshold)
val detected = CwToneShifter.detectToneHz(pooled, sampleRate)
assertEquals(
"the pooled window must be long enough to detect a tone",
1500.0, detected!!.toDouble(), 25.0
)
}
}
@@ -1,407 +0,0 @@
package com.rtbishop.look4sat.core.data.repository
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Locale
import java.util.TimeZone
/**
* ADVERSARIAL AUDIT SCRATCH FILE - delete when the audit report is written.
* Probes buildStatuses for aliasing, midnight arithmetic and boundary defects.
*/
class AmSatAuditTest {
private object UnusedSource : IRemoteSource {
override suspend fun getFileBytes(uri: String): ByteArray? = null
override suspend fun getNetworkBytes(url: String): ByteArray? = null
override suspend fun getAmSatCatalog(): String? = null
override suspend fun getAmSatReports(hours: Int, limit: Int): String? = null
override suspend fun getAmSatSummary(hours: Int): String? = null
}
private val repo = AmSatRepository(UnusedSource)
private fun utc(y: Int, mo: Int, d: Int, h: Int, mi: Int = 0, s: Int = 0): Long {
val c = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
c.clear(); c.set(y, mo - 1, d, h, mi, s)
return c.timeInMillis / 1000
}
private fun rep(name: String, at: Long, id: String, status: String = "heard") =
ApiReport(id, name, "T", status, "AA00", at)
private fun labelsAt(now: Long) =
repo.buildStatuses(listOf("X"), emptyList(), now).single().days.map { it.dateLabel }
/** Reference: the label a UTC instant's day should carry. */
private fun expectLabel(y: Int, mo: Int, d: Int): String {
val mn = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec")
return "${mn[mo - 1]} $d"
}
// ---------- 1. midnight arithmetic under hostile inputs ----------
@Test
fun auditMidnightExactlyAtMidnight() {
assertEquals(
listOf(expectLabel(2026, 8, 22), expectLabel(2026, 8, 21), expectLabel(2026, 8, 20)),
labelsAt(utc(2026, 8, 22, 0, 0, 0))
)
}
@Test
fun auditMidnightOneSecondBeforeAndAfter() {
assertEquals(
"23:59:59 on Aug 21 must still be Aug 21",
listOf("Aug 21", "Aug 20", "Aug 19"),
labelsAt(utc(2026, 8, 21, 23, 59, 59))
)
assertEquals(
"00:00:01 on Aug 22 must already be Aug 22",
listOf("Aug 22", "Aug 21", "Aug 20"),
labelsAt(utc(2026, 8, 22, 0, 0, 1))
)
}
@Test
fun auditLeapDay2028() {
assertEquals(
"Feb 29 2028 back to Feb 27",
listOf("Feb 29", "Feb 28", "Feb 27"),
labelsAt(utc(2028, 2, 29, 12))
)
assertEquals(
"Mar 1 2028 must reach back through the leap day",
listOf("Mar 1", "Feb 29", "Feb 28"),
labelsAt(utc(2028, 3, 1, 0, 0, 0))
)
assertEquals(
"Mar 1 2027 (no leap day) must skip straight to Feb 27",
listOf("Mar 1", "Feb 28", "Feb 27"),
labelsAt(utc(2027, 3, 1, 12))
)
}
@Test
fun auditYearBoundary() {
assertEquals(
listOf("Jan 1", "Dec 31", "Dec 30"),
labelsAt(utc(2027, 1, 1, 0, 0, 0))
)
assertEquals(
listOf("Jan 2", "Jan 1", "Dec 31"),
labelsAt(utc(2027, 1, 2, 23, 59, 59))
)
}
@Test
fun auditMonthBoundariesEveryMonth() {
// First of every month in a leap and a non-leap year.
for (year in listOf(2027, 2028)) {
for (mo in 1..12) {
val now = utc(year, mo, 1, 0, 0, 0)
val got = labelsAt(now)
val ref = GregorianCalendar(TimeZone.getTimeZone("UTC"))
ref.timeInMillis = now * 1000
val want = (0 until 3).map {
val c = ref.clone() as Calendar
c.add(Calendar.DAY_OF_MONTH, -it)
expectLabel(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH))
}
assertEquals("$year-$mo-01", want, got)
}
}
}
/**
* The load-bearing claim: subtracting 86400 equals Calendar day arithmetic in UTC.
* Proven exhaustively over 20 years of days rather than argued.
*/
@Test
fun auditSubtracting86400EqualsCalendarDayArithmeticForTwentyYears() {
val ref = GregorianCalendar(TimeZone.getTimeZone("UTC"))
var now = utc(2020, 1, 1, 12)
val end = utc(2040, 1, 1, 12)
var checked = 0
while (now < end) {
val got = labelsAt(now)
ref.timeInMillis = now * 1000
val want = (0 until 3).map {
val c = ref.clone() as Calendar
c.add(Calendar.DAY_OF_MONTH, -it)
expectLabel(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH))
}
assertEquals("at epoch $now", want, got)
now += 86400
checked++
}
assertTrue("must have checked >7000 days, got $checked", checked > 7000)
}
/**
* The device default zone must not reach the computation. Run the whole build under
* hostile default zones including ones with DST and half-hour offsets, and under the
* DST transition instants of those zones.
*/
@Test
fun auditDefaultTimeZoneCannotInfluenceTheGrid() {
val original = TimeZone.getDefault()
try {
val zones = listOf(
"UTC", "America/New_York", "Europe/Berlin", "Australia/Lord_Howe",
"Asia/Kolkata", "Pacific/Kiritimati", "Pacific/Niue", "Pacific/Chatham",
"America/Sao_Paulo", "Asia/Kathmandu"
)
// Instants that are DST transitions in at least one zone above.
val instants = listOf(
utc(2026, 3, 8, 7), utc(2026, 11, 1, 6), utc(2026, 3, 29, 1),
utc(2026, 10, 25, 1), utc(2026, 4, 5, 16), utc(2026, 10, 4, 16),
utc(2026, 8, 22, 0, 0, 0), utc(2026, 8, 22, 23, 59, 59),
utc(2027, 1, 1, 0, 0, 0), utc(2028, 2, 29, 0, 0, 0)
)
val baseline = HashMap<Long, List<String>>()
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
for (i in instants) baseline[i] = labelsAt(i)
for (z in zones) {
TimeZone.setDefault(TimeZone.getTimeZone(z))
for (i in instants) {
assertEquals("zone $z at $i", baseline[i], labelsAt(i))
// and the placement of a report must not move either
val s = repo.buildStatuses(
listOf("X"), listOf(rep("X", i - 3600, "r")), i
).single()
val cell = s.days.withIndex().flatMap { (d, day) ->
day.slots.withIndex().filter { "r" in it.value.reportIds }
.map { d to it.index }
}
assertEquals("zone $z placement at $i", 1, cell.size)
baseline["p$i".hashCode().toLong()]?.let { }
}
}
} finally {
TimeZone.setDefault(original)
}
}
/** Locale can swap the calendar system out from under Calendar.getInstance. */
@Test
fun auditDefaultLocaleCannotInfluenceTheGrid() {
val original = Locale.getDefault()
try {
val want = run {
Locale.setDefault(Locale.US)
labelsAt(utc(2026, 8, 22, 12))
}
for (l in listOf(
Locale("th", "TH", "TH"), Locale("ja", "JP", "JP"),
Locale("ar", "SA"), Locale.forLanguageTag("th-TH-u-ca-buddhist")
)) {
Locale.setDefault(l)
assertEquals("locale $l", want, labelsAt(utc(2026, 8, 22, 12)))
}
} finally {
Locale.setDefault(original)
}
}
// ---------- aliasing / shared Calendar state leak ----------
/**
* The shared Calendar is mutated by the labels loop after todayMidnightSec is read.
* If any later step re-read it, day 0 would inherit day 2's date. Prove day 0's
* slots are anchored on today, not on the last value the Calendar held.
*/
@Test
fun auditSharedCalendarIsNotReReadAfterTheLabelsLoop() {
val now = utc(2026, 8, 22, 12)
// A report at today 12:30 must be in day 0. If the anchor had leaked to Aug 20
// it would fall outside the grid entirely.
val s = repo.buildStatuses(
listOf("X"), listOf(rep("X", utc(2026, 8, 22, 12, 30), "r")), now
).single()
assertEquals("Aug 22", s.days[0].dateLabel)
assertTrue("today's report must be in day 0 slot 5", "r" in s.days[0].slots[5].reportIds)
assertTrue(
"no other day may hold it",
s.days.drop(1).all { d -> d.slots.all { it.count == 0 } }
)
}
/** Two consecutive calls on the same repository must be identical (no instance state). */
@Test
fun auditRepeatedCallsAreIdempotent() {
val now = utc(2026, 8, 22, 12)
val reports = listOf(
rep("X", utc(2026, 8, 22, 1), "a"), rep("X", utc(2026, 8, 21, 23), "b"),
rep("X", utc(2026, 8, 20, 0, 0, 0), "c")
)
fun shape() = repo.buildStatuses(listOf("X"), reports, now).single()
.days.map { d -> d.dateLabel to d.slots.map { it.reportIds } }
val first = shape()
repeat(5) { assertEquals("call must not drift", first, shape()) }
}
// ---------- slot boundary exactness ----------
/** No report may appear in two cells, and none inside the window may vanish. */
@Test
fun auditEveryBoundaryInstantLandsInExactlyOneCell() {
val now = utc(2026, 8, 22, 12)
val mid = utc(2026, 8, 22, 0, 0, 0)
// every slot edge of all three days, and one second either side of each
val probes = ArrayList<Long>()
for (d in 0 until 3) for (s in 0..12) {
val edge = mid - d * 86400L + s * 7200L
probes.add(edge - 1); probes.add(edge); probes.add(edge + 1)
}
for (t in probes.distinct()) {
val s = repo.buildStatuses(listOf("X"), listOf(rep("X", t, "r")), now).single()
val hits = s.days.withIndex().flatMap { (di, day) ->
day.slots.withIndex().filter { "r" in it.value.reportIds }.map { di to it.index }
}
val inWindow = t >= mid - 2 * 86400L && t < mid + 86400L
if (inWindow) {
assertEquals("epoch $t must occupy exactly one cell, got $hits", 1, hits.size)
// and the cell's day must match the report's UTC date
val c = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
c.timeInMillis = t * 1000
val want = expectLabel(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH))
assertEquals("epoch $t day label", want, s.days[hits[0].first].dateLabel)
// slot index must invert the hour band
assertEquals("epoch $t slot", 11 - c.get(Calendar.HOUR_OF_DAY) / 2, hits[0].second)
} else {
assertEquals("epoch $t is outside the window", 0, hits.size)
}
}
}
/** Counts must sum to the number of in-window reports: nothing dropped, nothing doubled. */
@Test
fun auditCountsConserveReports() {
val now = utc(2026, 8, 22, 12)
val mid = utc(2026, 8, 22, 0, 0, 0)
val reports = ArrayList<ApiReport>()
var i = 0
var t = mid - 2 * 86400L
while (t < mid + 86400L) { reports.add(rep("X", t, "r${i++}")); t += 1801 }
val s = repo.buildStatuses(listOf("X"), reports, now).single()
val total = s.days.sumOf { d -> d.slots.sumOf { it.count } }
val ids = s.days.flatMap { d -> d.slots.flatMap { it.reportIds } }
assertEquals("every in-window report must be counted once", reports.size, total)
assertEquals("no id may repeat", ids.size, ids.toSet().size)
assertEquals("id set must be complete", reports.map { it.id }.toSet(), ids.toSet())
}
// ---------- duplicate catalogue names ----------
@Test
fun auditDuplicateCatalogueNamesProduceDuplicateRows() {
val s = repo.buildStatuses(
listOf("DUP", "DUP", "OTHER"),
listOf(rep("DUP", utc(2026, 8, 22, 11), "r")),
utc(2026, 8, 22, 12)
)
assertEquals("a duplicated catalogue name yields a duplicated row", 3, s.size)
assertEquals(2, s.count { it.name == "DUP" })
// both duplicated rows carry the same report -> the tap dialog double lists it
assertEquals(
listOf(1, 1),
s.filter { it.name == "DUP" }.map { it.days[0].slots[6].count }
)
}
@Test
fun auditReportsForNamesAbsentFromCatalogueAreSilentlyDropped() {
val s = repo.buildStatuses(
listOf("IN-CATALOG"),
listOf(rep("NOT-IN-CATALOG", utc(2026, 8, 22, 11), "ghost")),
utc(2026, 8, 22, 12)
)
assertTrue(
"a report whose satellite is not in the catalogue never renders",
s.single().days.all { d -> d.slots.all { it.count == 0 } }
)
}
// ---------- unparsable timestamps ----------
@Test
fun auditZeroTimestampFromFailedParseIsDroppedNotShownAsEpoch() {
val s = repo.buildStatuses(
listOf("X"), listOf(rep("X", 0L, "unparsable")), utc(2026, 8, 22, 12)
).single()
assertTrue(
"a 0L timestamp (parse failure) must not render",
s.days.all { d -> d.slots.all { it.count == 0 } }
)
}
// ---------- future reports ----------
@Test
fun auditFutureReportsLaterTodayStillRender() {
// Fetched at 07:00; a report stamped 23:00 today lands in slot 0 of today.
val s = repo.buildStatuses(
listOf("X"), listOf(rep("X", utc(2026, 8, 22, 23), "later")), utc(2026, 8, 22, 7)
).single()
assertTrue("today's later bands are pre-drawn", "later" in s.days[0].slots[0].reportIds)
}
// ---------- complexity ----------
/** One pass per slot over the satellite's own reports; not O(all reports x slots). */
@Test
fun auditBuildIsLinearInReportsNotQuadratic() {
fun timeFor(nSats: Int, nReports: Int): Long {
val names = (0 until nSats).map { "S$it" }
val now = utc(2026, 8, 22, 12)
val mid = utc(2026, 8, 22, 0, 0, 0)
val reports = (0 until nReports).map {
rep(names[it % nSats], mid - (it % 172800).toLong(), "r$it")
}
repo.buildStatuses(names, reports, now) // warm
val t0 = System.nanoTime()
repeat(3) { repo.buildStatuses(names, reports, now) }
return System.nanoTime() - t0
}
val small = timeFor(88, 500)
val big = timeFor(88, 5000)
val ratio = big.toDouble() / small
println("AUDIT complexity: 500 reports=${small / 1_000_000}ms 5000=${big / 1_000_000}ms ratio=$ratio")
assertNotNull(ratio)
assertTrue("10x the reports must not cost >40x the time (ratio=$ratio)", ratio < 40)
}
/** toSatReport's YEAR is locale sensitive: proves whether the dialog date corrupts. */
@Test
fun auditReportDialogDateUnderThaiLocale() {
val original = Locale.getDefault()
try {
val c = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
Locale.setDefault(Locale.US)
c.timeInMillis = utc(2026, 8, 22, 11) * 1000
val gregorianYear = c.get(Calendar.YEAR)
Locale.setDefault(Locale("th", "TH", "TH"))
val c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
c2.timeInMillis = utc(2026, 8, 22, 11) * 1000
val thaiYear = c2.get(Calendar.YEAR)
println("AUDIT locale year: gregorian=$gregorianYear thai=$thaiYear class=${c2.javaClass.name}")
assertEquals(
"if these differ, toSatReport prints a Buddhist year in the dialog",
gregorianYear, thaiYear
)
} finally {
Locale.setDefault(original)
}
}
}
@@ -1,365 +0,0 @@
package com.rtbishop.look4sat.core.data.repository
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Calendar
import java.util.TimeZone
/**
* Pins the grid the AMSAT status page draws.
*
* Two contracts matter. The day cell renders one stripe per slot, so "every day has
* exactly 12 slots, newest first" became load-bearing. And the day columns are UTC
* calendar days, so a report must land in the cell whose label matches its UTC date - an
* earlier rolling window anchored on "now" put 17.9 hours of yesterday into the cell
* labelled today, and 73% of a live 1021-report page landed in the wrong column.
*
* This drives [AmSatRepository.buildStatuses] directly rather than `fetchStatus`, because
* the parsing around it uses Android's `JSONObject`, a stub on the JVM: a `fetchStatus`
* test returns null for every input and proves nothing.
*/
class AmSatSlotBuildTest {
private object UnusedSource : IRemoteSource {
override suspend fun getFileBytes(uri: String): ByteArray? = null
override suspend fun getNetworkBytes(url: String): ByteArray? = null
override suspend fun getAmSatCatalog(): String? = null
override suspend fun getAmSatReports(hours: Int, limit: Int): String? = null
override suspend fun getAmSatSummary(hours: Int): String? = null
}
private val repo = AmSatRepository(UnusedSource)
/** Epoch seconds for a UTC wall-clock instant, so every case reads unambiguously. */
private fun utc(year: Int, month: Int, day: Int, hour: Int, minute: Int = 0): Long {
val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.clear()
cal.set(year, month - 1, day, hour, minute, 0)
return cal.timeInMillis / 1000
}
/** Midday, so "today" has hours on both sides of the fetch. */
private val nowSec = utc(2026, 8, 22, 12)
private fun report(name: String, status: String, at: Long, id: String = "r-$name-$at") =
ApiReport(
id = id,
name = name,
callsign = "TEST",
report = status,
gridSquare = "AA00",
reportedTimeUtcSec = at
)
private fun build(names: List<String>, reports: List<ApiReport>) =
repo.buildStatuses(names, reports, nowSec)
@Test
fun `every day carries exactly twelve slots`() {
val statuses = build(
listOf("AO-91", "SO-50", "ISS"),
listOf(report("AO-91", "heard", utc(2026, 8, 22, 11)))
)
assertEquals(3, statuses.size)
for (status in statuses) {
assertEquals("${status.name} must have 3 days", 3, status.days.size)
for (day in status.days) {
assertEquals(
"${status.name} ${day.dateLabel} must have 12 slots for the stripe renderer",
12, day.slots.size
)
}
}
}
@Test
fun `a satellite nobody reported still gets twelve slots per day`() {
// The renderer must never receive an empty list, which would draw nothing at all.
val status = build(listOf("QUIET-1"), emptyList()).single()
assertEquals(3, status.days.size)
status.days.forEach { assertEquals(12, it.slots.size) }
assertTrue(
"a silent satellite must be all no-report slots",
status.days.all { day -> day.slots.all { it.count == 0 } }
)
}
@Test
fun `days are labelled with UTC calendar dates`() {
val status = build(listOf("AO-91"), emptyList()).single()
assertEquals("today", "Aug 22", status.days[0].dateLabel)
assertEquals("yesterday", "Aug 21", status.days[1].dateLabel)
assertEquals("the day before", "Aug 20", status.days[2].dateLabel)
}
@Test
fun `the label does not drift with the time of day`() {
// The old rolling window relabelled the same data depending on when it was
// fetched. A calendar day must not care.
for (hour in listOf(0, 6, 12, 18, 23)) {
val labels = repo.buildStatuses(listOf("AO-91"), emptyList(), utc(2026, 8, 22, hour))
.single().days.map { it.dateLabel }
assertEquals("fetched at ${hour}:00 UTC", listOf("Aug 22", "Aug 21", "Aug 20"), labels)
}
}
@Test
fun `slots cover fixed UTC bands, newest first`() {
// Slot 0 is 22:00-24:00 and slot 11 is 00:00-02:00, matching amsat.org.
val status = build(
listOf("AO-91"),
listOf(
report("AO-91", "heard", utc(2026, 8, 22, 23), id = "lateToday"),
report("AO-91", "not heard", utc(2026, 8, 22, 1), id = "earlyToday")
)
).single()
val today = status.days[0]
assertTrue(
"23:00 belongs in slot 0, the day's last band",
"lateToday" in today.slots[0].reportIds
)
assertTrue(
"01:00 belongs in slot 11, the day's first band",
"earlyToday" in today.slots[11].reportIds
)
}
@Test
fun `a report lands in the day matching its UTC date`() {
val status = build(
listOf("AO-91"),
listOf(
report("AO-91", "heard", utc(2026, 8, 22, 11), id = "today"),
report("AO-91", "heard", utc(2026, 8, 21, 15), id = "yesterday"),
report("AO-91", "heard", utc(2026, 8, 20, 5), id = "dayBefore")
)
).single()
// Positions computed from the UTC bands: 11:00 -> slot 6, 15:00 -> slot 4,
// 05:00 -> slot 9.
assertTrue("today's report", "today" in status.days[0].slots[6].reportIds)
assertTrue("yesterday's report", "yesterday" in status.days[1].slots[4].reportIds)
assertTrue("the day before", "dayBefore" in status.days[2].slots[9].reportIds)
}
@Test
fun `a report just after midnight stays in the new day`() {
// The boundary the rolling window got wrong: 00:30 today must not appear as
// yesterday.
val status = build(
listOf("AO-91"),
listOf(report("AO-91", "heard", utc(2026, 8, 22, 0, 30), id = "justAfterMidnight"))
).single()
assertTrue(
"00:30 belongs to today's first band",
"justAfterMidnight" in status.days[0].slots[11].reportIds
)
assertTrue(
"yesterday must stay empty",
status.days[1].slots.all { it.count == 0 }
)
}
@Test
fun `each status maps to its own colour`() {
// The stripes are now the only carrier of status, so distinct states must stay
// distinct all the way out of the repository.
val at = utc(2026, 8, 22, 11)
val statuses = build(
listOf("A", "B", "C", "D"),
listOf(
report("A", "heard", at),
report("B", "telemetry only", at),
report("C", "not heard", at),
report("D", "something the api invented", at)
)
)
val colours = statuses.map { status -> status.days[0].slots[6].statusColor }
assertTrue("no state may be colourless", colours.none { it == 0L })
assertEquals(
"heard, telemetry and not heard must be visually distinct",
3, colours.take(3).toSet().size
)
}
@Test
fun `a slot keeps every report it contains`() {
// The tap dialog lists reports from the slots, so none may be dropped when several
// land in the same two-hour window. 10:00-12:00 is slot 6.
val status = build(
listOf("AO-91"),
listOf(
report("AO-91", "heard", utc(2026, 8, 22, 10, 15), id = "a"),
report("AO-91", "heard", utc(2026, 8, 22, 11, 0), id = "b"),
report("AO-91", "not heard", utc(2026, 8, 22, 11, 45), id = "c")
)
).single()
val slot = status.days[0].slots[6]
assertEquals("all three reports fall in the same band", 3, slot.count)
assertEquals(setOf("a", "b", "c"), slot.reportIds.toSet())
}
@Test
fun `a slot shows the newest status when reports disagree`() {
// Within one band the most recent observation wins; anything else would keep
// showing a failure after the satellite recovered.
fun colourFor(firstStatus: String, secondStatus: String): Long = build(
listOf("AO-91"),
listOf(
report("AO-91", firstStatus, utc(2026, 8, 22, 10, 15), id = "older"),
report("AO-91", secondStatus, utc(2026, 8, 22, 11, 45), id = "newer")
)
).single().days[0].slots[6].statusColor
assertTrue(
"the slot colour must follow the newest report, not the first",
colourFor("not heard", "heard") != colourFor("heard", "not heard")
)
}
@Test
fun `reports outside the three-day window are ignored`() {
val status = build(
listOf("AO-91"),
listOf(
report("AO-91", "heard", utc(2026, 8, 18, 12), id = "tooOld"),
report("AO-91", "heard", utc(2026, 8, 23, 12), id = "future")
)
).single()
assertTrue(
"nothing outside the window may appear",
status.days.all { day -> day.slots.all { it.count == 0 } }
)
}
@Test
fun `reports for other satellites do not leak between rows`() {
val statuses = build(
listOf("AO-91", "SO-50"),
listOf(report("AO-91", "heard", utc(2026, 8, 22, 11), id = "onlyAo91"))
)
val ao91 = statuses.first { it.name == "AO-91" }
val so50 = statuses.first { it.name == "SO-50" }
assertEquals("AO-91 has its report", 1, ao91.days[0].slots[6].count)
assertTrue(
"SO-50 must stay empty",
so50.days.all { day -> day.slots.all { it.count == 0 } }
)
}
@Test
fun `an empty catalog yields no rows rather than a malformed grid`() {
assertTrue(build(emptyList(), emptyList()).isEmpty())
}
/**
* Slots older than the data we received must not claim nobody was listening.
*
* The API caps at 500 records however many hours are asked for. Measured live, a
* 72-hour request returned 500 reports covering only 49 hours, so the oldest 9.5 hours
* of the third day had no data at all - 352 of 3168 cells were painting "nobody heard
* it" over "we never looked".
*/
@Test
fun `slots before the data starts are marked no-data, not no-report`() {
// The only report is midday yesterday, so nothing older than that was covered.
val oldestReport = utc(2026, 8, 21, 12)
val status = build(
listOf("AO-91"),
listOf(report("AO-91", "heard", oldestReport, id = "only"))
).single()
val noReport = 0xFFC0C0C0
val noData = 0xFFE8E8E8
// The day before yesterday is entirely before the data begins.
assertTrue(
"every slot older than the data must read as no-data",
status.days[2].slots.all { it.statusColor == noData }
)
// Yesterday straddles it: bands after midday are covered, bands before are not.
val yesterday = status.days[1]
assertEquals("the report's own band", 1, yesterday.slots[5].count)
assertTrue(
"bands after the oldest report are covered, so silence there is real",
yesterday.slots.take(6).all { it.statusColor != noData }
)
assertTrue(
"the earliest band of yesterday is before any data",
yesterday.slots[11].statusColor == noData
)
// Today is entirely after the data starts, so its silence is genuine.
assertTrue(
"today's empty slots mean nobody reported",
status.days[0].slots.all { it.statusColor == noReport }
)
}
@Test
fun `coverage is judged from all reports, not one satellite's`() {
// A satellite nobody reported must not show as no-data for the whole grid: the
// slots were covered, that satellite simply was not heard.
val statuses = build(
listOf("LOUD", "QUIET"),
listOf(report("LOUD", "heard", utc(2026, 8, 20, 1), id = "early"))
)
val quiet = statuses.first { it.name == "QUIET" }
val noData = 0xFFE8E8E8
assertTrue(
"coverage reaches back to the earliest report of any satellite",
quiet.days.all { day -> day.slots.none { it.statusColor == noData } }
)
}
/**
* A report whose timestamp failed to parse must not disable the distinction.
*
* parseIsoUtcSec returns 0 for an unparseable reported_time, and coverage is the
* minimum timestamp in the response - so one such record would put the coverage
* boundary in 1970 and mark every slot as reported-on. Measured on a grid that should
* have had 18 no-data cells, a single zero timestamp took it to none.
*/
@Test
fun `a report with an unparseable timestamp does not disable the no-data marking`() {
val noData = 0xFFE8E8E8
val realReport = report("AO-91", "heard", utc(2026, 8, 21, 12), id = "real")
val brokenTimestamp = ApiReport(
id = "broken",
name = "AO-91",
callsign = "TEST",
report = "heard",
gridSquare = "AA00",
reportedTimeUtcSec = 0L
)
val withoutBroken = build(listOf("AO-91"), listOf(realReport))
.single().days.sumOf { day -> day.slots.count { it.statusColor == noData } }
val withBroken = build(listOf("AO-91"), listOf(realReport, brokenTimestamp))
.single().days.sumOf { day -> day.slots.count { it.statusColor == noData } }
assertTrue("the baseline must have uncovered slots to compare", withoutBroken > 0)
assertEquals(
"a zero timestamp must not change what counts as covered",
withoutBroken, withBroken
)
}
@Test
fun `an empty response marks nothing as covered`() {
// With no reports at all there is no evidence about any slot.
val status = build(listOf("AO-91"), emptyList()).single()
val noData = 0xFFE8E8E8
assertTrue(
"yesterday and earlier cannot be claimed as silent",
status.days.drop(1).all { day -> day.slots.all { it.statusColor == noData } }
)
}
}
@@ -18,7 +18,6 @@
package com.rtbishop.look4sat.core.data.repository
import com.rtbishop.look4sat.core.domain.model.DataSourcesSettings
import com.rtbishop.look4sat.core.domain.source.Sources
import com.rtbishop.look4sat.core.domain.model.DatabaseState
import com.rtbishop.look4sat.core.domain.model.OtherSettings
import com.rtbishop.look4sat.core.domain.model.PassesSettings
@@ -41,6 +40,7 @@ import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.InputStream
@OptIn(ExperimentalCoroutinesApi::class)
class DatabaseRepoTest {
@@ -53,7 +53,7 @@ class DatabaseRepoTest {
val uri = "content://look4sat/import/satellites"
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
fileData[uri] = { validCsvBytes() }
fileStreams[uri] = { validCsvStream() }
}
val settingsRepo = FakeSettingsRepo()
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
@@ -62,7 +62,6 @@ class DatabaseRepoTest {
assertEquals(1, localSource.insertedEntries.size)
assertEquals(25544, localSource.insertedEntries.first().catnum)
assertEquals(listOf(25544), settingsRepo.satelliteTypeIdsByType["Other"])
assertTrue(settingsRepo.databaseState.value.numberOfSatellites > 0)
}
@@ -71,7 +70,7 @@ class DatabaseRepoTest {
val uri = "content://look4sat/import/legacy"
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
fileData[uri] = { validTleBytes() }
fileStreams[uri] = { validTleStream() }
}
val settingsRepo = FakeSettingsRepo()
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
@@ -87,7 +86,7 @@ class DatabaseRepoTest {
val customCsvUrl = "https://example.com/custom-omm.csv"
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkData[customCsvUrl] = { validCsvBytes() }
networkStreams[customCsvUrl] = { validCsvStream() }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
@@ -102,129 +101,27 @@ class DatabaseRepoTest {
repository.updateFromRemote()
assertTrue(localSource.insertedEntries.any { it.catnum == 25544 })
// A custom URL replaces the built-in TLE sources: none of them is requested. The
// transceivers group is separate and its own switch is off here, so it still fetches.
val builtInTle = Sources.satelliteDataUrls.values.filter { it.isNotBlank() }
assertTrue(
"no built-in TLE source may be fetched, got " + remoteSource.requestedUrls,
builtInTle.none { it in remoteSource.requestedUrls }
)
assertTrue(
"the operator's URL must be fetched",
customCsvUrl in remoteSource.requestedUrls
)
// Indexed under "Custom". It used to go under "All", where setSatelliteTypeIds
// early-returns, so the type filter never saw these satellites and the old assertion here
// was checking a no-op.
assertEquals(listOf(25544), settingsRepo.satelliteTypeIdsByType["Custom"])
assertEquals(null, settingsRepo.satelliteTypeIdsByType["All"])
// NOT "Other": that key belongs to manual file import, and setSatelliteTypeIds overwrites
// rather than merges, so sharing it would have each source wipe the other's index.
assertEquals(null, settingsRepo.satelliteTypeIdsByType["Other"])
}
/** The switch-off path must be untouched: all built-in sources, exactly as before. */
@Test
fun `without a custom source every built-in source is fetched`() = runTest(dispatcher) {
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
// Every built-in TLE source has to answer, or updateFromRemote throws because all of
// them failed, which would mask what this test checks. The transceivers group is left
// unanswered on purpose: org.json is compileOnly in core:domain, so DataParser cannot
// parse a radio payload on the JVM anyway.
Sources.satelliteDataUrls.values.filter { it.isNotBlank() }
.forEach { networkData[it] = { validCsvBytes() } }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
useCustomTLE = false,
useCustomTransceivers = false,
tleUrl = "https://example.com/ignored.csv",
transceiversUrl = ""
)
)
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
val expected = Sources.satelliteDataUrls.values.filter { it.isNotBlank() }
assertTrue(
"expected all built-in sources, got " + remoteSource.requestedUrls.size,
expected.all { it in remoteSource.requestedUrls }
)
assertTrue(
"the custom URL must not be fetched when the switch is off",
"https://example.com/ignored.csv" !in remoteSource.requestedUrls
)
}
/**
* A dead custom URL must fail the update even when the transceivers source answers.
*
* The counts used to be added together, so one transceivers success covered a total orbital
* failure: no exception, and a fresh "updated successfully" timestamp for an update that
* refreshed nothing. Replacing the built-in sources shrank the denominator from 28 to 2 and
* made that easy to hit.
*/
@Test
fun `a dead custom url fails the update even if transceivers succeed`() = runTest(dispatcher) {
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
Sources.transceiversDataUrls.values.filter { it.isNotBlank() }
.forEach { networkData[it] = { "[]".encodeToByteArray() } }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
useCustomTLE = true,
useCustomTransceivers = false,
tleUrl = "https://example.com/dead.csv",
transceiversUrl = ""
)
)
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
var threw = false
try {
repository.updateFromRemote()
} catch (_: java.io.IOException) {
threw = true
}
assertTrue("a total orbital failure must raise", threw)
assertTrue("no entries may be inserted", localSource.insertedEntries.isEmpty())
}
private fun validCsvBytes(): ByteArray = """
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
""".trimIndent().encodeToByteArray()
""".trimIndent().byteInputStream()
private fun validTleBytes(): ByteArray = """
private fun validTleStream(): InputStream = """
ISS (ZARYA)
1 25544U 98067A 21320.51955234 .00001288 00000+0 31985-4 0 9990
2 25544 51.6447 309.4881 0004694 203.6966 299.8876 15.48582035312205
""".trimIndent().encodeToByteArray()
""".trimIndent().byteInputStream()
}
private class FakeRemoteSource : IRemoteSource {
val fileData: MutableMap<String, () -> ByteArray> = mutableMapOf()
val networkData: MutableMap<String, () -> ByteArray> = mutableMapOf()
val fileStreams: MutableMap<String, () -> InputStream> = mutableMapOf()
val networkStreams: MutableMap<String, () -> InputStream> = mutableMapOf()
/** Every URL asked for, so a test can assert WHICH sources were fetched, not just the result. */
val requestedUrls = mutableListOf<String>()
override suspend fun getFileStream(uri: String): InputStream? = fileStreams[uri]?.invoke()
override suspend fun getFileBytes(uri: String): ByteArray? = fileData[uri]?.invoke()
override suspend fun getNetworkBytes(url: String): ByteArray? {
requestedUrls += url
return networkData[url]?.invoke()
}
override suspend fun getAmSatCatalog(): String? = null
override suspend fun getAmSatReports(hours: Int, limit: Int): String? = null
override suspend fun getAmSatSummary(hours: Int): String? = null
override suspend fun getNetworkStream(url: String): InputStream? = networkStreams[url]?.invoke()
}
private class FakeLocalSource : ILocalSource {
@@ -277,7 +174,7 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
override val databaseState: MutableStateFlow<DatabaseState> = MutableStateFlow(DatabaseState(0, 0, 0L))
override val rcSettings: StateFlow<RCSettings> = MutableStateFlow(
RCSettings(false, "", "", "", false, "", "", "", 0L, false, "", "", "", false, "", "")
RCSettings(false, "", "", "", false, "", "", "", false, "", "", "", false, "", "")
)
override val otherSettings: StateFlow<OtherSettings> = MutableStateFlow(
@@ -290,8 +187,6 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
RadioControlSettings(false, RadioControlSettings.MODEL_YAESU_FT817, "", "", "", "", 9600)
)
val satelliteTypeIdsByType = mutableMapOf<String, List<Int>>()
override fun setSelectedIds(ids: List<Int>) = Unit
override fun setSelectedSatModes(modes: List<String>) = Unit
@@ -300,15 +195,10 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
override suspend fun setStationPosition(): 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>) {
satelliteTypeIdsByType[type] = ids
}
override fun updateDatabaseState(state: DatabaseState) {
databaseState.value = state
@@ -323,10 +213,6 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
}
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
override fun getSatelliteOffset(catnum: Int): String = ""
override fun setSatelliteOffset(catnum: Int, offset: String) = Unit
}
private fun defaultDataSourcesSettings(): DataSourcesSettings {
@@ -127,7 +127,7 @@ class SelectionRepoTest {
override val databaseState: MutableStateFlow<DatabaseState> = MutableStateFlow(DatabaseState(0, 0, 0L))
override val rcSettings: StateFlow<RCSettings> = MutableStateFlow(
RCSettings(false, "", "", "", false, "", "", "", 0L, false, "", "", "", false, "", "")
RCSettings(false, "", "", "", false, "", "", "", false, "", "", "", false, "", "")
)
override val otherSettings: StateFlow<OtherSettings> = MutableStateFlow(
@@ -152,14 +152,10 @@ class SelectionRepoTest {
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
override suspend fun setStationPosition(): 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 updateDatabaseState(state: DatabaseState) {
databaseState.value = state
}
@@ -171,10 +167,6 @@ class SelectionRepoTest {
override fun updateDataSourcesSettings(settings: DataSourcesSettings) = Unit
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
override fun getSatelliteOffset(catnum: Int): String = ""
override fun setSatelliteOffset(catnum: Int, offset: String) = Unit
}
}
@@ -1,156 +0,0 @@
/*
* 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.aprs
/**
* Builds the position line this station puts on APRS-IS, or refuses to.
*
* Separated from the reporter so the packet can be tested without a socket. Every rule here
* comes from aprs-is.net/connecting.aspx, and each of them was being broken:
*
* - the path must be exactly `TCPIP*`, and was absent entirely
* - the line must not exceed 512 bytes including CRLF, and had no cap
* - the comment must not contain a line break, or it injects a second packet
* - a station with no position must not transmit, where 0.0 was substituted so 0 degrees north,
* 0 degrees east - a point in the Gulf of Guinea - went out under the operator's callsign
*/
object AprsBeacon {
/** The only path a client-originated packet may carry. */
const val PATH = "TCPIP*"
/** Destination for a position report with no addressee. */
const val DESTINATION = "APRS"
/** Maximum line length including the CRLF the caller appends. */
const val MAX_LINE_BYTES = 512
/** Comment limit for this position format, per the APRS specification. */
const val MAX_COMMENT = 43
/** Why a beacon could not be built. */
sealed interface Refusal {
/** No position was available. Transmitting 0,0 would claim the Gulf of Guinea. */
data object NoPosition : Refusal
/** The callsign is missing, so the packet would have no valid source. */
data object NoCallsign : Refusal
/** Latitude or longitude outside the possible range. */
data class ImpossiblePosition(val latitude: Double, val longitude: Double) : Refusal
}
/** Either a line ready to send, or the reason there is none. */
sealed interface Result {
data class Line(val text: String) : Result
data class Blocked(val refusal: Refusal) : Result
}
/**
* Build the position line.
*
* Returns [Result.Blocked] rather than a placeholder: a beacon is a claim about where the
* operator is, and there is no honest default for "nowhere".
*/
fun build(
callsign: String,
ssid: String,
latitude: Double?,
longitude: Double?,
symbolTable: String,
symbolCode: String,
comment: String
): Result {
if (callsign.isBlank()) return Result.Blocked(Refusal.NoCallsign)
if (latitude == null || longitude == null) return Result.Blocked(Refusal.NoPosition)
if (latitude !in -90.0..90.0 || longitude !in -180.0..180.0) {
return Result.Blocked(Refusal.ImpossiblePosition(latitude, longitude))
}
val source = AprsPacket.formatCallSsid(callsign.trim().uppercase(), ssid.trim())
val position = AprsPosition(
latitude = latitude,
longitude = longitude,
symbolTable = tableOf(symbolTable),
symbolCode = codeOf(symbolCode)
)
val header = "$source>$DESTINATION,$PATH:="
val body = position.toUncompressedString()
val room = MAX_LINE_BYTES - CRLF_BYTES - header.encodeToByteArray().size - body.encodeToByteArray().size
return Result.Line(header + body + sanitiseComment(comment, room))
}
/**
* Strip anything that would break the line, then trim to fit.
*
* A newline typed into the comment field used to end the packet early and start a second one
* from the remaining text - an injection the operator could trigger by accident.
*/
fun sanitiseComment(comment: String, room: Int = MAX_COMMENT): String {
if (room <= 0) return ""
val cleaned = comment.asSequence()
// Printable ASCII only: line breaks split the packet, and control characters have no
// meaning in a comment while being able to confuse a parser.
.filter { it.code in 0x20..0x7E }
.joinToString("")
.trim()
val limit = minOf(MAX_COMMENT, room)
return if (cleaned.length <= limit) cleaned else cleaned.take(limit)
}
/**
* The symbol table byte, defaulting to the primary table.
*
* Must be `/`, `\` or an overlay character. It was previously whatever the operator typed
* first - any character at all, including one that breaks the fixed-width parse. aprs.fi
* names symbol misconfiguration as the most common reason a station never appears on the map.
*/
fun tableOf(entry: String): Char {
val candidate = entry.trim().firstOrNull() ?: return TABLE_PRIMARY
return when {
candidate == TABLE_PRIMARY || candidate == TABLE_ALTERNATE -> candidate
candidate.isDigit() -> candidate
candidate in 'A'..'Z' -> candidate
else -> TABLE_PRIMARY
}
}
/** The symbol byte. Any printable character is a valid symbol; anything else is not. */
fun codeOf(entry: String): Char {
val candidate = entry.trim().firstOrNull() ?: return DEFAULT_SYMBOL
return if (candidate.code in 0x21..0x7E) candidate else DEFAULT_SYMBOL
}
private const val TABLE_PRIMARY = '/'
private const val TABLE_ALTERNATE = '\\'
/** Bytes the caller adds after the line. */
private const val CRLF_BYTES = 2
/** Fallback symbol. `>` is a car on the primary table - a reasonable stand-in for a phone. */
/**
* Substituted when the stored code is unusable.
*
* A house, not a car. The old default was '>' (CAR) with a comment conceding it was "a
* reasonable stand-in for a phone" - but a station beaconing from a handset showed up as a
* vehicle for every operator who was not driving, and aprs.fi names transmit-side symbol
* misconfiguration among the first things to check when a station looks wrong. A house is
* correct for most users and obviously wrong rather than misleading for the rest.
*/
private const val DEFAULT_SYMBOL = '-'
}
@@ -1,140 +0,0 @@
/*
* 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.aprs
/**
* The APRS-IS login line and the verdict the server returns for it.
*
* Kept apart from the socket so it can be tested: whether a login was verified decides whether
* anything this app sends reaches the network, and that distinction used to be made by a
* substring check inside a runCatching whose result was discarded, so it could not fail loudly.
*
* Format per aprs-is.net/connecting.aspx:
* `user mycall[-ss] pass passcode [vers softwarename softwarevers [filter ...]]`
*/
object AprsLogin {
/** What the server decided about a login attempt. */
sealed interface Outcome {
/** The passcode matched the callsign. Packets from this client are accepted. */
data class Verified(val callsign: String) : Outcome
/**
* The server accepted the connection but did not verify the login.
*
* Not an error at the socket level, which is exactly why it needs surfacing: writes keep
* succeeding while the server discards every packet. A receive-only login (passcode -1)
* lands here legitimately.
*/
data class Unverified(val callsign: String) : Outcome
/** The server refused the login outright. */
data class Rejected(val detail: String) : Outcome
/** Nothing recognisable arrived. The connection may still work; we simply do not know. */
data class Unknown(val detail: String) : Outcome
}
/** Any run of whitespace, collapsed to a hyphen inside a single token. */
private val WHITESPACE = Regex("""\s+""")
/** Passcode value that asks for a receive-only connection. */
const val RECEIVE_ONLY_PASSCODE = -1
/**
* Build the login line.
*
* `vers` takes TWO tokens - a software name and a version, separated by a space. An earlier
* version of this replaced that space with a hyphen, reading the rule "softwarename must not
* contain a space" as "the field must be a single token". Live aprsc 2.1.21 rejects the result:
*
* sent: user N0CALL pass -1 vers Look4Sat-4.5.4
* got: # Invalid login: software name and version are not separated by a space
*
* So name and version stay apart, and whitespace is collapsed WITHIN each of them instead.
*/
fun line(
callsign: String,
ssid: String,
passcode: Int,
name: String,
version: String,
filter: String = ""
): String {
val callSsid = AprsPacket.formatCallSsid(callsign, ssid)
val safeName = name.trim().replace(WHITESPACE, "-").ifEmpty { "Look4Sat" }
val safeVersion = version.trim().replace(WHITESPACE, "-").ifEmpty { "0" }
val base = "user $callSsid pass $passcode vers $safeName $safeVersion"
val trimmedFilter = filter.trim()
return if (trimmedFilter.isEmpty()) base else "$base $trimmedFilter"
}
/**
* Interpret one line of server output, or null when it carries no verdict.
*
* Classified by what is KNOWN HARMLESS rather than by a list of known refusals, because that
* list was incomplete and the failure is silent. aprsc refuses with `# Invalid login: ...` but
* also `# Login by user not allowed` - observed live on rotate.aprs2.net - and `# Port full`
* and `# Server full`. Each was skipped as chatter, the login timed out into Unknown, Unknown
* is deliberately read as "may be working", and every send afterwards reported success to an
* operator the server had refused.
*
* So identification and keepalive comments return null, a logresp is parsed, and anything else
* the server bothers to say during login counts as it objecting.
*
* Note that "unverified" contains "verified", so the negative is tested first - a naive
* contains("verified") reports every refusal as acceptance.
*/
fun parse(line: String): Outcome? {
val trimmed = line.trim()
if (trimmed.isEmpty()) return null
if (!trimmed.startsWith("#")) {
// A non-comment line during login is the server objecting in plain text.
return Outcome.Rejected(trimmed)
}
val lower = trimmed.lowercase()
if (lower.contains("logresp")) {
val callsign = callsignFrom(trimmed)
return when {
lower.contains("unverified") -> Outcome.Unverified(callsign)
lower.contains("verified") -> Outcome.Verified(callsign)
else -> Outcome.Unknown(trimmed)
}
}
// Identification and keepalives are the only comments that mean "keep reading".
if (HARMLESS.any { lower.startsWith(it) }) return null
return Outcome.Rejected(trimmed.removePrefix("#").trim())
}
/**
* Comment prefixes that carry no verdict.
*
* Matching a prefix rather than searching for refusal words means a refusal nobody anticipated
* is treated as a refusal instead of being ignored.
*/
private val HARMLESS = listOf("# aprsc", "# javaprssrvr", "# aprsis", "# filter")
/** The callsign token in `# logresp CALL verified, ...`, or empty when absent. */
private fun callsignFrom(response: String): String {
val tokens = response.removePrefix("#").trim().split(Regex("\\s+"))
val index = tokens.indexOfFirst { it.equals("logresp", ignoreCase = true) }
if (index < 0) return ""
return tokens.getOrNull(index + 1)?.trimEnd(',') ?: ""
}
}
@@ -1,122 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import kotlin.math.abs
import kotlin.math.round
import com.rtbishop.look4sat.core.domain.utility.formatString
/**
* APRS-IS protocol core (pure Kotlin, no Android dependencies).
* Reverse-ported from APRSdroid 1.6.3d: AprsPacket$.scala + ab0oo Position.java.
*/
object AprsPacket {
/** APRS-IS passcode algorithm (standard): 0x73E2 seed, uppercase callsign + \0, XOR each char pair */
fun passcode(callsign: String): Int {
val s = callsign.split("-")[0].uppercase() + "\u0000"
var hash = 29666 // 0x73E2
var i = 0
while (i <= s.length - 2) {
hash = hash xor (s[i].code * 256 + s[i + 1].code)
i += 2
}
return hash and 0x7FFF
}
/** Callsign-SSID join (BG7NTA + 5 -> BG7NTA-5) */
fun formatCallSsid(callsign: String, ssid: String): String {
if (ssid.isNullOrEmpty()) return callsign
return "$callsign-$ssid"
}
/** Optional distance filter: filter r/lat/lon/dist */
fun formatRangeFilter(latitude: Double, longitude: Double, distKm: Int): String {
return formatString("r/%.3f/%.3f/%d", latitude, longitude, distKm)
}
/**
* Altitude extension /A=000000 (feet). The field is a fixed six-digit
* decimal, so a negative altitude (below sea level, or a bad GPS fix) must
* be clamped: "%06d" of -164 yields "/A=-00164", which is not a valid
* extension and corrupts the rest of the comment field.
*/
fun formatAltitude(altitudeMeters: Double?): String {
if (altitudeMeters == null) return ""
val feet = (altitudeMeters * 3.2808399).toInt().coerceIn(0, 999999)
return formatString("/A=%06d", feet)
}
/**
* Speed/course extension /CCC/SSS (degrees/knots). Course wraps into
* 0..359 and speed is clamped to three digits, because "%03d" of an
* out-of-range value widens the field and breaks the fixed-width format.
*/
fun formatCourseSpeed(speedMps: Double?, bearing: Float?): String {
if (speedMps == null || bearing == null) return ""
val knots = (speedMps * 1.94384449).toInt().coerceIn(0, 999)
val course = ((bearing.toInt() % 360) + 360) % 360
return formatString("/%03d/%03d", course, knots)
}
}
/**
* APRS position encoding (reverse-ported from ab0oo Position.java).
* Uncompressed: DDMM.MMN/DDDMM.MME; compressed: base91.
*/
class AprsPosition(
val latitude: Double,
val longitude: Double,
val symbolTable: Char,
val symbolCode: Char,
val positionAmbiguity: Int = 0
) {
/** Uncompressed format (APRS-IS default reporting format) */
fun toUncompressedString(): String {
val lat = getDMS(latitude, true)
val lon = getDMS(longitude, false)
return "$lat$symbolTable$lon$symbolCode"
}
/** Compressed format (base91, standard APRS algorithm) */
fun toCompressedString(): String {
val jRound = round((90.0 - latitude) * 380926.0).toLong()
val j = jRound / 753571 + 33
val j2 = jRound % 753571
val j3 = j2 / 8281 + 33
val j4 = j2 % 8281
val i = (j4 % 91).toInt() + 33
val jRound2 = round((longitude + 180.0) * 190463.0).toLong()
val j5 = jRound2 / 753571 + 33
val j6 = jRound2 % 753571
val j7 = 33 + j6 / 8281
val j8 = j6 % 8281
return "" + symbolTable + j.toInt().toChar() + j3.toInt().toChar() +
((j4 / 91).toInt() + 33).toChar() + i.toChar() +
j5.toInt().toChar() + j7.toInt().toChar() +
((j8 / 91).toInt() + 33).toChar() +
((j8 % 91).toInt() + 33).toChar() + symbolCode
}
/** Single-axis DMS encoding (hundredths) */
private fun getDMS(value: Double, isLat: Boolean): String {
var iRound = round(value * 6000.0).toInt()
if (iRound < 0) iRound = -iRound
val degrees = iRound / 6000
val minutes = (iRound / 100) % 60
val hundredths = iRound % 100
val frac = when (positionAmbiguity) {
1 -> " . "
2 -> formatString("%d . ", minutes / 10)
3 -> formatString("%02d. ", minutes)
4 -> formatString("%02d.%d ", minutes, hundredths / 10)
else -> formatString("%02d.%02d", minutes, hundredths)
}
return if (isLat) {
val ns = if (value >= 0) 'N' else 'S'
formatString("%02d%s%c", degrees, frac, ns)
} else {
val ew = if (value >= 0) 'E' else 'W'
formatString("%03d%s%c", degrees, frac, ew)
}
}
}
@@ -1,101 +0,0 @@
/*
* 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.aprs
/**
* Decides what passcode to present to APRS-IS, and whether the operator's entry is usable.
*
* The app must not derive a transmit passcode for the operator. APRS-IS states that supplying
* the correct passcode to a user is the software author's responsibility, and the passcode
* exists as a licence check - deriving it in-app and shipping the algorithm defeats the point.
* APRSdroid has the same algorithm in the same file and deliberately does not use it for this
* reason, validating the operator's entry instead and linking out to request one.
*
* So this validates. [AprsPacket.passcode] stays, because checking an entry means recomputing
* the expected value, but nothing here substitutes a derived code for a missing one.
*/
object AprsPasscode {
/** Value that asks APRS-IS for a receive-only connection. Always legitimate. */
const val RECEIVE_ONLY = -1
/** What the operator's passcode entry amounts to. */
sealed interface Entry {
/** A passcode that matches the callsign. Reports will be forwarded. */
data class Transmit(val passcode: Int) : Entry
/**
* An explicit -1, or a blank entry.
*
* A blank entry lands here rather than being filled in with a derived code: connecting
* receive-only is honest about what an operator without a passcode can do, where a
* derived code silently claims a licence check that was never performed.
*/
data object ReceiveOnly : Entry
/** Something was typed but it is not this callsign's passcode. */
data class Mismatch(val expectedFor: String) : Entry
/** Something was typed that is not a number at all. */
data object NotANumber : Entry
}
/**
* Classify what the operator typed.
*
* A mismatch is reported rather than corrected, so the UI can refuse to save and say why.
* Silently swapping in a derived code is how an operator ends up believing they are
* transmitting under a passcode they never obtained.
*/
fun classify(callsign: String, entry: String): Entry {
val trimmed = entry.trim()
if (trimmed.isEmpty()) return Entry.ReceiveOnly
val value = trimmed.toIntOrNull() ?: return Entry.NotANumber
// Checked before the callsign comparison: -1 is the documented receive-only value and
// is never anyone's passcode, so comparing it would report a deliberate choice as a typo.
if (value == RECEIVE_ONLY) return Entry.ReceiveOnly
val call = callsign.trim()
if (call.isEmpty()) return Entry.Mismatch("")
return if (value == AprsPacket.passcode(call)) {
Entry.Transmit(value)
} else {
Entry.Mismatch(call.uppercase())
}
}
/**
* The number to send in the login line for this entry.
*
* Anything not usable becomes [RECEIVE_ONLY]: the connection still works, the operator is
* told separately that their reports are not being forwarded, and no packet goes out under
* a passcode the app invented. The previous code sent a derived transmit passcode here,
* and `takeIf { it >= 0 }` additionally made an explicit -1 impossible to use - which also
* blocked the one safe way to test a setup, since a receive-only login is how you confirm
* the connection works without putting anything on the network.
*/
fun loginValue(callsign: String, entry: String): Int =
when (val classified = classify(callsign, entry)) {
is Entry.Transmit -> classified.passcode
else -> RECEIVE_ONLY
}
/** True when this entry lets the operator's reports reach the network. */
fun canTransmit(callsign: String, entry: String): Boolean =
classify(callsign, entry) is Entry.Transmit
}
@@ -1,81 +0,0 @@
/*
* 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.aprs
/**
* One APRS symbol an operator might plausibly want.
*
* [table] and [code] are the two characters that go into the packet. [descriptionKey] names a
* string resource rather than holding text, because core:domain has no access to resources and
* hardcoding English here would put wording outside the locale files.
*/
data class AprsSymbol(val table: Char, val code: Char, val descriptionKey: String)
/**
* A short list of symbols worth offering, instead of two free-text fields.
*
* The fields accepted anything and used only the first character, so typing "satellite" into the
* table field persisted the whole word and beaconed as `/` - the field lied about what it did.
* aprs.fi's own troubleshooting guidance puts transmit-side symbol misconfiguration among the first
* things to check when a station does not appear as expected.
*
* The strongest single argument for a list: `\S` is Satellite/Pacsat but `/S` is SHUTTLE. One
* keystroke apart, and both look correct to someone typing from memory.
*
* Renderings are from aprs.org/symbols/symbolsX.txt (WB4APR, 25 Nov 2015). The list is deliberately
* short - it covers fixed, portable, vehicle and satellite postures, not all 400-odd symbols.
*/
object AprsSymbols {
/** Fixed home station. Correct for most users, and wrong in an obvious way for the rest. */
val HOUSE = AprsSymbol('/', '-', "aprs_symbol_house")
val curated = listOf(
HOUSE,
AprsSymbol('\\', '-', "aprs_symbol_house_alt"),
AprsSymbol('/', '[', "aprs_symbol_person"),
AprsSymbol('/', 'y', "aprs_symbol_yagi"),
// Alternate table. /S is SHUTTLE, which is not what anyone means here.
AprsSymbol('\\', 'S', "aprs_symbol_satellite"),
AprsSymbol('/', ';', "aprs_symbol_portable"),
AprsSymbol('/', '$', "aprs_symbol_phone"),
AprsSymbol('/', 'I', "aprs_symbol_tcpip"),
AprsSymbol('\\', 'K', "aprs_symbol_ht"),
AprsSymbol('/', '>', "aprs_symbol_car"),
AprsSymbol('/', 'k', "aprs_symbol_truck"),
AprsSymbol('/', 'v', "aprs_symbol_van"),
AprsSymbol('/', 'R', "aprs_symbol_rv"),
AprsSymbol('/', 'b', "aprs_symbol_bike")
)
/**
* Find the curated entry matching a stored pair, or null when it is not on the list.
*
* Null matters: an operator may have set a symbol this list does not offer, and the picker must
* show it as-is rather than silently substituting the nearest entry.
*/
fun find(table: Char, code: Char): AprsSymbol? =
curated.firstOrNull { it.table == table && it.code == code }
/** Same, from whatever strings the settings screen holds. Blank means the shipped default. */
fun find(table: String, code: String): AprsSymbol? {
val t = table.firstOrNull() ?: HOUSE.table
val c = code.firstOrNull() ?: HOUSE.code
return find(t, c)
}
}
@@ -1,195 +0,0 @@
/*
* 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.cw
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
/**
* Low-pass filter applied before decimating to the model's sample rate.
*
* [CwDeepSpectrogram.resampleLinear] drops from the capture rate to 3200 Hz by
* interpolating between samples, with nothing removing the content above the new
* Nyquist of 1600 Hz first. Everything higher folds back into the audible window,
* which is not a subtle degradation - measured on 44100 Hz input a 3000 Hz tone
* reappears at 200 Hz at 119 times the spectral mean, indistinguishable from a real
* signal, and 1800 Hz lands on 1400 Hz. Worse for copy, the whole 1600-22050 Hz band
* of hiss folds down on top of the signal and lifts the noise floor across the entire
* display.
*
* The resampler itself is deliberately left alone: its comment notes it matches the
* reference implementation the model was trained against, so changing its arithmetic
* would move the spectrogram away from what DeepCW expects. Filtering first fixes the
* aliasing without touching that contract.
*
* A windowed-sinc FIR rather than a biquad cascade: the transition band has to be
* steep to keep 1600 Hz while rejecting 1800 Hz, and a linear-phase FIR does not
* smear the keying envelope the way a high-order IIR would.
*/
object CwAntiAlias {
/**
* Cut-off as a fraction of the target Nyquist.
*
* Below 1.0 so the transition band lands inside the discarded region rather than
* straddling it. At 0.92 the response is flat to 1470 Hz, which still covers the
* model's 1200 Hz window and the shifter's detection range with room to spare.
*/
private const val CUTOFF_FRACTION = 0.92
/**
* Filter length. Odd so the group delay is a whole number of samples.
*
* 127 taps at 44100 Hz gives roughly a 700 Hz transition width - enough to put
* 1800 Hz down by more than 40 dB while passing 1470 Hz unattenuated. Longer would
* be sharper and slower; this runs on a phone during a pass.
*/
private const val TAPS = 127
/** Delay introduced by [TAPS], for callers that need to align another path. */
const val GROUP_DELAY_SAMPLES = TAPS / 2
/**
* Filter [audio] so that decimating to [targetRate] cannot alias.
*
* A no-op when [sourceRate] is at or below [targetRate], since there is nothing
* above the target Nyquist to remove. Returns a new array; [audio] is unchanged.
*/
fun prepareForDecimation(audio: FloatArray, sourceRate: Int, targetRate: Int): FloatArray {
if (audio.isEmpty() || sourceRate <= targetRate) return audio
val cutoffHz = targetRate / 2.0 * CUTOFF_FRACTION
return applyFir(audio, kernelFor(cutoffHz, sourceRate))
}
/**
* Windowed-sinc low-pass kernel, normalised to unity gain at DC.
*
* Blackman window: its sidelobes are around -58 dB against the Hamming window's
* -41 dB, and sidelobe level is exactly what decides how much of the folded band
* survives.
*/
private fun kernelFor(cutoffHz: Double, sampleRate: Int): FloatArray {
val normalised = cutoffHz / sampleRate
val half = TAPS / 2
val raw = DoubleArray(TAPS) { i ->
val n = i - half
val sinc = if (n == 0) {
2.0 * normalised
} else {
sin(2.0 * PI * normalised * n) / (PI * n)
}
val window = 0.42 -
0.5 * cos(2.0 * PI * i / (TAPS - 1)) +
0.08 * cos(4.0 * PI * i / (TAPS - 1))
sinc * window
}
val sum = raw.sum()
// Unity DC gain, so filtering does not change the level the model was trained on.
return FloatArray(TAPS) { i -> (raw[i] / sum).toFloat() }
}
/**
* Convolve, compensating for the filter's own delay so the output lines up with
* the input. Edge taps that fall outside the buffer see zeros, which costs the
* first and last [GROUP_DELAY_SAMPLES] samples of an isolated buffer.
*/
private fun applyFir(audio: FloatArray, kernel: FloatArray): FloatArray {
val out = FloatArray(audio.size)
for (i in audio.indices) {
var sum = 0f
for (k in kernel.indices) {
val j = i - k + GROUP_DELAY_SAMPLES
if (j >= 0 && j < audio.size) sum += kernel[k] * audio[j]
}
out[i] = sum
}
return out
}
/**
* Chunk-by-chunk filter that carries the state [prepareForDecimation] cannot.
*
* Two things are needed for concatenated chunks to match a whole-buffer filter.
* History is the obvious one: the FIR spans [TAPS] samples, so a chunk's first
* outputs need the tail of the one before it.
*
* The second is less obvious and was measured rather than reasoned about. A
* linear-phase FIR is centred, so output sample `i` needs input up to
* `i + GROUP_DELAY_SAMPLES` - samples that have not been captured yet when the
* chunk arrives. A first attempt let those taps fall off the end of the buffer and
* read as zeros; against a whole-buffer filter that diverged by 0.134 across the
* last 44 samples of every chunk, which is a click at each boundary rather than a
* rounding difference.
*
* So output is held back by [GROUP_DELAY_SAMPLES] samples: each call emits the
* samples whose lookahead has now arrived, and keeps the rest until the next chunk
* completes them. The cost is a fixed 63-sample delay, about 1.4 ms at 44100 Hz,
* against a 20 WPM dot of roughly 60 ms.
*
* Not thread-safe: driven from the single capture coroutine.
*/
class Streaming(sourceRate: Int, targetRate: Int) {
private val kernel: FloatArray? =
if (sourceRate <= targetRate) {
null
} else {
kernelFor(targetRate / 2.0 * CUTOFF_FRACTION, sourceRate)
}
/** Samples not yet emitted: filter history plus the lookahead still owed. */
private var pending = FloatArray(0)
/** Filter one chunk, continuing from the previous call. */
fun process(chunk: FloatArray): FloatArray {
val k = kernel ?: return chunk
if (chunk.isEmpty()) return chunk
val combined = FloatArray(pending.size + chunk.size)
pending.copyInto(combined)
chunk.copyInto(combined, pending.size)
// Only samples with a full window on both sides are ready. Everything from
// here on still needs input that has not arrived.
val ready = combined.size - TAPS + 1
if (ready <= 0) {
pending = combined
return FloatArray(0)
}
val out = FloatArray(ready)
for (i in 0 until ready) {
var sum = 0f
for (t in k.indices) {
sum += k[t] * combined[i + TAPS - 1 - t]
}
out[i] = sum
}
// Carry the tail that the next chunk will complete.
pending = combined.copyOfRange(ready, combined.size)
return out
}
/** Clear pending state, e.g. after a decoder reset. */
fun reset() {
pending = FloatArray(0)
}
}
}
@@ -1,61 +0,0 @@
/*
* 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.cw
/**
* Turns the model's `log_probs` output into text.
*
* Mirrors the reference `greedy_ctc_decode`: take the best class per frame,
* drop blanks, and collapse runs of the same label. A blank between two
* identical labels is what keeps a genuine double letter (for example the
* two N's in "5NN") from collapsing into one.
*/
object CwCtcDecoder {
/**
* @param logProbs `[batch, time, class]`; only batch 0 is read.
* @param chars class index to symbol, excluding the blank.
* @param blankIndex the CTC blank class (41 for this model).
*/
fun greedy(
logProbs: Array<Array<FloatArray>>,
chars: List<String>,
blankIndex: Int
): String {
if (logProbs.isEmpty()) return ""
val frames = logProbs[0]
val builder = StringBuilder()
var previous = -1
for (frame in frames) {
var best = 0
for (i in 1 until frame.size) {
if (frame[i] > frame[best]) best = i
}
if (best == blankIndex) {
previous = -1
continue
}
if (best != previous && best < chars.size) {
builder.append(chars[best])
}
previous = best
}
return builder.toString()
}
}
@@ -1,140 +0,0 @@
/*
* 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.cw
/**
* Bounded rolling audio buffer that drives periodic full re-decodes.
*
* DeepCW is a whole-segment CTC model. It rewrites earlier output as more
* context arrives — measured on one clip, 6 of 11 progressively longer reads
* revised the prefix (`BM` -> `BG7` -> `BG7NTI` -> `BG7NTA`). Appending only
* the newest fragment therefore leaves those intermediate guesses on screen
* forever; measured character error rate for sliding-window stitching ranged
* from 67% to 294%, against 0% for decoding the whole segment at once.
*
* So we keep a fixed window, re-run the model over all of it every
* [redecodeIntervalMs], and replace the displayed text outright.
*
* Defaults come from measurement: 20 s is the smallest window that reaches
* 0.0% CER (16 s still errs at 5.9%), while inference cost grows
* super-linearly — 60 s of audio needs roughly 13x longer to decode than
* 20 s does, leaving too little real-time headroom.
*/
class CwDeepBuffer(
sampleRate: Int = CwDeepSpectrogram.SAMPLE_RATE,
maxSeconds: Double = DEFAULT_MAX_SECONDS,
private val redecodeIntervalMs: Int = DEFAULT_REDECODE_INTERVAL_MS
) {
companion object {
const val DEFAULT_MAX_SECONDS = 20.0
const val DEFAULT_REDECODE_INTERVAL_MS = 1500
}
/** Maximum number of samples retained. */
val capacity: Int = (sampleRate * maxSeconds).toInt()
private val samplesPerInterval: Int = sampleRate * redecodeIntervalMs / 1000
private val ring = FloatArray(capacity)
private var writeIndex = 0
private var filled = 0
private var sinceLastRedecode = 0
/**
* Samples evicted from the ring once it is full. They are the audio that
* has scrolled out of the 20 s window, and are handed off (via
* [drainOverflow]) so the decoder can archive them into permanent history
* instead of silently dropping the corresponding text. Pre-allocated to
* [capacity]: overflow never exceeds one window before it is drained.
*/
private val overflow = FloatArray(capacity)
private var overflowSize = 0
/** Samples currently buffered, never above [capacity]. */
val size: Int get() = filled
/** Samples currently held in the overflow (awaiting archival). */
val overflowCount: Int get() = overflowSize
/** True once there is enough audio for the spectrogram to yield a frame. */
val hasEnoughAudio: Boolean get() = filled >= CwDeepSpectrogram.FFT_LENGTH
/**
* Append captured audio, overwriting the oldest samples when full.
*
* @return true when [redecodeIntervalMs] of audio has accumulated since
* the last time this returned true, meaning the caller should re-decode.
*/
fun append(chunk: FloatArray): Boolean {
if (chunk.isNotEmpty()) {
// A chunk longer than the window can only contribute its tail.
val start = maxOf(0, chunk.size - capacity)
for (i in start until chunk.size) {
if (filled == capacity) {
// The slot we are about to overwrite holds the oldest
// sample — move it to the overflow for archival.
overflow[overflowSize++] = ring[writeIndex]
}
ring[writeIndex] = chunk[i]
writeIndex = (writeIndex + 1) % capacity
if (filled < capacity) filled++
}
}
sinceLastRedecode += chunk.size
if (sinceLastRedecode >= samplesPerInterval) {
sinceLastRedecode -= samplesPerInterval
return true
}
return false
}
/** Buffered audio in chronological order, as a copy safe to hand off. */
fun snapshot(): FloatArray {
val out = FloatArray(filled)
if (filled == 0) return out
val start = (writeIndex - filled + capacity) % capacity
val firstRun = minOf(filled, capacity - start)
ring.copyInto(out, 0, start, start + firstRun)
if (firstRun < filled) {
ring.copyInto(out, firstRun, 0, filled - firstRun)
}
return out
}
/**
* Return the evicted samples (chronological order) and clear the overflow.
* Safe to call every append; returns an empty array when nothing has been
* evicted yet.
*/
fun drainOverflow(): FloatArray {
if (overflowSize == 0) return FloatArray(0)
val out = overflow.copyOf(overflowSize)
overflowSize = 0
return out
}
/** Drop all audio (including pending overflow) and restart the interval. */
fun reset() {
writeIndex = 0
filled = 0
sinceLastRedecode = 0
overflowSize = 0
ring.fill(0f)
overflow.fill(0f)
}
}
@@ -1,242 +0,0 @@
/*
* 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.cw
import kotlin.math.PI
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.ln1p
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Audio front-end for the DeepCW model: turns PCM samples into the
* `[time, frequency]` log-magnitude spectrogram the network expects.
*
* Mirrors the upstream Python reference (deepcw-engine
* `examples/python/decode_morse.py`) step for step:
*
* resample -> 3200 Hz, reflect-pad by fft/2, periodic Hann window of 256,
* real FFT, keep bins [32, 97) i.e. 400-1200 Hz, then log1p.
*
* The model's fixed 400-1200 Hz window means pitch detection is built in —
* no spectral peak tracking or squelch gating is needed on our side.
*/
object CwDeepSpectrogram {
/** Model input sample rate, from `model.onnx.json`. */
const val SAMPLE_RATE = 3200
/** FFT window length in samples. */
const val FFT_LENGTH = 256
/** Hop between consecutive frames; 48/3200 = 15.0 ms per frame. */
const val HOP_LENGTH = 48
/**
* Lower edge of the model's analysis window. Public so [CwToneShifter] can
* decide whether a detected tone falls outside it; the value is fixed by the
* trained model and must not be changed without retraining.
*/
const val MIN_FREQ_HZ = 400.0
/** Upper edge of the model's analysis window; see [MIN_FREQ_HZ]. */
const val MAX_FREQ_HZ = 1200.0
/** Number of frequency bins the model expects. */
const val FREQUENCY_BINS = 65
/**
* Widest span worth displaying: DC to Nyquist.
*
* The model reads [MIN_FREQ_HZ]..[MAX_FREQ_HZ], but a tone outside that range leaves
* no trace inside it - measured on keyed audio, the brightest column in the narrow
* view swings 1.01x between key-down and key-up, against 13.76x for a tone the model
* can see. So the narrow view cannot even show that a signal exists, and the display
* spans the whole band instead. Nothing above Nyquist can be shown at all: it aliases.
*/
const val DISPLAY_MIN_FREQ_HZ = 0.0
/** Upper end of the display span; see [DISPLAY_MIN_FREQ_HZ]. */
const val DISPLAY_MAX_FREQ_HZ = SAMPLE_RATE / 2.0
/** Milliseconds of audio represented by one output frame. */
const val MS_PER_FRAME = 1000.0 * HOP_LENGTH / SAMPLE_RATE
private val hannWindow: FloatArray = FloatArray(FFT_LENGTH) { i ->
// numpy: np.hanning(N + 1)[:-1] — the periodic (not symmetric) variant.
(0.5 - 0.5 * cos(2.0 * PI * i / FFT_LENGTH)).toFloat()
}
/**
* Inclusive-exclusive bin range covering [minHz, maxHz].
* Returns `start to stop`, matching the reference's `frequency_bin_range`.
*/
fun frequencyBinRange(
sampleRate: Int,
fftLength: Int,
minHz: Double,
maxHz: Double
): Pair<Int, Int> {
val binHz = sampleRate.toDouble() / fftLength
val start = ceil(minHz / binHz).toInt()
val stop = floor(maxHz / binHz).toInt() + 1
return start to stop
}
/**
* Linear-interpolation resampler. Deliberately dependency-light and
* identical to the reference implementation so spectrograms match.
*/
fun resampleLinear(audio: FloatArray, sourceRate: Int, targetRate: Int): FloatArray {
if (sourceRate == targetRate || audio.isEmpty()) return audio
val targetLength = (audio.size.toDouble() * targetRate / sourceRate).roundToInt()
val out = FloatArray(targetLength)
val ratio = sourceRate.toDouble() / targetRate
for (i in 0 until targetLength) {
val position = i * ratio
val left = floor(position).toInt()
val right = minOf(left + 1, audio.size - 1)
val fraction = (position - left).toFloat()
out[i] = audio[left] * (1f - fraction) + audio[right] * fraction
}
return out
}
/**
* Build the log-magnitude spectrogram. Input must already be at
* [SAMPLE_RATE]; use [resampleLinear] first when it is not.
*
* @return `[frames][FREQUENCY_BINS]` values, all non-negative.
*/
fun compute(
audio: FloatArray,
minHz: Double = MIN_FREQ_HZ,
maxHz: Double = MAX_FREQ_HZ
): Array<FloatArray> {
require(audio.size >= FFT_LENGTH) {
"audio is too short for fftLength=$FFT_LENGTH, got ${audio.size}"
}
val (startBin, stopBin) = frequencyBinRange(SAMPLE_RATE, FFT_LENGTH, minHz, maxHz)
val bins = stopBin - startBin
require(bins > 0) { "empty bin range for $minHz..${maxHz}Hz" }
// The model's range must yield exactly the bin count it was trained on. Written as
// an implication rather than a disjunction of all three terms: `a != x || b != y ||
// bins == n` is satisfied by any custom range regardless of the bin count, which
// would leave the invariant unenforced for the caller most likely to break it.
val isModelRange = minHz == MIN_FREQ_HZ && maxHz == MAX_FREQ_HZ
require(!isModelRange || bins == FREQUENCY_BINS) {
"expected $FREQUENCY_BINS bins for the model range, computed $bins"
}
// Nothing may run off the end of the FFT output: a real signal has FFT_LENGTH / 2
// + 1 distinct bins, and asking beyond Nyquist would index past them.
require(stopBin <= FFT_LENGTH / 2 + 1) {
"maxHz ${maxHz}Hz is above Nyquist ${SAMPLE_RATE / 2}Hz"
}
val padded = reflectPad(audio, FFT_LENGTH / 2)
val frames = 1 + (padded.size - FFT_LENGTH) / HOP_LENGTH
val result = Array(frames) { FloatArray(bins) }
val real = FloatArray(FFT_LENGTH)
val imag = FloatArray(FFT_LENGTH)
for (frame in 0 until frames) {
val offset = frame * HOP_LENGTH
for (i in 0 until FFT_LENGTH) {
real[i] = padded[offset + i] * hannWindow[i]
imag[i] = 0f
}
fftInPlace(real, imag)
val row = result[frame]
for (bin in startBin until stopBin) {
val magnitude = sqrt(real[bin] * real[bin] + imag[bin] * imag[bin])
row[bin - startBin] = ln1p(magnitude.toDouble()).toFloat()
}
}
return result
}
/**
* numpy `mode="reflect"`: mirrors around the edge samples without
* repeating them, so [1,2,3] padded by 2 becomes [3,2,1,2,3,2,1].
*/
private fun reflectPad(audio: FloatArray, pad: Int): FloatArray {
if (pad == 0) return audio
val out = FloatArray(audio.size + 2 * pad)
for (i in 0 until pad) out[i] = audio[pad - i]
audio.copyInto(out, pad)
val last = audio.size - 1
for (i in 0 until pad) out[pad + audio.size + i] = audio[last - 1 - i]
return out
}
/**
* Iterative radix-2 Cooley-Tukey FFT. [FFT_LENGTH] is a power of two, so
* no padding case is needed. Only the first half of the output is read by
* [compute], which is the real-input equivalent of numpy's `rfft`.
*/
private fun fftInPlace(real: FloatArray, imag: FloatArray) {
val n = real.size
// Bit-reversal permutation.
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) {
j = j xor bit
bit = bit shr 1
}
j = j or bit
if (i < j) {
var tmp = real[i]; real[i] = real[j]; real[j] = tmp
tmp = imag[i]; imag[i] = imag[j]; imag[j] = tmp
}
}
var length = 2
while (length <= n) {
val angle = -2.0 * PI / length
val wReal = cos(angle).toFloat()
val wImag = kotlin.math.sin(angle).toFloat()
var i = 0
while (i < n) {
var curReal = 1f
var curImag = 0f
for (k in 0 until length / 2) {
val evenReal = real[i + k]
val evenImag = imag[i + k]
val oddReal = real[i + k + length / 2]
val oddImag = imag[i + k + length / 2]
val mulReal = oddReal * curReal - oddImag * curImag
val mulImag = oddReal * curImag + oddImag * curReal
real[i + k] = evenReal + mulReal
imag[i + k] = evenImag + mulImag
real[i + k + length / 2] = evenReal - mulReal
imag[i + k + length / 2] = evenImag - mulImag
val nextReal = curReal * wReal - curImag * wImag
curImag = curReal * wImag + curImag * wReal
curReal = nextReal
}
i += length
}
length = length shl 1
}
}
}
@@ -1,88 +0,0 @@
/*
* 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.cw
/**
* Pools capture chunks until enough audio is available for tone detection.
*
* [CwToneShifter.detectToneHz] scans bin by bin, so it needs a few hundred
* milliseconds to resolve a pitch. A capture chunk is only 320 samples once
* resampled to [CwDeepSpectrogram.SAMPLE_RATE], hence the pooling: without it a
* per-chunk size check can never be satisfied and detection silently never runs.
*
* A ring buffer rather than a sliding array. Detection is throttled to a couple of
* seconds while the pool fills in a few hundred milliseconds, so most chunks arrive
* at a full buffer; shifting the array down one slot per sample cost 320 copies of
* 1280 floats per chunk, measured at 24320 whole-array moves per 10 s of audio on
* the capture thread. Writing to a ring index is O(1).
*
* Not thread-safe: the decoder drives it from a single capture coroutine.
*
* @param capacity samples retained; also the size [drain] returns once full.
*/
class CwDetectionPool(val capacity: Int) {
init {
require(capacity > 0) { "capacity must be positive, was $capacity" }
}
private val samples = FloatArray(capacity)
private var writeIndex = 0
/** Samples currently pooled, never above [capacity]. */
var size: Int = 0
private set
/** True once [capacity] samples are pooled and detection can run. */
val isReady: Boolean get() = size >= capacity
/** Add a chunk, overwriting the oldest samples once full. */
fun add(chunk: FloatArray) {
if (chunk.isEmpty()) return
// A chunk longer than the pool can only contribute its tail.
val start = maxOf(0, chunk.size - capacity)
for (i in start until chunk.size) {
samples[writeIndex] = chunk[i]
writeIndex = (writeIndex + 1) % capacity
if (size < capacity) size++
}
}
/**
* Hand over the pooled audio in chronological order and empty the pool.
*
* Oldest sample first: the detector measures a waveform, so returning the ring in
* storage order would splice it at the wrap point and corrupt every estimate.
*/
fun drain(): FloatArray {
val out = FloatArray(size)
// Once full the oldest sample sits at the write cursor; before that at index 0.
val oldest = if (size == capacity) writeIndex else 0
for (i in 0 until size) {
out[i] = samples[(oldest + i) % capacity]
}
clear()
return out
}
/** Discard everything pooled so far. */
fun clear() {
size = 0
writeIndex = 0
}
}
@@ -1,115 +0,0 @@
/*
* 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.cw
import kotlin.math.abs
/**
* Decides what shift to apply from a sequence of tone estimates.
*
* Kept out of the decoder so the rule can be exercised directly. The decoder needs an
* Android Context and a loaded ONNX session, so a rule living inside it can only be
* tested by restating it - and a restated rule cannot fail when the real one is wrong.
* Mutation testing proved that: four defects injected into an in-decoder version of this
* logic left the whole suite green.
*
* @param hysteresisHz how far the tone must move before the shift is revised.
*/
class CwShiftDecider(private val hysteresisHz: Float = DEFAULT_HYSTERESIS_HZ) {
companion object {
/**
* Default margin before re-shifting, in Hz.
*
* Detection resolves to 12.5 Hz and a real tone wanders, so a couple of scan bins
* of jitter must not count as a retune: revising the shift costs the whole 20 s
* decode window, which is worth far more than perfect centring.
*/
const val DEFAULT_HYSTERESIS_HZ = 40f
}
/** Shift currently applied to incoming audio; 0 when the tone needs no move. */
var shiftHz: Float = 0f
private set
/**
* Tone that produced [shiftHz]. Hysteresis compares against this rather than against
* the previous shift, because a shift of 0 is a real state: at the window edge one
* 12.5 Hz estimate hop flips between "inside" (shift 0) and "outside" (a large
* shift), and a shift-space comparison lapses exactly where the jump is largest.
*/
var anchorToneHz: Float? = null
private set
/** What [accept] decided, for logging. */
enum class Outcome {
/** No tone in the window; the existing shift was retained. */
NO_TONE,
/** The tone moved less than the margin; the existing shift was retained. */
WITHIN_HYSTERESIS,
/** The tone is inside the model window, so no shift is needed. */
NO_SHIFT_NEEDED,
/** The shift was updated to move an out-of-window tone into range. */
SHIFTED
}
/** Result of feeding one detection to the decider. */
data class Decision(
val outcome: Outcome,
/** Shift in force after the decision. */
val shiftHz: Float,
/** True when [shiftHz] differs from the value before this decision. */
val changed: Boolean,
/** Tone the decision was based on, null when none was detected. */
val toneHz: Float?
)
/**
* Feed one tone analysis and get the shift to apply.
*
* Silence retains the current shift rather than clearing it: CW is keyed, so a
* detection window landing in a gap carries no information about the pitch. Treating
* it as an authoritative "no shift" collapsed established shifts - measured over
* 180 s of keyed audio at 1400 Hz, 11 of 90 windows saw no tone, and each one left
* the following audio unshifted and therefore invisible to the model.
*/
fun accept(analysis: CwToneShifter.Analysis): Decision {
val previousShift = shiftHz
val toneHz = analysis.toneHz
?: return Decision(Outcome.NO_TONE, previousShift, changed = false, toneHz = null)
val anchor = anchorToneHz
if (anchor != null && abs(toneHz - anchor) < hysteresisHz) {
return Decision(Outcome.WITHIN_HYSTERESIS, previousShift, changed = false, toneHz = toneHz)
}
shiftHz = analysis.shiftHz
anchorToneHz = toneHz
val outcome = if (analysis.needsShift) Outcome.SHIFTED else Outcome.NO_SHIFT_NEEDED
return Decision(outcome, shiftHz, changed = shiftHz != previousShift, toneHz = toneHz)
}
/** Forget the current shift and anchor, e.g. when the feature is toggled or reset. */
fun reset() {
shiftHz = 0f
anchorToneHz = null
}
}
@@ -1,323 +0,0 @@
/*
* 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.cw
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.hypot
import kotlin.math.sin
/**
* Moves an out-of-range CW tone into the model's analysis window.
*
* The DeepCW model only sees [CwDeepSpectrogram.MIN_FREQ_HZ]..[CwDeepSpectrogram.MAX_FREQ_HZ];
* its input tensor width is fixed, so the window itself cannot be widened without
* retraining. Instead a tone that sits outside the window is frequency-shifted to
* [TARGET_HZ] before the spectrogram is built, which extends the usable pitch range
* to roughly 100 Hz..Nyquist without touching the model.
*
* ### Why single-sideband mixing
* Plain real mixing (`x * cos(2*pi*delta*t)`) produces both `tone+delta` and
* `tone-delta`. Measured on a 1500 Hz tone shifted to 800 Hz, the unwanted image
* folded back to 1000 Hz at 0.999 of the wanted amplitude — inside the window and
* as loud as the signal. Upsampling first only moves the problem: shifting a 300 Hz
* tone up produced a 200 Hz image at 0.996.
*
* A Hilbert transformer removes the negative-frequency half first, so mixing the
* resulting analytic signal yields one sideband only. Across nine probe tones
* (150..1550 Hz) that leaves a single spectral peak at the target with no component
* above 0.3 relative amplitude.
*
* All functions are pure; the caller decides whether shifting is wanted.
*/
object CwToneShifter {
/**
* Where an out-of-window tone is moved to: the centre of the analysis window,
* so the keying sidebands have equal headroom on both sides.
*/
const val TARGET_HZ = 800.0
/**
* Tones below this are treated as absent rather than shifted. Mains hum and DC
* drift live down here, and a real CW note that low is unusable anyway.
*/
const val MIN_DETECTABLE_HZ = 100.0
/**
* A detected peak must exceed the spectrum mean by this factor to count as a tone.
*
* Chosen from measurements on 1280-sample (400 ms) windows of keyed CW in noise.
* Pure noise peaks at 2.2-3.4 times its own spectral mean, so 3.0 admitted roughly
* one noise window in five. Raising it as far as 8.0 then rejected comfortably
* copyable signals: keyed CW measures 7.6-9.0 at 0 dB SNR and only 5.2-6.7 at -3 dB.
*
* 4.5 gives zero false positives across 40 noise windows while keeping the weaker
* end of usable signals. The asymmetry is deliberate: a false tone is worse than a
* missed one, because it moves a perfectly good signal out of the model's range,
* whereas a miss just leaves the audio alone until a stronger window arrives.
*
* Windows dominated by keying gaps (a slow fist, under ~25% tone) sit at 2.4 and are
* indistinguishable from noise at any threshold; those are skipped, not guessed at.
*/
const val MIN_PROMINENCE = 4.5
/** Hilbert transformer length. Odd so the group delay is a whole sample. */
private const val HILBERT_TAPS = 63
/** Frequency resolution of [detectToneHz], in Hz. */
private const val DETECT_STEP_HZ = 12.5
/** Windowed Hilbert transformer: h[n] = 2/(pi*n) for odd n, 0 otherwise. */
private val hilbertKernel: FloatArray = FloatArray(HILBERT_TAPS) { i ->
val n = i - HILBERT_TAPS / 2
val ideal = if (n == 0 || n % 2 == 0) 0.0 else 2.0 / (PI * n)
// Hamming window; without it the truncated kernel ripples badly.
val window = 0.54 - 0.46 * cos(2.0 * PI * i / (HILBERT_TAPS - 1))
(ideal * window).toFloat()
}
/** Group delay of [hilbertKernel], applied to the real path to keep them aligned. */
private const val HILBERT_DELAY = HILBERT_TAPS / 2
/** Outcome of inspecting a chunk of audio. */
data class Analysis(
/** Detected tone in Hz, or null when the audio is noise. */
val toneHz: Float?,
/** True when [toneHz] sits outside the model's window and can be shifted. */
val needsShift: Boolean,
/** Hz the tone would be moved by; 0 when no shift applies. */
val shiftHz: Float
)
/**
* Estimate the dominant tone by scanning [MIN_DETECTABLE_HZ]..Nyquist with a
* Goertzel-style single-bin DFT.
*
* Deliberately not reusing [CwDeepSpectrogram]: that clips to the model window,
* which is exactly the region an out-of-range tone is *not* in.
*
* @return the peak frequency, or null when nothing stands out from the noise.
*/
fun detectToneHz(audio: FloatArray, sampleRate: Int): Float? {
if (audio.size < 64) return null
val nyquist = sampleRate / 2.0
// A Hann window stops the scan from smearing energy across neighbours.
val window = FloatArray(audio.size) { i ->
(0.5 - 0.5 * cos(2.0 * PI * i / (audio.size - 1))).toFloat()
}
var bestHz = 0.0
var bestMagnitude = 0.0
var total = 0.0
var bins = 0
var hz = MIN_DETECTABLE_HZ
while (hz <= nyquist) {
var real = 0.0
var imag = 0.0
val omega = 2.0 * PI * hz / sampleRate
for (i in audio.indices) {
val value = audio[i] * window[i]
real += value * cos(omega * i)
imag -= value * sin(omega * i)
}
val magnitude = hypot(real, imag) / audio.size
total += magnitude
bins++
if (magnitude > bestMagnitude) {
bestMagnitude = magnitude
bestHz = hz
}
hz += DETECT_STEP_HZ
}
if (bins == 0 || bestMagnitude <= 0.0) return null
val mean = total / bins
// Pure noise has a flat spectrum, so the peak barely beats the mean.
if (mean <= 0.0 || bestMagnitude < mean * MIN_PROMINENCE) return null
return bestHz.toFloat()
}
/**
* Decide whether [audio] needs shifting, without modifying it.
*
* A tone already inside the window is left alone: shifting it would add filter
* ringing and rounding for no benefit, and the model handles it natively.
*/
fun analyse(audio: FloatArray, sampleRate: Int): Analysis {
val tone = detectToneHz(audio, sampleRate)
?: return Analysis(toneHz = null, needsShift = false, shiftHz = 0f)
val inWindow = tone >= CwDeepSpectrogram.MIN_FREQ_HZ && tone <= CwDeepSpectrogram.MAX_FREQ_HZ
if (inWindow) return Analysis(toneHz = tone, needsShift = false, shiftHz = 0f)
return Analysis(
toneHz = tone,
needsShift = true,
shiftHz = (TARGET_HZ - tone).toFloat()
)
}
/**
* Shift [audio] by [shiftHz] using single-sideband mixing.
*
* The Hilbert transformer suppresses the negative-frequency half, so only the
* wanted sideband survives; see the class docs for the measured alternative.
* Returns a new array; [audio] is not modified.
*
* Stateless: [audio] is treated as an isolated signal, so the first and last
* [HILBERT_DELAY] samples convolve against zeros instead of the neighbouring
* audio. Fine for a whole buffer, but it corrupts 62 of every 320 samples when
* called per capture chunk, so streaming callers must use [Streaming].
*/
fun shift(audio: FloatArray, shiftHz: Float, sampleRate: Int): FloatArray {
if (shiftHz == 0f || audio.isEmpty()) return audio
// Quadrature path: audio convolved with the Hilbert kernel.
val quadrature = FloatArray(audio.size)
for (i in audio.indices) {
var sum = 0f
for (k in hilbertKernel.indices) {
val j = i - k + HILBERT_DELAY
if (j >= 0 && j < audio.size) sum += hilbertKernel[k] * audio[j]
}
quadrature[i] = sum
}
// Re{(inPhase + j*quadrature) * e^(j*2*pi*shift*t)}
val out = FloatArray(audio.size)
val step = 2.0 * PI * shiftHz / sampleRate
for (i in audio.indices) {
val phase = step * i
out[i] = clampToUnit(audio[i] * cos(phase) - quadrature[i] * sin(phase))
}
return out
}
/**
* Chunk-by-chunk shifter that carries the state [shift] cannot.
*
* Two things must survive across calls for concatenated chunks to form a clean
* signal:
*
* 1. **Filter history.** The Hilbert FIR spans [HILBERT_TAPS] samples, so the
* first outputs of a chunk need the previous chunk's tail. Without it those
* samples convolve against zeros; measured on 320-sample chunks that distorts
* 62 of them (19%) and inflates envelope ripple to 8.7x the whole-buffer
* baseline.
* 2. **Mixer phase.** Restarting the local oscillator at zero every chunk puts a
* phase step at every boundary.
*
* One difference from [shift] remains and is unavoidable: output sample `i` ideally
* needs input up to `i + HILBERT_DELAY`, which for the last samples of a chunk has
* not been captured yet. Those trailing taps therefore see zeros. Measured against
* a whole-buffer shift the divergence is confined to the final 3 samples of each
* 320-sample chunk and disappears immediately after the boundary — under 1% of the
* audio, versus a 20 WPM dot spanning 192 samples. Buffering a chunk to remove it
* would add 10 ms of latency for no decoding benefit.
*
* Not thread-safe: the decoder drives it from a single capture coroutine.
*/
class Streaming {
private val history = FloatArray(HILBERT_TAPS - 1)
private var phase = 0.0
/** Shift one chunk, continuing the filter and oscillator state. */
fun process(chunk: FloatArray, shiftHz: Float, sampleRate: Int): FloatArray {
if (shiftHz == 0f || chunk.isEmpty()) {
// Still advance the history, so enabling a shift later starts from real
// audio rather than the silence left over from before.
pushHistory(chunk)
return chunk
}
// Convolve over [history || chunk] so every output sees real samples.
val combined = FloatArray(history.size + chunk.size)
history.copyInto(combined)
chunk.copyInto(combined, history.size)
val out = FloatArray(chunk.size)
val step = 2.0 * PI * shiftHz / sampleRate
for (i in chunk.indices) {
val centre = history.size + i
var quadrature = 0f
for (k in hilbertKernel.indices) {
val j = centre - k + HILBERT_DELAY
if (j >= 0 && j < combined.size) quadrature += hilbertKernel[k] * combined[j]
}
val currentPhase = phase + step * i
val mixed = combined[centre] * cos(currentPhase) - quadrature * sin(currentPhase)
out[i] = clampToUnit(mixed)
}
// Keep the phase bounded; letting it grow loses float precision.
phase = (phase + step * chunk.size) % (2.0 * PI)
pushHistory(chunk)
return out
}
/** Clear filter history and phase, e.g. after a decoder reset. */
fun reset() {
history.fill(0f)
phase = 0.0
}
/** Keep the most recent [history] samples of the stream. */
private fun pushHistory(chunk: FloatArray) {
if (chunk.isEmpty()) return
if (chunk.size >= history.size) {
chunk.copyInto(history, 0, chunk.size - history.size, chunk.size)
} else {
history.copyInto(history, 0, chunk.size, history.size)
chunk.copyInto(history, history.size - chunk.size)
}
}
}
/**
* Convenience wrapper: analyse [audio] and shift it only when the tone is
* outside the model window.
*
* @return the audio to feed the model (the original array when no shift was
* needed) paired with the [Analysis] that produced the decision, so callers
* can log what happened.
*/
fun shiftIfOutsideWindow(audio: FloatArray, sampleRate: Int): Pair<FloatArray, Analysis> {
val analysis = analyse(audio, sampleRate)
if (!analysis.needsShift) return audio to analysis
return shift(audio, analysis.shiftHz, sampleRate) to analysis
}
/**
* Keep a mixed sample inside the +/-1.0 range the spectrogram assumes.
*
* The Hilbert kernel has an L1 gain of 2.51, so summing the in-phase and quadrature
* paths can exceed unity even for a full-scale sine (measured 1.05 at 1500 Hz, 2.35
* for a square wave). The spectrogram takes log1p of the magnitude, so an overshoot
* is not fatal, but it shifts the level the model was trained on.
*/
private fun clampToUnit(value: Double): Float = when {
value > 1.0 -> 1f
value < -1.0 -> -1f
else -> value.toFloat()
}
/** True when [toneHz] lies inside the model's analysis window. */
fun isInsideWindow(toneHz: Float): Boolean =
toneHz >= CwDeepSpectrogram.MIN_FREQ_HZ && toneHz <= CwDeepSpectrogram.MAX_FREQ_HZ
}
@@ -1,98 +0,0 @@
/*
* 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.cw
import kotlinx.coroutines.flow.StateFlow
/**
* A CW (Morse code) decoder fed with microphone PCM.
*
* Implementations live outside `core:domain` when they need platform APIs;
* this contract stays pure Kotlin so the UI can depend on it directly.
*/
interface ICwDecoder {
/**
* Decoded text for the *current* window.
*
* Note this is **replace** semantics, not append: a whole-segment model
* revises earlier characters as more audio arrives, so consumers must show
* the current value rather than accumulating emissions.
*/
val decodedText: StateFlow<String>
/**
* Transcript of audio that has been archived, and will not be revised.
*
* Only ever grows until [reset]. [decodedText] is rewritten from scratch on every
* redecode, so a pane that concatenates it loses text the operator has already read -
* which a paper log does not do. This is the flow such a pane must bind to.
*/
val historyText: StateFlow<String>
/**
* Pitch of the tone the model is decoding, in Hz, or null before one is found.
*
* Derived from the spectrogram, so it can only ever report a frequency inside the
* model's analysis window. For the pitch of a tone the model cannot see, use
* [detectedToneHz].
*/
val estimatedPitch: StateFlow<Float?>
/**
* Pitch of the loudest tone in the raw audio, in Hz, or null when none stands out.
*
* Unlike [estimatedPitch] this is measured before any shifting and over the full
* audio bandwidth, so it can report a tone the model's window excludes — which is
* the only way to tell the operator that nothing is being decoded because their tone
* is out of range.
*/
val detectedToneHz: StateFlow<Float?>
/** Current shift applied to bring the tone into the model's window, 0f when idle. */
val activeShiftHz: StateFlow<Float>
/** Relative signal strength in 0..1 for level meters. */
val signalStrength: StateFlow<Float>
/** Most recent inference duration in milliseconds, for diagnostics. */
val lastInferenceMs: StateFlow<Int>
/** Non-null when the decoder cannot run, for example the model failed to load. */
val errorMessage: StateFlow<String?>
/**
* Decode whatever audio is still held in the pipeline into [historyText].
*
* Nothing reaches [historyText] until audio has been pushed out of the live window and
* then accumulated into a full archive batch, so the last stretch of a session is always
* still in flight when capture stops - and neither holding place drains on its own. That
* stretch is the end of the transmission, the part with the call sign in it. Call on
* pause and before [close].
*/
suspend fun flush()
/** Feed captured mono PCM in -1..1. Safe to call from a capture thread. */
suspend fun processBuffer(samples: FloatArray, sampleRate: Int)
/** Clear decoded text and buffered audio. */
fun reset()
/** Release native resources. Must be called when the decoder goes away. */
fun close()
}
@@ -1,143 +0,0 @@
/*
* 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.navigation
/**
* Single source of truth for the navigation menu layout.
*
* The bottom bar holds at most [MAIN_SLOTS] pages; the rest live behind the More
* button. Both the bar and the settings editor resolve through here, so the list
* the user edits is exactly the list they get.
*
* Lives in `core:domain` (pure Kotlin) so it is unit-testable and KMP-ready.
*/
object MenuLayout {
/** Bottom-bar capacity, including the Settings entry. */
const val MAIN_SLOTS = 5
/** Must stay reachable from some menu, so the user cannot lock themselves out. */
const val SETTINGS_ID = "Settings"
/** Bar contents for a fresh install. */
val defaultMainOrder = listOf("Satellites", "Passes", "Radar", "Map", SETTINGS_ID)
/** More-menu contents for a fresh install. */
val defaultMoreOrder = listOf("Mutual", "Roaming", "CwDecode", "WavelogLog", "AMSAT")
/** What the bar and the More menu actually show. */
data class Layout(val mainIds: List<String>, val moreIds: List<String>)
/** A menu assignment ready to be persisted to settings. */
data class Assignment(val screenOrder: List<String>, val subMenuOrder: List<String>)
/**
* Map persisted preferences onto the two menus.
*
* A page named by neither persisted list is new to this install and follows
* the defaults, so upgrades never lose pages. Visible pages that overflow
* [MAIN_SLOTS] fall through to the More menu instead of disappearing, and
* [SETTINGS_ID] always survives the slot cut.
*/
fun resolve(
allScreenIds: List<String>,
screenOrder: List<String>,
subMenuOrder: List<String>,
hiddenScreenIds: List<String>
): Layout {
val visible = allScreenIds.filter { it !in hiddenScreenIds || it == SETTINGS_ID }
val wantMain = ArrayList<String>()
val wantMore = ArrayList<String>()
for (id in visible) {
when {
id in screenOrder -> wantMain.add(id)
id in subMenuOrder -> wantMore.add(id)
id in defaultMainOrder -> wantMain.add(id)
else -> wantMore.add(id)
}
}
wantMain.sortBy { rank(it, screenOrder, defaultMainOrder) }
wantMore.sortBy { rank(it, subMenuOrder, defaultMoreOrder) }
// Reserve the Settings slot before cutting so it cannot be truncated away.
val settingsOnBar = SETTINGS_ID in wantMain
val budget = if (settingsOnBar) MAIN_SLOTS - 1 else MAIN_SLOTS
val main = ArrayList<String>(MAIN_SLOTS)
for (id in wantMain) {
if (id == SETTINGS_ID) continue
if (main.size == budget) break
main.add(id)
}
if (settingsOnBar) main.add(SETTINGS_ID)
val overflow = wantMain.filter { it !in main }
return Layout(mainIds = main, moreIds = overflow + wantMore)
}
/** Move [screenId] onto the bar, evicting the last movable page when full. */
fun moveToMain(
screenId: String,
allScreenIds: List<String>,
screenOrder: List<String>,
subMenuOrder: List<String>
): Assignment {
val current = resolve(allScreenIds, screenOrder, subMenuOrder, emptyList())
val main = current.mainIds.toMutableList()
val more = current.moreIds.toMutableList()
val wasInMore = screenId in more
more.remove(screenId)
if (screenId !in main) {
val at = main.indexOf(SETTINGS_ID).let { if (it == -1) main.size else it }
main.add(at, screenId)
}
// Only evict when we actually added a new page from More; internal reordering must not evict.
if (wasInMore) {
val movable = main.filter { it != SETTINGS_ID && it != screenId }
if (main.size > MAIN_SLOTS && movable.isNotEmpty()) {
val evicted = movable.last()
main.remove(evicted)
more.add(0, evicted)
}
}
return Assignment(screenOrder = main, subMenuOrder = more)
}
/** Move [screenId] off the bar; Settings is refused so it stays reachable. */
fun moveToMore(
screenId: String,
allScreenIds: List<String>,
screenOrder: List<String>,
subMenuOrder: List<String>
): Assignment {
if (screenId == SETTINGS_ID) return Assignment(screenOrder, subMenuOrder)
val current = resolve(allScreenIds, screenOrder, subMenuOrder, emptyList())
val more = current.moreIds.toMutableList()
if (screenId !in more) more.add(screenId)
return Assignment(
screenOrder = current.mainIds.filter { it != screenId },
subMenuOrder = more
)
}
private fun rank(id: String, persisted: List<String>, fallback: List<String>): Int {
val persistedIndex = persisted.indexOf(id)
if (persistedIndex != -1) return persistedIndex
val fallbackIndex = fallback.indexOf(id)
return if (fallbackIndex != -1) fallbackIndex else Int.MAX_VALUE
}
}
@@ -1,45 +0,0 @@
/*
* 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.qrz
/**
* Looks up a station's grid square on QRZ.
*
* An interface so the log screen can ask for a grid without reaching into core:data, and without
* reading the stored cookie itself - a composable was fetching it straight out of
* SharedPreferences through LocalContext, which put disk access in composition and bypassed the
* repository layer entirely.
*/
interface IQrzGridLookup {
/**
* Look up [callsign].
*
* Returns [QrzGrid.SignedOut] when no cookie is stored, since the operator's remedy is the
* same either way: put a valid cookie in settings.
*/
suspend fun lookup(callsign: String): QrzGrid
/**
* Check the stored cookie by asking QRZ whose account it belongs to.
*
* Returns the callsign QRZ reports, or null when the cookie is absent or no longer valid. Lets
* settings tell the operator which account they pasted rather than only claiming success.
*/
suspend fun signedInAs(): String?
}
@@ -1,106 +0,0 @@
/*
* 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.qrz
/**
* Outcome of a QRZ grid lookup.
*
* Four outcomes rather than a nullable string, because the previous null meant any of "the
* station has no grid on file", "the cookie expired", "the request timed out" and "QRZ changed
* its markup" - and the operator saw the same blank either way, with no way to tell that
* re-pasting the cookie would fix it.
*/
sealed interface QrzGrid {
/** The station's Maidenhead locator, as QRZ has it. */
data class Found(val locator: String) : QrzGrid
/** The page was read and the station has no locator published. Not an error. */
data object NotOnFile : QrzGrid
/** The detail table was absent, which is what QRZ serves when the cookie is not valid. */
data object SignedOut : QrzGrid
/** The request never completed. [attempts] is how many tries were made before giving up. */
data class Unreachable(val attempts: Int) : QrzGrid
}
/**
* Parsing of QRZ's callsign page, separate from the fetch so it can be tested without a
* network. Pure string work over already-downloaded markup.
*/
object QrzGridParser {
/** The detail row QRZ renders for a station that published a locator. */
private val gridRow = Regex("""<td class="dh">Grid Square</td>\s*<td class="di">([^<]+)</td>""")
/**
* QRZ's own words on a callsign page served to a visitor who is not signed in.
*
* Classified on this positive notice rather than on the detail table being absent: measured
* against live responses, a callsign QRZ has never heard of also returns HTTP 200 with zero
* detail rows, because QRZ serves its search form instead of a callsign page. Keying on
* absence therefore reported a mistyped callsign as an expired cookie, and would have sent
* the operator off to re-paste a cookie that was never broken.
*/
private val signedOutNotice = Regex("""Login is required for additional detail""")
/** The account menu on a signed-in page, used to read back whose cookie this is. */
private val accountCallsign = Regex("""<li class="leaf last"[^>]*>\s*([A-Z0-9/]+)\s*<ul""")
/** A cookie name=value pair inside a browser extension's JSON export. */
private val jsonCookie = Regex(""""name"\s*:\s*"([^"]+)"\s*,\s*"value"\s*:\s*"([^"]*)"""")
/**
* Interpret a callsign page.
*
* Only QRZ explicitly saying that a login is required counts as signed out, so an absent
* locator degrades to the harmless [QrzGrid.NotOnFile] and only a genuinely stale cookie
* sends the operator back to settings. Getting this wrong in either direction misdirects
* them: the old client returned null for everything, and keying on the detail table being
* absent would have blamed the cookie for a mistyped callsign.
*/
fun parseGrid(html: String): QrzGrid {
val locator = gridRow.find(html)?.groupValues?.get(1)?.trim()
if (!locator.isNullOrBlank()) return QrzGrid.Found(locator)
if (signedOutNotice.containsMatchIn(html)) return QrzGrid.SignedOut
return QrzGrid.NotOnFile
}
/** The callsign this cookie is signed in as, or null when it is not signed in. */
fun parseOwnCallsign(html: String): String? =
accountCallsign.find(html)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotBlank() }
/**
* Normalise the pasted cookie into a Cookie header value.
*
* Accepts a raw `k=v; k=v` header or the JSON array a cookie-export extension produces,
* since the operator pastes whatever their browser handed them. Parsed by regex rather
* than a JSON library so it needs no extra dependency and stays testable as plain text.
*/
fun cookieHeader(raw: String): String {
val text = raw.trim()
if (text.isEmpty()) return ""
if (!text.startsWith("[")) return text
val pairs = jsonCookie.findAll(text)
.map { it.groupValues[1] to it.groupValues[2] }
.filter { it.first.isNotBlank() }
.toList()
return if (pairs.isEmpty()) text else pairs.joinToString("; ") { "${it.first}=${it.second}" }
}
}
@@ -1,28 +0,0 @@
/*
* 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.source
/** Minimal platform HTTP client used by Wavelog/QRZ features. Implemented per platform
* (OkHttp on Android, NSURLSession on iOS). */
interface IHttpClient {
suspend fun post(url: String, headers: Map<String, String>, body: String): HttpResult
suspend fun get(url: String, headers: Map<String, String>): HttpResult
}
/** [code] is the HTTP status code, or 0 when the request could not be sent at all. */
data class HttpResult(val code: Int, val body: String, val failure: String? = null)
@@ -1,34 +0,0 @@
/*
* 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.source
interface IRemoteSource {
suspend fun getFileBytes(uri: String): ByteArray?
suspend fun getNetworkBytes(url: String): ByteArray?
/** Fetch AMSAT API catalog (JSON string; null on failure) */
suspend fun getAmSatCatalog(): String?
/** Fetch AMSAT API reports for the past N hours (JSON string; null on failure) */
suspend fun getAmSatReports(hours: Int, limit: Int): String?
/** Fetch AMSAT API summary for the past N hours (JSON string; null on failure).
* Used to compare against the global reports response and flag satellites whose data
* was crowded out of the 500-record cap. */
suspend fun getAmSatSummary(hours: Int): String?
}
@@ -1,67 +0,0 @@
/*
* 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.source
object Sources {
// Default URL for online updates (user can change/reset it via the "Custom URL" dialog)
val defaultTleUrl = "https://celestrak.org/NORAD/elements/gp.php?GROUP=active&FORMAT=csv"
val defaultTransceiversUrl = "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",
"Brightest" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=visual&FORMAT=csv",
"Cubesat" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=cubesat&FORMAT=csv",
"Education" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=education&FORMAT=csv",
"Engineer" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=engineering&FORMAT=csv",
"Geostationary" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=geo&FORMAT=csv",
"Globalstar" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=globalstar&FORMAT=csv",
"GNSS" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=gnss&FORMAT=csv",
"Intelsat" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=intelsat&FORMAT=csv",
"Iridium" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=iridium-NEXT&FORMAT=csv",
"Military" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=military&FORMAT=csv",
"New" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=last-30-days&FORMAT=csv",
"OneWeb" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=oneweb&FORMAT=csv",
"Orbcomm" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=orbcomm&FORMAT=csv",
"Resource" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=resource&FORMAT=csv",
"SatNOGS" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=satnogs&FORMAT=csv",
"Science" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=science&FORMAT=csv",
"Spire" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=spire&FORMAT=csv",
"Starlink" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=starlink&FORMAT=csv",
"Swarm" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=swarm&FORMAT=csv",
"Weather" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=weather&FORMAT=csv",
"X-Comm" to "https://celestrak.org/NORAD/elements/gp.php?GROUP=x-comm&FORMAT=csv",
"Amsat" to "https://amsat.org/tle/current/nasabare.txt",
"Classified" to "https://www.mmccants.org/tles/classfd.zip",
"McCants" to "https://www.mmccants.org/tles/inttles.zip",
"R4UAB" to "https://r4uab.ru/satonline.txt",
"Other" to "" // key for sats filter
)
val satelliteModes = listOf(
"4FSK", "64-QAM", "AFSK", "AFSK TUBiX10", "AHRPT", "AM", "APT", "ASK", "BPSK",
"BPSK PMT-A3", "CERTO", "CW", "DATV", "DBPSK", "DOKA", "DPSK", "DQPSK", "DSB", "DSTAR",
"DUV", "DVB-S2", "FFSK", "FM", "FMN", "FSK", "FSK AX.100 Mode 5", "FSK AX.100 Mode 6",
"FSK AX.25 G3RUH", "FT8", "GENESIS FSK", "GFSK", "GFSK Pkst", "GFSK Rktr", "GFSK/BPSK",
"GMSK", "GMSK USP", "HRPT", "LoRa", "LRPT", "LSB", "MFSK", "MSK", "MSK AX.100 Mode 5",
"MSK AX.100 Mode 6", "OFDM", "OQPSK", "PPM", "PSK", "PSK31", "PSK63", "QPSK", "QPSK31",
"QPSK63", "SIDLOC", "SQPSK", "SSDV", "SSTV", "UNKNOWN", "USB", "WSJT"
)
val transceiversDataUrls = mapOf(
"SatNOGS" to "https://db.satnogs.org/api/transmitters/?format=json&status=active"
)
}
@@ -1,33 +0,0 @@
/*
* 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.usecase
interface IShowToast {
operator fun invoke(message: String)
/** Show by resource ID (four-language text) */
operator fun invoke(resId: Int)
/**
* Show a resource with format arguments, so a count can appear in a localised message.
*
* The alternative is building the string in a view model, which puts wording outside the
* resource files and hardcodes one language.
*/
operator fun invoke(resId: Int, vararg formatArgs: Any)
}
@@ -1,186 +0,0 @@
/*
* 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.utility
import kotlin.math.abs
/**
* Dependency-free replacement for jvm/Android `java.lang.String.format`, required because
* JVM formatting APIs do not exist on Kotlin/Native (iOS).
*
* Supported conversions: `%d` `%x` `%X` `%f` `%s` `%c` `%%`, plus the `0` flag, a width and
* `.precision` (for `%f`). Anything else throws, so an unsupported pattern never silently
* produces a wrong string.
*
* `%f` rounding matches java.lang.String.format (half-up on the exact double value) whenever
* the scaled value fits in a Long (< 2^53), which covers every frequency/coordinate string
* the app builds. Negative zero is preserved like the JVM does ("-0.000").
*/
fun formatString(pattern: String, vararg args: Any?): String {
val out = StringBuilder(pattern.length + 16)
var argIndex = 0
var i = 0
while (i < pattern.length) {
val ch = pattern[i]
if (ch != '%') {
out.append(ch); i++; continue
}
i++
if (i >= pattern.length) throw IllegalArgumentException("dangling '%' in pattern: $pattern")
if (pattern[i] == '%') {
out.append('%'); i++; continue
}
var zeroPadded = false
if (pattern[i] == '0') {
zeroPadded = true; i++
}
var width = 0
while (i < pattern.length && pattern[i].isDigit()) {
width = width * 10 + (pattern[i] - '0'); i++
}
// java.lang.String.format throws MissingFormatWidthException for this; an illegal
// pattern must not quietly format one way on Android and another way on iOS.
if (zeroPadded && width == 0) {
throw IllegalArgumentException("'0' flag without a width in pattern: $pattern")
}
var precision = -1 // java.lang.String.format defaults %f to 6 decimals
if (i < pattern.length && pattern[i] == '.') {
i++
precision = 0 // the digits accumulate from zero; -1 means "not specified"
while (i < pattern.length && pattern[i].isDigit()) {
precision = precision * 10 + (pattern[i] - '0'); i++
}
}
if (i >= pattern.length) throw IllegalArgumentException("truncated conversion in pattern: $pattern")
val conversion = pattern[i]
i++
val arg = if (argIndex < args.size) args[argIndex++] else null
val rendered = when (conversion) {
'd' -> longArg(arg, conversion, pattern).toString()
'x' -> longArg(arg, conversion, pattern).toString(16)
'X' -> longArg(arg, conversion, pattern).toString(16).uppercase()
'f' -> formatFixed(doubleArg(arg, pattern), if (precision < 0) 6 else precision, pattern)
's' -> arg?.toString() ?: "null"
'c' -> when (arg) {
is Char -> arg.toString()
is Int -> arg.toChar().toString()
else -> throw IllegalArgumentException("unsupported %c argument: $arg in pattern: $pattern")
}
else -> throw IllegalArgumentException("unsupported conversion %$conversion in pattern: $pattern")
}
if (width <= rendered.length) {
out.append(rendered)
} else if (zeroPadded && !rendered.startsWith("-") && !rendered.startsWith("+")) {
repeat(width - rendered.length) { out.append('0') }
out.append(rendered)
} else if (zeroPadded) {
out.append(rendered[0])
repeat(width - rendered.length) { out.append('0') }
out.append(rendered.substring(1))
} else {
repeat(width - rendered.length) { out.append(' ') }
out.append(rendered)
}
}
// Extra arguments are ignored, exactly like java.lang.String.format: call sites already
// pass what they pass and a port should not turn a latent extra argument into a crash.
return out.toString()
}
/** `"%.3f".format(1.2345)` -> `"1.235"` */
fun String.format(vararg args: Any?): String = formatString(this, *args)
private val POWERS_OF_TEN = longArrayOf(1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000)
private const val MAX_LONG_DIGITS = 18 // the most decimal digits that still fit in a Long
private fun longArg(arg: Any?, conversion: Char, pattern: String): Long = when (arg) {
is Int -> arg.toLong()
is Long -> arg
is Short -> arg.toLong()
is Byte -> arg.toLong()
else -> throw IllegalArgumentException("unsupported %$conversion argument: $arg in pattern: $pattern")
}
private fun doubleArg(arg: Any?, pattern: String): Double = when (arg) {
is Double -> arg
is Float -> arg.toDouble()
is Int -> arg.toDouble()
is Long -> arg.toDouble()
else -> throw IllegalArgumentException("unsupported %f argument: $arg in pattern: $pattern")
}
private fun formatFixed(value: Double, precision: Int, pattern: String): String {
if (precision !in 0..8) throw IllegalArgumentException("precision $precision too large in pattern: $pattern")
if (value.isNaN()) return "NaN"
if (value.isInfinite()) return if (value > 0.0) "Infinity" else "-Infinity"
val negative = value < 0.0 || (value == 0.0 && 1.0 / value < 0.0)
val rounded = roundHalfUp(abs(value), precision, value, pattern)
val power = POWERS_OF_TEN[precision]
val integerPart = rounded / power
val fractionPart = rounded % power
val result = StringBuilder()
if (negative) result.append('-')
result.append(integerPart)
if (precision > 0) {
result.append('.')
result.append(fractionPart.toString().padStart(precision, '0'))
}
return result.toString()
}
/**
* Rounds to [precision] decimals the way java.lang.String.format does: it rounds the shortest
* decimal representation of the double half-up, not its binary value. `"%.3f"` of 0.5005 is
* therefore `"0.501"`, even though the double holds 0.50049999999999994493.
*
* Scaling in binary first - floor(magnitude * 10^precision + 0.5) - loses exactly that and printed
* "0.500", so the digits come from the decimal representation and are rounded by integer
* arithmetic instead. Returns the value scaled by 10^precision.
*/
private fun roundHalfUp(magnitude: Double, precision: Int, value: Double, pattern: String): Long {
val text = magnitude.toString() // shortest representation that still round-trips
val exponentIndex = text.indexOfFirst { it == 'E' || it == 'e' }
val mantissa = if (exponentIndex < 0) text else text.substring(0, exponentIndex)
val exponent = if (exponentIndex < 0) 0 else text.substring(exponentIndex + 1).toInt()
val pointIndex = mantissa.indexOf('.')
val integerDigits = if (pointIndex < 0) mantissa else mantissa.substring(0, pointIndex)
val fractionDigits = if (pointIndex < 0) "" else mantissa.substring(pointIndex + 1)
val digits = integerDigits + fractionDigits
// magnitude == digits * 10^scale, so digits * 10^(scale + precision) is the scaled value.
val shift = exponent - fractionDigits.length + precision
val unscaled = digits.toLong()
if (shift >= 0) {
if (digits.length + shift > MAX_LONG_DIGITS) throw ValueTooLarge(value, precision, pattern)
var scaled = unscaled
repeat(shift) { scaled *= 10 }
return scaled
}
// Below half of the last printed digit everything rounds to zero, and 10^divisorDigits would
// no longer fit in a Long, so stop before building it.
val divisorDigits = -shift
if (divisorDigits > MAX_LONG_DIGITS) return 0L
var divisor = 1L
repeat(divisorDigits) { divisor *= 10 }
val quotient = unscaled / divisor
val remainder = unscaled % divisor
return if (2 * remainder >= divisor) quotient + 1 else quotient
}
// Values this large are never produced by the app; avoid silently wrong digits.
private class ValueTooLarge(value: Double, precision: Int, pattern: String) :
IllegalArgumentException("value $value too large for %.$precision" + "f in pattern: $pattern")
@@ -1,154 +0,0 @@
/*
* 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.utility
import com.rtbishop.look4sat.core.domain.predict.GeoPos
/**
* Converts a Maidenhead locator (QTH grid square) to a GeoPos.
* Supports 6-char (3 pair), 8-char (4 pair) and 10-char (5 pair) locators.
* The returned position is the center of the finest cell encoded by the locator:
* - 6 char: 5' lon x 2.5' lat cell center
* - 8 char: 30" lon x 15" lat cell center
* - 10 char: 1.25" lon x 0.625" lat cell center
*/
fun qthToPosition(locator: String): GeoPos? {
val trimmedQth = locator.trim().uppercase()
if (!isValidLocator(trimmedQth)) return null
val lonFirst = (trimmedQth[0].code - 65) * 20
val latFirst = (trimmedQth[1].code - 65) * 10
val lonSecond = trimmedQth[2].toString().toInt() * 2
val latSecond = trimmedQth[3].toString().toInt()
val lonThird = (trimmedQth[4].lowercaseChar().code - 97) / 12.0
val latThird = (trimmedQth[5].lowercaseChar().code - 97) / 24.0
var longitude = lonFirst + lonSecond + lonThird - 180
var latitude = latFirst + latSecond + latThird - 90
// 8-char extension: 4th pair, digits, 30" lon x 15" lat cells
if (trimmedQth.length >= 8) {
longitude += trimmedQth[6].toString().toInt() / 120.0
latitude += trimmedQth[7].toString().toInt() / 240.0
}
// 10-char extension: 5th pair, letters, 1.25" lon x 0.625" lat cells
if (trimmedQth.length >= 10) {
longitude += (trimmedQth[8].lowercaseChar().code - 97) / 2880.0
latitude += (trimmedQth[9].lowercaseChar().code - 97) / 5760.0
}
// Offset to the center of the finest encoded cell
when (trimmedQth.length) {
8 -> {
longitude += 1.0 / 240.0
latitude += 1.0 / 480.0
}
10 -> {
longitude += 1.0 / 5760.0
latitude += 1.0 / 11520.0
}
else -> {
longitude += 1.0 / 24.0
latitude += 1.0 / 48.0
}
}
return GeoPos(latitude.round(6), longitude.round(6))
}
/**
* Converts a GeoPos to a Maidenhead locator (QTH grid square).
* Default precision is 8 characters (4 pairs) giving 30" lon x 15" lat resolution,
* matching common 8-char grid square tools. Pass precision = 6 for the classic
* 5' x 2.5' resolution, or precision = 10 for the finest 1.25" x 0.625" resolution.
*/
fun positionToQth(latitude: Double, longitude: Double, precision: Int = 8): String? {
if (!isValidPosition(latitude, longitude)) return null
// The grid spans [0, 360) lon and [0, 180) lat once shifted. Clamping the
// field index alone (coerceIn below) is not enough: at exactly +90 lat or
// +180 lon the field saturates to R while the square/subsquare terms come
// from a modulo that has already wrapped to 0, so the encoded locator
// decoded back 10 degrees of latitude / 20 degrees of longitude away.
// Nudge the upper bound into the last cell instead.
val newLongitude = (longitude + 180).coerceIn(0.0, 360.0 - 1e-9)
val newLatitude = (latitude + 90).coerceIn(0.0, 180.0 - 1e-9)
val lonFirst = (65 + (newLongitude / 20).toInt().coerceIn(0, 17)).toChar()
val latFirst = (65 + (newLatitude / 10).toInt().coerceIn(0, 17)).toChar()
val lonSecond = ((newLongitude % 20) / 2).toInt()
val latSecond = (newLatitude % 10).toInt()
val lonThird = (65 + (newLongitude % 2) * 12).toInt().toChar().lowercaseChar()
val latThird = (65 + (newLatitude % 1) * 24).toInt().toChar().lowercaseChar()
val qth = "$lonFirst$latFirst$lonSecond$latSecond$lonThird$latThird"
if (precision < 8) return qth
val lonFourth = ((newLongitude % (1.0 / 12.0)) * 120).toInt()
val latFourth = ((newLatitude % (1.0 / 24.0)) * 240).toInt()
val qth8 = "$qth$lonFourth$latFourth"
if (precision < 10) return qth8
val lonFifth = (65 + (newLongitude % (1.0 / 120.0)) * 2880).toInt().toChar().lowercaseChar()
val latFifth = (65 + (newLatitude % (1.0 / 240.0)) * 5760).toInt().toChar().lowercaseChar()
return "$qth8$lonFifth$latFifth"
}
private fun isValidPosition(lat: Double, lon: Double): Boolean {
return lat in -90.0..90.0 && lon in -180.0..180.0
}
private fun isValidLocator(locator: String): Boolean {
// Maidenhead fields are A-R (18 x 18). Subsquare letters are A-X (24).
// Accepting S-X in the first pair decodes to latitude >90 / longitude >180.
return locator.matches("[a-rA-R]{2}\\d{2}[a-xA-X]{2}(?:\\d{2}(?:[a-xA-X]{2})?)?".toRegex())
}
/**
* Returns the 4-char field+square part of a locator, e.g. "OL42ih45" -> "OL42".
* A 4-char input is returned as-is when valid.
*/
fun qthToSquare(locator: String): String {
val upper = locator.trim().uppercase()
return when {
upper.length >= 4 && isValidLocator(upper) -> upper.take(4)
upper.length == 4 && upper.matches("[a-xA-X]{2}\\d{2}".toRegex()) -> upper
else -> "----"
}
}
/**
* Builds the 3x3 grid of 4-char squares surrounding [square] (e.g. "OL42").
* Row 0 = north (lat +1), col 0 = west (lon -1). Handles field/square carry
* at boundaries (e.g. "AA00" wraps to "RR99" at the south-west corner).
* Mirrors the neighbor logic decompiled from the QTH Locator app.
*/
fun qthNeighbors(square: String): List<String> {
if (square.length != 4) return emptyList()
val lonField = (square[0].uppercaseChar().code - 65).coerceIn(0, 17)
val latField = (square[1].uppercaseChar().code - 65).coerceIn(0, 17)
val lonSquare = square[2].digitToCharOrNull() ?: return emptyList()
val latSquare = square[3].digitToCharOrNull() ?: return emptyList()
val result = mutableListOf<String>()
for (dLat in 1 downTo -1) { // north -> south
for (dLon in -1..1) { // west -> east
var lf = lonField
var tf = latField
var ls = lonSquare + dLon
var ts = latSquare + dLat
if (ls < 0) { lf -= 1; ls = 9 } else if (ls > 9) { lf += 1; ls = 0 }
if (ts < 0) { tf -= 1; ts = 9 } else if (ts > 9) { tf += 1; ts = 0 }
lf = (lf + 18) % 18
tf = (tf + 18) % 18
result += "${('A' + lf).toChar()}${('A' + tf).toChar()}$ls$ts"
}
}
return result
}
private fun Char.digitToCharOrNull(): Int? = digitToIntOrNull()
@@ -1,29 +0,0 @@
/*
* 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.utility
/**
* Runs [block] while holding [lock]'s monitor, the way kotlin.jvm.Synchronized used to hold it
* before core:domain became a multiplatform module.
*
* The annotation survives in common code as an optional expectation, but the stdlib deprecated it
* there in Kotlin 1.8 and made it an error in 2.1: "Synchronizing methods on a class instance is
* not supported on platforms other than JVM." The monitor therefore moves behind a platform
* actual, which keeps the JVM semantics exactly and lets the iOS side say what it does instead.
*/
internal expect fun <T> synchronizedOn(lock: Any, block: () -> T): T
@@ -1,125 +0,0 @@
/*
* 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.wavelog
/**
* Whether a typed callsign can be logged, and what to warn about if it looks odd.
*
* Deliberately permissive. A survey of real callsigns against a typical strict pattern rejected
* 16 of 28 valid ones - `W1AW/4`, `2E0ABC`, `9A1CCY`, `SV2ASP/A` among them - while a pattern
* loose enough to accept those also accepts a Maidenhead locator as a callsign. There is no
* regex that catches typos without discarding legitimate calls, so anything plausible is
* accepted and doubt is reported rather than enforced.
*
* The previous behaviour was `if (call.length < 3) return`, which discarded the entry with no
* message: the operator pressed done during a pass and nothing happened, with no way to tell
* that the app had decided against them. None of the logging software surveyed - N1MM+, DXLog,
* PoLo, HAMRS - silently drops a submission.
*/
object CallsignEntry {
/** Shortest real callsign. Two characters occur in special event calls. */
private const val MIN_LENGTH = 2
/** Longest plausible entry, allowing a portable suffix such as `OH/W1AW/MM`. */
private const val MAX_LENGTH = 16
/** Characters a callsign may contain. */
private val allowed = Regex("^[A-Z0-9/-]+$")
/** The outcome of checking an entry. */
sealed interface Verdict {
/** Log it. [warning] is non-null when the entry is unusual but still plausible. */
data class Acceptable(val callsign: String, val warning: Warning? = null) : Verdict
/** Do not log it, and say why. */
data class Rejected(val reason: Reason) : Verdict
}
/** Why an entry cannot be logged at all. */
enum class Reason {
/** Nothing was typed. */
EMPTY,
/** Too short to be any callsign. */
TOO_SHORT,
/** Longer than any real callsign with a portable suffix. */
TOO_LONG,
/** Contains something a callsign cannot: punctuation, spaces, non-ASCII. */
ILLEGAL_CHARACTERS,
/** Digits only, or letters only - no callsign is either. */
NOT_A_CALLSIGN
}
/** Something worth mentioning without blocking the entry. */
enum class Warning {
/** Looks like a Maidenhead locator rather than a callsign, e.g. `GG77DH`. */
LOOKS_LIKE_A_GRID,
/** Already logged in this session - fine on a later pass, likely a slip on this one. */
ALREADY_WORKED
}
/**
* Check an entry, optionally against calls already logged in this pass.
*
* A repeat is a warning rather than a rejection: the same station on a later pass is a
* legitimate new contact, and contest loggers default to allowing duplicates - DXLog
* describes refusing them as an outdated habit.
*/
fun check(entry: String, workedThisSession: Set<String> = emptySet()): Verdict {
val call = entry.trim().uppercase()
if (call.isEmpty()) return Verdict.Rejected(Reason.EMPTY)
if (call.length < MIN_LENGTH) return Verdict.Rejected(Reason.TOO_SHORT)
if (call.length > MAX_LENGTH) return Verdict.Rejected(Reason.TOO_LONG)
if (!allowed.matches(call)) return Verdict.Rejected(Reason.ILLEGAL_CHARACTERS)
// Any segment may be the callsign, not just the first. A portable call can be written
// prefix-first - DL/W1AW, ZL/JA1ABC, OH/W1AW/MM - where the leading token is a country
// prefix with no digit in it. Testing only the first segment rejected all of those, which
// the old length-only check had accepted.
if (call.split('/', '-').none(::looksLikeCallsign)) {
return Verdict.Rejected(Reason.NOT_A_CALLSIGN)
}
val warning = when {
call in workedThisSession -> Warning.ALREADY_WORKED
looksLikeGrid(call) -> Warning.LOOKS_LIKE_A_GRID
else -> null
}
return Verdict.Acceptable(call, warning)
}
/** A segment that could be a callsign: contains both a letter and a digit. */
private fun looksLikeCallsign(segment: String): Boolean =
segment.any { it.isDigit() } && segment.any { it.isLetter() }
/**
* Whether this looks like a Maidenhead locator typed into the wrong field.
*
* Six characters of letter-letter-digit-digit-letter-letter. Worth mentioning because grid
* and callsign are exchanged together on FM satellites and the fields sit side by side.
*/
private fun looksLikeGrid(call: String): Boolean =
call.length == 6 &&
call[0].isLetter() && call[1].isLetter() &&
call[2].isDigit() && call[3].isDigit() &&
call[4].isLetter() && call[5].isLetter()
}
@@ -1,143 +0,0 @@
/*
* 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.wavelog
/**
* Checks a typed counterpart grid before it reaches the log.
*
* Separate from qthToPosition's validator, which requires six characters and is private. Plenty of
* satellite operators exchange only the four-character square, so requiring six would reject
* perfectly good entries - and this follows the same rule the callsign field settled on: refuse only
* what is certainly wrong, warn about the rest, never silently discard.
*
* The reason to check at all is that an unchecked value goes into the ADIF GRIDSQUARE field, and a
* malformed one is stored by Wavelog as-is. It then pollutes grid statistics and VUCC award
* tracking, where a wrong square is worse than a missing one.
*/
object GridEntry {
/** What a typed grid amounts to. */
sealed interface Verdict {
/** Usable. [normalised] is what should be logged - upper case for the pair, lower for the subsquare. */
data class Acceptable(val normalised: String, val warning: Warning? = null) : Verdict
/** Certainly not a grid. [reason] says which rule it broke. */
data class Unusable(val reason: Reason) : Verdict
/** Nothing typed. The QRZ lookup should run instead. */
data object Empty : Verdict
}
/** Worth mentioning but not worth refusing. */
enum class Warning {
/**
* Two characters. Legal per ADIF, but a field is 20 by 10 degrees - close to useless for a
* satellite contact, so it is worth saying rather than refusing.
*/
FIELD_ONLY,
/** Four characters, so the location is only accurate to about 100km. */
SQUARE_ONLY
}
/** Why an entry cannot be a grid. */
enum class Reason {
/** Not 4, 6 or 8 characters. Maidenhead has no other lengths. */
WRONG_LENGTH,
/** First pair outside A-R. S-X would decode past the poles. */
FIELD_OUT_OF_RANGE,
/** Second pair is not two digits. */
SQUARE_NOT_DIGITS,
/** Third pair outside A-X. */
SUBSQUARE_OUT_OF_RANGE
}
/**
* Judge a typed entry.
*
* Case is normalised on the way out rather than demanded on the way in - an operator typing
* one-handed outdoors should not have to care, and the conventional rendering is upper case for
* the field, digits, then lower case for the subsquare.
*/
fun check(entry: String): Verdict {
val text = entry.trim()
if (text.isEmpty()) return Verdict.Empty
if (text.length !in VALID_LENGTHS) return Verdict.Unusable(Reason.WRONG_LENGTH)
val upper = text.uppercase()
if (upper[0] !in FIELD_RANGE || upper[1] !in FIELD_RANGE) {
return Verdict.Unusable(Reason.FIELD_OUT_OF_RANGE)
}
// ASCII digits only. Char.isDigit() is Unicode-aware and covers the whole Nd category, so
// it accepted Arabic-Indic, Devanagari and fullwidth digits - which a localised keypad can
// produce without the operator seeing any difference. ADIF 3.1.7 defines Digit as "an ASCII
// character whose code lies in the range of 48 through 57", and Wavelog stores GRIDSQUARE
// verbatim, so such a value would never match a real grid in any statistics query.
// Guarded on length: a 2-character locator has no square pair, and reading index 2 of it
// would throw.
if (text.length >= SQUARE_LENGTH && (!upper[2].isAsciiDigit() || !upper[3].isAsciiDigit())) {
return Verdict.Unusable(Reason.SQUARE_NOT_DIGITS)
}
if (text.length >= SUBSQUARE_LENGTH) {
if (upper[4] !in SUBSQUARE_RANGE || upper[5] !in SUBSQUARE_RANGE) {
return Verdict.Unusable(Reason.SUBSQUARE_OUT_OF_RANGE)
}
}
if (text.length == EXTENDED_LENGTH && (!upper[6].isAsciiDigit() || !upper[7].isAsciiDigit())) {
return Verdict.Unusable(Reason.SQUARE_NOT_DIGITS)
}
return Verdict.Acceptable(
normalised = normalise(upper),
warning = when (text.length) {
FIELD_LENGTH -> Warning.FIELD_ONLY
SQUARE_LENGTH -> Warning.SQUARE_ONLY
else -> null
}
)
}
/** `OL72ap` - upper case field, digits, lower case subsquare, as the convention renders it. */
private fun normalise(upper: String): String = buildString {
append(upper.take(minOf(upper.length, SQUARE_LENGTH)))
if (upper.length >= SUBSQUARE_LENGTH) append(upper.substring(4, 6).lowercase())
if (upper.length == EXTENDED_LENGTH) append(upper.substring(6, 8))
}
/** ADIF 3.1.7 defines Digit as ASCII 48-57. Kotlin's isDigit() is far wider. */
private fun Char.isAsciiDigit(): Boolean = this in '0'..'9'
private const val FIELD_LENGTH = 2
private const val SQUARE_LENGTH = 4
private const val SUBSQUARE_LENGTH = 6
private const val EXTENDED_LENGTH = 8
/**
* ADIF 3.1.7: GRIDSQUARE takes "2-character, 4-character, 6-character, or 8-character" locators.
* A 10 or 12 character locator stores its first 8 here and the rest in GRIDSQUARE_EXT, which
* neither WavelogQso nor Wavelog's own field list carries - so the extra pair has nowhere to go
* and the UI clips at 8, which produces the spec-correct GRIDSQUARE value.
*/
private val VALID_LENGTHS = setOf(FIELD_LENGTH, SQUARE_LENGTH, SUBSQUARE_LENGTH, EXTENDED_LENGTH)
private val FIELD_RANGE = 'A'..'R'
private val SUBSQUARE_RANGE = 'A'..'X'
}
@@ -1,15 +0,0 @@
/* ILotwSatellitesRepo.kt - LoTW satellite list refresh interface (domain layer, 4.5.5).
* Impl: LotwSatellitesRepo in core/data (downloads ARRL config.tq6).
*/
package com.rtbishop.look4sat.core.domain.wavelog
interface ILotwSatellitesRepo {
sealed class RefreshResult {
data class Ok(val count: Int) : RefreshResult()
data class Error(val message: String) : RefreshResult()
}
fun restore()
suspend fun refresh(): RefreshResult
}
@@ -1,90 +0,0 @@
/* LotwSatelliteIds.kt - NORAD catalogue number to LoTW satellite name.
*
* Why the catalogue number and not the name: the same satellite carries different names in
* different TLE sources, so a name-keyed table misses whenever the user switches source.
* Measured across Celestrak amateur and AMSAT nasabare, 33 of the 49 satellites present in
* both are named differently - NORAD 43017 is "RADFXSAT (FOX-1B)" in one and "AO-91" in the
* other, 43700 is "ES'HAIL 2" against "QO-100". The catalogue number is identical in every
* source, so it is the only stable key.
*
* LoTW rejects a QSO whose SAT_NAME is not spelled exactly as in its accepted list
* (https://lotw.arrl.org/lotw-help/satellite-qsos: "if you enter the satellite name as AO7
* instead of AO-7 the data will be rejected"), which is why this maps to the exact spelling
* held in LotwSatellites rather than to whatever the TLE happens to say.
*
* Every number here was read out of live TLE data, never typed from memory. Entries cover the
* satellites that both appear in the app's own sources (Sources.satelliteDataUrls) and are in
* the LoTW list; the rest of that list is satellites no source still carries, so no user can
* track them and no mapping is needed for them.
*/
package com.rtbishop.look4sat.core.domain.wavelog
object LotwSatelliteIds {
/**
* NORAD catalogue number to the LoTW spelling. The trailing comment is one name the
* satellite goes by in the sources, kept so a reader can recognise the entry.
*
* Three numbers had to be decided rather than derived, because one name matched several
* catalogued objects. Each was settled by which object the amateur-specific sources carry:
* - ARISS is 25544, the station itself. Celestrak's full catalogue also lists ISS (UNITY),
* (ZVEZDA), (DESTINY) and (NAUKA), which are modules rather than stations you work.
* - IO-117 is 53109: four sources name that number GREENCUBE (IO-117) and only R4UAB calls
* it ROBUSTA 1F, which is a different satellite.
* - TO-108 is 44881, present in all three amateur sources; 44879 is TIANQIN 1 and appears
* only in the general catalogue.
*/
private val idToName: Map<Int, String> = mapOf(
7530 to "AO-7", // AO-07
14129 to "AO-10", // PHASE 3B (AO-10)
20439 to "AO-16", // OSCAR 16 (PACSAT)
20442 to "LO-19", // LO-19
22825 to "AO-27", // AO-27
23439 to "RS-15", // RADIO ROSTO (RS-15)
24278 to "FO-29", // FO-29
25544 to "ARISS", // ISS (ZARYA)
26609 to "AO-40", // PHASE 3D (AO-40)
26931 to "NO-44", // NO-44
27607 to "SO-50", // SAUDISAT 1C (SO-50)
28650 to "VO-52", // HAMSAT (VO-52)
39444 to "AO-73", // AO-73
40025 to "EO-79", // FUNCUBE-3 (EO-79)/QB50P1
40074 to "UKUBE1", // UKUBE-1
40908 to "CAS-3H", // LILACSAT-2
40931 to "IO-86", // IO-86
40967 to "AO-85", // FOX-1A (AO-85)
41847 to "CAS-2T", // CAS-2T
43017 to "AO-91", // AO-91
43678 to "PO-101", // DIWATA-2B
43700 to "QO-100", // ES'HAIL 2
43803 to "JO-97", // JO-97
44530 to "TAURUS", // TAURUS-1
44881 to "TO-108", // CAS-6 (TO-108)
44909 to "RS-44", // DOSAAF-85 (RS-44)
50466 to "HO-113", // CAMSAT XW-3 (CAS-9)
53109 to "IO-117", // GREENCUBE (IO-117)
61781 to "AO-123", // AO-123
// The TEVEL-2 constellation. Every source writes these TEVEL2-N while LoTW has TEV2-N,
// and no amount of separator-stripping bridges that - TEVEL21 is not TEV21 - so without
// these nine rows their QSOs upload under a name LoTW refuses. Note the numbering is not
// sequential: 63217 is TEVEL2-1 and 63213 is TEVEL2-4.
63213 to "TEV2-4",
63214 to "TEV2-5",
63215 to "TEV2-6",
63217 to "TEV2-1",
63218 to "TEV2-3",
63219 to "TEV2-2",
63237 to "TEV2-9",
63238 to "TEV2-7",
63239 to "TEV2-8"
)
/** The LoTW spelling for [catnum], or null when this satellite is not in the LoTW list. */
fun nameFor(catnum: Int): String? = idToName[catnum]
/** True when [catnum] names a satellite LoTW accepts, so a QSO on it can be confirmed. */
fun isKnown(catnum: Int): Boolean = catnum in idToName
/** Entry count, so a test can catch the table being emptied by a bad edit. */
val size: Int get() = idToName.size
}
@@ -1,26 +0,0 @@
/* LotwSatellites.kt - LoTW-supported satellite name list (112, statically embedded).
* Source: https://lotw.arrl.org/lotw/config.tq6 (gzip XML, official ARRL!)
* WaveLog updates its satellite table's lotw field from the same source (Update_model.php lotw_sats()).
* At runtime LotwSatellitesRepo can refresh it manually (settings WaveLog section button).
*/
package com.rtbishop.look4sat.core.domain.wavelog
// kotlin.jvm.Volatile 是 common 里 2.1 起的编译错误;kotlin.concurrent.Volatile 才是多平台的那个,
// 且在 JVM 与 Kotlin/Native 上都生效。
import kotlin.concurrent.Volatile
object LotwSatellites {
private val staticNames: Set<String> = setOf("AISAT1", "AO-10", "AO-109", "AO-123", "AO-13", "AO-16", "AO-21", "AO-27", "AO-3", "AO-4", "AO-40", "AO-51", "AO-6", "AO-7", "AO-73", "AO-8", "AO-85", "AO-91", "AO-92", "ARISS", "Arsene", "BO-102", "BY70-1", "CAS-2T", "CAS-3H", "CAS-4A", "CAS-4B", "DO-64", "EO-79", "EO-88", "FO-118", "FO-12", "FO-20", "FO-29", "FO-99", "FS-3", "HO-107", "HO-113", "HO-119", "HO-68", "INSPR7", "IO-117", "IO-86", "JO-97", "KEDR", "LEDSAT", "LO-19", "LO-78", "LO-87", "LO-90", "MAYA-3", "MAYA-4", "MIREX", "MO-112", "MO-122", "NO-103", "NO-104", "NO-44", "NO-83", "NO-84", "PO-101", "QO-100", "RS-1", "RS-10", "RS-11", "RS-12", "RS-13", "RS-15", "RS-2", "RS-44", "RS-5", "RS-6", "RS-7", "RS-8", "SAREX", "SO-121", "SO-124", "SO-125", "SO-35", "SO-41", "SO-50", "SO-67", "SONATE", "TAURUS", "TEVEL1", "TEVEL2", "TEVEL3", "TEVEL4", "TEVEL5", "TEVEL6", "TEVEL7", "TEVEL8", "TO-108", "UKUBE1", "UO-14", "UVSQ", "VO-52", "XW-2A", "XW-2B", "XW-2C", "XW-2D", "XW-2E", "XW-2F", "TEV2-1", "TEV2-2", "TEV2-3", "TEV2-4", "TEV2-5", "TEV2-6", "TEV2-7", "TEV2-8", "TEV2-9")
@Volatile
private var dynamicNames: Set<String> = emptySet()
/** Effective satellite names: static embedded set union runtime updates */
val names: Set<String>
get() = if (dynamicNames.isEmpty()) staticNames else staticNames + dynamicNames
/** Runtime update (settings button -> called after LotwSatellitesRepo.refresh()) */
fun updateNames(newNames: Set<String>) {
if (newNames.isNotEmpty()) dynamicNames = newNames
}
}
@@ -1,122 +0,0 @@
/*
* 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.wavelog
/**
* Works out what time a contact should carry.
*
* The logging screen used to stamp System.currentTimeMillis() and offer no way to change it. That
* assumes contacts are typed as they happen, and serious satellite operators do not work that way:
* the documented practice is to record the pass and transcribe it afterwards, because during eight
* minutes of a linear transponder there is no spare attention for a keyboard. A fixed clock makes
* every transcribed contact wrong by however long the transcription took.
*
* Two ways to say when: an absolute UTC time of day, or an offset from now. Both are typed into the
* same field, because a separate widget for each is more to reach for than an operator wants while
* holding an antenna.
*/
object PassClock {
/** What a typed token meant. */
sealed interface Command {
/** Log at this UTC time of day. [minuteOfDay] is minutes since 00:00 UTC. */
data class At(val minuteOfDay: Int) : Command
/** Log this many minutes from now. Negative counts backwards. */
data class Shift(val minutes: Int) : Command
/** Back to the current time. */
data object Live : Command
/** Not a time instruction. The caller should leave the clock alone. */
data object Unrecognised : Command
}
/**
* Interpret a typed token.
*
* Deliberately narrow. Anything that is not clearly a time is [Command.Unrecognised] rather than
* a guess, because a mis-parsed time silently backdates a contact and nothing downstream would
* catch it.
*
* Accepted: `14:55` or `1455` for a UTC time of day; `+3` or `-2` for a shift in minutes, with
* an optional `m`; empty or `now` to return to live time.
*/
fun parse(entry: String): Command {
val text = entry.trim().lowercase()
if (text.isEmpty() || text == "now") return Command.Live
if (text.startsWith("+") || text.startsWith("-")) return parseShift(text)
return parseTimeOfDay(text)
}
/** `+3`, `-2m`, `+15`. */
private fun parseShift(text: String): Command {
val negative = text.startsWith("-")
val digits = text.drop(1).removeSuffix("m")
val minutes = digits.toIntOrNull() ?: return Command.Unrecognised
if (minutes > MAX_SHIFT_MINUTES) return Command.Unrecognised
return Command.Shift(if (negative) -minutes else minutes)
}
/** `14:55` or `1455`. */
private fun parseTimeOfDay(text: String): Command {
val digits = text.replace(":", "")
if (digits.length != TIME_DIGITS || digits.any { !it.isDigit() }) return Command.Unrecognised
val hours = digits.take(2).toInt()
val minutes = digits.drop(2).toInt()
if (hours > MAX_HOUR || minutes > MAX_MINUTE) return Command.Unrecognised
return Command.At(hours * MINUTES_PER_HOUR + minutes)
}
/**
* Apply a command, returning the timestamp a contact should carry.
*
* [now] is the current UTC time in milliseconds and [dayStart] is midnight UTC of the day [now]
* falls in - passed in rather than computed, because core:domain holds no calendar and the
* caller already knows which day it is working with.
*
* An absolute time later than [now] is read as belonging to the previous day: transcription
* happens after the pass, so a pass that ran across midnight UTC is the common case, not an
* error. Without this a contact logged at 23:58 while transcribing at 00:05 would land a full
* day in the future.
*/
fun resolve(command: Command, now: Long, dayStart: Long): Long = when (command) {
is Command.At -> {
val candidate = dayStart + command.minuteOfDay * MILLIS_PER_MINUTE
if (candidate > now) candidate - MILLIS_PER_DAY else candidate
}
is Command.Shift -> now + command.minutes * MILLIS_PER_MINUTE
Command.Live, Command.Unrecognised -> now
}
/** Whether a command moves the clock off live time, so the UI can show that it has. */
fun isHolding(command: Command): Boolean =
command is Command.At || (command is Command.Shift && command.minutes != 0)
private const val TIME_DIGITS = 4
private const val MAX_HOUR = 23
private const val MAX_MINUTE = 59
private const val MINUTES_PER_HOUR = 60
/** A pass lasts minutes. Anything larger is a typo, not an intention. */
private const val MAX_SHIFT_MINUTES = 720
private const val MILLIS_PER_MINUTE = 60_000L
private const val MILLIS_PER_DAY = 86_400_000L
}
@@ -1,419 +0,0 @@
/*
* WaveLogApi.kt - WaveLog log server API client (4.5.2 override fix 2).
*
* Supports both v1 and v2 (user's server only has v1 in practice; v2 returns 404):
* v2: POST {base}/api/v2/qso (Authorization: Bearer + JSON fields)
* v1: POST {base}/index.php/api/qso (key in JSON body + ADIF string)
* Strategy: try v2 first, auto-fallback to v1 on 404.
* Test connection: v2 GET api/v2/token; on 404 use v1 POST api/get_contacts_adif.
* Station grid: only v2 has GET api/v2/station/{id}; v1 lacks it -> fall back to user QTH.
*/
package com.rtbishop.look4sat.core.domain.wavelog
import com.rtbishop.look4sat.core.domain.source.HttpResult
import com.rtbishop.look4sat.core.domain.source.IHttpClient
import com.rtbishop.look4sat.core.domain.utility.formatString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
/** Station info (GET /api/v2/station/{id} result) */
data class WavelogStation(
val id: Int,
val name: String,
val callsign: String,
val gridsquare: String
)
sealed class WavelogResult {
data class Success(val message: String) : WavelogResult()
data class Failure(val message: String) : WavelogResult()
}
object WaveLogApi {
/** Milliseconds in a day; date fields are derived from the QSO timestamp without Calendar. */
private const val MS_PER_DAY = 86_400_000L
/**
* Platform HTTP client for every request below. Handed over by the DI container because an
* object has no constructor for it, and a shared object has no platform socket API to use
* on its own.
*/
private var httpClient: IHttpClient? = null
fun installHttpClient(client: IHttpClient) {
httpClient = client
}
/** Normalize server URL: strip trailing slash/index.php; prepend https:// when missing */
fun normalizeUrl(raw: String): String {
var u = raw.trim().trimEnd('/')
if (u.isBlank()) return ""
if (!u.startsWith("http://") && !u.startsWith("https://")) u = "https://$u"
if (u.endsWith("/index.php")) u = u.removeSuffix("/index.php")
return u
}
/** Test connection: v2 GET api/v2/token; on 404 use v1 POST api/get_contacts_adif */
suspend fun testToken(url: String, apiKey: String, stationId: String = ""): WavelogResult {
val base = normalizeUrl(url)
if (base.isBlank()) return WavelogResult.Failure("服务器地址为空")
// v2: GET /index.php/api/v2/token
val v2 = httpRequest("$base/index.php/api/v2/token", apiKey, null)
if (v2.code in 200..299) return WavelogResult.Success("连接成功 (API v2)")
// v1: POST /index.php/api/get_contacts_adif (key in body)
if (stationId.isNotBlank()) {
val body = buildJsonObject {
put("key", apiKey)
put("station_id", stationId)
put("fetchfromid", 0)
}.toString()
val v1 = httpRequest("$base/index.php/api/get_contacts_adif", apiKey, body)
if (v1.code in 200..299) return WavelogResult.Success("连接成功 (API v1)")
if (v1.code == 401) return WavelogResult.Failure("API 密钥无效 (v1: 401)")
}
// v1 attempt without index.php
val body = buildJsonObject {
put("key", apiKey)
put("station_id", stationId)
put("fetchfromid", 0)
}.toString()
val v1b = httpRequest("$base/api/get_contacts_adif", apiKey, body)
if (v1b.code in 200..299) return WavelogResult.Success("连接成功 (API v1)")
if (v1b.code == 401) return WavelogResult.Failure("API 密钥无效 (v1: 401)")
return WavelogResult.Failure("连接失败: v2 HTTP ${v2.code}, v1 HTTP ${v1b.code} — 请确认服务器地址/密钥正确")
}
/** Station info: v2 only; v1 lacks the endpoint (grid check falls back to user QTH) */
suspend fun getStation(url: String, apiKey: String, stationId: String): WavelogResult {
val base = normalizeUrl(url)
if (base.isBlank()) return WavelogResult.Failure("服务器地址为空")
val (code, resp) = httpRequest("$base/index.php/api/v2/station/$stationId", apiKey, null)
if (code in 200..299) {
return try {
val obj = Json.parseToJsonElement(resp).jsonObject
val data = obj["data"] as? JsonObject ?: obj
val station = WavelogStation(
id = data["id"]?.jsonPrimitive?.intOrNull ?: 0,
name = data["name"]?.jsonPrimitive?.contentOrNull.orEmpty(),
callsign = data["callsign"]?.jsonPrimitive?.contentOrNull.orEmpty(),
gridsquare = data["gridsquare"]?.jsonPrimitive?.contentOrNull.orEmpty()
)
WavelogResult.Success(buildJsonObject {
put("id", station.id); put("name", station.name)
put("callsign", station.callsign); put("gridsquare", station.gridsquare)
}.toString())
} catch (e: Exception) {
WavelogResult.Failure("解析失败: ${e.message}")
}
}
// v1 has no station endpoint -> return empty Success (caller falls back to user QTH)
return WavelogResult.Success("")
}
/**
* ADIF band code from a frequency in Hz. "SAT" is NOT a legal ADIF band
* value (the Band enumeration is 160M/80M/.../2M/70CM/23CM...); a logger
* that fails to parse an illegal band falls back to a default such as
* 160m. Satellite QSOs must carry the real band of the TX frequency.
*/
fun bandFromHz(freqHz: Long): String = when {
freqHz >= 1240_000_000 -> "23CM"
freqHz >= 902_000_000 -> "33CM"
freqHz >= 420_000_000 -> "70CM"
freqHz >= 222_000_000 -> "1.25M"
freqHz >= 144_000_000 -> "2M"
freqHz >= 50_000_000 -> "6M"
freqHz >= 28_000_000 -> "10M"
freqHz >= 24_890_000 -> "12M"
freqHz >= 21_000_000 -> "15M"
freqHz >= 18_068_000 -> "17M"
freqHz >= 14_000_000 -> "20M"
freqHz >= 10_000_000 -> "30M"
freqHz >= 7_000_000 -> "40M"
freqHz >= 5_102_000 -> "60M"
freqHz >= 3_500_000 -> "80M"
freqHz >= 1_800_000 -> "160M"
else -> "160M"
}
/** Band class letter for satellite mode derivation: VHF=V, UHF=U, SHF=S. */
private fun bandLetter(freqHz: Long): String = when {
freqHz >= 1_240_000_000 -> "S"
freqHz >= 420_000_000 -> "U"
freqHz >= 144_000_000 -> "V"
else -> "V"
}
/**
* ADIF SAT_MODE (free text, satellite convention): "V/U" = VHF up /
* UHF down, "U/V", "V/S", "U/S"... Derived from the actual TX/RX bands.
*/
fun satModeFrom(txFreqHz: Long, rxFreqHz: Long): String {
if (rxFreqHz <= 0) return ""
val up = bandLetter(txFreqHz)
val down = bandLetter(rxFreqHz)
return if (up == down) "" else "$up/$down"
}
/**
* The name LoTW accepts for this satellite, resolved from its catalogue number when known.
*
* LoTW rejects a QSO whose SAT_NAME is not spelled as its accepted list has it - its help
* page gives AO7 against AO-7 as an example - so this has to produce the exact spelling or
* nothing useful at all.
*
* [catnum] is preferred because the name alone cannot decide it: TLE sources disagree, and
* of the 49 satellites carried by both Celestrak amateur and AMSAT nasabare, 33 are named
* differently. NORAD 43017 is "RADFXSAT (FOX-1B)" in one and "AO-91" in the other, 43700 is
* "ES'HAIL 2" against "QO-100". Deriving the name from the TLE text resolved 0 of 96
* satellites to something LoTW accepts, because the descriptive part of a TLE name is never
* the OSCAR designator.
*
* The name path remains as a fallback for QSOs logged before the catalogue number was
* recorded. It tries the whole name, then either side of the parentheses, since which side
* carries the designator varies - "SAUDISAT 1C (SO-50)" has it inside, "ISS (ZARYA)" does not.
*/
fun normalizeSatName(raw: String, catnum: Int? = null): String {
catnum?.let { LotwSatelliteIds.nameFor(it) }?.let { return it }
val trimmed = raw.trim()
for (candidate in nameCandidates(trimmed)) {
LotwSatellites.names.firstOrNull { it.equals(candidate, ignoreCase = true) }
?.let { return it }
}
// Tolerate a missing or extra hyphen: sources write RS15 where LoTW has RS-15.
for (candidate in nameCandidates(trimmed)) {
val squashed = candidate.squashSeparators()
LotwSatellites.names.firstOrNull { it.squashSeparators() == squashed }
?.let { return it }
}
return trimmed.uppercase()
}
/** True when [normalizeSatName] produced a name LoTW will accept rather than a guess. */
fun isLotwSatellite(name: String, catnum: Int? = null): Boolean {
val resolved = normalizeSatName(name, catnum)
return LotwSatellites.names.any { it.equals(resolved, ignoreCase = true) }
}
/** The whole name plus either side of the parentheses, longest first. */
private fun nameCandidates(raw: String): List<String> {
if (raw.isEmpty()) return emptyList()
val parts = mutableListOf(raw)
val open = raw.indexOf('(')
val close = raw.lastIndexOf(')')
if (open in 0..<close) {
parts += raw.substring(open + 1, close).trim()
parts += raw.substring(0, open).trim()
}
// Formation launches are catalogued as "RS-44 & BREEZE-KM R/B".
if ('&' in raw) parts += raw.substringBefore('&').trim()
return parts.filter { it.isNotEmpty() }.distinct()
}
private fun String.squashSeparators() = replace(Regex("[-\\s._/]"), "").uppercase()
/** Create QSO: v2 first, fall back to v1 (ADIF) on 404 */
suspend fun postQso(
url: String,
apiKey: String,
stationProfileId: String,
qso: WavelogQso,
gridsquare: String
): WavelogResult {
val base = normalizeUrl(url)
if (base.isBlank()) return WavelogResult.Failure("服务器地址为空")
val satName = normalizeSatName(qso.satName, qso.catnum.takeIf { it > 0 })
// v2: POST /index.php/api/v2/qso (JSON fields)
val satMode = satModeFrom(qso.freqTxHz, qso.freqRxHz)
val v2Body = buildJsonObject {
put("station_profile_id", stationProfileId.toIntOrNull() ?: 0)
put("call", qso.call)
put("band", bandFromHz(qso.freqTxHz))
put("mode", qso.mode)
put("qso_date", utcDate(qso.timeUtcMs))
put("time_on", utcTime(qso.timeUtcMs))
put("freq", formatString("%.6fM", qso.freqTxHz / 1_000_000.0))
put("freq_rx", formatString("%.6fM", qso.freqRxHz / 1_000_000.0))
put("gridsquare", gridsquare)
put("rst_sent", "59")
put("rst_rcvd", "59")
put("sat_name", satName)
if (satMode.isNotBlank()) put("sat_mode", satMode)
}
// The body decides, not the status code: Wavelog validates after responding, so a rejected
// QSO arrives as HTTP 200 with {"status":"failed"}. Trusting the code marked it uploaded
// and dropped it from the queue.
val (code, resp) = httpRequest("$base/index.php/api/v2/qso", apiKey, v2Body.toString())
val v2Verdict = WavelogResponse.verdict(code, resp)
when (v2Verdict) {
is WavelogResponse.Verdict.Accepted -> return WavelogResult.Success("v2")
WavelogResponse.Verdict.Duplicate -> return WavelogResult.Success("duplicate")
// Anything else falls through to v1. A rejection here is NOT final: v2 refuses a legacy
// v1 key with 401 invalid_token, and returning at that point stopped a v1-only operator
// from uploading at all. The v1 attempt below is the one that can speak for them.
else -> Unit
}
// v1: POST /index.php/api/qso (key in body + ADIF)
val v1Body = buildJsonObject {
put("key", apiKey)
put("station_profile_id", stationProfileId)
put("type", "adif")
put("string", toAdif(qso, gridsquare, satName))
}
val (code1, resp1) = httpRequest("$base/index.php/api/qso", apiKey, v1Body.toString())
val v1Verdict = WavelogResponse.verdict(code1, resp1)
when (v1Verdict) {
is WavelogResponse.Verdict.Accepted -> return WavelogResult.Success("v1")
WavelogResponse.Verdict.Duplicate -> return WavelogResult.Success("duplicate")
// Also falls through: a server with different rewrite rules answers this path with a
// 404 page, which is a rejection but says nothing about whether the QSO can be stored.
else -> Unit
}
// v1 without index.php, for a server whose rewrite rules differ
val (code1b, resp1b) = httpRequest("$base/api/qso", apiKey, v1Body.toString())
when (val verdict = WavelogResponse.verdict(code1b, resp1b)) {
is WavelogResponse.Verdict.Accepted -> return WavelogResult.Success("v1")
WavelogResponse.Verdict.Duplicate -> return WavelogResult.Success("duplicate")
is WavelogResponse.Verdict.Rejected ->
return WavelogResult.Failure(verdict.reason)
is WavelogResponse.Verdict.Unreadable -> Unit
}
// Every endpoint answered something we could not read. Keeping the QSO queued is the only
// honest outcome: it may have been stored, and dropping it would lose the contact.
// No endpoint accepted it. The v2 reason is preferred when it explained itself, since a 401
// invalid_token is the most actionable thing an operator can be told; otherwise all three
// status codes go out, because the third was previously dropped from this message.
val reasons = listOfNotNull(
(v1Verdict as? WavelogResponse.Verdict.Rejected)?.reason,
(v2Verdict as? WavelogResponse.Verdict.Rejected)?.reason
).filter { it.isNotBlank() }
return WavelogResult.Failure(
reasons.firstOrNull()
?: ("no endpoint accepted it: v2 HTTP $code, v1 HTTP $code1, v1-alt HTTP $code1b" +
" - " + shortError(resp1.ifBlank { resp1b }))
)
}
/** v1 ADIF string (freq in MHz, length = UTF-8 byte count, sat_name normalized) */
internal fun toAdif(qso: WavelogQso, gridsquare: String, satName: String): String {
fun field(name: String, value: String): String {
val bytes = value.encodeToByteArray().size
return "<$name:$bytes>$value"
}
val satMode = satModeFrom(qso.freqTxHz, qso.freqRxHz)
return buildString {
append(field("call", qso.call))
append(field("band", bandFromHz(qso.freqTxHz)))
append(field("mode", qso.mode))
append(field("freq", formatString("%.6f", qso.freqTxHz / 1_000_000.0)))
if (qso.freqRxHz > 0) {
append(field("freq_rx", formatString("%.6f", qso.freqRxHz / 1_000_000.0)))
}
append(field("qso_date", utcDateCompact(qso.timeUtcMs)))
append(field("time_on", utcTimeCompact(qso.timeUtcMs)))
append(field("rst_sent", "59"))
append(field("rst_rcvd", "59"))
// Send the grid at full precision. Truncating to 4 characters threw
// away the 6-character locator the QRZ lookup provides, coarsening the
// stored position from ~4.6 km to ~100 km and making a QSO logged via
// v1 disagree with the same QSO logged via v2 (which sends it whole).
if (gridsquare.isNotBlank()) append(field("gridsquare", gridsquare))
if (satName.isNotBlank()) {
append(field("sat_name", satName))
if (satMode.isNotBlank()) append(field("sat_mode", satMode))
append(field("prop_mode", "SAT"))
}
append("<eor>")
}
}
/**
* POST [jsonBody] when one is given, GET otherwise. A request that could not be sent at all
* comes back as code 0, so callers only have to look at the code.
*/
private suspend fun httpRequest(url: String, apiKey: String, jsonBody: String?): HttpResult {
val client = httpClient ?: error("WaveLogApi has no HTTP client installed")
val headers = buildMap {
if (apiKey.isNotBlank()) put("Authorization", "Bearer $apiKey")
if (jsonBody != null) {
put("Content-Type", "application/json")
put("Accept", "application/json")
}
}
val result = if (jsonBody != null) client.post(url, headers, jsonBody) else client.get(url, headers)
// A request that never left the phone used to report the exception text where the body
// goes, which is what the failure messages below read; keep it there.
val failure = result.failure
return if (result.body.isEmpty() && failure != null) result.copy(body = failure) else result
}
private fun shortError(body: String): String {
if (body.startsWith("<")) return body.take(80) // HTML error page
return try {
val obj = Json.parseToJsonElement(body).jsonObject
val err = obj["error"] as? JsonObject
if (err != null) {
err["message"]?.jsonPrimitive?.contentOrNull.orEmpty().ifBlank { body.take(120) }
} else {
obj["reason"]?.jsonPrimitive?.contentOrNull.orEmpty()
.ifBlank { obj["message"]?.jsonPrimitive?.contentOrNull.orEmpty().ifBlank { body.take(120) } }
}
} catch (_: Exception) {
body.take(120)
}
}
/** UTC civil time of a Unix millisecond stamp; the JVM Calendar is not multiplatform. */
private data class UtcFields(val year: Int, val month: Int, val day: Int, val hour: Int, val minute: Int, val second: Int)
private fun utcFieldsOf(ms: Long): UtcFields {
val days = ms.floorDiv(MS_PER_DAY)
val millisOfDay = ms.mod(MS_PER_DAY)
val shifted = days + 719_468
val era = shifted.floorDiv(146_097)
val dayOfEra = shifted - era * 146_097
val yearOfEra = (dayOfEra - dayOfEra / 1_460 + dayOfEra / 36_524 - dayOfEra / 146_096) / 365
val dayOfYear = dayOfEra - (365 * yearOfEra + yearOfEra / 4 - yearOfEra / 100)
val monthPart = (5 * dayOfYear + 2) / 153
val day = (dayOfYear - (153 * monthPart + 2) / 5 + 1).toInt()
val month = (if (monthPart < 10) monthPart + 3 else monthPart - 9).toInt()
val year = yearOfEra.toInt() + era.toInt() * 400 + (if (month <= 2) 1 else 0)
val secondOfDay = (millisOfDay / 1000).toInt()
return UtcFields(year, month, day, secondOfDay / 3_600, secondOfDay / 60 % 60, secondOfDay % 60)
}
private fun utcDate(ms: Long): String {
val utc = utcFieldsOf(ms)
return formatString("%04d-%02d-%02d", utc.year, utc.month, utc.day)
}
private fun utcTime(ms: Long): String {
val utc = utcFieldsOf(ms)
return formatString("%02d:%02d:%02d", utc.hour, utc.minute, utc.second)
}
private fun utcDateCompact(ms: Long): String {
val utc = utcFieldsOf(ms)
return formatString("%04d%02d%02d", utc.year, utc.month, utc.day)
}
private fun utcTimeCompact(ms: Long): String {
val utc = utcFieldsOf(ms)
return formatString("%02d%02d%02d", utc.hour, utc.minute, utc.second)
}
}
@@ -1,162 +0,0 @@
/*
* WavelogQueue.kt - WaveLog local log queue (4.5.2).
*
* Pure Kotlin (no Android deps): storage goes through the IWavelogQueueStore interface,
* implemented with SharedPreferences in core/data.
* Queue capped at 500 entries (oldest dropped beyond that).
*/
package com.rtbishop.look4sat.core.domain.wavelog
import com.rtbishop.look4sat.core.domain.utility.synchronizedOn
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
/** Storage abstraction (SharedPreferences impl lives in core/data) */
interface IWavelogQueueStore {
fun load(): String
fun save(json: String)
}
/** QSO entry awaiting upload (local queue element, mirrors POST /api/v2/qso fields) */
data class WavelogQso(
val id: String, // 本地唯一 id(UUID)
val timeUtcMs: Long, // 回车时刻 UTC 毫秒(本地显示 + 组装 qso_date/time_on)
val call: String,
val mode: String,
val freqTxHz: Long, // 上行(回车那一秒多普勒修正)
val freqRxHz: Long, // 下行
val satName: String,
/**
* NORAD catalogue number of the satellite, or 0 when it was not recorded.
*
* Carried because the name alone cannot decide the LoTW spelling - sources disagree, and
* the same satellite named two ways would upload two ways. Zero means a QSO logged before
* this field existed; those fall back to resolving from the name.
*/
val catnum: Int = 0,
val sessionId: String = "", // 场次 ID: 卫星名-AOS 时间戳(过境仰角 0 秒), 空=未分组(旧数据)
val gridsquare: String = "", // 对方网格(QRZ 爬虫填入, 4.5.5), 空=未查到
val uploaded: Boolean = false // 是否已成功上传(4.5.2 修复: 成功后保留标记, 表格打勾)
)
/**
* Every mutator is a read-modify-write over the single stored blob and serialises on a private
* monitor, so the Compose thread and the upload coroutine cannot drop each other's entries. The
* monitor is a platform actual (utility/SynchronizedOn.kt) because kotlin.jvm.Synchronized is an
* error in common code since Kotlin 2.1.
*/
class WavelogQueue(private val store: IWavelogQueueStore) {
private val key = "wavelog_queue"
private val lock = Any()
fun all(): List<WavelogQso> {
val raw = store.load()
return try {
Json.parseToJsonElement(raw).jsonArray.map { element ->
val o = element.jsonObject
WavelogQso(
id = o.getValue("id").jsonPrimitive.content,
timeUtcMs = o["timeUtcMs"].readLong(),
call = o["call"].readString(),
mode = o["mode"].readString(),
freqTxHz = o["freqTxHz"].readLong(),
freqRxHz = o["freqRxHz"].readLong(),
satName = o["satName"].readString(),
catnum = o["catnum"].readInt(),
sessionId = o["sessionId"].readString(),
gridsquare = o["gridsquare"].readString(),
uploaded = o["uploaded"].readBoolean()
)
}
} catch (_: Exception) {
emptyList()
}
}
fun add(qso: WavelogQso) {
synchronizedOn(lock) {
val list = all().toMutableList()
list.add(0, qso) // 最新在前
if (list.size > 500) list.removeAt(list.size - 1)
save(list)
}
}
fun remove(id: String) {
synchronizedOn(lock) { save(all().filter { it.id != id }) }
}
fun removeAll(ids: Set<String>) {
synchronizedOn(lock) { save(all().filter { it.id !in ids }) }
}
/** Mark as uploaded (kept in the queue; checkmark in the table) */
fun markUploaded(id: String) {
synchronizedOn(lock) { save(all().map { if (it.id == id) it.copy(uploaded = true) else it }) }
}
/** Update a QSO's counterpart grid (async backfill from the QRZ scraper, 4.5.5) */
fun updateGridsquare(id: String, grid: String) {
synchronizedOn(lock) { save(all().map { if (it.id == id) it.copy(gridsquare = grid) else it }) }
}
/** Remove all uploaded entries (optional; keeps the queue lean) */
fun removeUploaded() {
synchronizedOn(lock) { save(all().filter { !it.uploaded }) }
}
private fun save(list: List<WavelogQso>) {
val arr = buildJsonArray {
list.forEach { q ->
add(buildJsonObject {
put("id", q.id); put("timeUtcMs", q.timeUtcMs); put("call", q.call)
put("mode", q.mode); put("freqTxHz", q.freqTxHz)
put("freqRxHz", q.freqRxHz); put("satName", q.satName)
put("catnum", q.catnum)
put("sessionId", q.sessionId)
put("gridsquare", q.gridsquare)
put("uploaded", q.uploaded)
})
}
}
store.save(arr.toString())
}
}
/*
* org.json's opt* readers never threw: a decimal ("1234.0", or the string "1234.0") was coerced to
* a whole number, a missing or mismatched field fell back to the default, and a field holding an
* object was stringified. kotlinx answers null for the first two - which turned a readable
* timestamp into 0L, i.e. a QSO uploaded as 1970 - and throws for the third, which took the whole
* list down with it. These keep the old behaviour, except that a JSON null becomes the empty
* string or 0 instead of the literal "null".
*/
private fun JsonElement?.readLong(default: Long = 0L): Long {
val primitive = this as? JsonPrimitive ?: return default
primitive.longOrNull?.let { return it }
return primitive.content.toDoubleOrNull()?.takeIf { it.isFinite() }?.toLong() ?: default
}
private fun JsonElement?.readInt(default: Int = 0): Int {
val primitive = this as? JsonPrimitive ?: return default
primitive.intOrNull?.let { return it }
return primitive.content.toDoubleOrNull()?.takeIf { it.isFinite() }?.toInt() ?: default
}
private fun JsonElement?.readString(default: String = ""): String =
(this as? JsonPrimitive)?.contentOrNull ?: default
private fun JsonElement?.readBoolean(default: Boolean = false): Boolean =
(this as? JsonPrimitive)?.booleanOrNull ?: default
@@ -1,161 +0,0 @@
/*
* 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.wavelog
/**
* Decides whether Wavelog actually accepted a QSO.
*
* The status code is not the answer. Wavelog validates after responding 200 and reports the
* outcome in the body, so a rejected QSO arrives as HTTP 200 with `{"status":"failed"}`. Trusting
* the code alone marked it uploaded and dropped it from the queue - the same class of defect as
* the APRS reporter claiming a send succeeded when nothing had left the phone.
*
* Parsed as text rather than through a JSON library on purpose: what Wavelog answers is sparse and
* freely worded, and matching it as text keeps the verdict testable without a parser.
*/
object WavelogResponse {
/** What the server said about one QSO. */
sealed interface Verdict {
/** Stored. Safe to drop from the queue. */
data class Accepted(val detail: String) : Verdict
/** Wavelog already has it. Also safe to drop - the log is correct either way. */
data object Duplicate : Verdict
/** Rejected. [reason] carries the server's own wording when it gave one. */
data class Rejected(val reason: String) : Verdict
/** Unreadable, so keep the QSO queued rather than guess in either direction. */
data class Unreadable(val detail: String) : Verdict
}
/**
* Interpret a response.
*
* A body that reports failure beats a success code, because that is exactly the case the code
* alone gets wrong. An empty body with a success code counts as accepted, since the v1
* endpoint answers that way.
*/
fun verdict(statusCode: Int, body: String): Verdict {
val text = body.trim()
// Whitespace around separators is collapsed before matching, rather than listing every
// spacing a server might use: `{ "status" : "failed" }` is as valid as
// `{"status":"failed"}` and enumerating the combinations is endless.
val lower = text.lowercase().replace(AROUND_SEPARATORS, "")
// Duplicate reported three ways: a 409, the word in a message, or Wavelog's own
// `{"status":"dupe"}` - which arrives with HTTP 200 and is documented, not guessed.
// An HTML body is a proxy or a PHP fatal, never a verdict. Checked first because such a
// page carries no status token and would otherwise read as an acceptance, so a
// misconfigured reverse proxy answering 200 would eat contacts.
if (lower.startsWith("<")) return Verdict.Unreadable(text.take(MAX_DETAIL))
// Duplicate only when the STATUS says so, or on a 409. The word alone is not enough: the
// server's own rejection text is "Duplicate for <call>", and Api_v2 surfaces that inside
// validation_error bodies - so matching the bare substring classified a hard rejection as
// a duplicate, which maps to success and drops the QSO from the queue. That is the very
// defect this class was written to prevent, reached through a different door.
if (statusCode == DUPLICATE_CODE || lower.contains(DUPE_STATUS)) return Verdict.Duplicate
if (statusCode !in SUCCESS_CODES) {
return Verdict.Rejected(reasonFrom(text).ifBlank { "HTTP $statusCode" })
}
if (FAILURE_MARKERS.any { lower.contains(it) }) {
return Verdict.Rejected(reasonFrom(text).ifBlank { "server reported failure" })
}
// The v2 endpoint reports errors in an envelope with no status key at all.
if (lower.contains("\"error\":")) {
return Verdict.Rejected(reasonFrom(text).ifBlank { "server reported an error" })
}
// A status field we cannot read is not a success. Saying so keeps the QSO queued.
if (lower.contains("\"status\"") && SUCCESS_MARKERS.none { lower.contains(it) }) {
return Verdict.Unreadable(text.take(MAX_DETAIL))
}
// A bulk reply that stored nothing is not an acceptance, whatever its status says. Look4Sat
// posts one QSO per request so this is latent today, but `imported:0` reading as success
// would silently clear the queue if that ever changes.
if (importedZero(lower)) return Verdict.Rejected("server imported nothing")
return Verdict.Accepted(text.take(MAX_DETAIL))
}
/** Whether a bulk reply reports that no record was stored. */
private fun importedZero(lower: String): Boolean =
IMPORT_COUNT_KEYS.any { lower.contains("\"" + it + "\":0") }
/**
* The server's own explanation, when it gave one.
*
* Reads `reason`, `message` or `error` out of the JSON by hand. Crude, but it only has to work
* well enough to show the operator something more useful than a status code.
*/
private fun reasonFrom(body: String): String {
for (key in REASON_KEYS) {
Regex("\"$key\"\\s*:\\s*\"([^\"]*)\"").find(body)
?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() }
?.let { return it }
}
// An array of messages, which the v1 endpoint returns for a malformed ADIF record.
Regex("\"messages\"\\s*:\\s*\\[\\s*\"([^\"]*)\"").find(body)
?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() }
?.let { return it }
return ""
}
private val SUCCESS_CODES = 200..299
private const val DUPLICATE_CODE = 409
private const val MAX_DETAIL = 200
/** Matched against the whitespace-collapsed body, so one spelling of each suffices. */
private val FAILURE_MARKERS = listOf(
"\"status\":\"failed\"",
"\"status\":\"error\"",
"\"result\":\"failed\""
)
/**
* Wavelog's documented success wordings, plus the ones its other endpoints use.
*
* `successful` matters as much as `success`: the API reference uses both, and treating one as
* unrecognised would leave a stored QSO queued forever.
*/
/**
* Success wordings, taken from the Wavelog server source rather than its documentation.
*
* The QSO endpoint answers `created`; `success` and `successful` come from other endpoints and
* are kept because a future version may use them. `abort` is NOT here - v1 uses it when any
* record in a batch failed, and it arrives with a 400.
*/
private val SUCCESS_MARKERS = listOf(
"\"status\":\"created\"",
"\"status\":\"success\"",
"\"status\":\"successful\"",
"\"status\":\"ok\""
)
/** `dupe` is Wavelog's own wording and arrives with a 200. */
/** Wavelog's own duplicate status. The bare word "duplicate" is deliberately NOT a marker. */
private const val DUPE_STATUS = "\"status\":\"dupe\""
/** Whitespace next to a colon or comma, which JSON allows and servers use inconsistently. */
private val AROUND_SEPARATORS = Regex("""\s*(?=[:,])|(?<=[:,])\s*""")
/** Count fields a bulk reply uses to say how many records it stored. */
private val IMPORT_COUNT_KEYS = listOf("imported", "adif_count")
private val REASON_KEYS = listOf("reason", "message", "error")
}
@@ -1,117 +0,0 @@
/*
* WavelogUploader.kt - WaveLog queue upload scheduler (4.5.2).
*
* Manual/periodic uploads share: per-batch grid check (user QTH first 4 chars vs station grid first 4 chars)
* -> POST /api/v2/qso -> success removes from the queue.
* Grid mismatch: returns NeedConfirm (UI dialog "Ignore and upload / Cancel"),
* retrying the batch with force=true once confirmed.
*/
package com.rtbishop.look4sat.core.domain.wavelog
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
sealed class UploadOutcome {
data class NeedConfirm(val stationGrid: String, val userGrid: String) : UploadOutcome()
/**
* The upload finished. [failedCount] entries stay in the queue.
*
* [reason] is machine-readable so the UI can pick its own wording; [firstError] carries the
* server's own explanation for the first failure, which is worth showing verbatim because it
* is the only thing that says WHY Wavelog refused a QSO.
*/
data class Done(
val successCount: Int,
val failedCount: Int,
val reason: Reason = Reason.COMPLETED,
val firstError: String = ""
) : UploadOutcome()
/** Why an upload ended, for the UI to phrase. */
enum class Reason {
/** Ran to completion. Check the counts. */
COMPLETED,
/** No server, key or station id configured. */
NOT_CONFIGURED,
/** The station profile could not be read - wrong id, or a key without permission. */
NO_STATION_INFO
}
}
class WavelogUploader(
private val settingsRepo: ISettingsRepo,
private val queue: WavelogQueue
) {
// Station grid cache (refreshed before each upload; stale value kept on failure)
private var cachedStationGrid: String? = null
/** Upload the whole queue. force=true skips the grid confirm (user chose "Ignore and upload") */
suspend fun uploadQueue(force: Boolean = false): UploadOutcome {
val settings = settingsRepo.otherSettings.value
val url = settings.wavelogUrl
val apiKey = settings.wavelogApiKey
val stationId = settings.wavelogStationId
if (url.isBlank() || apiKey.isBlank() || stationId.isBlank()) {
return UploadOutcome.Done(0, queue.all().size, UploadOutcome.Reason.NOT_CONFIGURED)
}
// 1. Fetch station info (station grid); fall back to user QTH when v1 lacks the endpoint
val stationGrid = getStationGrid(url, apiKey, stationId) ?: userQthGrid()
if (stationGrid.isNullOrBlank()) {
return UploadOutcome.Done(0, queue.all().size, UploadOutcome.Reason.NO_STATION_INFO)
}
// 2. Grid check: cloud station grid first 4 chars vs current station QTH first 4 chars
// (guards against a misconfigured station; unrelated to the QSO counterpart grid - per user)
if (!force) {
val userGrid = userQthGrid()
if (userGrid != null && stationGrid.take(4).lowercase() != userGrid.take(4).lowercase()) {
return UploadOutcome.NeedConfirm(stationGrid, userGrid)
}
}
// 3. Upload one by one. ADIF gridsquare = counterpart grid (the QSO partner); blank until the scraper lands
val entries = queue.all()
var uploaded = 0
var failed = 0
var firstError = ""
for (qso in entries) {
// Entries already confirmed by the server are skipped, and NOT counted: adding them to
// the total made a re-run report "N uploaded" for QSOs that went up days ago.
if (qso.uploaded) continue
val result = WaveLogApi.postQso(url, apiKey, stationId, qso, qso.gridsquare)
if (result is WavelogResult.Success) {
uploaded++
queue.markUploaded(qso.id)
} else {
failed++
if (firstError.isBlank()) firstError = (result as? WavelogResult.Failure)?.message ?: ""
}
}
return UploadOutcome.Done(uploaded, failed, UploadOutcome.Reason.COMPLETED, firstError)
}
private suspend fun getStationGrid(url: String, apiKey: String, stationId: String): String? {
val result = WaveLogApi.getStation(url, apiKey, stationId)
if (result is WavelogResult.Success) {
return try {
Json.parseToJsonElement(result.message).jsonObject["gridsquare"]
?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }
?: cachedStationGrid
} catch (_: Exception) { cachedStationGrid }
}
return cachedStationGrid
}
/** User's current QTH grid (first 4 chars; null when no QTH = check skipped) */
private fun userQthGrid(): String? {
return settingsRepo.stationPosition.value.qthLocator?.takeIf { it.length >= 4 }
}
}
@@ -1,181 +0,0 @@
/*
* 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
import com.rtbishop.look4sat.core.domain.utility.positionToQth
import com.rtbishop.look4sat.core.domain.utility.qthNeighbors
import com.rtbishop.look4sat.core.domain.utility.qthToPosition
import com.rtbishop.look4sat.core.domain.utility.qthToSquare
import kotlin.test.Test
import kotlin.test.assertTrue
class QthConverterTest {
@Test
fun `Given valid QTH returns correct POS`() {
var result = qthToPosition("io91VL39FX")
assertTrue(result?.latitude == 51.499913 && result.longitude == -0.22309)
result = qthToPosition("gf15vc")
assertTrue(result?.latitude == -34.895833 && result.longitude == -56.208333)
// 8-char locators: finer 30" x 15" cell center
result = qthToPosition("io91vl47")
assertTrue(result?.latitude == 51.489583 && result.longitude == -0.2125)
result = qthToPosition("jn58td25")
assertTrue(result?.latitude == 48.147917 && result.longitude == 11.604167)
}
@Test
fun `Given invalid QTH returns null`() {
assertTrue(qthToPosition("ZZ00zz") == null)
assertTrue(qthToPosition("JN58") == null)
assertTrue(qthToPosition("io9") == null)
assertTrue(qthToPosition("IO91VL7") == null)
assertTrue(qthToPosition("IO91VL4X") == null)
}
@Test
fun `Given valid POS returns correct QTH`() {
// default precision is 8 chars
assertTrue(positionToQth(51.4878, -0.2146) == "IO91vl47")
assertTrue(positionToQth(48.1466, 11.6083) == "JN58td25")
// 6-char precision still available for backwards compatibility
assertTrue(positionToQth(51.4878, -0.2146, 6) == "IO91vl")
assertTrue(positionToQth(48.1466, 11.6083, 6) == "JN58td")
// 10-char precision
assertTrue(positionToQth(51.4878, -0.2146, 10) == "IO91vl47fb")
assertTrue(positionToQth(48.1466, 11.6083, 10) == "JN58td25xe")
}
@Test
fun `Given invalid POS returns null`() {
assertTrue(positionToQth(91.0542, -170.1142) == null)
assertTrue(positionToQth(89.0542, -240.1142) == null)
}
@Test
fun `Given boundary POS stays in valid grid`() {
// antipodal / edge cases must not overflow the A-R / 0-9 / a-x alphabet
assertTrue(positionToQth(-90.0, -180.0, 8) == "AA00aa00")
// Exact positive bounds belong to the final cell, not a modulo-wrapped
// R-field/0-square combination that decodes 10°/20° away.
assertTrue(positionToQth(90.0, 180.0, 8) == "RR99xx99")
assertTrue(positionToQth(0.0, 0.0, 8) == "JJ00aa00")
// roundtrip stability: 8-char roundtrip is stable across a sample of positions
val positions = listOf(
Pair(51.4878, -0.2146), Pair(48.1466, 11.6083), Pair(-33.8688, 151.2093),
Pair(39.9042, 116.4074), Pair(35.6895, 139.6917), Pair(41.714, -72.727)
)
positions.forEach { (lat, lon) ->
val qth = positionToQth(lat, lon, 8)
val pos = qthToPosition(qth!!)
val qth2 = positionToQth(pos!!.latitude, pos.longitude, 8)
assertTrue(qth == qth2, "Roundtrip failed for ($lat, $lon): $qth -> $qth2")
}
}
@Test
fun `Encoded locator always decodes back within one cell`() {
// An 8-char cell is 30" lon x 15" lat, so a correct encode/decode pair
// can never differ by more than that. Field clamping used to break this
// near +90 / +180 and produced errors up to 10 deg lat / 20 deg lon.
var worstLat = 0.0
var worstLon = 0.0
var worst = ""
var lat = -90.0
while (lat <= 90.0) {
var lon = -180.0
while (lon <= 180.0) {
val qth = positionToQth(lat, lon, 8)
?: error("valid position rejected: ($lat, $lon)")
val pos = qthToPosition(qth) ?: error("own output rejected: $qth")
val dLat = kotlin.math.abs(pos.latitude - lat)
val dLon = kotlin.math.abs(pos.longitude - lon)
if (dLat > worstLat || dLon > worstLon) {
worstLat = maxOf(worstLat, dLat)
worstLon = maxOf(worstLon, dLon)
worst = "($lat, $lon) -> $qth -> (${pos.latitude}, ${pos.longitude})"
}
lon += 0.5
}
lat += 0.5
}
assertTrue(
worstLat <= 0.01 && worstLon <= 0.01,
"roundtrip drifted by (${worstLat}, ${worstLon}) deg, worst: $worst"
)
}
@Test
fun `Given out of range longitude returns null`() {
// Maidenhead only covers -180..180; 181..360 used to be accepted and
// encoded into a plausible-looking locator 20-200 deg away.
assertTrue(positionToQth(0.0, 181.0) == null)
assertTrue(positionToQth(0.0, 270.0) == null)
assertTrue(positionToQth(0.0, 360.0) == null)
}
@Test
fun `Given locator with out of range field returns null`() {
// Fields run A-R; S-X in the first pair decoded past the poles.
assertTrue(qthToPosition("SS00aa") == null)
assertTrue(qthToPosition("XX99xx") == null)
assertTrue(qthToPosition("AS00aa") == null)
assertTrue(qthToPosition("AX99xx") == null)
}
@Test
fun `Given square returns correct 3x3 neighbors`() {
// Reference grid from the QTH Locator screenshot: OL42
val neighbors = qthNeighbors("OL42")
assertTrue(
neighbors == listOf(
"OL33", "OL43", "OL53",
"OL32", "OL42", "OL52",
"OL31", "OL41", "OL51"
),
"OL42 grid mismatch: $neighbors"
)
// Center cell must be the input itself
assertTrue(neighbors[4] == "OL42")
// 9 cells, all distinct
assertTrue(neighbors.size == 9 && neighbors.toSet().size == 9)
}
@Test
fun `Given boundary square wraps fields correctly`() {
// South-west corner: AA00 neighbors wrap to RR99 / RA90 etc.
val sw = qthNeighbors("AA00")
assertTrue(sw.size == 9 && sw.toSet().size == 9)
assertTrue(sw[0] == "RA91" && sw[4] == "AA00" && sw[6] == "RR99" && sw[8] == "AR19")
// North-east corner: RR99 wraps to AA00
val ne = qthNeighbors("RR99")
assertTrue(ne.size == 9 && ne.toSet().size == 9)
assertTrue(ne[0] == "RA80" && ne[4] == "RR99" && ne[8] == "AR08")
// Field boundary: IO91's east neighbors cross into J field
val london = qthNeighbors("IO91")
assertTrue(london[2] == "JO02" && london[5] == "JO01")
}
@Test
fun `Given full locator returns square part`() {
assertTrue(qthToSquare("OL42ih45") == "OL42")
assertTrue(qthToSquare("io91VL39FX") == "IO91")
assertTrue(qthToSquare("JN58") == "JN58")
assertTrue(qthToSquare("garbage!!") == "----")
}
}
@@ -1,165 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* These pin the rules that decide whether a packet is legal on APRS-IS, each of which was being
* broken by the previous one-line string template.
*/
class AprsBeaconTest {
private fun line(
latitude: Double? = 51.5,
longitude: Double? = -0.12,
callsign: String = "BG7NTA",
ssid: String = "5",
table: String = "/",
code: String = "[",
comment: String = "Look4Sat"
): String {
val result = AprsBeacon.build(callsign, ssid, latitude, longitude, table, code, comment)
assertTrue(result is AprsBeacon.Result.Line, "expected a line, got $result")
return (result as AprsBeacon.Result.Line).text
}
/**
* The specification is explicit: a client-originated packet carries TCPIP* in the path,
* "nothing more or less". The old template emitted `CALL>APRS:=...` with no path at all.
*/
@Test
fun `the path is exactly TCPIP star`() {
val text = line()
assertTrue(text.startsWith("BG7NTA-5>APRS,TCPIP*:="), text)
assertEquals(1, Regex(Regex.escape("TCPIP*")).findAll(text).count())
}
/**
* No position means no beacon. Substituting 0.0 put the station at 0N 0E - the Gulf of
* Guinea - on the global network, under the operator's own callsign.
*/
@Test
fun `a missing position refuses to build rather than claiming zero`() {
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.NoPosition),
AprsBeacon.build("BG7NTA", "5", null, null, "/", "[", "x")
)
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.NoPosition),
AprsBeacon.build("BG7NTA", "5", 51.5, null, "/", "[", "x")
)
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.NoPosition),
AprsBeacon.build("BG7NTA", "5", null, -0.12, "/", "[", "x")
)
}
/** A genuine 0,0 fix is legal and must still be sent - the refusal is about absence. */
@Test
fun `an actual zero position is still a position`() {
val result = AprsBeacon.build("BG7NTA", "5", 0.0, 0.0, "/", "[", "x")
assertTrue(result is AprsBeacon.Result.Line)
}
@Test
fun `an impossible position is refused`() {
val result = AprsBeacon.build("BG7NTA", "5", 91.0, 0.0, "/", "[", "x")
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.ImpossiblePosition(91.0, 0.0)),
result
)
}
@Test
fun `no callsign means no packet`() {
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.NoCallsign),
AprsBeacon.build("", "5", 51.5, -0.12, "/", "[", "x")
)
assertEquals(
AprsBeacon.Result.Blocked(AprsBeacon.Refusal.NoCallsign),
AprsBeacon.build(" ", "5", 51.5, -0.12, "/", "[", "x")
)
}
/**
* A newline in the comment ended the packet early and started a second one from the rest.
* The operator could trigger that by pressing return in a text field.
*/
@Test
fun `a line break in the comment cannot split the packet`() {
val text = line(comment = "hello\r\nCALL>APRS,TCPIP*:=injected")
// Only the line break matters. The text of a second packet surviving inside the comment
// is harmless - without a terminator the server reads one line, and a comment is free to
// contain any printable characters the operator likes.
assertFalse(text.contains('\n'), text)
assertFalse(text.contains('\r'), text)
assertEquals(1, text.lines().size, "must remain a single line")
}
@Test
fun `control characters are stripped from the comment`() {
val text = line(comment = "a\tb\u0000c")
assertTrue(text.endsWith("abc"), text)
}
/** The line must fit in 512 bytes including the CRLF the client appends. */
@Test
fun `an over-long comment is trimmed to keep the line legal`() {
val text = line(comment = "x".repeat(600))
assertTrue(text.encodeToByteArray().size + 2 <= 512, "line was ${text.encodeToByteArray().size} bytes")
}
/** The comment limit for this format is 43 characters. */
@Test
fun `the comment respects the format's own limit`() {
assertEquals(AprsBeacon.MAX_COMMENT, AprsBeacon.sanitiseComment("y".repeat(100)).length)
}
/**
* Symbol misconfiguration is, per aprs.fi, the most common reason a station never appears.
* The table byte was previously the first character of whatever was typed.
*/
@Test
fun `the symbol table falls back to the primary table when invalid`() {
assertEquals('/', AprsBeacon.tableOf(""))
assertEquals('/', AprsBeacon.tableOf("!"))
assertEquals('/', AprsBeacon.tableOf(" "))
assertEquals('/', AprsBeacon.tableOf("/"))
assertEquals('\\', AprsBeacon.tableOf("\\"))
// Overlays are legal: a digit or an upper-case letter selects the alternate table.
assertEquals('7', AprsBeacon.tableOf("7"))
assertEquals('S', AprsBeacon.tableOf("S"))
}
@Test
fun `the symbol code falls back when unprintable`() {
// A house, not a car. The old fallback was '>' (CAR), which showed a phone-based beacon as
// a vehicle for every operator who was not driving.
assertEquals('-', AprsBeacon.codeOf(""))
assertEquals('-', AprsBeacon.codeOf(" "))
assertEquals('[', AprsBeacon.codeOf("["))
}
/**
* Coordinates are fixed-width digits. A locale that formats decimals with a comma would
* corrupt every position, and a Turkish locale additionally lower-cases I to a dotless i.
*
* The three-locale sweep this replaced needed Locale.setDefault, which is JVM-only and so
* cannot be compiled for iOS. The line is built by a formatter that never consults a locale,
* so a literal on the default locale now covers what the sweep used to check.
*/
@Test
fun `a comma-decimal locale does not corrupt the coordinates`() {
assertEquals("BG7NTA-5>APRS,TCPIP*:=5130.00N/00007.20W[Look4Sat", line())
}
/** The whole line must be ASCII: APRS-IS is a byte protocol with no encoding negotiation. */
@Test
fun `the line is pure ascii`() {
val text = line(comment = "café 北京")
assertTrue(text.all { it.code in 0x20..0x7E }, text)
}
}
@@ -1,209 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* The verified/unverified distinction is the point of these tests: an unverified client stays
* connected and its writes keep succeeding while the server discards every packet, so getting this
* wrong means the operator watches reports "succeed" for hours with nothing landing.
*
* Several are transcriptions of live aprsc 2.1.21 traffic rather than guesses, because an earlier
* version of this file froze a wrong login format as correct and that defect survived nine commits
* and two audits.
*/
class AprsLoginTest {
@Test
fun `builds the line the specification asks for`() {
assertEquals(
"user BG7NTA-5 pass 12345 vers Look4Sat 4.6.0",
AprsLogin.line("BG7NTA", "5", 12345, "Look4Sat", "4.6.0")
)
}
/**
* The format a live server rejects, and the reason this file was rewritten.
*
* sent: user N0CALL pass -1 vers Look4Sat-4.5.4
* got: # Invalid login: software name and version are not separated by a space
*
* `vers` is two tokens. The previous code hyphenated the space between them to satisfy the rule
* that the software NAME contains no space, and the test asserted that as correct.
*/
@Test
fun `the software name and version stay separate tokens`() {
val line = AprsLogin.line("N0CALL", "", AprsLogin.RECEIVE_ONLY_PASSCODE, "Look4Sat", "4.5.4")
assertEquals("user N0CALL pass -1 vers Look4Sat 4.5.4", line)
assertEquals(7, line.split(" ").size)
assertTrue(!line.contains("Look4Sat-4.5.4"), "name and version must not be joined")
}
/** No SSID means no hyphen; the spec says never to write -0 explicitly. */
@Test
fun `omits the ssid when there is none`() {
assertEquals(
"user BG7NTA pass 12345 vers Look4Sat 4.6.0",
AprsLogin.line("BG7NTA", "", 12345, "Look4Sat", "4.6.0")
)
}
/** Whitespace inside either token would shift every field after it, so it is collapsed. */
@Test
fun `whitespace within a token is collapsed rather than passed through`() {
val line = AprsLogin.line("BG7NTA", "5", 12345, "Look 4 Sat", "4.6.0 beta")
assertEquals("user BG7NTA-5 pass 12345 vers Look-4-Sat 4.6.0-beta", line)
assertEquals(7, line.split(" ").size)
}
@Test
fun `appends a filter when one is given`() {
val line = AprsLogin.line("BG7NTA", "5", 12345, "Look4Sat", "4.6.0", "r/33.25/-96.5/50")
assertEquals("user BG7NTA-5 pass 12345 vers Look4Sat 4.6.0 r/33.25/-96.5/50", line)
}
@Test
fun `receive-only logins use the documented passcode`() {
val line = AprsLogin.line("BG7NTA", "", AprsLogin.RECEIVE_ONLY_PASSCODE, "Look4Sat", "4.6.0")
assertEquals("user BG7NTA pass -1 vers Look4Sat 4.6.0", line)
}
/** Empty tokens would produce a malformed line, so each has a fallback. */
@Test
fun `empty name or version does not produce a malformed line`() {
val line = AprsLogin.line("BG7NTA", "", 12345, "", "")
assertEquals("user BG7NTA pass 12345 vers Look4Sat 0", line)
assertEquals(7, line.split(" ").size)
}
/**
* The refusal that used to be invisible. It is a comment but not a logresp, so it was skipped
* as chatter; the login then timed out into Unknown, which is treated as "may be working", and
* every send afterwards reported success against a server that had refused the login.
*/
@Test
fun `an invalid login comment is a refusal rather than chatter`() {
val outcome = AprsLogin.parse(
"# Invalid login: software name and version are not separated by a space"
)
assertTrue(outcome is AprsLogin.Outcome.Rejected, "must be a refusal, got $outcome")
assertEquals(
"Invalid login: software name and version are not separated by a space",
(outcome as AprsLogin.Outcome.Rejected).detail
)
}
@Test
fun `a login denied comment is also a refusal`() {
assertTrue(AprsLogin.parse("# Login denied") is AprsLogin.Outcome.Rejected)
}
/**
* Every refusal, not only the anticipated ones. A first attempt listed the wordings it knew and
* skipped everything else as chatter, which missed three - including `# Login by user not
* allowed`, observed live on rotate.aprs2.net, the most commonly used rotating hostname.
*/
@Test
fun `refusals nobody anticipated are still refusals`() {
val refusals = listOf(
"# Login by user not allowed",
"# Port full",
"# Server full",
"# Invalid login: software name and version are not separated by a space",
"# Some wording nobody has seen yet"
)
for (line in refusals) {
assertTrue(
AprsLogin.parse(line) is AprsLogin.Outcome.Rejected,
"must be a refusal: $line"
)
}
}
/** The greetings and keepalives that must NOT read as refusals under that rule. */
@Test
fun `greetings and keepalives are still skipped`() {
val harmless = listOf(
"# aprsc 2.1.21-gbfc2090",
"# aprsc 2.1.19-g730c5c0",
"# javAPRSSrvr 4.4.3b19",
"# filter myfilter active"
)
for (line in harmless) {
assertNull(AprsLogin.parse(line), "must be skipped so the caller keeps reading: $line")
}
}
/**
* "unverified" contains "verified", so the negative has to be tested first. A naive
* contains("verified") reports every rejected login as accepted.
*/
@Test
fun `unverified is not mistaken for verified`() {
val outcome = AprsLogin.parse("# logresp BG7NTA unverified, server T2SYDNEY")
assertEquals(AprsLogin.Outcome.Unverified("BG7NTA"), outcome)
}
@Test
fun `a verified login is recognised with its callsign`() {
val outcome = AprsLogin.parse("# logresp BG7NTA-5 verified, server T2SYDNEY")
assertEquals(AprsLogin.Outcome.Verified("BG7NTA-5"), outcome)
}
/**
* Identification and keepalives must return null so the caller keeps reading. The greeting here
* is verbatim from aprsc 2.1.21.
*/
@Test
fun `comments without a verdict are skipped`() {
assertNull(AprsLogin.parse("# aprsc 2.1.21-gbfc2090"))
// The real keepalive, captured from euro.aprs2.net: it repeats the server identification
// with a timestamp rather than sending a bare date, so it carries the same prefix.
assertNull(
AprsLogin.parse("# aprsc 2.1.21-gbfc2090 25 Aug 2026 16:41:07 GMT T2UK 1.2.3.4:14580")
)
assertNull(AprsLogin.parse(""))
assertNull(AprsLogin.parse(" "))
}
/** A non-comment line during login is the server objecting in plain text. */
@Test
fun `a plain text line during login is a rejection`() {
val outcome = AprsLogin.parse("Invalid callsign format")
assertTrue(outcome is AprsLogin.Outcome.Rejected)
assertEquals("Invalid callsign format", (outcome as AprsLogin.Outcome.Rejected).detail)
}
/** A logresp with no recognisable verdict is Unknown, not silently Verified. */
@Test
fun `an unrecognised logresp is not treated as success`() {
assertTrue(
AprsLogin.parse("# logresp BG7NTA something-new, server X")
is AprsLogin.Outcome.Unknown
)
}
@Test
fun `case does not change the verdict`() {
assertEquals(
AprsLogin.Outcome.Unverified("BG7NTA"),
AprsLogin.parse("# LOGRESP BG7NTA UNVERIFIED, server X")
)
assertEquals(
AprsLogin.Outcome.Verified("BG7NTA"),
AprsLogin.parse("# LogResp BG7NTA Verified, server X")
)
assertTrue(AprsLogin.parse("# INVALID LOGIN: nope") is AprsLogin.Outcome.Rejected)
}
/** The callsign is read back so the UI can show whose login the server acknowledged. */
@Test
fun `reads the callsign even when the line is oddly spaced`() {
assertEquals(
AprsLogin.Outcome.Verified("BG7NTA-9"),
AprsLogin.parse("# logresp BG7NTA-9 verified, server X")
)
}
}
@@ -1,86 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import com.rtbishop.look4sat.core.domain.utility.formatString
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* APRS-IS is an ASCII line protocol. Formatting the position, altitude and
* course/speed extensions with the JVM default locale produced Eastern Arabic
* or Bengali digits on devices set to ar/fa/bn, and the server rejects those
* packets.
*
* Regression guard: every formatted field must stay ASCII, and every expected
* value below is a hardcoded literal. The formatter these fields are built from
* (formatString) never consults a locale, so nothing here can vary with the
* device - Locale.setDefault itself is JVM-only and does not exist on iOS.
*/
class AprsPacketLocaleTest {
private val asciiPacket = Regex("^[\\x20-\\x7E]*$")
/** The primitive the fields above are built from: fixed digits, never a locale's digits. */
@Test
fun formatString_producesAsciiLiterals() {
assertEquals("/A=000328", formatString("/A=%06d", 328))
assertEquals("/090/019", formatString("/%03d/%03d", 90, 19))
assertEquals("r/39.904/116.407/100", formatString("r/%.3f/%.3f/%d", 39.9042, 116.4074, 100))
assertEquals("3954.25N", formatString("%02d%s%c", 39, "54.25", 'N'))
}
@Test
fun position_staysAscii() {
val encoded = AprsPosition(39.9042, 116.4074, '/', '>').toUncompressedString()
assertTrue(asciiPacket.matches(encoded), "not ASCII: $encoded")
assertEquals("3954.25N/11624.44E>", encoded)
}
@Test
fun position_staysAsciiForSouthernCoordinates() {
val encoded = AprsPosition(-33.8688, 151.2093, '/', '>').toUncompressedString()
assertTrue(asciiPacket.matches(encoded), "not ASCII: $encoded")
assertEquals("3352.13S/15112.56E>", encoded)
}
@Test
fun altitudeAndCourseSpeed_stayAscii() {
val altitude = AprsPacket.formatAltitude(100.0)
val courseSpeed = AprsPacket.formatCourseSpeed(10.0, 90f)
val filter = AprsPacket.formatRangeFilter(39.9042, 116.4074, 100)
assertTrue(asciiPacket.matches(altitude), "not ASCII: $altitude")
assertTrue(asciiPacket.matches(courseSpeed), "not ASCII: $courseSpeed")
assertTrue(asciiPacket.matches(filter), "not ASCII: $filter")
assertEquals("/A=000328", altitude)
assertEquals("/090/019", courseSpeed)
assertEquals("r/39.904/116.407/100", filter)
}
@Test
fun altitude_clampsNegativeToKeepSixDigitField() {
// "%06d" of a negative value yields "/A=-00164": the '-' takes a digit
// slot, so the extension is no longer a valid fixed-width field.
assertEquals("/A=000000", AprsPacket.formatAltitude(-50.0))
assertEquals("/A=000000", AprsPacket.formatAltitude(-1.0))
assertEquals("/A=000328", AprsPacket.formatAltitude(100.0))
}
@Test
fun courseSpeed_wrapsCourseIntoValidRange() {
assertEquals("/000/019", AprsPacket.formatCourseSpeed(10.0, 360f))
assertEquals("/359/019", AprsPacket.formatCourseSpeed(10.0, -1f))
assertEquals("/090/019", AprsPacket.formatCourseSpeed(10.0, 90f))
}
@Test
fun ambiguousPosition_staysAscii() {
for (ambiguity in 1..4) {
val encoded = AprsPosition(39.9042, 116.4074, '/', '>', ambiguity)
.toUncompressedString()
assertTrue(asciiPacket.matches(encoded), "ambiguity=$ambiguity not ASCII: $encoded")
}
}
}
@@ -1,129 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* The rule these pin down: the app never invents a transmit passcode.
*
* APRS-IS treats the passcode as a licence check and says supplying it to a user is the software
* author's job. The previous code derived one from the callsign whenever the entry was blank or
* unparseable, so an operator who had never obtained a passcode transmitted anyway - under a
* check that was never performed.
*/
class AprsPasscodeTest {
/** Recomputed rather than hardcoded: the point is agreement with the shipped algorithm. */
private val callsign = "BG7NTA"
private val correct = AprsPacket.passcode(callsign)
@Test
fun `the callsign's own passcode allows transmitting`() {
assertEquals(
AprsPasscode.Entry.Transmit(correct),
AprsPasscode.classify(callsign, correct.toString())
)
assertTrue(AprsPasscode.canTransmit(callsign, correct.toString()))
assertEquals(correct, AprsPasscode.loginValue(callsign, correct.toString()))
}
/**
* A blank entry becomes receive-only rather than a derived code. This is the defect: the old
* line was `cfg.passcode.toIntOrNull()?.takeIf { it >= 0 } ?: AprsPacket.passcode(callsign)`,
* so leaving the field empty transmitted under a computed passcode.
*/
@Test
fun `a blank entry connects receive-only instead of deriving one`() {
assertEquals(AprsPasscode.Entry.ReceiveOnly, AprsPasscode.classify(callsign, ""))
assertEquals(AprsPasscode.Entry.ReceiveOnly, AprsPasscode.classify(callsign, " "))
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue(callsign, ""))
assertFalse(AprsPasscode.canTransmit(callsign, ""))
}
/**
* -1 is the documented receive-only value and has to survive. `takeIf { it >= 0 }` used to
* discard it and substitute a transmit passcode, which removed the only safe way to test a
* setup - connecting receive-only puts nothing on the network.
*/
@Test
fun `an explicit -1 stays receive-only`() {
assertEquals(AprsPasscode.Entry.ReceiveOnly, AprsPasscode.classify(callsign, "-1"))
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue(callsign, "-1"))
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue(callsign, " -1 "))
}
/** A wrong passcode is reported, not quietly corrected to the right one. */
@Test
fun `a mismatched passcode is reported rather than fixed`() {
val wrong = (correct + 1).toString()
assertEquals(AprsPasscode.Entry.Mismatch("BG7NTA"), AprsPasscode.classify(callsign, wrong))
assertFalse(AprsPasscode.canTransmit(callsign, wrong))
// And it must not be sent: a mismatch logs in receive-only, never as the derived value.
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue(callsign, wrong))
}
/**
* The three-way distinction the reporter depends on, and why it must not use canTransmit for
* it: that collapses a deliberate receive-only choice and a typo into one boolean. Telling an
* operator who mistyped their passcode that they are in receive-only mode is the same
* mis-diagnosis as telling a deliberate receive-only user their passcode is wrong, pointing
* the other way.
*/
@Test
fun `a deliberate receive-only entry is distinguishable from a typo`() {
val deliberate = AprsPasscode.classify(callsign, "-1")
val blank = AprsPasscode.classify(callsign, "")
val typo = AprsPasscode.classify(callsign, (correct + 1).toString())
val garbage = AprsPasscode.classify(callsign, "abcde")
assertTrue(deliberate is AprsPasscode.Entry.ReceiveOnly)
assertTrue(blank is AprsPasscode.Entry.ReceiveOnly)
assertFalse(typo is AprsPasscode.Entry.ReceiveOnly, "a typo must not read as receive-only")
assertFalse(garbage is AprsPasscode.Entry.ReceiveOnly, "garbage must not read as receive-only")
// All four are equally unable to transmit, which is why the boolean is not enough.
for (entry in listOf("-1", "", (correct + 1).toString(), "abcde")) {
assertFalse(AprsPasscode.canTransmit(callsign, entry))
}
}
@Test
fun `something that is not a number is its own case`() {
assertEquals(AprsPasscode.Entry.NotANumber, AprsPasscode.classify(callsign, "abcde"))
assertEquals(AprsPasscode.Entry.NotANumber, AprsPasscode.classify(callsign, "12a45"))
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue(callsign, "abcde"))
}
/** Surrounding whitespace from a paste must not turn a valid passcode into a mismatch. */
@Test
fun `whitespace around a valid passcode is tolerated`() {
assertTrue(AprsPasscode.canTransmit(callsign, " $correct "))
}
/** The passcode depends on the callsign, so it must not validate against a different one. */
@Test
fun `a passcode for one callsign does not validate another`() {
assertFalse(AprsPasscode.canTransmit("W1AW", correct.toString()))
assertEquals(
AprsPasscode.Entry.Mismatch("W1AW"),
AprsPasscode.classify("W1AW", correct.toString())
)
}
/** Case must not matter: the algorithm upper-cases before hashing. */
@Test
fun `a lower case callsign validates the same passcode`() {
assertTrue(AprsPasscode.canTransmit("bg7nta", correct.toString()))
}
/** The SSID is not part of the hash, so the base callsign's code is the right one. */
@Test
fun `no callsign cannot transmit`() {
assertEquals(AprsPasscode.Entry.Mismatch(""), AprsPasscode.classify("", "12345"))
assertEquals(AprsPasscode.RECEIVE_ONLY, AprsPasscode.loginValue("", "12345"))
// A blank entry with a blank callsign is still just receive-only, not a mismatch.
assertEquals(AprsPasscode.Entry.ReceiveOnly, AprsPasscode.classify("", ""))
}
}
@@ -1,102 +0,0 @@
package com.rtbishop.look4sat.core.domain.aprs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* The list exists because two free-text fields accepted anything and used only the first character,
* so an operator could type a word, watch it persist, and beacon as something else entirely.
*/
class AprsSymbolsTest {
/**
* The pair that justifies the whole feature. `\S` is Satellite/Pacsat; `/S` is SHUTTLE. One
* keystroke apart, and both look right to someone typing from memory.
*/
@Test
fun `the satellite symbol uses the alternate table`() {
val satellite = AprsSymbols.curated.single { it.descriptionKey == "aprs_symbol_satellite" }
assertEquals('\\', satellite.table)
assertEquals('S', satellite.code)
}
/** Every entry must survive the sanitiser that runs at packet-build time. */
@Test
fun `every curated symbol passes the transmit sanitiser`() {
for (symbol in AprsSymbols.curated) {
assertEquals(
symbol.table,
AprsBeacon.tableOf(symbol.table.toString()),
symbol.descriptionKey + " table must survive tableOf"
)
assertEquals(
symbol.code,
AprsBeacon.codeOf(symbol.code.toString()),
symbol.descriptionKey + " code must survive codeOf"
)
}
}
/** Two entries rendering the same pair would be a UI ambiguity. */
@Test
fun `no two curated symbols are the same pair`() {
val pairs = AprsSymbols.curated.map { it.table to it.code }
assertEquals(pairs.size, pairs.toSet().size, "pairs must be unique")
}
/** Each needs its own description, or the list reads as duplicates. */
@Test
fun `every curated symbol has a distinct description key`() {
val keys = AprsSymbols.curated.map { it.descriptionKey }
assertEquals(keys.size, keys.toSet().size, "description keys must be unique")
assertTrue(keys.all { it.startsWith("aprs_symbol_") }, "keys must be resource names")
}
@Test
fun `a stored pair on the list is found`() {
assertEquals(AprsSymbols.HOUSE, AprsSymbols.find('/', '-'))
assertNotNull(AprsSymbols.find('\\', 'S'))
}
/**
* A pair the list does not offer must report as absent rather than resolving to something near
* it. The picker relies on this to show an existing setting untouched.
*/
@Test
fun `a stored pair off the list is not silently substituted`() {
assertNull(AprsSymbols.find('/', 'S'))
assertNull(AprsSymbols.find('/', '!'))
assertNull(AprsSymbols.find('\\', 'y'))
}
/** The settings screen holds strings, and only the first character counts. */
@Test
fun `the string overload reads the first character`() {
assertEquals(AprsSymbols.HOUSE, AprsSymbols.find("/", "-"))
assertEquals(AprsSymbols.HOUSE, AprsSymbols.find("/junk", "-junk"))
}
/** Blank fields mean the shipped default, which is what the save path substitutes. */
@Test
fun `blank strings resolve to the default symbol`() {
assertEquals(AprsSymbols.HOUSE, AprsSymbols.find("", ""))
}
/** The default has to be on the list, or the picker opens showing nothing selected. */
@Test
fun `the default symbol is on the curated list`() {
assertTrue(AprsSymbols.HOUSE in AprsSymbols.curated)
}
/** Short enough to scan in a bottom sheet during setup. */
@Test
fun `the list stays short`() {
assertTrue(
AprsSymbols.curated.size in 8..20,
"a curated list of ${AprsSymbols.curated.size} defeats the point"
)
}
}
@@ -1,198 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.hypot
import kotlin.math.sin
import kotlin.test.Test
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Aliasing is not a subtle degradation here: without this filter a 3000 Hz tone reappeared at
* 200 Hz at 119 times the spectral mean, which reads as a real signal, and the whole band above
* 1600 Hz folded down and lifted the noise floor across the display.
*/
class CwAntiAliasTest {
private val captureRate = 44100
private val targetRate = CwDeepSpectrogram.SAMPLE_RATE
private val nyquist = targetRate / 2.0
/** Magnitude at one frequency, Hann-windowed so neighbours do not smear in. */
private fun magnitudeAt(signal: FloatArray, hz: Double, rate: Int): Double {
val n = signal.size
var real = 0.0
var imag = 0.0
val omega = 2.0 * PI * hz / rate
for (i in 0 until n) {
val window = 0.5 - 0.5 * kotlin.math.cos(2.0 * PI * i / (n - 1))
val value = signal[i] * window
real += value * kotlin.math.cos(omega * i)
imag -= value * sin(omega * i)
}
return hypot(real, imag) / n
}
private fun tone(hz: Double, rate: Int, seconds: Double = 0.4): FloatArray {
val n = (rate * seconds).toInt()
return FloatArray(n) { i -> sin(2.0 * PI * hz * i / rate).toFloat() }
}
/** A tone the model needs must survive the filter. */
@Test
fun `tones inside the window pass through`() {
for (hz in listOf(300.0, 700.0, 1000.0, 1200.0)) {
val clean = tone(hz, captureRate)
val filtered = CwAntiAlias.prepareForDecimation(clean, captureRate, targetRate)
val before = magnitudeAt(clean, hz, captureRate)
val after = magnitudeAt(filtered, hz, captureRate)
assertTrue(
after > before * 0.7,
"$hz Hz lost too much: $before -> $after"
)
}
}
/**
* The defect. 3000 Hz used to fold to 200 Hz and look like a strong signal; the filter has to
* remove it before the resampler can alias it.
*/
@Test
fun `tones that would alias are suppressed`() {
// Limits are the measured response, not aspirations. 1800 Hz sits just past the 1472 Hz
// cut-off, and 127 taps cannot give a steeper transition than that - a longer filter would
// be sharper and slower, and this runs on a phone during a pass. What matters is that the
// wideband hiss well above the window, which is what smears across the whole display, is
// gone: 2400 Hz and up measure below a thousandth.
val cases = listOf(
Triple(1800.0, 1400.0, 0.20),
Triple(2400.0, 800.0, 0.01),
Triple(3000.0, 200.0, 0.01),
Triple(5000.0, 1400.0, 0.01)
)
for ((source, foldedTo, limit) in cases) {
val raw = tone(source, captureRate)
val filtered = CwAntiAlias.prepareForDecimation(raw, captureRate, targetRate)
val aliasedRaw = CwDeepSpectrogram.resampleLinear(raw, captureRate, targetRate)
val aliasedFiltered = CwDeepSpectrogram.resampleLinear(filtered, captureRate, targetRate)
val ghostBefore = magnitudeAt(aliasedRaw, foldedTo, targetRate)
val ghostAfter = magnitudeAt(aliasedFiltered, foldedTo, targetRate)
assertTrue(
ghostAfter < ghostBefore * limit,
"$source Hz folds to $foldedTo Hz too strongly: $ghostBefore -> $ghostAfter"
)
}
}
/** Nothing above the target Nyquist means nothing to do. */
@Test
fun `no filtering when the rate is already low enough`() {
val audio = tone(700.0, targetRate)
assertSame(audio, CwAntiAlias.prepareForDecimation(audio, targetRate, targetRate))
assertSame(audio, CwAntiAlias.prepareForDecimation(audio, 2000, targetRate))
}
@Test
fun `an empty buffer is returned unchanged`() {
val empty = FloatArray(0)
assertSame(empty, CwAntiAlias.prepareForDecimation(empty, captureRate, targetRate))
}
/** Unity DC gain: filtering must not move the level the model was trained on. */
@Test
fun `a steady level is preserved`() {
val flat = FloatArray(4410) { 0.5f }
val filtered = CwAntiAlias.prepareForDecimation(flat, captureRate, targetRate)
// Skip the edges, where taps fall outside the buffer.
val middle = filtered.copyOfRange(
CwAntiAlias.GROUP_DELAY_SAMPLES + 1,
filtered.size - CwAntiAlias.GROUP_DELAY_SAMPLES - 1
)
for (v in middle) {
assertTrue(kotlin.math.abs(v - 0.5f) < 0.02f, "level drifted to $v")
}
}
/**
* Chunked filtering has to match whole-buffer filtering, or every chunk boundary becomes a
* click - the same failure the tone shifter's streaming path exists to prevent.
*/
/**
* Chunked filtering must equal whole-buffer filtering exactly, or every chunk boundary is a
* click. A first attempt let the lookahead taps read zeros at the end of each chunk and
* diverged by 0.134 across the last 44 samples of every one; holding output back by the group
* delay makes the two identical.
*/
@Test
fun `streaming matches whole-buffer filtering`() {
val audio = tone(700.0, captureRate, seconds = 0.3)
val whole = CwAntiAlias.prepareForDecimation(audio, captureRate, targetRate)
val streaming = CwAntiAlias.Streaming(captureRate, targetRate)
val chunkSize = captureRate / 10
val pieces = mutableListOf<Float>()
var offset = 0
while (offset < audio.size) {
val end = minOf(offset + chunkSize, audio.size)
pieces += streaming.process(audio.copyOfRange(offset, end)).toList()
offset = end
}
val streamed = pieces.toFloatArray()
// Output is delayed by the group delay, so streamed[i] corresponds to whole[i + delay].
var worst = 0f
for (i in streamed.indices) {
val j = i + CwAntiAlias.GROUP_DELAY_SAMPLES
if (j >= whole.size) break
val diff = kotlin.math.abs(streamed[i] - whole[j])
if (diff > worst) worst = diff
}
assertTrue(worst < 1e-5f, "streaming diverges by $worst")
}
/** Streaming must not lift the noise floor either. */
@Test
fun `streaming suppresses an aliasing tone too`() {
val raw = tone(3000.0, captureRate, seconds = 0.3)
val streaming = CwAntiAlias.Streaming(captureRate, targetRate)
val chunkSize = captureRate / 10
val pieces = mutableListOf<Float>()
var offset = 0
while (offset < raw.size) {
val end = minOf(offset + chunkSize, raw.size)
pieces += streaming.process(raw.copyOfRange(offset, end)).toList()
offset = end
}
val filtered = pieces.toFloatArray()
val ghostBefore = magnitudeAt(
CwDeepSpectrogram.resampleLinear(raw, captureRate, targetRate), 200.0, targetRate
)
val ghostAfter = magnitudeAt(
CwDeepSpectrogram.resampleLinear(filtered, captureRate, targetRate), 200.0, targetRate
)
assertTrue(ghostAfter < ghostBefore * 0.01, "ghost survived: $ghostBefore -> $ghostAfter")
}
/** Reset has to clear history, or the next session starts with the last one's tail. */
@Test
fun `reset clears the history`() {
val streaming = CwAntiAlias.Streaming(captureRate, targetRate)
val loud = FloatArray(4410) { 0.9f }
streaming.process(loud)
streaming.reset()
val silence = FloatArray(4410)
val after = streaming.process(silence)
for (v in after) {
assertTrue(kotlin.math.abs(v) < 0.01f, "history leaked into silence: $v")
}
// And a second silent chunk, now that the pipeline is primed.
for (v in streaming.process(FloatArray(4410))) {
assertTrue(kotlin.math.abs(v) < 0.01f, "history still leaking: $v")
}
}
}
@@ -1,90 +0,0 @@
/*
* 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.cw
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Greedy CTC collapse, matching the reference implementation's
* `greedy_ctc_decode`: drop blanks, then drop runs of the same label.
*
* Alphabet from `model.onnx.json` — 41 symbols plus blank at index 41.
*/
class CwCtcDecoderTest {
private val chars = listOf(
",", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "?",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "
)
private val blank = 41
/** Build a `[1, T, 42]` log-prob tensor whose argmax follows [path]. */
private fun logits(path: IntArray): Array<Array<FloatArray>> {
val frames = Array(path.size) { t ->
FloatArray(42) { -10f }.also { it[path[t]] = 0f }
}
return arrayOf(frames)
}
@Test
fun alphabetSizeMatchesModelMetadata() {
assertEquals(41, chars.size, "41 symbols + blank = 42 classes")
}
@Test
fun greedy_dropsRunsOfTheSameLabel() {
assertEquals("A", CwCtcDecoder.greedy(logits(intArrayOf(14, 14, 14)), chars, blank))
}
@Test
fun greedy_keepsRepeatsSeparatedByBlank() {
// A A <blank> A collapses to "AA": the blank breaks the run.
assertEquals("AA", CwCtcDecoder.greedy(logits(intArrayOf(14, 14, blank, 14)), chars, blank))
}
@Test
fun greedy_allBlanksYieldEmptyString() {
assertEquals("", CwCtcDecoder.greedy(logits(intArrayOf(blank, blank, blank)), chars, blank))
}
@Test
fun greedy_emptyInputYieldsEmptyString() {
assertEquals("", CwCtcDecoder.greedy(logits(intArrayOf()), chars, blank))
}
@Test
fun greedy_decodesCallsignWithSpaceAndDigits() {
// "CQ BG7" — C=16 Q=30 space=40 B=15 G=20 7=10
val path = intArrayOf(
blank, 16, 16, blank, 30, blank, 40,
15, blank, 20, blank, 10, blank
)
assertEquals("CQ BG7", CwCtcDecoder.greedy(logits(path), chars, blank))
}
@Test
fun greedy_picksHighestScoringClassPerFrame() {
// Frame favours S (32) over T (33); only S must survive.
val frame = FloatArray(42) { -10f }
frame[33] = -1f
frame[32] = -0.1f
assertEquals("S", CwCtcDecoder.greedy(arrayOf(arrayOf(frame)), chars, blank))
}
}
@@ -1,152 +0,0 @@
/*
* 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.cw
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* The rolling audio buffer feeding DeepCW.
*
* DeepCW is a whole-segment CTC model, not a sample-by-sample decoder: it
* rewrites earlier output whenever more context arrives, so incremental
* stitching is impossible. Instead we keep a bounded window and re-decode all
* of it periodically, replacing the displayed text.
*/
class CwDeepBufferTest {
@Test
fun capacityIsCappedAtMaxSeconds() {
val buffer = CwDeepBuffer(sampleRate = 3200, maxSeconds = 20.0)
repeat(30) { buffer.append(FloatArray(3200)) }
assertEquals(3200 * 20, buffer.size)
}
@Test
fun oldestSamplesAreDiscardedFirst() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f))
buffer.append(floatArrayOf(4f, 5f))
assertContentEquals(floatArrayOf(2f, 3f, 4f, 5f), buffer.snapshot())
}
@Test
fun snapshotIsChronologicalAfterWrapAround() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f))
assertContentEquals(floatArrayOf(3f, 4f, 5f, 6f), buffer.snapshot())
}
@Test
fun appendLargerThanCapacityKeepsOnlyTheTail() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f))
assertEquals(4, buffer.size)
assertContentEquals(floatArrayOf(6f, 7f, 8f, 9f), buffer.snapshot())
}
@Test
fun redecodeIsSignalledOncePerInterval() {
// 1.5 s at 3200 Hz is 4800 samples; 1600 samples is 0.5 s.
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
assertFalse(buffer.append(FloatArray(3200)), "1.0s elapsed: interval not reached")
assertTrue(buffer.append(FloatArray(1600)), "1.5s elapsed: first trigger")
assertFalse(buffer.append(FloatArray(1600)), "2.0s: only 0.5s since trigger")
assertFalse(buffer.append(FloatArray(1600)), "2.5s: only 1.0s since trigger")
assertTrue(buffer.append(FloatArray(1600)), "3.0s: 1.5s since trigger, fires again")
}
@Test
fun redecodeIntervalDoesNotDriftOverManyChunks() {
// 100 ms chunks, as AudioCapture emits them: exactly 15 chunks per
// 1.5 s interval, so 150 chunks must fire exactly 10 times.
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
var fired = 0
repeat(150) { if (buffer.append(FloatArray(320))) fired++ }
assertEquals(10, fired)
}
@Test
fun snapshotDoesNotAliasInternalStorage() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.snapshot()[0] = 99f
assertEquals(1f, buffer.snapshot()[0], absoluteTolerance = 0f, "caller must not be able to mutate the buffer")
}
@Test
fun resetClearsSamplesAndIntervalCounter() {
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
buffer.append(FloatArray(3200))
buffer.reset()
assertEquals(0, buffer.size)
assertFalse(buffer.append(FloatArray(3200)), "counter restarted, 1.0s must not trigger")
}
@Test
fun hasEnoughAudioTracksTheModelMinimum() {
// compute() needs at least FFT_LENGTH samples to produce one frame.
val buffer = CwDeepBuffer(3200, 20.0)
buffer.append(FloatArray(100))
assertFalse(buffer.hasEnoughAudio)
buffer.append(FloatArray(200))
assertTrue(buffer.hasEnoughAudio)
}
@Test
fun defaultsMatchTheMeasuredOptimum() {
// 20s / 1.5s were chosen from measurements: 20s is the smallest window
// reaching 0.0% CER, and keeps inference well inside real time.
val buffer = CwDeepBuffer()
assertEquals(CwDeepSpectrogram.SAMPLE_RATE * 20, buffer.capacity)
}
@Test
fun overflowCollectsEvictedSamplesInOrder() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0) // capacity 4
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
assertEquals(0, buffer.overflowCount, "nothing evicted before the window is full")
buffer.append(floatArrayOf(5f, 6f)) // overwrites 1, 2
assertContentEquals(floatArrayOf(1f, 2f), buffer.drainOverflow(), "evicted samples, oldest first")
assertContentEquals(floatArrayOf(3f, 4f, 5f, 6f), buffer.snapshot(), "live window still correct")
}
@Test
fun drainOverflowClearsItself() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.append(floatArrayOf(5f))
assertEquals(1, buffer.overflowCount)
buffer.drainOverflow()
assertEquals(0, buffer.overflowCount)
assertContentEquals(FloatArray(0), buffer.drainOverflow())
}
@Test
fun resetClearsOverflow() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.append(floatArrayOf(5f))
assertEquals(1, buffer.overflowCount)
buffer.reset()
assertEquals(0, buffer.overflowCount)
}
}
@@ -1,152 +0,0 @@
/*
* 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.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Verifies the DeepCW front-end against the upstream Python reference
* implementation (deepcw-engine examples/python/decode_morse.py).
*
* Model metadata: sampleRate 3200, fftLength 256, hopLength 48,
* 400-1200 Hz -> 65 bins, log1p normalization.
*/
class CwDeepSpectrogramTest {
@Test
fun frequencyBinRange_matchesModelMetadata() {
// binHz = 3200/256 = 12.5; start = ceil(400/12.5) = 32; stop = floor(1200/12.5)+1 = 97
val (start, stop) = CwDeepSpectrogram.frequencyBinRange(3200, 256, 400.0, 1200.0)
assertEquals(32, start)
assertEquals(97, stop)
assertEquals(65, stop - start, "metadata declares 65 frequency bins")
}
@Test
fun compute_producesTimeBy65Matrix() {
// 1 second at 3200 Hz. Reflect padding adds fft/2 on both sides,
// so frames = 1 + (3200 + 256 - 256)/48 = 1 + 66 = 67
val spec = CwDeepSpectrogram.compute(FloatArray(3200))
assertEquals(67, spec.size)
assertEquals(65, spec[0].size)
}
@Test
fun compute_toneLandsInExpectedBin() {
// 700 Hz -> absolute bin 700/12.5 = 56 -> relative index 56 - 32 = 24
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 700.0 * it / 3200.0)).toFloat() }
val spec = CwDeepSpectrogram.compute(audio)
val middle = spec[spec.size / 2]
val peak = middle.indices.maxByOrNull { middle[it] } ?: -1
assertTrue(abs(peak - 24) <= 1, "peak at index $peak, expected near 24")
}
/**
* The waterfall asks for the whole band so that a tone the model cannot read is still
* in the picture. Inside the model's window such a tone leaves nothing to see: the
* brightest column there is noise, and it does not even follow the keying.
*/
@Test
fun compute_wholeBandPlacesAnOutOfWindowTone() {
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 1500.0 * it / 3200.0)).toFloat() }
val display = CwDeepSpectrogram.compute(
audio,
CwDeepSpectrogram.DISPLAY_MIN_FREQ_HZ,
CwDeepSpectrogram.DISPLAY_MAX_FREQ_HZ
)
// DC to Nyquist inclusive: 0..1600 Hz in 12.5 Hz steps.
assertEquals(129, display[0].size)
val middle = display[display.size / 2]
val peak = middle.indices.maxByOrNull { middle[it] } ?: -1
val binHz = CwDeepSpectrogram.SAMPLE_RATE.toDouble() / CwDeepSpectrogram.FFT_LENGTH
assertEquals(1500.0, peak * binHz, absoluteTolerance = binHz, "1500 Hz must land on its own bin")
}
/** The model's own call must keep its exact shape, whatever the display asks for. */
@Test
fun compute_defaultsToTheModelWindow() {
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 700.0 * it / 3200.0)).toFloat() }
val model = CwDeepSpectrogram.compute(audio)
val explicit = CwDeepSpectrogram.compute(
audio, CwDeepSpectrogram.MIN_FREQ_HZ, CwDeepSpectrogram.MAX_FREQ_HZ
)
assertEquals(CwDeepSpectrogram.FREQUENCY_BINS, model[0].size)
assertEquals(model.size, explicit.size)
for (frame in model.indices) {
assertContentEquals(
model[frame],
explicit[frame],
"explicit model range must equal the default"
)
}
}
@Test
fun compute_appliesLog1pSoValuesAreNonNegative() {
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 700.0 * it / 3200.0)).toFloat() }
val spec = CwDeepSpectrogram.compute(audio)
for (frame in spec) {
for (v in frame) {
assertTrue(v >= 0f, "log1p of a magnitude must be >= 0, got $v")
}
}
}
@Test
fun resampleLinear_convertsRateAndLength() {
assertEquals(3200, CwDeepSpectrogram.resampleLinear(FloatArray(8000), 8000, 3200).size)
assertEquals(3200, CwDeepSpectrogram.resampleLinear(FloatArray(44100), 44100, 3200).size)
}
@Test
fun resampleLinear_sameRateIsIdentity() {
val input = floatArrayOf(0.1f, 0.2f, 0.3f)
val out = CwDeepSpectrogram.resampleLinear(input, 3200, 3200)
assertEquals(3, out.size)
assertEquals(0.2f, out[1], absoluteTolerance = 1e-6f)
}
@Test
fun resampleLinear_preservesToneFrequency() {
// A 700 Hz tone sampled at 8000 Hz must still peak at bin 24 after
// resampling to 3200 Hz — this is the path real microphone audio takes.
val at8k = FloatArray(8000) { (0.6 * sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() }
val at3200 = CwDeepSpectrogram.resampleLinear(at8k, 8000, 3200)
val spec = CwDeepSpectrogram.compute(at3200)
val middle = spec[spec.size / 2]
val peak = middle.indices.maxByOrNull { middle[it] } ?: -1
assertTrue(abs(peak - 24) <= 1, "resampled tone peak at $peak, expected near 24")
}
@Test
fun compute_rejectsAudioShorterThanFftLength() {
try {
CwDeepSpectrogram.compute(FloatArray(100))
throw AssertionError("expected an exception for audio shorter than fftLength")
} catch (expected: IllegalArgumentException) {
// desired path
}
}
}
@@ -1,186 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* The pool feeds [CwToneShifter.detectToneHz], which measures a waveform, so the
* samples it hands over must be the most recent audio in chronological order. Getting
* the ring wrap wrong would splice the waveform and corrupt every pitch estimate
* silently - no downstream assertion would notice, which is why these tests drive the
* real class rather than restating its logic.
*/
class CwDetectionPoolTest {
private val capacity = 1280
/** Chunk of a monotonic ramp, so any reordering is visible. */
private fun ramp(from: Int, count: Int) = FloatArray(count) { (from + it).toFloat() }
private fun assertAscending(values: FloatArray) {
for (i in 1 until values.size) {
assertEquals(
values[i - 1] + 1f,
values[i],
absoluteTolerance = 0f,
"sample $i breaks the ramp, so the ring wrap is wrong"
)
}
}
@Test
fun `reports readiness only once capacity is reached`() {
val pool = CwDetectionPool(capacity)
assertFalse(pool.isReady, "an empty pool is not ready")
assertEquals(0, pool.size)
// Three 320-sample chunks are 960 samples: still short.
repeat(3) { pool.add(ramp(it * 320, 320)) }
assertEquals(960, pool.size)
assertFalse(pool.isReady, "960 of $capacity samples is not ready")
pool.add(ramp(960, 320))
assertEquals(capacity, pool.size)
assertTrue(pool.isReady, "a full pool must report ready")
}
@Test
fun `drains a partial fill without stale slots`() {
val pool = CwDetectionPool(capacity)
pool.add(ramp(500, 320))
val drained = pool.drain()
assertEquals(320, drained.size, "only what was added may come back")
assertEquals(500f, drained.first(), absoluteTolerance = 0f)
assertEquals(819f, drained.last(), absoluteTolerance = 0f)
assertAscending(drained)
assertEquals(0, pool.size, "draining empties the pool")
}
@Test
fun `drains exactly the most recent samples once wrapped`() {
val pool = CwDetectionPool(capacity)
// 10 chunks of 320 = 3200 samples through a 1280-sample pool.
repeat(10) { pool.add(ramp(it * 320, 320)) }
val drained = pool.drain()
assertEquals(capacity, drained.size)
assertEquals(3199f, drained.last(), absoluteTolerance = 0f, "the newest sample fed must be last")
assertEquals((3200 - capacity).toFloat(), drained.first(), absoluteTolerance = 0f, "the oldest retained sample must be first")
assertAscending(drained)
}
@Test
fun `keeps only the tail of an oversized chunk`() {
val pool = CwDetectionPool(capacity)
pool.add(ramp(0, 5000))
val drained = pool.drain()
assertEquals(capacity, drained.size)
assertEquals(4999f, drained.last(), absoluteTolerance = 0f)
assertEquals((5000 - capacity).toFloat(), drained.first(), absoluteTolerance = 0f)
assertAscending(drained)
}
@Test
fun `handles single-sample chunks`() {
val pool = CwDetectionPool(capacity)
// Far more single-sample adds than the capacity, exercising every wrap position.
repeat(2000) { pool.add(floatArrayOf(it.toFloat())) }
val drained = pool.drain()
assertEquals(capacity, drained.size)
assertEquals(1999f, drained.last(), absoluteTolerance = 0f)
assertEquals((2000 - capacity).toFloat(), drained.first(), absoluteTolerance = 0f)
assertAscending(drained)
}
@Test
fun `is reusable after draining`() {
val pool = CwDetectionPool(capacity)
repeat(5) { pool.add(ramp(it * 320, 320)) }
pool.drain()
// A second pass must not inherit anything from the first.
pool.add(ramp(9000, 320))
val drained = pool.drain()
assertEquals(320, drained.size)
assertEquals(9000f, drained.first(), absoluteTolerance = 0f)
assertEquals(9319f, drained.last(), absoluteTolerance = 0f)
assertAscending(drained)
}
@Test
fun `clear discards pooled audio`() {
val pool = CwDetectionPool(capacity)
pool.add(ramp(0, 640))
pool.clear()
assertEquals(0, pool.size)
assertFalse(pool.isReady)
pool.add(ramp(7000, 320))
val drained = pool.drain()
assertEquals(320, drained.size, "cleared samples must not reappear")
assertEquals(7000f, drained.first(), absoluteTolerance = 0f)
}
@Test
fun `empty chunks are ignored`() {
val pool = CwDetectionPool(capacity)
pool.add(ramp(0, 320))
pool.add(FloatArray(0))
assertEquals(320, pool.size, "an empty chunk must not change the pool")
assertAscending(pool.drain())
}
@Test
fun `chunk exactly the size of the pool is kept whole`() {
val pool = CwDetectionPool(capacity)
pool.add(ramp(100, capacity))
val drained = pool.drain()
assertEquals(capacity, drained.size)
assertEquals(100f, drained.first(), absoluteTolerance = 0f)
assertEquals((100 + capacity - 1).toFloat(), drained.last(), absoluteTolerance = 0f)
assertAscending(drained)
}
@Test
fun `pooled audio is long enough for the detector to resolve a pitch`() {
// The pool exists to make detection possible at all; prove the pooled length
// actually works rather than only that the plumbing moves samples around.
val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
val pool = CwDetectionPool(capacity)
var phase = 0
repeat(4) {
pool.add(FloatArray(320) { i ->
kotlin.math.sin(2.0 * kotlin.math.PI * 1500.0 * (phase + i) / sampleRate).toFloat()
})
phase += 320
}
assertTrue(pool.isReady)
val detected = CwToneShifter.detectToneHz(pool.drain(), sampleRate)
assertEquals(
1500.0,
detected!!.toDouble(),
absoluteTolerance = 25.0,
"four pooled capture chunks must be enough to detect a 1500 Hz tone"
)
}
@Test
fun `rejects a non-positive capacity`() {
for (bad in listOf(0, -1, -1280)) {
try {
CwDetectionPool(bad)
throw AssertionError("capacity $bad should have been rejected")
} catch (expected: IllegalArgumentException) {
// The decoder derives capacity from a constant; a zero would otherwise
// fail later as a division by zero in the ring arithmetic.
}
}
}
}
@@ -1,287 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Drives the real [CwShiftDecider] with the real [CwToneShifter.analyse].
*
* This suite exists because an earlier version of the same rule lived inside the decoder,
* where tests could only restate it. Mutation testing then showed four injected defects -
* removing the silence guard, comparing shifts instead of tones, never setting the anchor,
* and inverting the hysteresis comparison - all left the suite green. Every test below
* targets one of those, so each is now a real tripwire.
*/
class CwShiftDeciderTest {
private val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
private val hysteresisHz = CwShiftDecider.DEFAULT_HYSTERESIS_HZ
private fun steadyTone(hz: Double, samples: Int = 1280): FloatArray =
FloatArray(samples) { i -> sin(2.0 * PI * hz * i / sampleRate).toFloat() }
private fun noise(samples: Int = 1280, seed: Int = 1, level: Double = 0.02): FloatArray {
val random = Random(seed)
return FloatArray(samples) { ((random.nextDouble() - 0.5) * 2 * level).toFloat() }
}
private fun analyse(audio: FloatArray) = CwToneShifter.analyse(audio, sampleRate)
private fun feed(decider: CwShiftDecider, audio: FloatArray) = decider.accept(analyse(audio))
// --- Mutant (a): the silence guard ---------------------------------------------
@Test
fun `silence retains an established shift`() {
val decider = CwShiftDecider()
val established = feed(decider, steadyTone(1400.0))
assertEquals(CwShiftDecider.Outcome.SHIFTED, established.outcome)
assertTrue(established.shiftHz != 0f, "a 1400 Hz tone must produce a shift")
val silent = feed(decider, noise())
assertEquals(
CwShiftDecider.Outcome.NO_TONE,
silent.outcome,
"silence must be reported as no tone, not as a zero shift"
)
assertEquals(
established.shiftHz,
silent.shiftHz,
absoluteTolerance = 0f,
"silence must not change the shift"
)
assertFalse(silent.changed, "a silent window is not a change")
assertEquals(
established.shiftHz,
decider.shiftHz,
absoluteTolerance = 0f,
"the decider's state must still hold the shift"
)
}
@Test
fun `a run of silence does not erode the shift`() {
val decider = CwShiftDecider()
val established = feed(decider, steadyTone(1400.0)).shiftHz
repeat(8) { i ->
val decision = feed(decider, noise(seed = i + 2))
assertEquals(
established,
decision.shiftHz,
absoluteTolerance = 0f,
"silent window $i changed the shift"
)
}
assertEquals(established, decider.shiftHz, absoluteTolerance = 0f)
assertNotNull(decider.anchorToneHz, "the anchor must survive silence")
}
// --- Mutants (b) and (c): hysteresis anchored on the tone ----------------------
@Test
fun `an estimate hopping across the window edge does not re-shift`() {
// 1200.0 Hz is inside the window (shift 0); 1212.5 Hz, one scan bin away, is
// outside (a large shift). A shift-space comparison lapses here because one side
// is zero, which is exactly where the jump is largest.
val decider = CwShiftDecider()
val first = feed(decider, steadyTone(1212.5))
assertEquals(CwShiftDecider.Outcome.SHIFTED, first.outcome)
val hop = feed(decider, steadyTone(1200.0))
assertEquals(
CwShiftDecider.Outcome.WITHIN_HYSTERESIS,
hop.outcome,
"a one-bin hop back across the edge must be absorbed"
)
assertEquals(first.shiftHz, hop.shiftHz, absoluteTolerance = 0f, "the shift must not move")
assertFalse(hop.changed)
}
@Test
fun `the anchor is set from the tone that produced the shift`() {
val decider = CwShiftDecider()
assertNull(decider.anchorToneHz, "no anchor before the first detection")
feed(decider, steadyTone(1400.0))
assertEquals(
1400.0,
decider.anchorToneHz!!.toDouble(),
absoluteTolerance = 25.0,
"the anchor must be the detected tone"
)
// An in-window tone must anchor too, otherwise a tone drifting from inside the
// window to outside would be measured against a stale reference.
feed(decider, steadyTone(700.0))
assertEquals(
700.0,
decider.anchorToneHz!!.toDouble(),
absoluteTolerance = 25.0,
"an in-window tone must also become the anchor"
)
assertEquals(0f, decider.shiftHz, absoluteTolerance = 0f, "an in-window tone needs no shift")
}
@Test
fun `hysteresis is measured against the anchor rather than the previous estimate`() {
// Walk in 25 Hz steps: each step is under the 40 Hz margin, so a comparison
// against the previous estimate would never fire. Anchored, the shift updates
// once the accumulated move clears the margin.
val decider = CwShiftDecider()
feed(decider, steadyTone(1300.0))
val anchorAtStart = decider.anchorToneHz!!
var tone = 1325.0
var updates = 0
while (tone <= 1450.0) {
if (feed(decider, steadyTone(tone)).changed) updates++
tone += 25.0
}
assertTrue(
updates >= 1,
"accumulated drift must eventually re-shift; anchor started at $anchorAtStart " +
"and the shift updated $updates times"
)
}
// --- Mutant (d): the comparison direction --------------------------------------
@Test
fun `a large retune is followed while small moves are absorbed`() {
val decider = CwShiftDecider()
val before = feed(decider, steadyTone(1400.0)).shiftHz
// Well inside the margin: must be absorbed.
val small = feed(decider, steadyTone(1412.5))
assertEquals(CwShiftDecider.Outcome.WITHIN_HYSTERESIS, small.outcome)
assertEquals(before, small.shiftHz, absoluteTolerance = 0f)
// Well beyond it: must be followed. An inverted comparison would absorb this and
// react to the small move instead.
val large = feed(decider, steadyTone(1000.0))
assertTrue(
large.changed,
"a 400 Hz retune must change the shift (was $before, now ${large.shiftHz})"
)
assertEquals(
CwShiftDecider.Outcome.NO_SHIFT_NEEDED,
large.outcome,
"a 1000 Hz tone is inside the window, so no shift is needed"
)
assertEquals(0f, large.shiftHz, absoluteTolerance = 0f)
}
@Test
fun `an edge tone settles instead of thrashing`() {
val decider = CwShiftDecider()
var changes = 0
// Estimates hopping around the 1200 Hz edge, the worst case for a shift-space rule.
val hops = listOf(1200.0, 1212.5, 1200.0, 1187.5, 1212.5, 1200.0, 1225.0, 1200.0)
repeat(4) {
for (hz in hops) {
if (feed(decider, steadyTone(hz)).changed) changes++
}
}
assertTrue(
changes <= 3,
"an edge tone must settle; the shift changed $changes times in ${hops.size * 4} detections"
)
}
// --- Drift and state consistency ----------------------------------------------
@Test
fun `slow drift keeps the shifted tone inside the model window`() {
val decider = CwShiftDecider()
var tone = 1300.0
var worstOffset = 0.0
while (tone <= 1550.0) {
val decision = feed(decider, steadyTone(tone))
val landed = tone + decision.shiftHz
worstOffset = maxOf(worstOffset, abs(landed - CwToneShifter.TARGET_HZ))
assertTrue(
CwToneShifter.isInsideWindow(landed.toFloat()),
"a ${tone}Hz tone landed at ${landed}Hz, outside the model window"
)
tone += 12.5
}
assertTrue(
worstOffset <= hysteresisHz + 12.5,
"staleness must stay near the margin, worst offset was $worstOffset Hz"
)
}
@Test
fun `reset clears both the shift and the anchor together`() {
val decider = CwShiftDecider()
feed(decider, steadyTone(1400.0))
assertTrue(decider.shiftHz != 0f)
assertNotNull(decider.anchorToneHz)
decider.reset()
assertEquals(0f, decider.shiftHz, absoluteTolerance = 0f, "reset must clear the shift")
assertNull(decider.anchorToneHz, "reset must clear the anchor")
// After a reset the next tone must be acted on rather than absorbed.
val decision = feed(decider, steadyTone(1400.0))
assertEquals(CwShiftDecider.Outcome.SHIFTED, decision.outcome)
assertTrue(decision.changed)
}
@Test
fun `a non-zero shift always has an anchor`() {
// An inconsistent pair would make hysteresis behave differently depending on how
// the state was reached, so pin the invariant across a mixed sequence.
val decider = CwShiftDecider()
val sequence = listOf(
steadyTone(1400.0), noise(), steadyTone(1412.5), steadyTone(300.0),
noise(seed = 5), steadyTone(700.0), steadyTone(1500.0), noise(seed = 9)
)
for ((index, audio) in sequence.withIndex()) {
feed(decider, audio)
if (decider.shiftHz != 0f) {
assertNotNull(
decider.anchorToneHz,
"step $index left a shift of ${decider.shiftHz}Hz with no anchor"
)
}
}
}
@Test
fun `shift always lands the tone on the target`() {
for (hz in listOf(150.0, 250.0, 300.0, 1250.0, 1400.0, 1500.0)) {
val decider = CwShiftDecider()
val decision = feed(decider, steadyTone(hz))
assertEquals(
CwToneShifter.TARGET_HZ,
hz + decision.shiftHz,
absoluteTolerance = 30.0,
"a ${hz}Hz tone must be shifted to the window centre"
)
}
}
@Test
fun `in-window tones are never shifted`() {
for (hz in listOf(400.0, 500.0, 800.0, 1100.0, 1200.0)) {
val decider = CwShiftDecider()
val decision = feed(decider, steadyTone(hz))
assertEquals(
CwShiftDecider.Outcome.NO_SHIFT_NEEDED,
decision.outcome,
"a ${hz}Hz tone is inside the window and must not be shifted"
)
assertEquals(0f, decision.shiftHz, absoluteTolerance = 0f)
}
}
}
@@ -1,175 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Signal-level properties of the shifter: the range the spectrogram expects, the
* detector's threshold trade-off, and behaviour on inputs a phone mic can really produce.
*
* The decision rule that consumes these estimates is covered by [CwShiftDeciderTest].
*/
class CwToneShiftSignalTest {
private val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
/** Keyed CW: gated tone with noise, 60 ms on / 30 ms off, roughly 20 WPM. */
private fun keyedTone(hz: Double, samples: Int = 1280, seed: Int = 1, noise: Double = 0.02): FloatArray {
val random = Random(seed)
val period = sampleRate * 90 / 1000
return FloatArray(samples) { i ->
val gate = if (i % period < sampleRate * 60 / 1000) 1.0 else 0.0
(gate * sin(2.0 * PI * hz * i / sampleRate) +
(random.nextDouble() - 0.5) * 2 * noise).toFloat()
}
}
private fun noiseOnly(samples: Int = 1280, seed: Int = 2, level: Double = 1.0): FloatArray {
val random = Random(seed)
return FloatArray(samples) { ((random.nextDouble() - 0.5) * 2 * level).toFloat() }
}
/**
* The prominence threshold sits between two measured populations and both sides
* matter. Too low and noise is mistaken for a tone, which moves a good signal out of
* the model's range; too high and copyable weak signals are never shifted, which is
* the very failure the feature exists to prevent.
*/
@Test
fun `prominence threshold rejects noise without rejecting weak signals`() {
var falsePositives = 0
repeat(20) { seed ->
if (CwToneShifter.detectToneHz(noiseOnly(seed = seed + 500), sampleRate) != null) {
falsePositives++
}
}
assertEquals(0, falsePositives, "noise must never be reported as a tone")
// Noise at 0.7 against a unit-amplitude tone is roughly 3 dB SNR: audible,
// decodable, and the region an over-tight threshold silently discards.
for (hz in listOf(300.0, 800.0, 1400.0)) {
val detected = CwToneShifter.detectToneHz(keyedTone(hz, noise = 0.7), sampleRate)
assertEquals(
hz,
detected!!.toDouble(),
absoluteTolerance = 25.0,
"a weak but usable ${hz}Hz signal must be detected, not rejected as noise"
)
}
assertTrue(
CwToneShifter.MIN_PROMINENCE > 3.4,
"MIN_PROMINENCE ${CwToneShifter.MIN_PROMINENCE} must clear the measured noise " +
"ceiling of ~3.4"
)
assertTrue(
CwToneShifter.MIN_PROMINENCE < 5.2,
"MIN_PROMINENCE ${CwToneShifter.MIN_PROMINENCE} must not reject weak signals; " +
"keyed CW measures 7.6-9.0 at 0 dB SNR and 5.2-6.7 at -3 dB"
)
}
/**
* The Hilbert kernel's L1 gain is 2.51, so summing the in-phase and quadrature paths
* overshoots: a full-scale square wave measured 2.35 and even a plain sine 1.05. The
* spectrogram takes log1p of the magnitude, so an overshoot is not fatal, but it
* moves the level away from what the model was trained on.
*/
@Test
fun `shifted output stays within the range the spectrogram expects`() {
val shifter = CwToneShifter.Streaming()
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
val square = FloatArray(1280) { if ((it / 8) % 2 == 0) 1f else -1f }
val shiftedSquare = shifter.process(square, shiftHz, sampleRate)
assertTrue(
shiftedSquare.all { abs(it) <= 1f },
"a full-scale square wave overshot: peak was ${shiftedSquare.maxOf { abs(it) }}"
)
shifter.reset()
val sine = FloatArray(1280) { i -> sin(2.0 * PI * 1500.0 * i / sampleRate).toFloat() }
val shiftedSine = shifter.process(sine, shiftHz, sampleRate)
assertTrue(
shiftedSine.all { abs(it) <= 1f },
"a full-scale sine overshot: peak was ${shiftedSine.maxOf { abs(it) }}"
)
// Limiting must not flatten the signal away: the tone still has to be there.
val detected = CwToneShifter.detectToneHz(shiftedSine, sampleRate)
assertEquals(
CwToneShifter.TARGET_HZ,
detected!!.toDouble(),
absoluteTolerance = 30.0,
"limiting must preserve the shifted tone"
)
}
@Test
fun `stateless shift also stays in range`() {
val square = FloatArray(1280) { if ((it / 8) % 2 == 0) 1f else -1f }
val shifted = CwToneShifter.shift(square, -700f, sampleRate)
assertTrue(
shifted.all { abs(it) <= 1f },
"peak was ${shifted.maxOf { abs(it) }}"
)
}
@Test
fun `detector tolerates pathological input`() {
// A wrong shift moves a perfectly good tone out of range, so a bogus estimate is
// worse than none: these inputs must produce the right tone or nothing at all.
for (offset in listOf(0.5, 1.0, 5.0, 50.0)) {
val biased = FloatArray(1280) { i ->
(offset + sin(2.0 * PI * 800.0 * i / sampleRate)).toFloat()
}
val detected = CwToneShifter.detectToneHz(biased, sampleRate)
assertEquals(
800.0,
detected!!.toDouble(),
absoluteTolerance = 25.0,
"a DC offset of $offset must not hide the tone"
)
}
assertNull(
CwToneShifter.detectToneHz(FloatArray(1280), sampleRate),
"all zeros must not report a tone"
)
for (size in listOf(0, 1, 2, 63)) {
assertNull(
CwToneShifter.detectToneHz(FloatArray(size), sampleRate),
"a $size-sample buffer is too short to detect from"
)
}
val withNan = FloatArray(1280) { i ->
if (i == 640) Float.NaN else sin(2.0 * PI * 800.0 * i / sampleRate).toFloat()
}
assertNull(
CwToneShifter.detectToneHz(withNan, sampleRate),
"a NaN sample must yield no tone rather than a garbage shift"
)
// Clipping must not let a harmonic outrank the fundamental.
for (drive in listOf(1.0, 4.0, 20.0, 200.0)) {
val clipped = FloatArray(1280) { i ->
(drive * sin(2.0 * PI * 500.0 * i / sampleRate)).coerceIn(-1.0, 1.0).toFloat()
}
val detected = CwToneShifter.detectToneHz(clipped, sampleRate)
assertEquals(
500.0,
detected!!.toDouble(),
absoluteTolerance = 25.0,
"at ${drive}x drive the fundamental must still win"
)
}
}
}
@@ -1,245 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* [CwToneShifter.Streaming] exists because the decoder shifts one ~320-sample chunk at
* a time. Shifting each chunk in isolation makes the Hilbert FIR convolve against zeros
* at both edges, which distorted 62 of every 320 samples and inflated envelope ripple
* to 8.7x the whole-buffer baseline. These tests fail if that state handling regresses.
*/
class CwToneShifterStreamingTest {
private val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
/** ~100 ms of audio once resampled to 3200 Hz, matching what the decoder receives. */
private val chunkSize = 320
private fun continuousTone(hz: Double, samples: Int): FloatArray =
FloatArray(samples) { i -> sin(2.0 * PI * hz * i / sampleRate).toFloat() }
/** RMS envelope; a steady tone must produce a flat one. */
private fun envelope(audio: FloatArray, window: Int = 48): List<Double> {
val out = mutableListOf<Double>()
var i = 0
while (i + window <= audio.size) {
var sum = 0.0
for (j in i until i + window) sum += audio[j].toDouble() * audio[j]
out += sqrt(sum / window)
i += window / 2
}
return out
}
/** Coefficient of variation of the envelope, as a percentage. */
private fun ripple(audio: FloatArray, skip: Int = 0): Double {
val env = envelope(audio.copyOfRange(skip, audio.size))
val mean = env.average()
if (mean == 0.0) return 0.0
val variance = env.sumOf { (it - mean) * (it - mean) } / env.size
return sqrt(variance) / mean * 100.0
}
private fun processInChunks(audio: FloatArray, shiftHz: Float): FloatArray {
val shifter = CwToneShifter.Streaming()
val out = FloatArray(audio.size)
var offset = 0
while (offset < audio.size) {
val end = minOf(offset + chunkSize, audio.size)
val chunk = audio.copyOfRange(offset, end)
shifter.process(chunk, shiftHz, sampleRate).copyInto(out, offset)
offset = end
}
return out
}
@Test
fun `chunked streaming keeps a steady tone flat`() {
val audio = continuousTone(1500.0, chunkSize * 20)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
val streamed = processInChunks(audio, shiftHz)
// Skip the filter's start-up transient: with no history the first taps are cold.
val skip = 128
val streamedRipple = ripple(streamed, skip)
// Absolute, not relative to the whole-buffer figure: clamping pins a full-scale
// tone at exactly 1.0, so the whole-buffer ripple collapses to ~0.001% and any
// ratio against it explodes. What matters is the absolute number - a 20 WPM dot
// spans 192 samples, so sub-2% envelope ripple cannot move a keying decision.
// Measured 0.79% with state carried across chunks; dropping the filter history
// takes it to several percent, and dropping the phase far higher.
assertTrue(
streamedRipple < 2.0,
"streaming envelope ripple ${streamedRipple}% is too high; chunk-edge " +
"filter state or mixer phase is not being carried"
)
}
/**
* Streaming must match whole-buffer shifting everywhere except the last
* [lookahead] samples of each chunk.
*
* That exception is causal, not a defect: producing output sample `i` needs input
* up to `i + HILBERT_DELAY`, which for the tail of a chunk has not been captured
* yet. A whole-buffer call sees those samples; a live stream cannot. Measured, the
* divergence is confined to the final 3 samples of each 320-sample chunk (under 1%
* of the audio) and vanishes immediately after the boundary, which is why the
* decoder accepts it rather than delaying output by 10 ms.
*/
@Test
fun `chunked output matches whole-buffer output except the causal tail`() {
val audio = continuousTone(1500.0, chunkSize * 12)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
val whole = CwToneShifter.shift(audio, shiftHz, sampleRate)
val streamed = processInChunks(audio, shiftHz)
val lookahead = 32 // HILBERT_TAPS / 2, rounded up
val skip = 128 // filter start-up transient
var worstInterior = 0.0
var worstTail = 0.0
for (i in skip until audio.size) {
val distanceToBoundary = chunkSize - (i % chunkSize)
val delta = abs(whole[i] - streamed[i]).toDouble()
if (distanceToBoundary <= lookahead) {
worstTail = maxOf(worstTail, delta)
} else {
worstInterior = maxOf(worstInterior, delta)
}
}
assertTrue(
worstInterior < 0.01,
"away from chunk tails the two must agree; worst divergence was " +
"$worstInterior, so filter history or mixer phase is not being carried"
)
// The tail is allowed to differ, but not wildly: a broken implementation would
// diverge by the full signal amplitude rather than a fraction of it.
assertTrue(
worstTail < 0.5,
"chunk-tail divergence $worstTail exceeds the causal lookahead budget"
)
}
@Test
fun `shifted chunks land on the target frequency`() {
val audio = continuousTone(1500.0, chunkSize * 16)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
val streamed = processInChunks(audio, shiftHz)
val detected = CwToneShifter.detectToneHz(streamed, sampleRate)
assertEquals(
CwToneShifter.TARGET_HZ,
detected!!.toDouble(),
absoluteTolerance = 30.0,
"streamed audio must end up at the target pitch"
)
}
@Test
fun `zero shift passes chunks through untouched`() {
val shifter = CwToneShifter.Streaming()
val chunk = continuousTone(800.0, chunkSize)
assertSame(
chunk,
shifter.process(chunk, 0f, sampleRate),
"a zero shift must not copy or alter the chunk"
)
}
@Test
fun `history survives a run of zero-shift chunks`() {
// Feeding audio while disabled must still fill the history, so that enabling
// the shift mid-stream does not convolve against leftover silence.
val shifter = CwToneShifter.Streaming()
val audio = continuousTone(1500.0, chunkSize * 6)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
// First three chunks with no shift, then start shifting.
var offset = 0
repeat(3) {
shifter.process(audio.copyOfRange(offset, offset + chunkSize), 0f, sampleRate)
offset += chunkSize
}
val firstShifted = shifter.process(
audio.copyOfRange(offset, offset + chunkSize), shiftHz, sampleRate
)
// With history primed the very first shifted chunk should already be clean;
// a cold filter would show a large amplitude dip at its start.
val head = envelope(firstShifted.copyOfRange(0, 96)).average()
val tail = envelope(firstShifted.copyOfRange(firstShifted.size - 96, firstShifted.size)).average()
assertTrue(
head > tail * 0.7,
"first shifted chunk starts at $head but settles at $tail; history was not kept"
)
}
@Test
fun `reset clears state so the next chunk starts cold`() {
val shifter = CwToneShifter.Streaming()
val audio = continuousTone(1500.0, chunkSize * 4)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
var offset = 0
repeat(3) {
shifter.process(audio.copyOfRange(offset, offset + chunkSize), shiftHz, sampleRate)
offset += chunkSize
}
shifter.reset()
val afterReset = shifter.process(
audio.copyOfRange(offset, offset + chunkSize), shiftHz, sampleRate
)
// Cold filter: the leading samples are attenuated relative to the settled tail.
val head = envelope(afterReset.copyOfRange(0, 64)).average()
val tail = envelope(afterReset.copyOfRange(afterReset.size - 64, afterReset.size)).average()
assertTrue(
head < tail,
"reset must clear history, so the head ($head) should be quieter than " +
"the settled tail ($tail)"
)
}
@Test
fun `handles chunks larger than the history window`() {
val shifter = CwToneShifter.Streaming()
val big = continuousTone(1500.0, 5000)
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
val out = shifter.process(big, shiftHz, sampleRate)
assertEquals(big.size, out.size)
assertTrue(out.all { it.isFinite() }, "output must be finite")
}
@Test
fun `handles chunks smaller than the history window`() {
val shifter = CwToneShifter.Streaming()
val shiftHz = (CwToneShifter.TARGET_HZ - 1500.0).toFloat()
// 16-sample chunks are far below the 62-sample history; the ring must still work.
val audio = continuousTone(1500.0, 16 * 40)
var offset = 0
val collected = FloatArray(audio.size)
while (offset < audio.size) {
val chunk = audio.copyOfRange(offset, offset + 16)
shifter.process(chunk, shiftHz, sampleRate).copyInto(collected, offset)
offset += 16
}
assertTrue(collected.all { it.isFinite() }, "output must be finite")
val detected = CwToneShifter.detectToneHz(collected, sampleRate)
assertEquals(
CwToneShifter.TARGET_HZ,
detected!!.toDouble(),
absoluteTolerance = 40.0,
"even tiny chunks must end up at the target pitch"
)
}
}
@@ -1,212 +0,0 @@
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.hypot
import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* The shifter exists so pitches outside the model's 400-1200 Hz window can still be
* decoded. These tests pin the two properties that make it safe to enable:
* in-window audio is returned untouched, and shifted audio contains one clean tone.
*/
class CwToneShifterTest {
private val sampleRate = CwDeepSpectrogram.SAMPLE_RATE
/** Keyed CW-like tone: a gated sine with smooth edges, plus noise. */
private fun cwTone(hz: Double, samples: Int = 1600, noise: Double = 0.02): FloatArray {
val random = Random(42)
return FloatArray(samples) { i ->
// Gate on for 60 ms, off for 30 ms, repeating - roughly 20 WPM keying.
val cyclePos = (i % (sampleRate * 90 / 1000))
val gate = if (cyclePos < sampleRate * 60 / 1000) 1.0 else 0.0
val value = gate * sin(2.0 * PI * hz * i / sampleRate)
(value + (random.nextDouble() - 0.5) * 2 * noise).toFloat()
}
}
/** Relative magnitude at [hz] using a single-bin DFT with a Hann window. */
private fun magnitudeAt(audio: FloatArray, hz: Double): Double {
var real = 0.0
var imag = 0.0
val omega = 2.0 * PI * hz / sampleRate
for (i in audio.indices) {
val window = 0.5 - 0.5 * cos(2.0 * PI * i / (audio.size - 1))
val value = audio[i] * window
real += value * cos(omega * i)
imag -= value * sin(omega * i)
}
return hypot(real, imag) / audio.size
}
/** Scan 100 Hz..Nyquist and return the strongest bin plus everything above a ratio. */
private fun peaks(audio: FloatArray, minRatio: Double = 0.3): Pair<Double, List<Double>> {
val magnitudes = mutableListOf<Pair<Double, Double>>()
var hz = 100.0
while (hz <= sampleRate / 2.0) {
magnitudes += hz to magnitudeAt(audio, hz)
hz += 12.5
}
val strongest = magnitudes.maxByOrNull { it.second }!!
val others = magnitudes
.filter { it.first != strongest.first && it.second >= strongest.second * minRatio }
// Collapse adjacent bins of the same lobe; only distinct tones matter.
.filter { abs(it.first - strongest.first) > 50.0 }
.map { it.first }
return strongest.first to others
}
@Test
fun `detects tones across the audible range`() {
for (tone in listOf(150.0, 300.0, 500.0, 700.0, 800.0, 1100.0, 1300.0, 1500.0)) {
val detected = CwToneShifter.detectToneHz(cwTone(tone), sampleRate)
assertNotNull(detected, "no tone detected at $tone Hz")
assertEquals(tone, detected!!.toDouble(), absoluteTolerance = 25.0, "detected pitch off at $tone Hz")
}
}
@Test
fun `reports no tone for noise`() {
val random = Random(7)
val noise = FloatArray(1600) { ((random.nextDouble() - 0.5) * 2).toFloat() }
assertNull(CwToneShifter.detectToneHz(noise, sampleRate), "noise must not be mistaken for a tone")
}
@Test
fun `in-window tones are returned untouched`() {
for (tone in listOf(400.0, 500.0, 700.0, 800.0, 1100.0, 1200.0)) {
val audio = cwTone(tone)
val (result, analysis) = CwToneShifter.shiftIfOutsideWindow(audio, sampleRate)
assertFalse(analysis.needsShift, "$tone Hz is inside the window, must not shift")
assertEquals(0f, analysis.shiftHz, absoluteTolerance = 0f, "no shift expected at $tone Hz")
// Same instance: the caller's array must not even be copied.
assertSame(audio, result, "in-window audio must be passed through")
}
}
/**
* The decoder runs this scan even with shifting switched off, purely to tell the
* operator why nothing is decoding. That only works if the scan reaches past the
* model's window: the spectrogram's own pitch readout cannot, being confined to the
* window by construction, and it reports edge leakage as though it were the tone.
*/
@Test
fun `the scan reports tones the model window excludes`() {
for (tone in listOf(120.0, 250.0, 1400.0, 1500.0)) {
val analysis = CwToneShifter.analyse(cwTone(tone), sampleRate)
val reported = analysis.toneHz
assertNotNull(reported, "$tone Hz went undetected, so the UI has nothing to report")
assertEquals(tone, reported!!.toDouble(), absoluteTolerance = 30.0, "$tone Hz was misreported")
assertFalse(
CwToneShifter.isInsideWindow(reported),
"$tone Hz must read as outside the window"
)
}
}
/**
* The waterfall draws a marker at [CwToneShifter.TARGET_HZ] to show the operator where
* a shifted tone is being delivered. Moving the target outside the model's window, or
* moving the window off the target, would leave that marker pointing at a frequency
* nothing arrives at — and nothing else in the build would object.
*/
@Test
fun `the shift target sits inside the model window and clear of its edges`() {
assertTrue(
CwToneShifter.isInsideWindow(CwToneShifter.TARGET_HZ.toFloat()),
"TARGET_HZ ${CwToneShifter.TARGET_HZ} is outside the model window " +
"${CwDeepSpectrogram.MIN_FREQ_HZ}-${CwDeepSpectrogram.MAX_FREQ_HZ} Hz"
)
// Clear of the edges by a decent margin, so a tone landing a little off target
// still lands inside: a target hugging an edge would make the shift pointless.
val margin = (CwDeepSpectrogram.MAX_FREQ_HZ - CwDeepSpectrogram.MIN_FREQ_HZ) / 4
assertTrue(
CwToneShifter.TARGET_HZ >= CwDeepSpectrogram.MIN_FREQ_HZ + margin &&
CwToneShifter.TARGET_HZ <= CwDeepSpectrogram.MAX_FREQ_HZ - margin,
"TARGET_HZ ${CwToneShifter.TARGET_HZ} is within $margin Hz of a window edge"
)
}
@Test
fun `out-of-window tones move to the target with no competing tone`() {
for (tone in listOf(150.0, 200.0, 250.0, 300.0, 350.0, 1300.0, 1400.0, 1500.0)) {
val audio = cwTone(tone)
val (result, analysis) = CwToneShifter.shiftIfOutsideWindow(audio, sampleRate)
assertTrue(analysis.needsShift, "$tone Hz is outside the window, must shift")
val (strongest, competing) = peaks(result)
assertEquals(
CwToneShifter.TARGET_HZ,
strongest,
absoluteTolerance = 30.0,
"$tone Hz did not land on the target"
)
assertTrue(
competing.isEmpty(),
"$tone Hz left a competing tone at $competing (single-sideband mixing failed)"
)
assertTrue(
CwToneShifter.isInsideWindow(strongest.toFloat()),
"shifted tone must land inside the model window"
)
}
}
@Test
fun `shift with zero offset returns the same array`() {
val audio = cwTone(800.0)
assertSame(audio, CwToneShifter.shift(audio, 0f, sampleRate))
}
@Test
fun `shift preserves length and stays finite`() {
val audio = cwTone(1500.0)
val shifted = CwToneShifter.shift(audio, -700f, sampleRate)
assertEquals(audio.size, shifted.size, "length must be preserved")
assertTrue(shifted.all { it.isFinite() }, "output must be finite")
}
@Test
fun `empty input is handled`() {
val empty = FloatArray(0)
assertSame(empty, CwToneShifter.shift(empty, -700f, sampleRate))
assertNull(CwToneShifter.detectToneHz(empty, sampleRate))
val (result, analysis) = CwToneShifter.shiftIfOutsideWindow(empty, sampleRate)
assertSame(empty, result)
assertFalse(analysis.needsShift)
}
@Test
fun `shifted audio survives the spectrogram with energy inside the window`() {
// End-to-end: a 1500 Hz tone is invisible to the model, the shifted one is not.
val audio = cwTone(1500.0, samples = 3200)
val rawSpectrogram = CwDeepSpectrogram.compute(audio)
val rawEnergy = rawSpectrogram.sumOf { frame -> frame.sumOf { it.toDouble() } }
val (shifted, analysis) = CwToneShifter.shiftIfOutsideWindow(audio, sampleRate)
assertTrue(analysis.needsShift)
val shiftedSpectrogram = CwDeepSpectrogram.compute(shifted)
val shiftedEnergy = shiftedSpectrogram.sumOf { frame -> frame.sumOf { it.toDouble() } }
assertTrue(
shiftedEnergy > rawEnergy * 1.5,
"shifting must put more energy in the model window (raw=$rawEnergy shifted=$shiftedEnergy)"
)
assertEquals(
CwDeepSpectrogram.FREQUENCY_BINS,
shiftedSpectrogram[0].size,
"bin count must stay compatible with the model"
)
}
}
@@ -1,154 +0,0 @@
/*
* 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.navigation
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Menu layout rules. Every case here is a bug that shipped at least once, so
* treat a failure as a regression rather than a spec question.
*/
class MenuLayoutTest {
private val all = listOf(
"Satellites", "Passes", "Radar", "Mutual", "Roaming",
"CwDecode", "WavelogLog", "AMSAT", "Map", "Settings"
)
private fun layout(
screenOrder: List<String> = emptyList(),
subMenuOrder: List<String> = emptyList(),
hidden: List<String> = emptyList()
) = MenuLayout.resolve(all, screenOrder, subMenuOrder, hidden)
@Test
fun defaultsPutFivePagesOnTheBarAndTheRestBehindMore() {
val l = layout()
assertEquals(listOf("Satellites", "Passes", "Radar", "Map", "Settings"), l.mainIds)
assertEquals(listOf("Mutual", "Roaming", "CwDecode", "WavelogLog", "AMSAT"), l.moreIds)
}
@Test
fun settingsIsAlwaysReachable() {
// Moving any page onto the bar used to push Settings out of BOTH menus,
// permanently locking the user out of the settings page.
for (page in listOf("Mutual", "Roaming", "CwDecode", "WavelogLog", "AMSAT")) {
val moved = MenuLayout.moveToMain(page, all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue(
"Settings" in l.mainIds || "Settings" in l.moreIds,
"moving $page hid Settings: main=${l.mainIds} more=${l.moreIds}"
)
}
}
@Test
fun movingAmsatToMainActuallyTakesEffect() {
// The legacy migration re-appended AMSAT to the sub-menu unconditionally,
// silently undoing the user's choice.
val moved = MenuLayout.moveToMain("AMSAT", all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue("AMSAT" in l.mainIds, "AMSAT missing from the bar: ${l.mainIds}")
assertTrue("AMSAT" !in l.moreIds, "AMSAT still behind More: ${l.moreIds}")
}
@Test
fun movingWavelogLogToMainActuallyTakesEffect() {
val moved = MenuLayout.moveToMain("WavelogLog", all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue("WavelogLog" in l.mainIds, "WavelogLog missing from the bar: ${l.mainIds}")
}
@Test
fun newPagesUnknownToPersistedOrderDefaultToTheMoreMenu() {
// Upgrading from a build that predates AMSAT and WavelogLog: neither list
// mentions them, so both must land behind More rather than vanishing.
val l = layout(
screenOrder = listOf("Satellites", "Passes", "Radar", "Map", "Settings"),
subMenuOrder = listOf("Mutual", "Roaming", "CwDecode")
)
assertTrue("AMSAT" in l.moreIds, "AMSAT should land behind More")
assertTrue("WavelogLog" in l.moreIds, "WavelogLog should land behind More")
}
@Test
fun everyVisiblePageIsReachableFromSomeMenu() {
// Pages beyond the five slots used to vanish instead of overflowing.
val l = layout(
screenOrder = listOf("Satellites", "Passes", "Radar", "Mutual", "Roaming", "Map", "Settings"),
subMenuOrder = listOf("CwDecode", "WavelogLog", "AMSAT")
)
assertEquals(all.toSet(), (l.mainIds + l.moreIds).toSet(), "every page must be reachable")
}
@Test
fun hiddenPagesAppearInNeitherMenu() {
val l = layout(hidden = listOf("Radar", "Map"))
assertTrue("Radar" !in l.mainIds && "Radar" !in l.moreIds)
assertTrue("Map" !in l.mainIds && "Map" !in l.moreIds)
}
@Test
fun settingsCannotBeHidden() {
val l = layout(hidden = listOf("Settings"))
assertTrue("Settings" in l.mainIds || "Settings" in l.moreIds)
}
@Test
fun theBarNeverExceedsFiveSlots() {
val l = layout(screenOrder = all)
assertTrue(l.mainIds.size <= MenuLayout.MAIN_SLOTS, "bar had ${l.mainIds.size} slots: ${l.mainIds}")
}
@Test
fun movingAPageOutOfTheBarPutsItBehindMore() {
val moved = MenuLayout.moveToMore("Radar", all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue("Radar" in l.moreIds)
assertTrue("Radar" !in l.mainIds)
}
@Test
fun settingsCannotBeMovedOffTheBar() {
val moved = MenuLayout.moveToMore("Settings", all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue("Settings" in l.mainIds || "Settings" in l.moreIds)
}
@Test
fun resolveIsStableWhenAppliedTwice() {
// Persisting what resolve() produced must not change the outcome, or the
// settings list and the bar drift apart on the next recomposition.
val first = layout()
val second = layout(first.mainIds, first.moreIds)
assertEquals(first.mainIds, second.mainIds)
assertEquals(first.moreIds, second.moreIds)
}
@Test
fun movingAPageOntoAFullBarEvictsAnotherPageIntoMore() {
// The bar starts full (5 including Settings), so making room must push an
// existing page into More instead of dropping it.
val moved = MenuLayout.moveToMain("CwDecode", all, emptyList(), emptyList())
val l = layout(moved.screenOrder, moved.subMenuOrder)
assertTrue("CwDecode" in l.mainIds)
assertEquals(all.toSet(), (l.mainIds + l.moreIds).toSet(), "nothing may be lost")
}
}
@@ -1,106 +0,0 @@
/*
* 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.predict
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.time.Instant
class CelestialComputerTest {
private val observer = GeoPos(22.314066, 108.706575)
private fun subLunarLongitude(gha: Double) = if (gha <= 180.0) -gha else 360.0 - gha
@Test
fun `moon hour angle stays within one revolution`() {
// Sample a full synodic month at 37-minute steps so the sweep crosses
// every hour-angle quadrant many times over.
var timeMillis = 1786060800_000L // 2026-08-07T00:00:00Z
val stepMillis = 37 * 60 * 1000L
val endMillis = timeMillis + 30L * 86400_000L
var samples = 0
while (timeMillis < endMillis) {
val gha = CelestialComputer.getMoonPosition(observer, timeMillis).gha
assertTrue(gha >= 0.0 && gha < 360.0, "gha=$gha out of 0..360 at $timeMillis")
val longitude = subLunarLongitude(gha)
assertTrue(
longitude >= -180.0 && longitude <= 180.0,
"sub-lunar longitude=$longitude out of -180..180 at $timeMillis"
)
samples++
timeMillis += stepMillis
}
assertTrue(samples > 1000, "expected a meaningful sweep, got $samples samples")
}
private data class RiseSetCase(
val name: String,
val observer: GeoPos,
val startIso: String
)
@Test
fun `findSunRiseSet returns distinct sunrise and sunset for representative locations`() {
val cases = listOf(
RiseSetCase("Equator at March equinox", GeoPos(0.0, 0.0), "2026-03-20T00:00:00Z"),
RiseSetCase("Equator at September equinox", GeoPos(0.0, 0.0), "2026-09-23T00:00:00Z"),
RiseSetCase("Sydney winter", GeoPos(-33.8688, 151.2093), "2026-06-21T00:00:00Z"),
RiseSetCase("Buenos Aires winter", GeoPos(-34.6037, -58.3816), "2026-06-21T00:00:00Z"),
RiseSetCase("Cape Town winter", GeoPos(-33.9249, 18.4241), "2026-06-21T00:00:00Z"),
RiseSetCase("London summer", GeoPos(51.5074, -0.1278), "2026-06-21T00:00:00Z")
)
cases.forEach { testCase ->
val result = CelestialComputer.findSunRiseSet(testCase.observer, testCase.startIso.toMillis())
val daylightDuration = result.setTimeMillis - result.riseTimeMillis
assertTrue(result.riseTimeMillis > 0L, "${testCase.name}: sunrise should be non-zero")
assertTrue(result.setTimeMillis > 0L, "${testCase.name}: sunset should be non-zero")
assertTrue(result.setTimeMillis > result.riseTimeMillis, "${testCase.name}: sunset should be after sunrise")
assertTrue(daylightDuration > HOUR_MILLIS, "${testCase.name}: daylight duration should be longer than 1 hour")
assertTrue(daylightDuration < DAY_MILLIS, "${testCase.name}: daylight duration should be shorter than 24 hours")
val riseElevation = CelestialComputer.getSunPosition(testCase.observer, result.riseTimeMillis).elevation
val setElevation = CelestialComputer.getSunPosition(testCase.observer, result.setTimeMillis).elevation
assertEquals(SUNRISE_SET_THRESHOLD, riseElevation, absoluteTolerance = 0.02, "${testCase.name}: sunrise should converge near the standard threshold")
assertEquals(SUNRISE_SET_THRESHOLD, setElevation, absoluteTolerance = 0.02, "${testCase.name}: sunset should converge near the standard threshold")
}
}
@Test
fun `findSunRiseSet does not return the same instant for equinox regression cases`() {
listOf("2026-03-20T00:00:00Z", "2026-09-23T00:00:00Z").forEach { startIso ->
val result = CelestialComputer.findSunRiseSet(GeoPos(0.0, 0.0), startIso.toMillis())
val separationMillis = abs(result.setTimeMillis - result.riseTimeMillis)
assertTrue(separationMillis > HOUR_MILLIS, "$startIso: sunrise and sunset should be separated")
}
}
/** ISO-8601 to epoch millis; kotlin.time.Instant is the multiplatform stand-in for the JVM's Instant. */
private fun String.toMillis(): Long = Instant.parse(this).toEpochMilliseconds()
private companion object {
private const val SUNRISE_SET_THRESHOLD = -0.8333
private const val HOUR_MILLIS = 60L * 60L * 1000L
private const val DAY_MILLIS = 24L * HOUR_MILLIS
}
}
@@ -1,133 +0,0 @@
package com.rtbishop.look4sat.core.domain.qrz
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class QrzGridParserTest {
/** A signed-in page for a station that published a locator. */
private val withGrid = """
<table class="detail">
<tr><td class="dh">Callsign</td><td class="di">BG7NTA</td></tr>
<tr><td class="dh">Grid Square</td><td class="di">OL72</td></tr>
<tr><td class="dh">Country</td><td class="di">China</td></tr>
</table>
""".trimIndent()
/** Signed in, but this station has no Grid Square row at all. */
private val withoutGrid = """
<table class="detail">
<tr><td class="dh">Callsign</td><td class="di">W1AW</td></tr>
<tr><td class="dh">Country</td><td class="di">United States</td></tr>
</table>
""".trimIndent()
/**
* What QRZ actually serves for a real callsign when nobody is signed in: no detail table,
* plus its own notice saying why. Transcribed from a live response rather than invented.
*/
private val signedOut = """
<div class="csgn">W1AW</div>
<div>Login is required for additional detail.</div>
<div>Email: Login required to view</div>
""".trimIndent()
/**
* A callsign QRZ has never heard of. Also HTTP 200, also zero detail rows, but no login
* notice - QRZ serves its search form instead of a callsign page.
*/
private val unknownCallsign = """
<div class="search">The available search types are callsign, name, address.</div>
""".trimIndent()
@Test
fun `reads the locator when the station published one`() {
assertEquals(QrzGrid.Found("OL72"), QrzGridParser.parseGrid(withGrid))
}
/**
* The distinction that matters: a station with no grid must not look like an expired
* cookie, because the fix for one is nothing and the fix for the other is re-pasting it.
*/
@Test
fun `a station with no grid is not confused with being signed out`() {
assertEquals(QrzGrid.NotOnFile, QrzGridParser.parseGrid(withoutGrid))
assertEquals(QrzGrid.SignedOut, QrzGridParser.parseGrid(signedOut))
}
/**
* The cookie prompt must fire only when the cookie is the problem. Measured against live
* responses, a mistyped callsign returns a page with no detail rows either - so classifying
* on their absence would blame the cookie and send the operator off to re-paste a working
* one, mid-pass, over a satellite that is about to set.
*/
@Test
fun `an unknown callsign does not read as an expired cookie`() {
assertEquals(QrzGrid.NotOnFile, QrzGridParser.parseGrid(unknownCallsign))
}
@Test
fun `an empty grid cell counts as not on file`() {
val blank = withGrid.replace(">OL72<", "><")
assertEquals(QrzGrid.NotOnFile, QrzGridParser.parseGrid(blank))
}
@Test
fun `whitespace around the locator is trimmed`() {
val padded = withGrid.replace(">OL72<", "> OL72 <")
assertEquals(QrzGrid.Found("OL72"), QrzGridParser.parseGrid(padded))
}
/** Six-character locators are as common as four; nothing may truncate them. */
@Test
fun `a six character locator survives intact`() {
val six = withGrid.replace(">OL72<", ">OL72ab<")
assertEquals(QrzGrid.Found("OL72ab"), QrzGridParser.parseGrid(six))
}
/** QRZ puts the two cells adjacent, but whitespace between them must not break the match. */
@Test
fun `whitespace between the two table cells is tolerated`() {
val spaced = withGrid.replace(
"<td class=\"dh\">Grid Square</td><td class=\"di\">OL72</td>",
"<td class=\"dh\">Grid Square</td>\n <td class=\"di\">OL72</td>"
)
assertEquals(QrzGrid.Found("OL72"), QrzGridParser.parseGrid(spaced))
}
@Test
fun `reads back which callsign the cookie belongs to`() {
val menu = """<li class="leaf last" onclick="return true">BG7NTA <ul class="sub">"""
assertEquals("BG7NTA", QrzGridParser.parseOwnCallsign(menu))
assertNull(QrzGridParser.parseOwnCallsign(signedOut))
}
@Test
fun `a raw cookie header is passed through unchanged`() {
val raw = "qz_userid=1266043; qz_sess=abc123"
assertEquals(raw, QrzGridParser.cookieHeader(raw))
}
/** The shape a cookie-export extension produces. */
@Test
fun `a json cookie export is flattened into a header`() {
val json = """
[{"domain":".qrz.com","name":"qz_userid","value":"1266043"},
{"domain":".qrz.com","name":"qz_sess","value":"abc123"}]
""".trimIndent()
assertEquals("qz_userid=1266043; qz_sess=abc123", QrzGridParser.cookieHeader(json))
}
@Test
fun `an empty cookie yields an empty header`() {
assertEquals("", QrzGridParser.cookieHeader(" "))
}
/** Malformed JSON is handed over as-is rather than silently becoming empty. */
@Test
fun `unparseable json is passed through rather than dropped`() {
val broken = """[{"nope":"nothing here"}]"""
assertEquals(broken, QrzGridParser.cookieHeader(broken))
}
}
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff. Show more