Compare commits

..
173 Commits
Author SHA1 Message Date
mckero 9ca122a734 test(kmp): make commonTest sources compile on kotlin/native
With the main source sets now compiling on both platforms the native
test compilation finally ran, and it rejected a handful of test-side
forms the jvm toolchain silently accepts.

Backtick test names are mapped onto native symbols, where a comma is
an illegal character, so three names drop the comma; the wording keeps
the same meaning. java.lang.Math.PI has no common analogue and becomes
kotlin.math.PI, matching the already-qualified kotlin.math.sin call on
the same line. String.toByteArray() is jvm-only, and the byte-length
assertion for the APRS line budget switches to encodeToByteArray(),
the same replacement the production sources went through.
2026-09-27 10:54:16 +01:00
mckero 904d1ffbea fix(kmp): replace remaining jvm-only encoding calls in common sources
The previous round fixed the convention plugin and the native expect
declarations, which let both platforms compile far enough to reveal the
next layer: a handful of jvm-only call forms that survived the original
kotlin/native sweep because they look like plain kotlin.

String.toByteArray() and Charsets.UTF_8 live in java.nio.charset and do
not exist on kotlin/native; the stdlib equivalents encodeToByteArray()
compile everywhere and are byte-identical for utf-8, so the APRS packet
length budget and the ADIF field length calculation keep their exact
arithmetic. The DatabaseRepoTest helpers kept an InputStream return type
after their bodies were moved to ByteArray sources, and the java.io
import was gone with the sweep, so the android unit test task could not
resolve them; the fake source maps were already typed () -> ByteArray,
so the return type simply follows the data it now feeds.
2026-09-27 10:44:48 +01:00
mckero 9deb517874 fix(build): configure core domain source sets through container members
The second CI round got past the missing configure import but still
failed in the same file: bare name accessors inside sourceSets { }
(commonMain.dependencies { ... }, commonTest, jvmTest) are kotlin-dsl
script syntax generated for .kts files. Plugin source compiled as plain
Kotlin has no such accessors on its classpath, so the four dependency
blocks failed with receiver type mismatches while every real member call
around them - jvmToolchain, jvm(), the ios targets, binaries.framework -
already resolved.

Configure the source sets through the container API instead:
sourceSets.getByName("commonMain").dependencies { ... }. getByName,
dependencies and implementation are all members on types that ship with
KGP 2.4.10, verified against the gradle plugin jars byte for byte.
getByName is safe at this point because jvm() above has just created the
jvm source sets synchronously; commonMain and commonTest exist as soon
as the multiplatform plugin is applied.
2026-09-27 10:28:37 +01:00
mckero fa91e89024 fix(build): add missing gradle-kotlin-dsl import to the core domain convention plugin
The iOS CI run failed in both jobs before reaching any product code: the
convention plugin itself did not compile. CoreDomainPlugin.kt used the
reified extensions.configure<KotlinMultiplatformExtension> { } form, but
unlike every other plugin in this directory it was missing the
org.gradle.kotlin.dsl.configure import. Without it only the member
overloads taking an explicit type parameter resolve, so the extension
receiver cannot be inferred and all twenty subsequent unresolved
references - jvmToolchain, jvm(), iosArm64(), binaries.framework,
sourceSets with the commonMain/commonTest/jvmTest accessors - are one
cascading failure, not twenty bugs.

build-logic is the first thing both CI jobs compile, and it has never
been compiled anywhere before this run, so the workflow is doing exactly
what it was added for: catching what no local machine can check.
2026-09-27 10:07:08 +01:00
mckero 1a3c94f1e0 refactor(domain): make core:domain multiplatform so iOS can reuse it
The orbital maths, the satellite models and the repository contracts sat in a Kotlin/JVM
module, so an iOS target could not share a single line of them: java.lang.String.format,
InputStream, System.currentTimeMillis, java.util.Locale and org.json are all JVM-only, and
the tests that covered them used JUnit4. core:domain now declares jvm, iosArm64 and
iosSimulatorArm64 targets, its sources moved to commonMain/commonTest, and the JVM-only
pieces were replaced with multiplatform equivalents: java.lang.String.format by a shared
printf implementation, System.currentTimeMillis by kotlin.time.Clock, InputStream by
ByteArray, org.json by kotlinx-serialization, Locale by nothing at all. Tests that read
classpath resources (javaClass.classLoader) moved to jvmTest, because that is JVM-only
behaviour rather than a JVM-only API.

Auditing the migration against the old module turned up four things that were wrong rather
than merely ported:

- java.lang.String.format rounds the shortest decimal representation of a double half-up,
  not the binary value: "%.3f" of 0.5005 is "0.501", because the stored double is
  0.50049999999999994493. The shared implementation scaled in binary first and printed
  "0.500", which would have changed APRS position packets and the Wavelog frequency fields
  against the released Android app. It now takes the digits from the decimal representation
  and rounds them with integer arithmetic, and jvmTest compares it against
  String.format(Locale.ROOT, ...) over 40 000 sampled doubles plus the boundary cases, while
  commonTest pins literals so the iOS run checks the same digits.

- The queue mutators lost the kotlin.jvm.Synchronized monitor each of them had. It is not a
  JVM-only annotation - it is an optional expectation, so it still compiles in common code -
  but the stdlib deprecated it for common use in 1.8 and made it an error in 2.1. The monitor
  is a platform actual now: the JVM keeps the real monitor, since Compose and the upload
  coroutine both reach the queue there, and iOS carries a documented placeholder until the
  iOS side has a second thread to protect against.

- 107 assertions in DataParserTest and QthConverterTest were bare kotlin.assert calls, which
  a build without -ea skips silently: they are assertTrue now, so the iOS run cannot pass
  vacuously. The three Locale.setDefault cases (ar-EG, bn-BD, fa-IR) that used to guard APRS
  output against Eastern Arabic digits moved to jvmTest instead of being deleted with the
  Locale dependency - APRS-IS is an ASCII protocol, and Locale.setDefault does not exist on
  iOS.

- @Volatile on the LoTW name cache would not have compiled for iOS either: kotlin.jvm's
  variant is an error in common code since 2.1. kotlin.concurrent.Volatile is the
  multiplatform annotation, and it is the stronger form: it takes effect on Kotlin/Native
  rather than being ignored.

A second audit pass over the files the first one could not reach - the HTTP client, the
parsers, the queue and the injection - found three more:

- OkHttpHttpClient built its Request outside the try, so a URL OkHttp refuses to parse left
  postQso/testToken/getStation as an exception, and neither caller catches one. The client it
  replaced reported HTTP -1 and let the caller treat it as a failure; building the request
  inside the try restores that, and a transport failure reports -1 again rather than 0.

- WavelogQueue's readers were stricter than the org.json ones they replaced. A timestamp
  stored as 1234.0 (or "1234.0") read back as 0L instead of 1234 - a QSO uploaded as 1970 -
  and a field holding an object or array threw the whole list away instead of falling back.
  The readers coerce decimals, keep the old defaults and no longer throw, matching optLong,
  optInt, optString and optBoolean.

- The ADIF dates went through the JVM default locale before, so a device set to Arabic wrote
  Eastern Arabic digits into the QSO date. The shared formatter only ever produces ASCII,
  which the locale cases in AprsPacketDefaultLocaleTest pin down.

Verified locally with ./gradlew jvmTest (343 tests, 0 failures) and the multiplatform gate
in check-multiplatform.sh, which now also refuses JVM-only stdlib APIs that resolve in common
code but fail to compile for iOS: @Synchronized, kotlin.jvm.Volatile, synchronized(),
toUpperCase/toLowerCase/capitalize, BigDecimal. The iOS targets themselves need the macOS
runner in .github/workflows/ios-kmp.yml.
2026-09-27 08:55:49 +01:00
mckero abb73ffef7 build: bump to 4.6.2 (versionCode 469)
Carries the CW record fixes: the record no longer deletes its own text while decoding,
a drifting tone no longer wipes it instead of filling it, the archive path no longer
races itself when capture stops, and the decoded text can finally be copied off the
screen.

Also stops the APRS version string drifting, which the comment on it had predicted and
which had already happened again: it still read 4.6.0 while the app shipped 4.6.1, so
every station on the network was told the wrong version. AprsReporter now takes the
version as a parameter and the app module passes BuildConfig.VERSION_NAME, which
required turning on the buildConfig feature - AGP 8 does not generate the class
otherwise. The literal cannot fall out of step with the build again.
2026-08-27 15:41:07 +00:00
mckero cc4f156c83 fix(cw): a drifting tone wiped the record instead of filling it
The record could go from a screenful of text to less, and then to nothing at all, while
decoding was still running. The cause is dropBufferedAudio(), which runs on every change
of shift - and the shift tracks the detected tone, which drifts across a pass.

The live window is the only route into the archive: audio gets there by being pushed out
by newer audio. Clearing the window therefore did not merely discard 20 s, it reset the
progress towards ever archiving anything. Modelled at 18 WPM, a drift every 20 s meant
five minutes of listening archived not one character, however long the operator waited -
the window was always wiped before the first sample could be evicted. With the record
still concatenating the live decode at the time, each wipe also cut the visible
transcript short, which is the text going backwards and then never accumulating.

Retiring the window instead of dropping it fixes both. Those samples cannot stay - one
spectrogram over two shift amounts smears the tone - but they were shifted consistently
and they are complete, so they decode fine on their own. They are queued and archived by
the normal path, keeping dropBufferedAudio() non-suspending: both callers sit on the
synchronous capture path, and decoding there would put an inference inside the tone
scan. Modelled over 300 s, a drift every 5 s goes from 0 characters archived to 449.

An earlier attempt at this - keeping archiveSize instead of zeroing it - was wrong and
the probe rejected it: with the window wiped before it ever overflowed, that buffer was
empty, so preserving it preserved nothing.

The queue is synchronised (written from capture, drained from capture and flush) and
capped at four windows, dropping the oldest when full: a tone drifting on every
detection scan would otherwise queue faster than the decoder can drain.

Also from an audit of the previous two commits:

- The copy button was gated on the record, which is empty for the opening half-minute
  while the first batch accumulates. That greyed out the one control that rescues the
  text over exactly the short exchange most likely to be lost. It now copies the live
  window too, and the empty state says which surface updates sooner.
- cw_copy, cw_copied, cw_record_label and cw_record_empty were missing from values-id,
  values-in and values-tr, which carry the full UI strings, so those users saw English.
- Dropped a KDoc block left dangling by 8445c170, which had removed the constant it
  documented.
2026-08-27 15:24:01 +00:00
mckero 3810e76ea2 fix(cw): the archive path raced itself when capture stopped
flush() runs on a different coroutine from processBuffer - on pause from the screen's
own effect, and from the app scope as the screen leaves - so both were appending to
committedText concurrently. That append is a read, an inference lasting hundreds of
milliseconds, and only then a write, so the window for interleaving is the whole
inference: the later write wins and an entire batch of text is gone. Modelled over 40
trials the unlocked version lost 160 characters, averaging a full batch each time.

Worse, both paths touch archiveBuffer and archiveSize. flush() zeroes the index after
copying out a snapshot; the capture coroutine then writes from zero into slots that
snapshot already covered, so the same audio decodes twice and the text appears twice.

Both failures land at the moment the operator stops listening and starts reading,
which is the worst possible time for the record to be wrong.

archiveLock now serialises the archive path. It is a separate mutex from
inferenceLock, which is a tryLock that drops work when contended - right for the live
window, where another decode is 1.5 s away, and wrong here, where dropping a batch
discards the audio for good. Mutex is not reentrant, so archiveDecode is split into a
locking shell and archiveDecodeLocked for callers already holding it.

reset() is left unsynchronised and now says so: an archive decode in flight can land
after it returns, leaving a few characters behind. Making it suspend to close that
window would push suspension onto every caller including a button handler, and the
operator who asked to clear can ask again.
2026-08-27 15:09:24 +00:00
mckero 5ed76dba31 fix(cw): the record deleted its own text while decoding
The record pane concatenated the live decode onto the archived text. The live decode
is the 20 s window, replaced wholesale every 1.5 s because DeepCW is a whole-segment
CTC model that rewrites earlier characters as more context arrives. So the tail of
the record kept changing and could get shorter - text vanishing from under the
operator while the decoder was still running.

A previous attempt (828fd0fb) added decodePending() to cover the gap while audio
waits to be archived, but the call site was never wired up. The function had no
callers and pendingText was only ever cleared, never assigned, so that fix has never
once run and the gap it targeted stayed open. Both are deleted here.

The record now binds to archived text only, which is append-only, so it cannot
shrink. That moves the whole problem to latency, which was 20 s window + 15 s batch:
nothing at all in the record for the first 35 s of a session, and thereafter a stall
of up to 15 s each cycle. The batch is now 4 s, holding the stall under the ~4.7 s a
seven-character call sign takes at 18 WPM, while the archive path still fires less
than half as often as the live redecode.

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. So pausing
or leaving the screen discarded whatever was in flight - the end of every
transmission, the part with the call sign in it. flush() archives both, pending batch
first so the text is not transposed, and is called on pause and before close(). On
the way out it runs on appScope, because the screen's own scope is cancelled as it
leaves and would abort the decode.

Also: the record was an unlabelled grey box showing a bare ellipsis, which reads as a
disabled text field. It now has a label, an empty state that says what it is for, and
a copy button - until now there was no way to get the decoded text off the screen at
all, so an operator who had just copied a call sign by ear had to transcribe it a
second time by hand.

CwArchiveTimingTest covers the timing against the real constants rather than copies;
it caught a 5 s batch exceeding the call-sign bound during this change. The archive
path had no test coverage before.
2026-08-27 15:01:04 +00:00
mckero 78a6f270bf fix(cw): filter before decimating, so high tones stop smearing across the band
The operator reported that any tone leaked across the whole display - "even 3 kHz spreads
over the entire band, like taking a piss". The tone shifter was the suspect, since it had
been changed recently. It turned out to be innocent: the audio reaching it was already
ruined.

Capture runs at 44100 Hz and the model needs 3200 Hz, so resampleLinear decimates by a
factor of nearly 14. It interpolates between samples and nothing removes the content above
the new Nyquist of 1600 Hz first, which is the one thing decimation cannot skip. Measured on
44100 Hz input:

    3000 Hz tone  ->  ghost at  200 Hz, 119x the spectral mean
    2400 Hz tone  ->  ghost at  800 Hz
    1800 Hz tone  ->  ghost at 1400 Hz
    5000 Hz tone  ->  ghost at 1400 Hz

Each ghost is as strong as a real signal, so a tone nothing is transmitting on looks
entirely convincing. Worse for actually copying anything: the whole 1600-22050 Hz band of
hiss folds down on top of the signal and lifts the noise floor across the display. That is
the smearing.

CwAntiAlias is a 127-tap windowed-sinc low-pass, Blackman-windowed because sidelobe level is
what decides how much of the folded band survives, cut off at 92% of the target Nyquist so
the transition lands inside the discarded region. Measured suppression at the fold
frequency: 2400 Hz down 69 dB, 3000 Hz down 81 dB, 5000 Hz down 96 dB. 1800 Hz only makes
16 dB - it sits just past the 1472 Hz cut-off and 127 taps cannot be steeper without costing
more time than a phone has during a pass. The tests assert the measured numbers rather than
the ones I hoped for.

resampleLinear itself is untouched. Its comment notes it matches the reference implementation
DeepCW was trained against, so changing its arithmetic would move the spectrogram away from
what the model expects.

The streaming path holds output back by the group delay. A first attempt let the lookahead
taps read zeros at the end of each chunk, which diverged from whole-buffer filtering by
0.134 across the last 44 samples of every chunk - a click at each boundary. Holding output
back makes the two identical to within 1e-8. The cost is 63 samples, 1.4 ms, against a 20 WPM
dot of about 60 ms.

Both the decoder and the waterfall filter now. The waterfall mattered as much as the
decoder: it was showing the folded spectrum, which is what the operator was looking at.
2026-08-27 14:03:30 +00:00
mckero 8445c17033 fix: remove the receive-only notice, and stop the CW record scrolling itself
Two things the operator asked for after running 4.6.1.

The receive-only notice named a state this app does not have. APRS-IS lets an unverified
station connect and then discards its packets, which is what "receive-only" means at the
protocol level - but this app only reports its own position. There is no receiving side to
it, and none intended, so telling the operator they are in receive-only mode described a
mode that does not exist here. Without a passcode the packet does not arrive, and the
unverified notice already says exactly that. The string is gone from all five locales,
along with the AprsReport.receiveOnly field, which had no remaining consumer.

AprsPasscode.classify stays: loginValue still uses it, and its tests hold the distinction
between a deliberate -1 and a typo, which is a separate defect worth keeping fixed.

The CW history pane no longer follows the decode. Its whole purpose is to be read back, and
a record that scrolls itself is worse than paper - as the operator put it, if it scrolls
away then why use a decoder instead of listening and writing it down, since paper does not
erase itself. The single line above it is where new characters appear; that still scrolls,
because that is its job. A down arrow in the toolbar jumps to the newest text when wanted.

Not fixed here: logged times in the log page look wrong and inconsistent. I proposed a
timezone explanation and wrote a probe, and the probe disproved it - on a real JVM both the
session header and the row times are stable and both resolve to local time. That reverted
attempt is not in this commit. The cause is still unknown.
2026-08-27 07:31:20 +00:00
mckero e315c87f05 build: bump to 4.6.1 (versionCode 468)
34 commits since 4.6.0, 56 files, +4902/-365. Three areas that were diagnosed as broken and
rebuilt: APRS beaconing, WaveLog upload, and the satellite data source URLs.

The one that mattered most: 4.6.0 reported every APRS beacon as sent regardless of outcome,
so nobody running it could tell whether their station had ever reached the network. That is
fixed, and the login and refusal paths are verified against live APRS-IS servers - the old
login line was malformed and euro.aprs2.net, noam.aprs2.net and rotate.aprs2.net all refused
it, which the app read as success.

WaveLog uploads now read the reply body. A rejected contact used to be marked uploaded and
dropped from the queue, so the contact was lost while the screen said it went up.

In-app release notes updated in the five locales that carry them. Turkish, Indonesian and
Malay get the English text rather than the previous version's notes, which would otherwise
describe the wrong release.

What is NOT verified: no packet from this build has been confirmed on aprs.fi, and nothing
about the foreground service, the Doze-proof alarm or any composable has been executed on a
device - there is no emulator here. The transmit path needs a licensed callsign and a real
passcode. A six-step checklist for that is in
.hermes/plans/2026-08-26_aprs-verification-checklist.md.
2026-08-27 01:00:24 +00:00
mckero e27d692e8f fix(log): the grid check let non-ASCII digits through and refused a legal length
Checked against ADIF 3.1.7 (2026-03-22, the current release) rather than my own reading. Two
of my rules were wrong.

Char.isDigit() is Unicode-aware and covers the whole Nd category - some 600 characters. So
Arabic-Indic, Devanagari, Persian and fullwidth digits all passed as a square pair, which a
localised keypad produces without the operator seeing any difference. The spec is explicit:
"Digit - an ASCII character whose code lies in the range of 48 through 57, inclusive."
Wavelog stores GRIDSQUARE verbatim, so such a value would never match a real grid in any
statistics or VUCC query - the exact failure this validation exists to prevent.

Two-character locators are legal. The GridSquare type is "a case-insensitive 2-character,
4-character, 6-character, or 8-character Maidenhead locator" and the GRIDSQUARE field
description repeats all four. My comment claimed Maidenhead had no other lengths, and a test
name asserted there was no two-character form. Both were wrong. It is accepted now with a
note that a field is accurate to about 1000km - the same treatment four characters already
had. That also uncovered a latent crash: the square-pair check read index 2 of a string that
may only have two characters.

What survived the check: the A-R field range is right, verified by replicating
qthToPosition's arithmetic - SS12AA decodes to 92N 182E, past both the pole and the
antimeridian, while RR99 is the last cell inside the world. Wavelog's own Qra.php validates
with the same range. The subsquare A-X range and digits in positions 7-8 are also correct.

On 10 and 12 character locators the spec says store the first 8 in GRIDSQUARE and the rest in
GRIDSQUARE_EXT. Neither WavelogQso nor Wavelog's field list carries GRIDSQUARE_EXT, so the
extra pair has nowhere to go; the field clips at 8, which produces the spec-correct GRIDSQUARE
value. Recorded in a comment rather than pretended to be deliberate.

17 tests now, including the four non-ASCII digit families and the two-character boundary.
2026-08-26 12:54:51 +00:00
mckero 6c67aa2718 feat(log): check a typed grid before it reaches the log
The grid field accepted anything six characters long, so "ZZ99ZZ", "123456" and a callsign
all reached WavelogQso.gridsquare and then the ADIF GRIDSQUARE field. Wavelog stores what
arrives, and a wrong square is worse than a missing one: it pollutes grid statistics and VUCC
tracking, where the error is invisible until an award check disagrees with the log.

GridEntry follows the rule the callsign field settled on - refuse only what is certainly
wrong. It rejects a length Maidenhead does not have, a field pair past R (S-X decodes beyond
the poles, which is how a plausible entry produces an impossible position), a square pair
that is not digits, and a subsquare past X. Everything else is accepted.

Four characters is accepted with a note that it is only accurate to about 100km, because
plenty of satellite operators exchange only the square and refusing that would reject good
data. The app's own isValidLocator could not be reused: it requires six characters and is
private.

Two things the field does better now. It takes eight characters rather than six, since the
extended form exists and truncating it would silently move the location. And case is
normalised on commit rather than while typing, so the cursor no longer jumps mid-entry - the
logged value is OL72ap, the conventional rendering, whatever was typed.

14 tests, including a cross-check that anything accepted at six characters or more also
decodes through the app's own qthToPosition. Without that the two would be free to disagree
about what a grid is.
2026-08-26 11:32:49 +00:00
mckero cb3ebe7870 feat(log): the counterpart grid can be typed
On FM satellites the grid is the exchange - it is what the other station sends you and what
you send back. Until now it could only arrive by scraping QRZ, which needs a cookie the
operator may not have pasted, and which returns nothing at all for a station with no locator
on file. So the field that carries the actual content of an FM contact was the one field the
operator could not fill in.

It is the second field, optional, six characters, uppercased. A typed grid also skips the
QRZ lookup entirely rather than racing it: what the operator heard on the air beats what a
web page says, and letting the scrape overwrite it would silently replace good data with a
guess.

The value is captured before the field clears, so the QSO carries it and the next contact
starts empty. WavelogQso.gridsquare already existed for the scraper to fill, so nothing about
the stored shape changes and no migration is needed.

This was the interaction study's second-ranked conclusion, after the editable time. Both come
from the same observation: the screen was built for someone typing during a pass, and the
operators it is for are working the radio instead.
2026-08-26 10:38:24 +00:00
mckero e2263668ce fix(log): the table grid was nearly invisible and the sent column vanished at night
Three contrast defects, each measured with a WCAG relative-luminance probe rather than
eyeballed.

GridLineColor was 0xFF3A3A3A: 1.65:1 against the navBar background and 1.36:1 against a
card, where Material asks 3:1 for non-text elements. Every rule and column separator on the
Log page is drawn with it, so the grid the page is built around was barely there - and gone
in sunlight. 0xFF6D6D6D is the lowest grey clearing 3:1 against both (3.62:1 and 3.00:1).

The upload column was a green tick and nothing else. This app applies a night filter that
zeroes green and blue, under which CheckGreen computes to 1.17:1 - the column disappeared
entirely. Changing the colour does not fix it, because colour was also the only thing
separating sent from waiting, which is the case Material calls out directly. The cell now
reads OK or an ellipsis, so the state survives both the filter and colour blindness, and a
contact that has not been tried is finally distinguishable from one that has.

The linear-transponder passband range was 11sp, below Material's body-small floor of 12sp.
That is the frequency an operator reads mid-pass to know where the transponder ends. The
session group header stays at 11sp: it is a label, not information.

Yellow survives the night filter at 4.69:1 because it is red-dominant, so the swipe and undo
affordances needed nothing here.
2026-08-26 10:25:39 +00:00
mckero 91263674a9 fix(log): a screen reader could not delete a contact at all
A Material 3 conformance audit measured three real defects on the logging screen.

Deleting was reachable only by dragging. SwipeDeleteRow declared no semantics, so TalkBack
saw a row of text with no actions - a switch or Voice Access user could not delete a record,
not with difficulty but at all. The arming threshold was 75% of row width, roughly 249dp of
continuous travel on a 360dp phone, against 120dp in this project's own SwipeableItem. Delete
and undo are now custom accessibility actions on the row, which is the case the Compose
accessibility guide names explicitly: swipe gestures should be exposed this way because they
are hard or impossible for users with motor impairments.

The undo affordance was a 29dp target with a five-second countdown running behind it - the
worst place in the screen to be hard to hit, because a miss is unrecoverable. Now 48dp by
64dp, matching the mode and time rows.

The trash glyph was the emoji U+1F5D1, which renders differently on every device and font
and which this project forbids as an icon. ic_delete.xml already existed and is used in three
other screens.

Not addressed, and worth recording from the same audit: the table grid line at 0xFF3A3A3A
computes to 1.65:1 against its background where Material asks 3:1, so the grid the Log page
is built around is nearly invisible and gone in sunlight; and under the app's night filter
the green upload tick collapses to 1.27:1 while being encoded in colour alone.
2026-08-26 07:13:43 +00:00
mckero 9576607fc6 fix(log): mark a held clock in words, not only in colour
Three corrections to the editable-time commit.

The held clock was distinguished only by colorScheme.primary. Material is explicit that
colour must not be the sole carrier of meaning, and roughly one man in twelve cannot
reliably separate that colour from the default text. Missing it costs every remaining
contact the wrong time and, for a pass across midnight UTC, the wrong day. The row now reads
"Held at 23:58" rather than just showing it in a different colour.

The comment on the state claimed rememberSaveable survives rotation but not process death.
Official documentation says the opposite: it goes through the saved instance state and does
survive system-initiated process death. A probe traced the one case that genuinely loses the
hold - the user swiping the app away - and not restoring it there is correct, since a clock
pressed hours ago would put the next session's contacts on the wrong day. The comment says
that now instead of something false.

MenuAnchorType is deprecated in favour of ExposedDropdownMenuAnchorType. Surfaced by a
subagent's build log rather than mine, because my grep filter was hiding warnings.
2026-08-26 06:43:53 +00:00
mckero 00b7b25cc1 feat(log): the contact time can be set, for transcribing after a pass
The screen stamped System.currentTimeMillis() with no way to change it, which assumes
contacts are typed as they happen. Serious satellite operators do not work that way: the
documented practice from AMSAT and DX Engineering 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.

Measured with a probe against a realistic pass - eight minutes, five contacts, twelve
minutes to transcribe: every contact was stamped 10 to 12 minutes late. LoTW wants both
sides within 30 minutes, so that survives a brisk transcription and fails a slow one.

The case that fails outright is a pass crossing midnight UTC. Transcribing 23:58 at 00:05
the next day put the contact a full 24 hours in the future, which can never be confirmed.
PassClock reads an absolute time later than now as belonging to the previous day, because
passes cross midnight routinely and transcription always happens afterwards.

One field takes both forms: an absolute UTC time (14:55 or 1455) or an offset (+3, -2m).
A separate widget for each is more to reach for than an operator wants while holding an
antenna. The parse is deliberately narrow - anything unclear is Unrecognised and the clock
stays put, because a mis-parsed time silently backdates a contact and nothing downstream
would catch it. The field says so while it is being typed rather than after committing.

A held clock is shown in the primary colour, since logging at the wrong time silently is the
failure this exists to prevent. The row is 48dp with Role.Button, like the mode row.

PassClock is pure and lives in core:domain with 15 tests. The day boundary is passed in
rather than computed there, because core:domain holds no calendar.
2026-08-26 06:32:34 +00:00
mckero a3e3932f73 fix(log): TalkBack could not find the mode row
The tappable mode row used a bare `clickable`, which declares no role. TalkBack read it as
two pieces of text with nothing to say it could be activated, so the only way to correct a
wrong mode was invisible to anyone using a screen reader - and the row had just become the
only way to reach that field.

Role.Button plus an onClickLabel naming the action. The label lives in the resource files
like every other user-visible string.

Caught by self-review against the project's own accessibility pattern in Components.kt
rather than by a test; Compose UI is not unit-tested here, so this class of defect is only
ever found by reading.
2026-08-26 06:17:38 +00:00
mckero 3d3db784a3 fix(log): the mode field kept the previous transponder's value
Two things about the mode on the logging surface.

It was held in `remember` with no key, so switching transponder mid-session kept the mode
from the transponder before it. The operator saw the old value in the field and it went out
with the upload - a wrong mode nobody chose. It is now keyed on the transponder uuid.

It was also a text field the operator had to look at on every contact, when the value comes
from the transponder record anyway. A pass lasts eight minutes; the study on satellite
logging is blunt that the fast surface should carry one typed field, not two. The mode is
now shown as a row and the field appears when the row is tapped, because a transponder
record can be wrong and the operator still has to be able to say so.

The row is 48dp tall, which is the Material Design minimum for anything tappable. Vertical
padding alone had left it around 20dp - visually fine, awkward to hit, and a real problem
for anyone with reduced dexterity.
2026-08-26 06:12:37 +00:00
mckero 08f9106749 feat(aprs): pick a map symbol from a list instead of typing two characters
The symbol table and code were free-text fields with no validation and no hint. Only the
first character was ever used, and only at packet-build time, so an operator could type
"satellite" into the table field, watch it persist, and beacon as "/" - the field lied about
what it did. aprs.fi's troubleshooting guidance puts transmit-side symbol misconfiguration
among the first things to check when a station never appears correctly.

The single strongest argument for a list: \S is Satellite/Pacsat but /S is SHUTTLE. One
keystroke apart, and both look right to someone typing from memory.

Fourteen entries covering fixed, on-foot, field, four vehicle classes, satellite, yagi,
phone, internet-only and handheld. Renderings are from aprs.org/symbols/symbolsX.txt
(WB4APR, Nov 2015) rather than recalled. A symbol the operator already set that is not on
the list appears first in the menu and stays selected, so opening the picker cannot silently
change an existing station's appearance.

The default changes from "/>" (CAR) to "/-" (House). The old default's own comment conceded
it was "a reasonable stand-in for a phone", but it showed every non-driving operator as a
vehicle. A house is right for most users and obviously wrong rather than misleading for the
rest. This cannot disturb an existing install: 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 the changed fallbacks cannot reach them. All three sites move together -
AprsStore's load fallback, AprsCard's blank-field fallback, and AprsBeacon.DEFAULT_SYMBOL -
because leaving one behind would substitute a car whenever the stored code was unusable.

The list lives in core:domain as pure data holding resource names rather than text, so the
wording stays in the locale files. Tests assert that every entry survives the transmit
sanitiser, that the pairs and description keys are unique, and that a pair off the list
reports as absent rather than resolving to something near it.
2026-08-26 05:53:46 +00:00
mckero 6db10b5b72 fix(sources): a dead custom URL no longer counts as a successful update
Found by an audit of the replace-semantics commit rather than by the change itself.

The success count added orbital and transceivers sources together, so one could stand in
for the other. With the built-in sources replaced there are two requests instead of 28: if
the operator's TLE URL was down and SatNOGS answered, the count was 1, no exception was
raised, and setUpdateSuccessful stamped a fresh timestamp for an update that refreshed no
orbital elements at all. That also suppressed the 48-hour auto-update retry, which keys off
that timestamp - so the operator was left with stale orbits, a screen saying the update
worked, and nothing scheduled to correct it.

The failure existed before this rebuild, but 26 other sources masked it. Narrowing the
source set made it easy to hit, which is why it belongs with these commits rather than in a
backlog.

Orbital sources are now counted on their own. A test covers the exact case: transceivers
answers, the custom TLE URL does not, and the update must raise rather than record success.

Also: an upload that found nothing waiting said "Uploaded 0 QSO". Accurate, but it reads
oddly when the queue was already clear, so that case has its own wording now.
2026-08-26 04:56:44 +00:00
mckero cd70e3654c fix(sources): a custom URL no longer wipes the manual-import type index
The previous commit indexed custom-URL satellites under "Other", which is the key manual
file import already writes. setSatelliteTypeIds overwrites rather than merges, so importing
a file and then updating from a custom URL erased each other's type index - a probe
confirmed it in both directions.

The satellites were never at risk: database rows survive because insertEntries is REPLACE
with no delete, and the selection is a separate id list. What was lost was their grouping in
the type filter. Still worth a distinct key, since a URL and a hand-picked file are
different things.

Custom URLs now use "Custom". Manual import keeps "Other". The test asserts the new key and
that "Other" stays untouched, so the collision cannot come back unnoticed.
2026-08-26 03:51:03 +00:00
mckero a25f0fe2cf fix(sources): a custom URL now replaces the built-in sources
Switching "Custom TLE URL" on used to mean "my source AND yours". The map overwrote only
the value keyed "All" and the other 26 built-in sources were still fetched, so pointing
Look4Sat at a mirror, a filtered subset, an offline server or a URL reachable on a censored
network did not stop it hitting Celestrak 26 more times. On a blocked link the real
behaviour was 26 failing requests.

This was a fossil rather than a decision: upstream has satelliteDataUrls as a plain list of
six URLs with no keys and no custom-URL concept, all fetched unconditionally. The fork
turned the list into a keyed map and bolted the override onto one key.

Three things made replacing safe to choose, all checked rather than assumed. Stored
satellites do not disappear, because insertEntries is OnConflictStrategy.REPLACE and
updateFromRemote deletes nothing first, so rows the new source does not mention survive.
The selection is a plain id list and is untouched. What degrades is the type filter for the
skipped keys, which goes stale rather than empty - the last known membership, not a claim
about the current fetch.

The key is now customSourceType ("Other"), not "All". setSatelliteTypeIds early-returns on
"All", so indexing there was always a no-op - satellites from a custom URL were never
reachable by the type filter at all. "Other" is what manual file import already uses, which
is the same meaning: satellites from a source the operator supplied. The existing test
asserted the "All" index, which means it was asserting a no-op; it now checks that no
built-in source is fetched and that the entries land somewhere the filter can see.

A second test covers the switch-off path, which must fetch every built-in source exactly as
before.
2026-08-26 03:44:59 +00:00
mckero b1dce9c518 fix(wavelog): the upload count included QSOs sent days ago
Two smaller findings from the same audit.

Entries already confirmed by the server were added to the success total, so re-running an
upload reported "N uploaded" counting contacts that went up days ago. They are skipped and
no longer counted.

A bulk reply that stored nothing read as an acceptance. `{"imported":0}` has a success
status and would have cleared the queue. The count is checked now. Look4Sat posts one QSO
per request so this was latent, but it would have become real the moment that changed.

The count check deliberately looks only at `imported` and `adif_count`, never
`adif_errors`: v1 answers a successful upload with `adif_errors:0` beside `adif_count:1`,
and matching the wrong key would have rejected every stored QSO. A probe confirms the six
relevant shapes classify correctly.
2026-08-26 02:22:00 +00:00
mckero 13c5fc9584 fix(wavelog): the response reader lost contacts three more ways
An audit cloned the Wavelog server and read the QSO endpoints rather than the
documentation. The previous commit had transcribed the wrong endpoint - `success`,
`successful` and `dupe` come from create_station; the QSO path answers `created` on
success and `abort` with a 400 when a record in a batch failed. Three defects followed,
and the worst reintroduced the very failure the class was written to prevent.

Matching the bare word "duplicate" anywhere in the body classified a hard rejection as a
duplicate, which maps to success and drops the QSO from the queue. This is not
hypothetical: the server's own rejection text is "Duplicate for <call>", built in
Logbook_model::import, and Api_v2 puts strip_tags'd copies of those messages into
validation_error bodies. Probed against real response bodies, five of ten lost the
contact. Only the status field counts now, or a 409.

An HTML body was accepted. A reverse proxy, a maintenance page or a PHP fatal answers 200
with HTML and no status token, so it fell through to Accepted and a misconfigured proxy
ate contacts silently. A body starting with `<` is Unreadable, which keeps the QSO queued.

A rejection from v2 stopped the upload. v2 refuses a legacy v1 key with 401 invalid_token
- the app sends the v1 key as a Bearer token, and Api_v2::authenticate requires a wl2_
prefix - so a v1-only operator could not upload at all. That was a regression against the
pre-fix code, which fell through on any non-2xx. Both v2 and the first v1 endpoint now
always fall through; only the last one is final, and the failure message carries the most
specific reason any endpoint gave plus all three status codes. The third was previously
dropped from that message.

Also: the v2 error envelope has no status key at all, so `"error":` is now recognised on
its own.
2026-08-26 02:11:55 +00:00
mckero e8e67b74cd fix(sources): the custom-source switch stopped turning itself off
Two defects in how the data source settings were read.

The switch reported a state nobody had chosen. `useCustomTLE` was ANDed with
`tleUrl != Sources.defaultTleUrl`, so an operator who enabled custom sources and then
typed the default URL by hand saw the switch flip itself off. It now reports what they set.

The example.com placeholder rewrite ran on every read. A 4.4.7-era build could persist
`https://example.com/tle.txt`, and the fix for that rewrote the value each time it was
read - so the stored value and the returned value disagreed indefinitely and nothing ever
settled it. It is now a one-time migration following migrateRCFormats, which writes the
correction back and records that it has run.

Not addressed here, and the reason the settings screen still misleads: a custom TLE URL
replaces only the source keyed "All" and the other 27 hardcoded sources are still fetched
unconditionally, so "use custom sources" actually means "my source plus 27 others". Which
way that should go is a decision about intent rather than a defect to patch, and upstream
fetches all of its sources unconditionally, which is where the behaviour came from.
2026-08-26 01:35:02 +00:00
mckero 758dc6d567 fix(wavelog): the auto-upload switch had nothing behind it
Deleting the ten-minute polling loop left the "auto upload" switch in settings with no
consumer - the operator could turn it on and nothing would ever act on it, which is worse
than the loop it replaced.

Uploading now happens when a contact is saved. That is what the switch always meant, and
doing it at that moment means somebody is present to see the outcome: a partial failure
says so, and the QSOs that did not go stay in the queue for a manual upload from settings.
The loop reported nothing at all - a grid mismatch hit an empty if block and every other
failure retried forever in the background.

The upload goes through the view model rather than the composable, so the log screen still
touches no repository.
2026-08-26 01:30:14 +00:00
mckero 4567f46867 fix(wavelog): a 200 is not an acceptance
WaveLogApi decided an upload had succeeded from the HTTP status alone. Wavelog validates
after responding, so a rejected QSO comes back as 200 with `{"status":"failed","reason":
"..."}` - and the uploader then called markUploaded and dropped it from the queue. The
contact was lost and the operator was told the upload succeeded.

Response shapes are transcribed from the Wavelog API reference, not guessed: success is
`status: success` or `successful`, a duplicate is `status: dupe` with a 200, failures are
`status: failed` with `reason` or `status: error` with `message`.

WavelogResponse reads the body. Four outcomes: accepted and duplicate both clear the
queue entry, because the log holds the QSO either way; rejected keeps it and surfaces the
server's own explanation; and a status field we cannot recognise also keeps it, since
costing a retry beats losing a contact. Parsed as text rather than with JSONObject because
org.json is compileOnly in core:domain and a JVM test would otherwise assert against a
stub. Whitespace around separators is collapsed before matching - a first attempt listed
spacings and missed `{ "status" : "failed" }`, which a probe caught.

Two other things in the same area.

The ten-minute auto-upload loop is gone. It retried the queue in the background with no
way to tell the operator anything: a grid mismatch was swallowed by an empty if block and
every other failure retried silently forever. A QSO that cannot be uploaded now waits for
a manual upload from settings, where the result is actually shown.

The upload path no longer builds user-facing text in Kotlin. UploadOutcome carried a
pre-formatted Chinese string, so the message ignored the device language whatever the
locale files said. It now reports a Reason the view model maps to resources, which needed
a format-argument overload on IShowToast to get a count into a localised message.
2026-08-26 01:20:26 +00:00
mckero fe6d0af8b7 fix: two regressions this rebuild introduced for non-APRS users
Both found by an auditor comparing behaviour against the released build rather than
against the intent of the change.

Prefix-first portable callsigns were rejected. CallsignEntry took the first segment -
`call.substringBefore('/')` - and required a letter and a digit in it. A portable call can
be written prefix-first, DL/W1AW or ZL/JA1ABC or OH/W1AW/MM, where the leading token is a
country prefix with no digit at all. Measured: five such forms were refused where the old
length-only check had accepted them. Any segment may now carry the callsign.

JSON cookie exports stopped working for QRZ. QrzGridParser.cookieHeader converts the JSON
array a browser extension produces into a Cookie header, and it had zero production
callers - the raw pasted text went straight into the header. The old client normalised it.
So an operator whose export had been working would see their cookie sent as a literal JSON
blob, QRZ would serve its signed-out page, and the app would tell them the cookie had
expired when it was perfectly good. A raw `k=v; k=v` paste was unaffected, which is why
this survived review.

Both are cases where a rewrite lost behaviour the old code had. Neither had a test.
2026-08-26 00:21:11 +00:00
mckero 3a8086eb05 chore: ignore Kotlin build caches outside the root module
The existing rule covered only /.kotlin/sessions/ at the repository root, so
build-logic/.kotlin/ showed up as untracked after any build.
2026-08-25 17:23:32 +00:00
mckero e8ad51fd1b fix(aprs): the ack read disagreed with the login parser
sendPacket had its own idea of what a server response means: any leading `#` counted as
harmless chatter. The login parser had just been taught that `# Port full` and `# Login
by user not allowed` are refusals - the server announcing it is about to drop us - so the
two paths reached opposite conclusions about the same line, and the send path was the
optimistic one.

Probed across the responses captured from live servers, they disagreed on four of six.

classifyAck now shares AprsLogin's judgement. A greeting or keepalive still counts as
sent, because APRS-IS does not acknowledge position reports and silence is the normal
outcome; anything the server says that is not harmless fails the report. A late login
verdict arriving here also counts as sent, since it is not about this packet and the
login state already carries it.

Two socket tests cover both directions: a `# Port full` after the write fails the report,
and a real captured keepalive after the write does not.
2026-08-25 17:16:40 +00:00
mckero 6859c825d7 fix(aprs): treat any unrecognised login response as a refusal
The previous commit listed the refusal wordings it knew - "invalid login" and "login
denied" - and skipped everything else as chatter. That list was incomplete. Probing the
parser against responses captured from live servers found three it missed:

    # Login by user not allowed     observed on rotate.aprs2.net
    # Port full
    # Server full

Each was skipped as a keepalive, so 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. Exactly the failure the previous commit fixed, reached
by a different wording.

Inverted: identification and keepalive comments are recognised positively, and anything
else the server says during login counts as an objection. The trade is that an unforeseen
harmless comment would read as a refusal - but that errs towards reporting failure rather
than claiming success, which is the direction this feature has been wrong in throughout.

The keepalive prefixes come from a live capture rather than guesswork. aprsc repeats its
own identification with a timestamp every twenty seconds:

    # aprsc 2.1.21-gbfc2090 25 Aug 2026 16:41:07 GMT T2UK 195.201.15.71:14580

Two tests had invented a `# Tue Aug 25 ...` date line and a `# keepalive N`, neither of
which any server sends. Both now use the captured format.

Also here: the QRZ cookie test in settings goes through the repository instead of
scraping from the UI. It was the last caller of QrzGridClient, which is deleted, and it
built its result from hardcoded Chinese strings inside the composable - those move to
resources, and the four outcomes are now distinguished, where before an expired cookie
and a station with no grid on file produced the same message.
2026-08-25 17:06:37 +00:00
mckero 271488a43e fix(aprs): the notification showed the previous cycle's verdict
updateNotification was called from onReport but read lastState, which onState only sets
afterwards - so the persistent notification was rebuilt from the previous report's
outcome. It now derives the state from the report in hand.

This matters most where it is least visible: an alarm-driven report at 03:00 posts a
Toast nobody sees, leaving the notification as the only surface, and that surface was
showing a stale verdict.
2026-08-25 16:10:53 +00:00
mckero 321cd8f2fa fix(aprs): the login line was malformed, and the refusal was invisible
An auditor ran the plan's own release gate against live APRS-IS servers. It failed at
the login step, on every server tried:

    sent: user N0CALL pass -1 vers Look4Sat-4.5.4
    got:  # Invalid login: software name and version are not separated by a space

Reproduced on euro.aprs2.net and noam.aprs2.net, aprsc 2.1.21. `vers` takes TWO tokens,
a software name and a version. An earlier commit read the rule "softwarename must not
contain a space" as "the field must be one token" and hyphenated the space between them
- and the unit test asserted that as correct, so the mistake was frozen in place.

Worse than the malformed line was what happened next. `# Invalid login:` is a comment
but not a logresp, so parse skipped it as keepalive chatter; the login then timed out
into Unknown, which is deliberately treated as "may be working"; so `ok = sent &&
!refused` was true and the operator was shown "APRS: report sent OK" for a login the
server had refused. That is v4.6.0's defining defect - every send reported successful
regardless of outcome - still live on the exact path every operator takes. The rebuild
narrowed it rather than closing it.

Both halves are fixed: the name and version stay separate tokens with whitespace
collapsed within each, and a refusal comment is classified as a refusal before the
logresp test. A socket test now replays the server's actual bytes.

Three smaller things from the same review:

The foreground service type goes back to dataSync. The previous commit chose location
to escape dataSync's six-hour cap, but a location-typed service is refused outright
unless a location runtime permission has already been granted, and the settings card
requests only notifications - so it would have failed silently for anyone who declined
location access. The cap that prompted the switch applies only when targetSdk is 35 or
higher, which this project does not declare. A test now reads the manifest and the
service source and fails if they disagree, which is the only way this class of defect
is visible from a JVM test.

The version string in the login was 4.5.4 while the app was 4.6.0. Now split into name
and version and corrected, though it is still hardcoded - core:data has no BuildConfig,
so passing it in properly is a separate change.

The passcode hint said "empty = auto-computed from callsign" in all five locales. The
app stopped doing that two commits ago; it now connects receive-only, and the hint says
so. It was the first thing an operator read next to the field, promising the behaviour
that was deliberately removed.

Not fixed, and known: the notification body is rebuilt from the previous cycle's state
so it can show a stale verdict, a deliberate receive-only choice is still styled as an
error, and no last-success timestamp exists - so an operator still cannot establish
whether their station has ever reached the network.
2026-08-25 16:04:47 +00:00
mckero 0208a577c4 fix(aprs): do not tell a mistyped passcode it is in receive-only mode
The previous commit derived "wants receive-only" from AprsPasscode.canTransmit, which is
a boolean over four cases. Both a deliberate -1 and a mistyped passcode return false, so
fixing the mis-diagnosis in one direction introduced it in the other: measured against
the shipped algorithm, three entries - a passcode off by one digit, an arbitrary number,
and a non-numeric entry - were all told they were connected in receive-only mode, when
what they needed to hear was that the passcode does not match the callsign.

classify already distinguishes these; only its ReceiveOnly case counts as a deliberate
choice. A test now pins the distinction, including the fact that all four entries are
equally unable to transmit - which is exactly why the boolean was not enough.

Found by probe before review, not by the suite, which had no test for the reporter's use
of this and still does not.
2026-08-25 15:25:32 +00:00
mckero eb66a77cae refactor(qrz): move the grid lookup out of the composable
LogTab read the QRZ cookie straight out of SharedPreferences through LocalContext,
inside composition, on every submission - disk access in a composable, around the
repository layer, with the client referenced by fully-qualified name inline. And it
did `if (grid != null)`, so a lookup that failed for any reason left the QSO without
a grid and told the operator nothing.

IQrzGridLookup lives in core:domain, QrzGridLookup in core:data owns the cookie read,
and the view model exposes lookupGrid. The composable now takes a callback and handles
each outcome: a locator is attached, no locator on file passes quietly because nothing
is wrong, an expired cookie says to paste a fresh one, and an unreachable QRZ says so.
That is what the four-outcome QrzGrid type from ce68f487 was for - until now nothing
consumed it and the old nullable client was still the one being called.

Note for anyone extending RadarScreen: the local holding the view model cannot be
referenced as `viewModel` inside a lambda, because that name also resolves to the
composable factory function. Hence the explicitly typed local.

The old QrzGridClient is now unused here but left in place; removing it belongs with
the settings screen, which still calls it to validate a pasted cookie.
2026-08-25 15:18:40 +00:00
mckero 0a67f74369 fix(aprs): the service could not start at all on Android 10 and later
The previous commit changed the manifest's foregroundServiceType to location and left
startForeground passing FOREGROUND_SERVICE_TYPE_DATA_SYNC. AOSP requires the passed
type to be a subset of the declared one - location is 0x08, dataSync is 0x01 - and
throws IllegalArgumentException otherwise, a check that has been there since API 29.
That throw landed in the surrounding catch, which calls stopSelf().

So APRS started, died, and said nothing. No notification, no beacon, no Toast, no
last-report row, and the settings switch stayed on because the config had already been
saved. This is worse than the defect the rewrite was written to fix: reporting success
for packets that never left at least sometimes worked, whereas this never ran at all,
on essentially every device in use, with no visible symptom. Two auditors found it
independently by reading the constants against AOSP's own check.

Two more findings from the same review.

Receive-only was reported as a wrong passcode. Both a deliberate -1 and a mismatched
entry log in with -1, and the server answers "unverified" to each, so the operator who
chose receive-only - the one way to test a setup without putting anything on the network
- was told to go and fix the passcode they had set on purpose. The report now carries
whether receive-only was asked for, and says so instead.

The card could show "failed - sent". The detail string was the write's own verdict, and
a write that succeeds on a refused login is exactly the case where those two disagree.
A failure now reports what actually failed.

Also: the packet is built before connecting. The reporter used to open a session and log
in only to discover it had nothing to send, which for an operator with no station
position set meant a pointless login every five minutes.

Still outstanding, and the reason this is not enough on its own: nothing tests the
service, so neither this defect nor the missing line terminator in 7ac54f0a could have
been caught by the suite. Both were found by audit. A location-typed foreground service
on API 34+ may also require a granted location permission before startForeground, which
the settings card does not request - that needs checking on hardware.
2026-08-25 15:18:15 +00:00
mckero e0900778f0 fix(log): say why a callsign was not logged instead of dropping it
`submit()` opened with `if (call.length < 3) return`. During a pass the operator typed
a callsign, pressed done, and nothing happened - no entry, no message, no way to tell
the app had decided against them. None of the logging software surveyed for this work
- N1MM+, DXLog, PoLo, HAMRS - discards a submission silently.

Validation is deliberately loose, because strictness costs more than it saves. Checked
against 28 real callsigns, a typical strict pattern rejects 16 of them: W1AW/4, 2E0ABC,
9A1CCY and SV2ASP/A among others. A pattern permissive enough to accept those also
accepts a Maidenhead locator as a callsign. There is no regex that catches typos without
throwing away legitimate calls, so CallsignEntry rejects only what cannot be a callsign
- empty, one character, illegal characters, all digits, all letters - and reports doubt
as a warning that still logs the contact.

Two warnings exist. A six-character grid-shaped entry says so, because grid and callsign
are exchanged together on FM satellites and the fields sit side by side. A station already
worked this pass says so too, without blocking: the same station on a later pass is a
legitimate new contact, and contest loggers default to working duplicates - DXLog
describes refusing them as an outdated habit.

That warning also replaces the duplicate suppression, which was a 300ms window comparing
the last callsign, admitted in its own comment to be a workaround. It could silently
discard a real second contact, and a set of calls worked this pass is both honest and
more useful. It survives configuration changes via rememberSaveable.

Not addressed here: the QRZ grid backfill still reads the cookie out of SharedPreferences
from inside a composable through LocalContext, and still reports nothing when a lookup
fails. IQrzGridLookup is added for that, but wiring it needs the container, the view model
and the UI to change together.
2026-08-25 14:32:42 +00:00
mckero 2ff8643988 fix(aprs): build a legal packet, and keep beaconing when the screen locks
The position line was one string template, and it broke four rules at once.

No path. The specification says a client-originated packet carries TCPIP* in the
path, "nothing more or less", and there was none - `CALL>APRS:=...` went out bare.

No position meant 0,0. When the station QTH was unset and no GPS fix was available,
`lat ?: 0.0` put the operator at 0 degrees north, 0 degrees east - a point in the
Gulf of Guinea - on the global network, under their own callsign. There is no honest
default for "nowhere", so AprsBeacon refuses instead and the reporter says why. A
genuine 0,0 fix is still legal and still sent; the refusal is about absence.

No comment sanitising. A line break typed into the status field ended the packet and
started a second one from the remaining text, which an operator could trigger by
pressing return. Measured: the old builder emitted two lines from one call, the second
impersonating whatever callsign the text contained. Only printable ASCII survives now.

No length cap. A 600-character status produced a 636-byte line against a 512-byte
limit including CRLF. The comment is trimmed to whatever room is left after the
header and the coordinates, bounded also by the format's own 43-character limit.

Symbol handling was whatever character the operator typed first, including one that
breaks the fixed-width parse. It now accepts only what the specification allows -
the two table selectors and overlay characters - and falls back to the primary table.
aprs.fi names symbol misconfiguration as the most common reason a station never
appears on the map, so this is not cosmetic.

Separately, beaconing stopped whenever the screen locked. The interval was a coroutine
delay inside the reporter, and Doze suspends network access and ignores wake locks even
for a foreground service: the timer fired on schedule and then could not reach the
network, while the notification went on claiming the service was running. The service
now books each beacon with setExactAndAllowWhileIdle, which is the only scheduling that
survives Doze, and reschedules after each tick so a changed interval applies at once.
If the operator has revoked exact alarms it falls back to an inexact one, which beacons
late rather than not at all.

The foreground service type changes from dataSync to location. dataSync is capped at
six hours in any 24-hour window on recent Android and then stopped by the system, which
would silently end a beacon meant to run all day; the service reads the station position
and falls back to GPS, so location describes what it actually does.

The interval floor becomes five minutes rather than one. This station is fixed or
walking, and APRS-IS etiquette is to beacon no more often than the position changes.

The packet builder moves to core:domain as pure logic, so all of this is testable
without a socket - including that a comma-decimal locale cannot corrupt the coordinates,
which nothing covered before.
2026-08-25 14:17:23 +00:00
mckero b19c78441c feat(aprs): link out to request a passcode instead of computing one
The settings card had a "Compute passcode" button that derived the value from the
callsign and filled the field in. It was added by request, so it stayed while the
previous commit removed the same derivation from the connection path - which left
the app contradicting itself: the background no longer invented a passcode, but the
UI still offered to.

APRS-IS treats the passcode as a licence check and states that supplying it to a
user is the software author's responsibility. APRSdroid carries the identical
algorithm in the same source file and deliberately does not use it for this, opting
to validate what the operator typed and link out to request one. Filling the field
in claims a check that nobody performed.

The button now opens the passcode request page. AprsPacket.passcode stays in
core:domain because validating an entry means recomputing the expected value, and
its import is dropped from the card, which no longer needs it.
2026-08-25 13:18:51 +00:00
mckero 262ae45432 fix(aprs): stop inventing a transmit passcode, and let the report notices appear
AprsReporter derived a passcode from the callsign whenever the operator's entry was
unusable:

    passcode = cfg.passcode.toIntOrNull()?.takeIf { it >= 0 } ?: AprsPacket.passcode(cfg.callsign)

Measured against the shipped algorithm for BG7NTA, whose passcode is 21162, four
inputs produced a transmit passcode the operator never obtained: blank, whitespace,
non-numeric, and an explicit -1. That last one is the documented receive-only value,
so `takeIf { it >= 0 }` also made receive-only unreachable - and a receive-only login
is the one way to confirm a setup works without putting anything on the network,
which is exactly how this feature was supposed to be validated before release.

This is a policy question more than a bug. APRS-IS states that supplying the correct
passcode to a user is the software author's responsibility, and the passcode functions
as a licence check for transmitting. APRSdroid carries the same algorithm in the same
source file and deliberately does not use it to fill a blank, validating the operator's
entry instead. AprsPasscode follows that: it classifies an entry as Transmit,
ReceiveOnly, Mismatch or NotANumber, and anything not usable logs in as -1. The
connection still works and the operator is told separately that reports are not being
forwarded, but no packet goes out under a code the app made up.

AprsPacket.passcode stays, because validating an entry means recomputing the expected
value. Nothing substitutes it for a missing one.

Separately, and worse than the line above: the report notices never appeared at all.
onReport is invoked from AprsReporter's Dispatchers.IO scope, where constructing a
Toast throws because the thread has no Looper - and the surrounding runCatching
swallowed it. So the whole reporting path, including the unverified-login warning
added in the previous commit, was writing messages nobody could see. They now post to
the main looper. The one in startReporting is left alone: onStartCommand already runs
on the main thread.

Still outstanding for APRS, and not addressed here: the 0N 0E position fallback, the
missing TCPIP* path, the unbounded status field, the coroutine delay that does not fire
in Doze, and the dataSync foreground service type. Also unaddressed is the "Compute
passcode" button in AprsCard, which offers the operator the derived value directly and
so contradicts the policy this commit establishes - it was added by request, so it needs
a decision rather than a quiet removal.
2026-08-25 12:37:04 +00:00
mckero 7ac54f0a37 fix(aprs): report a failed send as failed, and a refused login as refused
Two defects made every APRS failure invisible. sendPacket ended with
`.getOrElse { Pair(true, "OK") }`, so a read that threw - including on a dead
socket - was reported as a successful send. And the login check threw inside a
runCatching whose result was discarded, so a server that refused to verify the
passcode could not propagate: aprsc keeps such a client connected and its writes
succeed while silently discarding every packet, which the app reported as success.
An audit put it plainly - twelve commits are all fix(aprs), none added a
socket-level test, so "it worked" was never evidence a packet had landed.

sendPacket now separates the cases. A read timeout stays a success, because
APRS-IS does not acknowledge position reports and silence is the normal outcome.
A closed stream or an IOException is a failure. The catch order matters and is
load-bearing: SocketTimeoutException extends IOException, so reversing them would
mark every normal report as failed.

The login handshake follows the spec: read the server's identification line first,
then log in, then read until a verdict arrives. AprsLogin holds that as pure logic
in core:domain with the parsing that decides it, including one trap worth naming -
"unverified" contains "verified", so the negative has to be tested first or every
refusal reads as acceptance. An explicit refusal now fails the report and shows
the operator its own message pointing at the callsign and passcode, in five
locales. A response we could not parse does not, since the packets may well be
landing and blaming the passcode would send them to fix something that works.

Three defects came out of review after that. The verdict is now bounded by a
deadline rather than a five-line budget, because a server that sent six keepalives
before its answer turned an accepted login into Unknown - telling the operator
their passcode was wrong when it had just been accepted. The greeting gets a short
two-second probe instead of the full login window, which cost eight seconds on
every connect to a server that sends none. And a refusal detected in the greeting
now aborts the connection instead of being overwritten by the next read, which had
made that branch and its comment a lie.

The worst of the three was mine: rewriting the write as print + flush dropped the
line terminator entirely. APRS-IS is a line protocol, so the server's reader never
saw a packet, while the send reported success and the read timed out into the
"silence is normal" branch. It broke healthy connections rather than dead ones and
was designed to have no symptom. Both the packet and the login line now end in an
explicit CRLF as the spec requires, rather than println's platform separator.

That defect is why this adds AprsIsClientSocketTest, which runs the client against
a stand-in server and reads the bytes back: it asserts two packets arrive as two
lines, that a login line arrives complete, that keepalive chatter does not bury the
verdict, that a greeting-less server connects promptly, and that a send to a closed
peer reports failure. Nothing in the pure-logic tests could have caught a missing
newline. Note for anyone extending it: closing the ServerSocket leaves an
established connection alive, so the dead-peer test has to close the accepted
socket - assuming otherwise made a correct implementation look broken.

AprsPacket.formatLogin is deleted, its work moved into AprsLogin.line, which also
replaces spaces in the version string because the server splits that field on
whitespace and the shipped value contained one.
2026-08-25 10:30:41 +00:00
mckero ce68f48765 feat(qrz): tell an expired cookie apart from a station with no grid
The grid lookup returned String? and swallowed everything with catch { null }, so a
timeout, an expired cookie, a QRZ layout change and a station that simply has not
published a locator were one indistinguishable blank. The operator saw an empty grid
with no way to know that re-pasting their cookie would fix it. There was also no
retry at all, on a phone, mid-pass, on mobile data.

QrzGrid names the four outcomes and QrzGridParser holds the parsing, which is pure
string work and now testable without a network. The fetch moves to core:data as
QrzGridSource, using the project's own OkHttp client with three attempts and 700ms
then 2000ms of backoff. Only transport failures and 5xx are retried; a 4xx would
repeat identically. This also gets java.net.URL I/O out of core:domain, which that
module is meant to stay clear of for the KMP move.

Classifying signed-out took two goes. Keying on the detail table being absent held
for an expired cookie - QRZ genuinely serves no detail rows to an anonymous visitor,
verified against a live response - but an audit found that a callsign QRZ has never
heard of returns HTTP 200 with no detail rows either, because QRZ serves its search
form instead. That would have reported a mistyped callsign as an expired cookie and
sent the operator into settings mid-pass to re-paste one that was never broken. It
now keys on QRZ's own "Login is required for additional detail" notice, so an absent
locator degrades to the harmless outcome and only QRZ actually asking for a login
triggers the cookie prompt. All three cases are measured against live responses.

Not yet wired in: LogTab and SettingsScreen still call the old QrzGridClient, so
nothing changes for the operator yet. Cutting over needs an interface in core:domain
and a MainContainer provider, because feature modules cannot reach core:data
directly - and the cookie itself belongs in SettingsRepo rather than the separate
prefs file a composable currently reads through LocalContext.
2026-08-25 08:39:40 +00:00
mckero 38f939bd49 fix(wavelog): resolve the LoTW satellite name from the catalogue number
LoTW refuses a QSO whose SAT_NAME is not spelled as its accepted list has it - its
own help page gives AO7 against AO-7 as a rejection - so the name we upload decides
whether a contact can ever be confirmed. The old code derived it with
substringBefore('('), which returns the descriptive half of a TLE name rather than
the OSCAR designator: measured against live Celestrak amateur data, 0 of 96
satellites resolved to something LoTW accepts. ASRTU-1 went up as ASRTU-1 where
LoTW wants AO-123.

Keying on the name cannot be made to work, because the sources disagree. Of the 49
satellites carried by both Celestrak amateur and AMSAT nasabare, 33 are named
differently - 43017 is RADFXSAT (FOX-1B) in one and AO-91 in the other, 43700 is
ES'HAIL 2 against QO-100 - so which name a QSO got depended on where the operator
fetched their TLE. The catalogue number is identical everywhere, so the table is
keyed on it and OrbitalPass.catNum is now threaded through to the QSO and persisted.

The name path stays as a fallback for contacts logged before the number was
recorded, and got two fixes of its own: it tries either side of the parentheses
rather than assuming the designator is on the left, and tolerates a differing
separator so RADIO ROSTO (RS15) reaches RS-15. Resolution now returns the list's own
spelling, so Arsene is not uploaded as ARSENE and rejected the same way AO7 would be.

Measured on the same data: 3 names resolved before, 20 by name alone now, 30 with
the catalogue number, and no satellite that used to resolve stopped resolving.

The table gained the nine TEVEL-2 satellites after an audit found them missing.
Every source writes those TEVEL2-N while LoTW has TEV2-N, which stripping separators
does not bridge - TEVEL21 is not TEV21 - so they resolved to nothing at all. They
launched in 2025 and are workable now. Their numbering is not sequential: 63217 is
TEVEL2-1 while 63213 is TEVEL2-4.

All 38 entries were cross-checked two independent ways: every catalogue number
appears in the app's own configured sources under a name consistent with the LoTW
spelling, and ARRL's startDate for each name agrees with the launch year in the
TLE international designator - which is what would catch a number pointing at the
wrong object, since a name can match by luck. Nothing here was typed from memory;
an early hand-written draft had AO-123 as 62690 when it is 61781.
2026-08-25 08:38:45 +00:00
mckero bdc6db5aff build: bump to 4.6.0 (versionCode 467)
Carries the transcript-stall fix, which was committed but never pushed - v4.5.9 was
tagged at the version-bump commit before it, so the APK users have does not contain
it and their history box still appears to delete text.

Release notes gain one line in the five locales that carry them, describing that fix.
2026-08-25 06:18:59 +00:00
mckero 92499b1cf1 feat(wavelog): map NORAD catalogue numbers to LoTW satellite names
LoTW refuses a QSO whose SAT_NAME is not spelled as in its accepted list - its own
help page gives AO7 against AO-7 as a rejection - so the name we upload has to match
exactly. The existing code derives that name with substringBefore('('), which returns
the descriptive part of a TLE name rather than the OSCAR designator: measured against
live Celestrak amateur data, 0 of 96 satellites resolved to a name LoTW accepts.
ASRTU-1 uploads as ASRTU-1 where LoTW wants AO-123.

Keying on the name cannot be made to work, because sources disagree. Of the 49
satellites carried by both Celestrak amateur and AMSAT nasabare, 33 are named
differently - 43017 is RADFXSAT (FOX-1B) in one and AO-91 in the other, 43700 is
ES'HAIL 2 against QO-100 - so which name a user gets depends on the source they
happen to fetch from. The NORAD catalogue number is identical everywhere, so this
table is keyed on it.

Coverage is 29 entries, not the 112 names LoTW lists, because the rest are satellites
no source still carries: they have re-entered, no user can track them, and a mapping
for them would never be consulted. Every number was read out of live TLE data from the
app's own configured sources rather than typed from memory - a first attempt at writing
them by hand had AO-123 as 62690 when it is 61781.

Three names matched more than one catalogued object and were settled by which object
the amateur-specific sources carry. ARISS is 25544, the station; the full catalogue
also lists ISS (UNITY), (ZVEZDA), (DESTINY) and (NAUKA), which are modules. IO-117 is
53109, named GREENCUBE (IO-117) by four sources against R4UAB alone calling it
ROBUSTA 1F. TO-108 is 44881, in all three amateur sources, where 44879 is TIANQIN 1.

Not yet wired into the upload path: WavelogQso carries only a satellite name, so the
catalogue number has to be threaded through from the radar screen first. This commit
adds the table and its tests only, leaving behaviour unchanged.
2026-08-25 06:16:08 +00:00
mckero 828fd0fb6f fix(cw): stop the transcript stalling while audio waits to be archived
The history box appeared to delete text. Audio leaving the 20 s live window is
decoded into the archive only once a full 15 s batch has accumulated, so until
then its characters were in neither place: not in the live decode, which had
scrolled past them, and not in the history, which had not seen them yet.

Measured on a 20 WPM timeline, the concatenated transcript held at 40 characters
from t=24 s to t=34.5 s - eleven seconds of no growth - then jumped to 70 when the
batch flushed. Up to 30 characters sat in that gap. Reading it as deletion is
reasonable; the text really was missing from the box.

The pending batch is now decoded too, on the same 1.5 s cycle as the live window,
and shown as a provisional tail after the committed text. The final archive decode
replaces it, having the whole batch for context. The transcript is monotonic
afterwards: +3 characters every cycle with no stalls.

Decoding each 100 ms capture chunk instead would have removed the gap entirely but
measured 14x the inference load - over 250% of one core across ten minutes - and a
chunk that short carries under two dot-lengths of context, so the decode would be
poor as well as expensive. One extra inference per redecode cycle costs 24.7%
against 18.3%.

Discarding buffered audio drops the provisional text with it, since that text
describes audio that no longer exists. Committed text stays: it was correct for
audio that really was archived.
2026-08-23 11:40:22 +00:00
mckero 07df22d287 build: bump to 4.5.9 (versionCode 466)
The v4.5.8 tag was already published against the version-bump commit alone, so
the twelve commits of actual work had no release to land in - moving the tag made
the CI job fail on an existing release rather than replacing it. A new version
number is the right way round, per the project's own rule against re-cutting a
tag.

Release notes are unchanged: the five locales already describe exactly what these
commits contain.
2026-08-23 11:06:21 +00:00
mckero ac45ed0efb docs: describe the waterfall, transcript and screen-reader work in 4.5.8
Three lines the release notes were missing, across the five locales that carry
them: the waterfall now spanning the whole audio band, the transcript following
new text, and the CW waterfall and AMSAT day cells being readable by a screen
reader.
2026-08-23 10:55:58 +00:00
mckero 96bbb022e8 fix(cw): follow the transcript reliably, and keep the AMSAT grid dense
Two corrections to 10c415fa and 0889a3bd, keeping what those got right and
undoing what they cost.

The transcript now follows new text through an explicit follow flag rather than
comparing scroll position against maxValue. maxValue is written during layout,
after the composition that would read it, so the comparison tested the previous
frame's height: following fell progressively short of the true bottom and, once
the gap passed the slack, latched the operator out of follow-mode until they hit
the exact end. Scrolling away still stops it, which is the point.

The AMSAT day cell goes back to 28 dp. Raising it to 48 dp for the minimum touch
target measured a 71% increase in row pitch - 14 satellites per screen down to 8
on a 6.1" phone - and comparing many satellites at a glance is what that page is
for. Compose cannot extend a touch target past the layout bounds, so this is a
choice rather than a fix; 28 dp is also what shipped before, so the regression
was mine. The contentDescription added alongside it stays, since it costs nothing.
2026-08-23 09:46:36 +00:00
mckero b6753a4fa6 Revert "fix(cw): scale and band-pass the shifted audio instead of clipping it"
This reverts commit 0889a3bd88.
2026-08-23 09:42:45 +00:00
mckero 0889a3bd88 fix(cw): scale and band-pass the shifted audio instead of clipping it
The mixer runs above unity for any ordinary input - the Hilbert kernel's L1 gain
is 2.51, so amplitude 0.7 peaks at about 1.76 - and the output was hard clipped
to fit. Clipping squares the waveform off and generates odd harmonics, which the
widened waterfall would now put on screen.

Measured, the harmonics happen to be harmless today: TARGET_HZ is a quarter of
the sample rate, so 3f, 5f, 7f and 9f all fold back onto the tone itself and
out-of-band energy stayed at 0.00%. That is a coincidence between two constants,
not a property of the design. At a 700 Hz target the third harmonic folds to
1100 Hz - inside the analysis window, where no filter may remove it and the model
would read it as a second tone.

So two changes, because neither alone is enough. A peak-following gain scales the
mixer output to fit rather than clipping it: measured 0 of 3200 samples on the
rail, against a clipped waveform parking there for much of every cycle. And a
95-tap windowed-sinc band-pass over the model's window removes whatever the mix
leaves outside it - images, harmonics, the far sideband - measured at 58-60 dB
rejection with 0.09 dB of passband ripple and out-of-band energy down to 0.0002%.
The gain is shared across chunks so it cannot step at a boundary, and the filter
carries tap history for the same reason the Hilbert filter already did.

The band-pass adds 47 samples of linear-phase group delay, 14.7 ms, which delays
the keying envelope without distorting it - 4% of a dot at 40 WPM.

CwToneShifterStreamingTest's boundary criterion was wrong, and the band-pass
exposed it: distanceToBoundary measured only forward, so the first samples of a
chunk came out 320 away from "the" boundary and counted as interior when they are
the far side of the same seam. Both filters need samples ahead of the output they
are producing - 32 for the Hilbert transform, 47 for the band-pass - and with the
distance measured to the nearest boundary either way, interior divergence is
0.000116 against a 0.01 budget.

Also: the CW transcript now follows the newest text, but only while the operator
is already at the bottom, so scrolling back to read earlier traffic is not undone
by the next decoded character.
2026-08-23 06:27:10 +00:00
mckero 10c415fabd feat(cw): draw the whole audio band so an out-of-window tone is visible
The waterfall showed only the model's 400-1200 Hz window, so a tone outside it
was absent from the picture entirely. Measured on keyed audio, the brightest
column in that narrow view swings 1.01x between key-down and key-up against
13.76x for a tone in range - it carries no keying at all, so the operator could
not tell a signal was present, let alone where it was. Markers alone could not
fix that: they pointed at a frequency with nothing drawn there.

compute() now takes an optional bin range, defaulting to the model's own, so the
decoder path is byte-identical and the golden-vector test still holds. The
display asks for DC to Nyquist, 129 bins against 65. The FFT already computed
every bin - this only changes which are kept - so the cost is a wider copy.

The decoder window is framed and faintly lifted, since half the picture is now
outside what the model reads and nothing said which half.

Marker fixes found while reviewing the render: the tone marker was orange, which
is a colour the inferno ramp itself passes through, so a marker sitting on the
trace it pointed at was indistinguishable from the keying gaps in that trace -
invisible in exactly the case it existed for. It is cyan now, and both markers
are pips in a gutter above the spectrum rather than lines across it.

Also from the release audit:

- compute()'s bin-count guard was written as a three-term disjunction, which any
  custom range satisfies regardless of bin count, leaving the model invariant
  unenforced for the caller most able to break it. Rewritten as an implication,
  with a Nyquist bound so no range can index past the FFT output.
- signalStrength was gated on a confirmed out-of-window tone, which is false when
  detection fails - and it fails for a slow fist, measured at prominence 2.5
  against a 4.5 threshold for 15% duty. So the meter still read half scale beside
  an empty transcript. It now requires a tone confirmed decodable: 11 flow
  combinations, 3 wrong before, 0 wrong after.
- detectedToneHz never expired, so after retuning into the band the hint kept
  naming the frequency the operator had left, indefinitely. It now clears after
  10 s without a tone, which is clear of any real gap - the longest being 1.7 s
  between words at 5 WPM.
- The waterfall label read estimatedPitch while the hint read detectedToneHz, two
  numbers up to 800 Hz apart both claiming to be the tone. Both read the latter.
- Removed a redundant toFloat() that the compiler warned about.

Accessibility, untouched until now: the waterfall was a bare Canvas and the AMSAT
day cells bare Boxes, so both announced nothing at all - on the status page that
is the entire content of the screen. Both now carry a contentDescription naming
the tone or the day's worst status and report count. The AMSAT tap target goes
from 28 dp to 48 dp with the coloured tile still 28 dp, so the grid keeps its
density. Strings in all nine locales for both modules.
2026-08-23 05:50:59 +00:00
mckero 984a139a81 feat(amsat): let the operator choose the day-cell style
Opinion split on the stripes, so Settings > Other now has a switch. On by
default, since the flat tile it replaced hid intra-day outages, which is the
problem the stripes were introduced to solve.

Flat mode is deliberately not the old behaviour. The old cell took its colour
from the first slot with a report and its count from that same slot, so a day
that worked in the morning and failed all afternoon read as "worked" - measured
across eight representative day shapes, two of them had their failure hidden
outright, and the count reported 1 where the day held 24 reports. Flat mode now
takes the day's worst status and the day's total count, so the summary can
understate detail but not hide bad news. The help text says so, in case someone
turns the switch off expecting the tile they remember.

The count is drawn in black or white by relative luminance rather than always
white: on the telemetry amber, white measured 1.83:1 against WCAG's 3:1 for
large text, and that cell does carry a count whenever a day held nothing but
telemetry reports. All six status colours now clear 3:1, the worst being 3.03.

SatStatusViewModel collects the setting rather than reading it once - the switch
is on another screen, so the operator is always elsewhere when they change it
and would otherwise return to the old style.

Strings in all nine locales.
2026-08-23 02:56:05 +00:00
mckero 4cb03111bc fix(cw): stop the decoder claiming a healthy signal it cannot hear
With tone shift off and the operator tuned outside 400-1200 Hz, the page did not
go quiet - it went confidently wrong. Three measurements, all reproduced against
the real spectrogram path:

estimatedPitch is (32 + loudestBin) * 12.5 - shiftHz with the bin confined to
0..64, so with no shift applied it can only ever report 400-1200 Hz. It cannot
express 1500 Hz, and it does not try: it publishes whichever window edge the
leakage piles against. For a 1500 Hz tone that is 1200 Hz.

That leakage is not faint. The waterfall normalises to the loudest value on
screen, so 50 of 65 bins clear the 0.06 draw threshold and the picture shows a
keyed-looking column pinned to the right edge - the 1200 Hz column runs 25 times
the 400 Hz one.

signalStrength is prominence over the window mean, so the same leakage scores
0.78 and paints the meter to 78% of full width.

So the operator got a strong-signal bar, a plausible 1200 Hz readout, a picture
that looked like a signal, and an empty transcript, with nothing saying why.

The scan that can see past the window now runs whether or not shifting is
enabled - it is the only measurement that can - and publishes through a new
detectedToneHz flow kept separate from estimatedPitch. Overloading the latter is
what let the 1200 Hz claim out in the first place, so the two meanings stay in
two flows. The shift decision still only happens when the setting is on. Cost is
one 121-bin scan every 2 s.

The meter now reads zero when a tone is out of range and not being shifted in: it
is a claim that something decodable is present, and in that state nothing is.

A line under the waterfall says which case the operator is in - the tone was
moved in, or it is out of range and tone shift is off, naming the frequency and
the remedy. Strings in all nine locales; feature:cw only had five, so values-es,
values-ru, values-si and values-uk are new, with the Turkish apostrophe escaped.

CwToneShifterTest pins the premise the hint rests on: that the scan reports tones
the model window excludes, at 120, 250, 1400 and 1500 Hz.
2026-08-23 01:42:37 +00:00
mckero 23f47d9122 fix(cw): keep the shift marker visible when the pitch readout goes negative
The guard suppressed every marker, the target line included, whenever the
reported pitch was not positive. Shifting a low tone UP makes that routine:
pitch is (loudestBin * 12.5 - shiftHz), so with a 100 Hz tone shifted +700 Hz it
goes negative for 25 of the 65 bins, down to -300 Hz, and updateSignalMetrics
applies no prominence test so mains hum in a key-up gap is enough to park the
argmax down there. 77 reachable (tone, bin) pairs across 100-350 Hz produce it.
The result was the display showing nothing at all while the shift was active -
exactly what the previous commit set out to fix.

The target line is now drawn on the strength of the shift alone, since a shift
being applied is the fact worth showing and it does not depend on the pitch. A
non-positive pitch marks the low edge, which is where such a tone actually is,
and only the numeric label is suppressed because the number itself is nonsense.
A NaN pitch previously slipped past all three comparisons and rendered the HIGH
edge marker labelled "0 Hz"; it now draws the target line only.

TONE_SHIFT_TARGET_HZ reads CwToneShifter.TARGET_HZ instead of recomputing the
window midpoint. The two are equal today by coincidence, not construction:
retuning either would leave the green line marking a frequency nothing is
delivered to, silently. CwToneShifterTest now pins TARGET_HZ inside the window
and clear of its edges, which is the one part of this the JVM suite can hold.

The label side now tips at the target rather than the window maximum, so a pitch
sitting on the upper edge gets its text on the same side as its line.
2026-08-23 01:15:03 +00:00
mckero 5a45aab2b1 fix(cw): make the out-of-window tone marker actually visible
The edge marker was drawn outward from the canvas edge, so every one of its
three line segments fell outside the clip and nothing rendered. Measured at a
typical 320 px width: 0 of 3 segments visible on either side. That is the one
case the marker exists for - an out-of-window tone is absent from this picture
by definition, so with the marker clipped away the operator has no signal at all
that a shift is happening. Which is what was reported.

It is now a solid bar along the edge the tone lies beyond, plus a chevron whose
arms open inward from it, so the whole marker sits inside the clip while still
reading as pointing off-picture.

Three further defects in the same code:

The frequency label was pinned to TopStart while its background rect tracked the
tone's frequency, so at 1500 Hz the rect sat at x=278 and the text at x=11. The
rect is gone and the label now sits on whichever side the marker is on.

Markers were drawn after two early returns that fire on an empty or silent
spectrum. A shift is deliberately held through key-up gaps, so the markers were
blinking out during the very silences the shift survives. They now draw
unconditionally, after the spectrum so it cannot bury them.

dashCount floored, leaving up to 8 px of the column undrawn at the bottom.

Also extracts the marker drawing into a DrawScope extension, hoists the shared
colours and the target frequency to file-level constants, and rounds the label
instead of truncating it.
2026-08-23 00:28:54 +00:00
mckero 9367878702 fix(cw): show the correct original tone frequency in the waterfall label
The Canvas marker was fixed to draw at estimatedPitch, but the overlay Text
still computed its label from estimatedPitch + toneShiftHz, which showed the
shifted position (800 Hz) instead of the original tone (e.g. 1500 Hz).
2026-08-22 15:53:52 +00:00
mckero 8fbc639a82 fix(cw): draw the original-tone marker at the correct waterfall position
estimatedPitch is already corrected back to the original tone frequency
(the spectrogram computes from shifted audio, and updateSignalMetrics undoes
the shift), so adding toneShiftHz to it again placed the orange marker at the
shifted position - right on top of the green target line, making them
indistinguishable.

The orange marker now goes directly on estimatedPitch. When the original pitch
is outside the visible 400-1200 Hz band, an arrow at the nearest edge points
toward it instead.
2026-08-22 15:36:17 +00:00
mckero fa73328936 feat(cw): show tone-shift markers on the waterfall spectrogram
When the tone-shift feature moves a tone into the model's 400-1200 Hz window,
the waterfall now shows two visual markers so the operator can see what is
happening: a green dashed line at the target (800 Hz) and an orange frequency
label at the top-left showing the original pitch.

The waterfall draws the RAW audio, not the shifted audio, so a 1500 Hz tone was
always invisible regardless of the shift setting. The markers close the gap:
the operator can now see that a tone was detected and where it was moved, even
when the original pitch is outside the visible band.

activeShiftHz is now a StateFlow exposed through ICwDecoder so the UI can
observe it without polling.
2026-08-22 15:32:33 +00:00
mckero 50a644f417 build: bump to 4.5.8 (versionCode 465)
AMSAT status page: 12 two-hour stripes per day, UTC calendar days, two distinct
greys for no-report vs no-data, and a data-coverage marker from the summary
endpoint that flags satellites crowded out of the global 500-record pull.
2026-08-22 13:05:31 +00:00
mckero 7a2bbb8701 chore(amsat): update User-Agent to match the current release version
All three AMSAT endpoint calls still declared Look4Sat/4.5.5 while the project
has been at 4.5.7 for several releases. The API does not appear to validate the
header, but it misrepresents the client version in server logs.
2026-08-22 12:34:53 +00:00
mckero 018a3afd2b fix(amsat): mark satellites whose reports were crowded out of the global pull
The API caps at 500 records regardless of the hours requested. With 88 catalog
satellites, eight of them more active than 50 reports per 72 hours, quieter
satellites get crowded out. Measured live: the global pull returned 500 reports
covering 36 satellites, while the summary endpoint reported 743 reports across 38
satellites. 26 of 38 satellites had incomplete data, and two (PO-101_[FM] and
TEVEL2-6_[FM]) had zero reports in the global pull despite having reports in the
summary.

The summary endpoint (api/v1/summary.php) returns per-satellite report counts in
one request, so the fix adds one extra call rather than the 88-request
alternative of per-satellite pulls. A satellite whose global pull is incomplete
gets a subdued "68 / 116" marker next to its name, telling the operator the page
knows there is more data it could not fetch. The marker is silent when the
summary is unavailable or the counts match, so the feature degrades gracefully.

The earlier no-data grey (0xFFE8E8E8) already prevented the worst case: slots
crowded out of the global pull were marked as "we never looked" rather than
claiming "nobody reported". The marker now closes the remaining gap: the page
can honestly say "we know there are 116 reports for this satellite but we could
only show you 68 of them".

Also fixed a subagent mutation-testing residue: the coverage floor had been
moved from global (reports.minOfOrNull) to per-satellite (satReports.minOfOrNull)
and left in the tree. One test caught it (coverage is judged from all reports,
not one satellite's), proving the test has teeth.

Adds getAmSatSummary to IRemoteSource and RemoteSource, parseSummary to
AmSatRepository, and summaryCount to SatStatus. All eight test-file
implementations of IRemoteSource were updated for the new method.
2026-08-22 11:47:42 +00:00
mckero 3612e662e7 fix(amsat): distinguish slots we have no data for from slots nobody reported
Grey meant two different things. The API caps at 500 records however many hours
are requested: measured against the live endpoint, a 72-hour request returned 500
reports spanning only 49 hours, so the oldest 9.5 hours of the third day had no
data at all. Those cells were painted the same grey as "nobody reported", which
claimed knowledge we did not have - 352 of 3168 cells on a real page, a third of
the third day's column.

Slots entirely older than the earliest report in the response now use a lighter
grey. Coverage is judged from all reports 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, so it must read as "not heard" rather than "unknown".

The two greys are now in the legend, which previously listed only the four active
states. That matters more than it sounds: on the live page 81% of cells are
"nobody reported" and 11% are outside our data, so a user looking at a mostly-grey
row had no way to tell a dead satellite from a gap in what we fetched. The legend
chips use a solid dot, so the two greys stay distinguishable despite the 25%
alpha background. Strings added to all nine locales.

Three tests cover it: a day entirely before the data starts, a day straddling the
boundary, and an empty response marking nothing as covered.
2026-08-22 10:27:44 +00:00
mckero 79215e7623 test(amsat): pin the slot arithmetic against hostile dates and boundaries
The UTC alignment landed with tests covering the normal cases; these cover the
ones that would have made it wrong quietly.

Midnight arithmetic is exercised at exactly midnight, a second either side,
every leap-day combination around 2028-02-29, both year boundaries, and the
first of all twelve months in a leap and a non-leap year. Since the code steps
back a day by subtracting 86400 rather than using Calendar arithmetic, those
dates are where a naive step would drift.

Every slot edge across all three days is probed at the boundary and one second
either side, asserting each instant occupies exactly one cell and that the cell's
day matches the report's UTC date - `until` versus `..` on the slot range is a
one-character mistake that would double-count edge reports.

Also pinned: the shared Calendar is not re-read after the labels loop (it points
at the oldest day by then), repeated calls are idempotent, duplicate catalogue
names produce duplicate rows carrying the same report, reports for names absent
from the catalogue are dropped, and the build stays linear in reports rather than
quadratic.

Adds a comment recording why reusing that Calendar is safe: each pass assigns
timeInMillis outright instead of adjusting fields.

235 tests pass.
2026-08-22 09:15:23 +00:00
mckero 8f646d76f9 fix(amsat): align the status grid to UTC calendar days, one stripe per slot
Two defects in our own AMSAT page, both found by auditing the change that exposed
them.

The day columns claimed to be dates but were a rolling window anchored on the
fetch time. Fetching at 06:07 UTC put 17.9 hours of yesterday into the cell
labelled today; measured against a live amsat.org page of 1021 reports, 73% of
them landed in the wrong day column and none matched the official cell. Days are
now UTC calendar days and slots are fixed UTC bands - slot 0 is 22:00-24:00, slot
11 is 00:00-02:00 - so a cell's contents match its label whenever it is fetched.

The day cell painted one colour for the whole day, taken from the first slot that
had a report, so a satellite that worked all morning and failed all afternoon
looked identical to one that worked once - the reported symptom. It now draws one
stripe per two-hour slot in the same 64x28 dp footprint. Twelve stripes are about
5 dp each, roughly 15 px at 440 dpi, and runs of the same status merge visually,
so a day reads as a few blocks rather than twelve lines. Every density from ldpi
up allocates all twelve without dropping one, and the 4 dp corner radius leaves
95% of the end stripes visible. The report count text is gone; tapping a day
still lists every report from it, which was already the richer view.

buildStatuses and ApiReport are internal rather than private so the grid contract
can be tested. AmSatSlotBuildTest drives it directly: fetchStatus cannot be
tested here because the parsing around it uses Android's JSONObject, a JVM stub
that makes every call return null - eight of nine tests written against it failed
for that reason before being rewritten.

Also corrects three KDoc comments claiming 5 days when the code builds 3, and
records in AGENTS.md that the status colours are ARGB literals in core:data,
duplicated in MainTheme, which anything needing themeable or colour-blind-safe
colours has to fix first.
2026-08-22 06:59:39 +00:00
mckero ea125d7db4 refactor(cw): move the shift decision into core:domain so tests can reach it
Mutation testing found the decision rule was effectively untested. Four defects
injected into it - removing the silence guard, comparing shifts instead of
tones, never setting the hysteresis anchor, and inverting the comparison - all
left the entire suite green. The rule lived inside CwDeepDecoder, which needs an
Android Context and a loaded ONNX session, so tests could only restate it, and a
restated rule cannot fail when the real one is wrong.

CwShiftDecider now holds the rule as a pure class that both the decoder and the
tests drive. Its outcome is reported as an enum so the decoder's logging is a
presentation concern rather than a second copy of the logic. CwShiftDeciderTest
targets each of the four surviving mutants directly.

MIN_PROMINENCE lowered from 8.0 to 4.5. Raising it to 8.0 last round overshot:
measured on 400 ms windows of keyed CW in noise, a comfortably copyable signal
reaches only 7.6-9.0 at 0 dB SNR and 5.2-6.7 at -3 dB, so 8.0 silently refused
to shift weak out-of-window signals - the exact failure the feature exists to
prevent. Pure noise peaks at 2.2-3.4, so 4.5 keeps zero false positives across
40 noise windows while retaining the weak end. A false tone is worse than a
missed one: it moves a good signal out of range, whereas a miss leaves the audio
alone until a stronger window arrives. Windows dominated by keying gaps measure
2.4 and are indistinguishable from noise at any threshold; those are skipped.

Test files reorganised to match: the decision rule is covered by
CwShiftDeciderTest against real code, signal-level properties by
CwToneShiftSignalTest, and the restated-logic file it replaces is gone.

80 CW tests pass, golden vectors included.
2026-08-22 04:02:28 +00:00
mckero fdb44af9ff fix(cw): stop silence and edge estimates from defeating the tone shift
Two audit findings, both measured, both able to silently disable the feature.

A detection window landing in a keying gap used to collapse an established
shift to zero. CW is keyed, so gaps are normal: over 180 s of keyed audio at
1400 Hz, 11 of 90 detections saw no tone, and each one wiped the decode window
and left the next ~2 s buffered unshifted - outside the model's range and
therefore invisible to it. Absence of a tone is now absence of evidence and the
active shift is retained.

Hysteresis moved from shift space to tone space, anchored on the pitch that
produced the active shift. The old rule required a non-zero previous shift and
a needed shift, so it lapsed exactly where the jump is largest: at the 1200 Hz
edge one 12.5 Hz estimate hop flips between "inside" (shift 0) and "outside"
(a large shift). Measured 35 window drops in 60 detections for a 1205 Hz tone,
and 10 in 10 for a bare one-bin hop. A shift of zero is a real state, not the
absence of one. Slow drift still catches up, since the anchor bounds staleness
at the margin rather than letting it accumulate.

Detection prominence raised from 3.0 to 8.0. Pure noise peaks at 2.0-3.3 times
its own spectral mean, so 3.0 admitted roughly one noise window in five as a
"tone" - and a false tone is worse than none, since it moves a good signal out
of range. Keyed CW measures 47-51, so the gap is wide.

Shifted output is clamped to the +/-1.0 range the spectrogram assumes. The
Hilbert kernel's L1 gain is 2.51, so mixing overshoots: a full-scale square
wave measured 2.35 and even a plain sine 1.05.

The detection pool moved to core:domain as CwDetectionPool so its ring
behaviour can be tested directly - mutation testing showed the previous private
implementation was unreachable from any test. Its chronological-order contract
now has 11 tests driving the real class.

Removed the write-only detectedToneHz field.

74 CW tests pass, golden vectors included.
2026-08-22 02:35:58 +00:00
mckero f6db55b35c perf(cw): pool detection samples in a ring buffer
The detection pool shifted its whole array down one slot per incoming sample
once full. Detection is throttled to 2 s but the pool fills in 400 ms, so for
the remaining 1.6 s of every cycle each chunk arrived at a full buffer: 320
copies of 1280 floats per chunk, measured at 24320 whole-array moves per 10 s
of audio, all on the capture thread.

Writing to a ring index is O(1) per sample. Draining walks the ring from the
oldest slot so the analyser still receives the most recent audio in
chronological order - a test feeds a ramp past capacity and asserts the exact
contents, since getting the wrap wrong would splice the waveform and corrupt
every estimate silently.
2026-08-22 01:37:16 +00:00
mckero 1b8f8c46f6 fix(cw): drop stale audio on a tone-shift change, and damp detector jitter
Follow-up to the tone-shift feature, closing gaps the audits surfaced.

Toggling the setting, or the detector settling on a materially different shift,
now discards the buffered audio. Without it the 20 s decode window kept feeding
the model samples moved by the old amount for up to 20 s after the user acted,
and updateSignalMetrics corrected the pitch readout by an offset that no longer
matched the window. Text already committed to the history is kept: it was
correct when it was decoded.

The previous-state flag is nullable and seeded from the current setting on the
first chunk, so a decoder created while the setting is already on does not
report a spurious change and wipe an empty buffer. reset() clears it back to
null for the same reason. Two decoders can be live at once (the CW screen and
the Radar panel) and each tracks its own state.

Re-shifting is now gated by a 40 Hz hysteresis. Detection resolution is 12.5 Hz
and a real tone wanders, so without it an estimate hopping between adjacent
scan bins would drop the window every 2 s - costing far more decoding context
than re-centring gains. 40 Hz absorbs two bins of jitter while still following
a genuine retune; a test pins both halves of that trade-off.
2026-08-22 01:15:11 +00:00
mckero 9798107d37 feat(cw): optionally shift out-of-window CW tones into the model's range
DeepCW only analyses 400-1200 Hz - its input tensor is 65 bins wide, fixed at
training time - so a CW note outside that range is invisible to the decoder.
This adds an opt-in preprocessing step that moves such a tone to 800 Hz, the
window centre, extending the usable pitch range without touching the model.

Single-sideband mixing via a 63-tap Hilbert transformer. Plain real mixing was
measured and rejected: shifting 1500 Hz to 800 Hz left a fold-back image at
1000 Hz at 0.999 of the wanted amplitude, inside the window. Zero-stuff
upsampling plus lowpass handled downward shifts but left a 0.996 image when
shifting 300 Hz upward. The Hilbert approach measures clean on nine tones from
150 to 1550 Hz: one peak at the target, nothing above 0.3 relative amplitude.
In-window energy for a 1500 Hz input goes from 6.8% to 94.6%.

Only out-of-range audio is processed. A tone already inside 400-1200 Hz is
returned untouched (same array instance, no copy), and with the setting off the
audio path is exactly what it was before.

CwToneShifter.Streaming carries the Hilbert filter history and mixer phase
across capture chunks. Shifting each chunk in isolation left 62 of every 320
samples convolving against zeros, inflating envelope ripple to 8.7x the
whole-buffer baseline. A residual difference in the last ~3 samples of each
chunk is causal and documented: those output samples would need input that has
not been captured yet.

Detection pools chunks rather than gating on one. A capture chunk is 4410
samples at 44.1 kHz but only 320 after resampling to 3200 Hz, so requiring
1280 samples in a single chunk would have made the feature dead code - the two
independent audits both found this before it shipped. Detection now runs on a
pooled 0.4 s window, at most every 2 s.

Toggling the setting or a change in the detected shift drops the buffered
audio: the 20 s window would otherwise keep decoding samples moved by the old
amount, and the pitch readout could only be correct for one of them. The
readout itself subtracts the active shift so it shows the pitch on the radio,
not the shifted one.

Settings: OtherSettings.cwToneShiftEnabled, off by default, persisted and read
back in SettingsRepo, toggled from the Other card in Settings with a help line
explaining the 400-1200 Hz limit. Strings added to all nine locales. The
decoder reads the flag per chunk, so the toggle applies without restarting
capture.

Debug: the enabled-state transition, each detection verdict (no tone / inside
window / shifting by N Hz), and every shift change are logged, with the noisy
paths throttled to the 2 s detection interval. CwProbe records shift changes
only, keeping well inside its 1 MiB cap.

Tests: 8 shifter tests (detection sweep, noise rejection, pass-through
identity, image-free shifting across 8 tones, end-to-end spectrogram energy),
8 streaming tests (chunk continuity, history retention, reset semantics, chunk
sizes above and below the history window), and 6 gate tests including a
regression guard that a 320-sample chunk must be able to reach the detection
threshold. All 53 CW tests pass, golden vectors included.
2026-08-22 01:07:38 +00:00
mckero e3d7238721 chore(release): bump build number to 464 for the v4.5.7 rebuild
Version name stays 4.5.7 so the release is overwritten in place; the build
number must increase for Android to accept the update. This rebuild carries
the upstream rt-bishop merge (18 commits) on top of the 30 audit fixes.
2026-08-21 11:25:26 +00:00
mckero 40ba3fecdf chore(amsat): remove the HTML scraping path superseded by the JSON API
The merged upstream AMSAT implementation fetches status data from AMSAT's JSON
endpoints (getAmSatCatalog / getAmSatReports), so the fork's HTML scraping path
no longer has a caller:

- core/data/.../source/AmSatParser.kt (136 lines): parsed the amsat.org status
  table, deriving state from the page's inline colour codes.
- IRemoteSource.getStatusHtml() plus its RemoteSource implementation and the
  DatabaseRepoTest fake override.

Verified zero references repo-wide before removing, and again afterwards.
Request / CancellationException imports in RemoteSource remain in use by the
other fetchers. compileReleaseKotlin plus core:domain / core:data /
feature:map / feature:roaming unit tests stay green.
2026-08-20 15:00:13 +00:00
mckero 57d6f9d7ed chore(merge): drop dead leftovers from the upstream merge
Post-merge audit found code the merge left unreferenced:

- SettingsRepo: keySatelliteUrls / keyTransceiversUrls / separatorUrl were
  upstream's list-shaped data-source keys. The merge kept the fork's map-shaped
  DataSourcesSettings, so these three had a definition and zero uses.
- feature/status/res/drawable/ic_refresh.xml: SatStatusScreen imports
  core.presentation.R only, so its R.drawable.ic_refresh resolves to the
  core copy; the feature-local copy was never addressable. It was the only
  file under feature/status/src/main/res, so the directory goes with it.

Verified zero references with a repo-wide grep before removing each symbol.
compileReleaseKotlin plus core:domain / core:data / feature:map /
feature:roaming unit tests stay green.
2026-08-20 13:24:45 +00:00
mckero a654735337 merge: upstream rt-bishop main (18 commits) with conflict resolution
Merges rt-bishop/Look4Sat main (a42a5f1f, 18 commits: AMSAT status page,
customizable data sources, Doppler calculator, radar compass offset, per-sat
offset memory, localized date formats) into the fork's 30-commit audit
baseline.

Conflict resolution policy (user-directed):
- AMSAT feature (AmSatRepository, SatStatusScreen/ViewModel, SatStatus model):
  upstream version, which the user judged better built. MainScreen routes
  Screen.AmSat through SatStatusDestination().
- Localization: our values-zh/values-tr restored (upstream's merge dropped the
  fork-only strings); new upstream strings (sat_group counts, compass offset,
  frequency offset help) added in EN + ZH.
- fork-only features kept (CW decoder, Mutual/Roaming, WaveLog, APRS, Log tab,
  custom TLE/transceiver source switches): ours.
- Both sides' additions merged where independent: radar compass offset fields
  (Settings/SettingsRepo/RadarState), calculatorOffsetKHz action, wider linear
  transponder detection, deduplicateTransponders + its tests, sunrise/sunset
  tests merged with the moon hour-angle test.
- Sources kept as the fork's map structure (DatabaseRepo depends on it);
  satelliteModes list re-added for SelectionRepo. getSatelliteTypesIds /
  setSatelliteTypeIds re-added to ISettingsRepo+SettingsRepo; SharedDialog
  re-added to Components; providePairedBluetoothDevices added to
  IMainContainer/MainContainer.
- Icons renamed upstream (ic_satellites->ic_sputnik, ic_radar->ic_satellite)
  applied to Navigation/MutualScreen.

Build verified: all modules compileReleaseKotlin + unit tests
(core:domain, core:data, feature:map, feature:roaming) green.
2026-08-20 12:35:01 +00:00
atsunatsuandatsunatsu a42a5f1f0d Tweaked sunrise/sunset calculations, added unit tests (#241)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
2026-08-19 14:46:39 +02:00
mckero c547a126ee chore(release): bump build number to 463 for the v4.5.7 rebuild
Version name stays 4.5.7 so the existing release can be overwritten in place;
the build number must still increase for Android to accept the update.
2026-08-18 03:12:45 +00:00
mckero 16c746f552 fix(mutual): advance the search when refine collapses a pass window
findMutualPassesFallback skips a candidate with `if (refinedLos <= refinedAos)
continue` but left searchStart untouched, so the next loop iteration called
findNextMutualPass with the same start time and received the same pass again.
Today that branch is theoretically unreachable: refineEdge's 70 s window always
spans findNextMutualPass's 60 s sampling step, so the refined AOS/LOS can only
move inward and never cross. But the invariant is fragile - any future change
to the search step or the refine window (or a near-horizon pass whose
crossings land at the window edges) makes the loop spin forever on one pass,
freezing the query coroutine.

Advance searchStart past the collapsed pass before skipping, breaking the
cycle regardless of how the windows shift. Behaviour for the current reachable
paths is unchanged.
2026-08-17 17:56:09 +00:00
mckero 8f56ea05ec refactor(roaming): reuse positionToQth instead of the ported grid tables
RoamingScreen carried ~170 lines of decompiled range-lookup tables
(encodeLon/encodeLat) that re-implemented exactly what core:domain's
positionToQth already does. A probe calling both over 16,471 sampled
coordinates (every 2 degrees across the full globe) found byte-identical
8-char locators, so the tables were pure duplication - two implementations of
the same Maidenhead encoding that had to be kept in sync (the earlier boundary
fix had to be applied twice).

Replace them with positionToQth and split its standard-ordered output
(lonField latField lonSquare latSquare lonSub latSub lonSubsub latSubsub) back
into the per-axis segments the UI consumes: the 3x3 ring (first 4 chars),
markerLeft (lon subsquare), markerTop (lat subsquare). Out-of-range input
keeps the old blank-segment behaviour: positionToQth returns null, the locator
becomes spaces, qthNeighbors returns an empty ring, and the marker lookups
fall back to 0.

Net -160 lines. All existing RoamingState tests and the new equivalence probe
pass; :feature:roaming compiles.
2026-08-17 17:17:19 +00:00
mckero b749733289 fix(audio): keep cleanup from masking start failures or skipping release
AudioCapture.audioFlow's finally ran recorder.stop() then release() naked. If
startRecording() threw - permission revoked mid-request, audio device error -
the finally's stop() threw IllegalStateException (stop on an uninitialized
recorder), which replaced the original error AND skipped release(), leaking
the AudioRecord. The flow's caller saw "recorder failure" instead of "no
permission" and the native recorder was never freed.

Wrapping each cleanup step in runCatching preserves the original exception
while guaranteeing release() runs. Probe: a start failure previously surfaced
as RuntimeError with released=false; it now surfaces as the original
PermissionError with released=true.
2026-08-17 16:57:33 +00:00
mckero b4cfb16159 fix(radio): don't record frequencies the radio rejected
RadioTrackingService wrote lastSetTxFreq/lastSetRxFreq unconditionally after
calling setFrequency, ignoring its Boolean result. When the radio rejected the
frequency - the FT-817 CAT limit added in the previous commit, a dropped
Bluetooth link, or a failed ack - the remembered value no longer matched what
the radio actually holds. The manual-tuning detector then saw a phantom dial
change on the next read-back (read is the real frequency, lastSet is the one
that never landed) and entered tuning mode: it locked onto the wrong base and
kept rewriting the radio.

Probe of the state machine: before the fix, a rejected 1.26 GHz write against
a radio sitting on 145.5 MHz left lastSet at 1.26 GHz, so every subsequent
cycle read a 1.1 GHz gap and flagged manual tuning forever. After the fix the
lastSet is only updated on success, so the detector sees no change and the
loop keeps applying the next valid frequency. Same fix applied to the split
IC-705 path (setWorkingFrequency/setTxVfoFrequency).
2026-08-17 16:54:23 +00:00
mckero 7319cf8f5b fix(coroutines): propagate cancellation in remote source and status view model
RemoteSource's five suspend functions and SatStatusViewModel's two fetch paths
caught bare Exception, which also swallows CancellationException. When the
owning scope is cancelled (screen leaves, app closes) a cancelled network call
was reported as a null/error result instead of stopping: the caller kept
running until the next suspension point, and SatStatusViewModel wrote state
updates into an already-cancelled scope. Correct coroutine hygiene is to let
cancellation propagate - rethrow CancellationException before the generic
catch. Verified semantically with an asyncio probe: a swallowed cancel returns
a normal-looking null and the caller continues; a propagated cancel stops the
coroutine immediately.

No behaviour change for real errors; :core:data and :feature:status compile.
2026-08-17 16:46:09 +00:00
mckero baf2a7022d fix(aprs): hold the client lock across the response read in sendPacket
sendPacket wrote the packet under the lock but read the server response
outside it. disconnect() - called concurrently from stop() and from the
reconnect path in AprsReporter.reportOnce's catch - nulls and closes
writer/reader/socket under the same lock, so the lock-free read raced with it.
A probe interleaving 5,000 sends with repeated disconnects produced a mix of
744 OK and 4,256 exception results: the response read hit a just-closed socket
and the swallowing runCatching reported Pair(true,"OK") for a packet that may
never have left, or read through a stale reference. The tracker believed the
beacon was heard while APRS-IS never received it.

Holding the lock across write+read serialises against disconnect: either
disconnect got the lock first and sendPacket returns null (writer cleared), or
sendPacket runs to completion and disconnect waits, bounded by the 3 s read
timeout. Re-ran the interleaving probe: 3,000 sends, zero inconsistent
results. Compiles and :core:data tests stay green.
2026-08-17 16:33:12 +00:00
mckero b95a86c97f fix(radio): reject FT-817 frequencies the CAT protocol cannot express
The FT-817 CAT frequency field is 4 BCD bytes at 10 Hz resolution, so the
largest representable value is 999,999,990 Hz. encodeFrequencyBcd is exact
below that, but for anything above it the %08d formatting silently drops the
leading digit: 1,267.6 MHz encodes as 126.76 MHz. Verified against the release
bytecode - 1,000,000,000 Hz -> [10 00 00 00] -> 100,000,000 Hz, ten times
lower - and the SatNOGS catalogue has 17 transmitters with uplinks over 1 GHz
(QO-100 at 2400.05 MHz, several 23 cm links), so the wrong value is reachable
via RadioTrackingService when an FT-817 is mis-configured as the TX radio.
The tracking loop's read-back then locks onto the wrong band with no warning.

Reject out-of-range frequencies at setFrequency with a log and return false
instead of sending a corrupted command. In-range values are unaffected
(probe: 7.074/145.5/435.1 MHz and both 999,999,98x/99x MHz round-trip exactly;
every value above the limit is refused before the encoder runs).
2026-08-16 09:47:26 +00:00
mckero ed1fe66892 fix(geo): replace the clipLon while-loop with a modulo reduction
clipLon reduced longitudes by looping += 360 until in range. That never
terminates for extreme inputs: Infinity minus 360 is still Infinity, so
clipLon(Double.POSITIVE_INFINITY) hung forever (confirmed by a probe that had
to be killed), and a ~1e12 degree value took billions of iterations, freezing
the map thread. NaN came back as NaN either way.

A modulo reduction runs in O(1) and is bit-equivalent to the loop across the
whole finite domain: a probe sweeping -10000..10000 at 0.01 degree steps (2
million points) plus the boundary values -180/-179.999/0/179.999/180/180.001/
±360/±540 shows zero mismatches. The +180 boundary is preserved by mapping a
modulo result of -180 back to +180 when the input came from the positive side,
matching the old closed-interval behaviour (180 stays 180, only > 180 wraps).

Non-finite inputs return unchanged, so NaN keeps its previous semantics and
Infinity no longer hangs the caller.

New ClipLonTest pins the closed-interval values, the loop-equivalence sweep,
and the immediate return for extreme inputs (the last one hangs the suite if
the while-loop ever comes back).
2026-08-16 09:41:35 +00:00
mckero 1e24673632 fix(network): close sockets on setup failure and on write failure
Two leaks in NetworkReporter, the same family as the Bluetooth/APRS/radio
socket leaks fixed earlier:

1. ensureRotatorConnected/ensureFrequencyConnected assigned the field directly,
   so a channel that opened but threw during the rest of setup was never
   closed and remained referenced. Use a local `opened` and close it in the
   catch, matching the pattern used in AprsIsClient/Ic705Controller/
   Ft817Controller/BluetoothReporter.

2. write() only flipped connected=false on failure. The broken channel stayed
   in the field, the next ensure* reconnected and overwrote it, and the old
   channel was never closed. Now a failed write closes the channel and nulls
   the field. The null check is identity-based (socket === field) so a stale
   reference from a concurrent report can never close a newer channel.

State-machine probe: normal write keeps the socket, failed write closes and
nulls, next report reconnects fresh, and passing a stale reference does not
close the newer socket.
2026-08-16 09:36:08 +00:00
mckero ed0f5678b3 fix(cw): cap the crash-probe log file at 1 MiB
CwProbe.step() appended one line per call with no size limit, rotation or
cleanup, and it runs on every build: CwDeepDecoder is the only ICwDecoder
implementation and writes infer_begin + infer_done every 1.5 s inference tick.
Measured against the actual line format that is ~170 KB/hour, ~4 MB/day of
unbounded growth in files/probe_cw.txt while CW audio is monitored, plus
synchronous disk I/O on every inference.

Truncate when the file exceeds 1 MiB instead of deleting, so the probe keeps
the most recent diagnostics (the reason it exists: the last lines show where a
flash-crash died). Simulated 10 h of continuous use: 2.7 MB written in total,
file stays bounded around ~640 KB; previously it would have kept all 2.7 MB
and grown without limit.
2026-08-16 09:33:44 +00:00
mckero aac1fa0da5 fix(map): pick the pass by time instead of a field that is never set
The map info panel chose which pass to describe with

    allPasses.find { it.catNum == catnum && it.progress < 1 }

but OrbitalPass.progress defaults to 0 and nothing in the repository or the
prediction layer ever assigns it - PassesViewModel computes progress on its own
local copy of the list and never writes it back. The predicate was therefore
always true, so the lookup returned the satellite's *first* pass forever.

Simulated over an ISS timeline with three passes (10:00, 12:00, 14:00), 4 of 6
sampled instants were wrong: from 10:30 onwards the panel still pointed at the
10:00 pass with its countdown frozen at 00:00:00, instead of counting down to the
12:00 and 14:00 passes. Only re-fetching the pass list refreshed it.

Select by time now: the pass currently in progress, otherwise the earliest one
still upcoming. Extracted as the pure internal selectCurrentOrNextPass so it is
testable, with the reasoning recorded so the progress field is not reintroduced
as a filter here.

Restoring the old predicate fails 5 of the 6 new tests; with the fix
:feature:map:testDebugUnitTest, :core:domain:test, :core:data:testDebugUnitTest
and :feature:roaming:testDebugUnitTest are all green.
2026-08-14 19:49:32 +00:00
mckero c7bb253981 fix(map): close both sides of an antimeridian crossing
The ground track is cut into polylines so none of them spans 180 degrees, but the
cut only ever appended the outgoing edge point. The next polyline therefore began
at the first sample past the meridian - typically around -178 - so the drawn
track stopped at the edge on one side and reappeared inland on the other,
leaving a visible gap on every orbit that crosses the Pacific.

The edge point also reused the *next* sample's latitude, so the closing leg
jumped: for 179 -> -178 spanning 14 -> 16 degrees latitude the edge was placed at
16.0 instead of the true crossing at 14.667.

Now a crossing closes the current polyline on the edge it leaves through and
opens the next one on the opposite edge, both at the interpolated crossing
latitude, so the seam is continuous.

The split is extracted as the pure internal splitAtAntimeridian/crossingLatitude
pair, which also gives feature:map its first unit tests. Verified against a
standalone Java probe first (eastward, westward, repeated crossings, and a track
hugging the edge without crossing), then as Kotlin tests: restoring the old
single-point behaviour fails four of them, and the current code is green
alongside :core:domain:test and :feature:roaming:testDebugUnitTest.

Also drops the misleading "left/right terminal position" comments: the branch
that fires when the previous sample sat near +180 is the eastward crossing, and
it correctly closes on +180.
2026-08-14 19:19:42 +00:00
mckero af96fe1cf0 test(predict): pin the Moon hour angle to a reduced range
MapViewModel converts MoonPosition.gha into the sub-lunar longitude with
`if (gha <= 180) -gha else 360 - gha`, which is only a valid longitude while gha
stays inside 0..360. Nothing enforced that: getMoonPosition relies on
`while (teg > 360) teg -= 360` reducing GMST before the single
`if (gha < 0) gha += 360` correction, and the raw GMST polynomial is about
3.5e6 degrees today, so losing that one line silently pushes the Moon marker
millions of degrees off the map instead of failing loudly.

Sweep a synodic month at 37-minute steps (1,167 samples) asserting gha stays in
0..360 and the derived longitude in -180..180, plus a check that the hour angle
advances 10-20 degrees per hour.

Verified the test has teeth: deleting the teg reduction makes both cases fail;
with the current implementation :core:domain:test is green. No production change
- the existing code is correct.
2026-08-14 18:54:26 +00:00
mckero 27d41eb2ee fix(amsat): render only the days the API actually returned
The status grid always drew six day columns, but the AMSAT reports endpoint
cannot supply six days for the full catalogue. Measured against the live API:

  limit=500  -> meta.count=500, covers 4 days (Aug 11..Aug 14)
  limit=1000 -> meta.count=500, same 4 days   (server clamps the limit)
  hours=336  -> meta.count=500, same 4 days   (window size does not help)
  before/offset/page -> ignored, same 500 newest rows

With ~90 catalogued satellites the 500 newest rows only reach about four days
back, so the two oldest columns were guaranteed to be uniformly gray. Gray means
"no report" in this UI, so the screen asserted nobody reported those days when
the truth was that the data was never fetched.

Derive the column count from the oldest report actually received, capped at six.
On live data that yields four columns labelled Aug 14..Aug 11 instead of six with
Aug 10 and Aug 9 blank. The UI already renders whatever days it is given, so no
UI change is needed.

Also name the request constants and record what was measured about the endpoint,
so the 500 is not mistaken for an arbitrary choice that can simply be raised.

Note for a future change: the per-satellite form of the endpoint
(reports.php?name=...) is not affected by the cap - sampling eight satellites
returned 926 rows spanning eight days, i.e. full six-day coverage - but it needs
one request per satellite (~0.8 s each, ~68 s for the whole catalogue), so
switching to it is a deliberate trade-off rather than a bug fix.

:core:data:compileReleaseKotlin, :core:data:testDebugUnitTest and
:core:domain:test all BUILD SUCCESSFUL.
2026-08-14 18:30:31 +00:00
mckero 2bac6655f3 fix(amsat): align status slots to their UTC calendar-day labels
AmSatRepository labelled columns by calendar date but filled them by slicing a
rolling 72-slot window ending at fetch time. The two timelines coincide only
near 23:59 UTC. At common fetch times the status grid lied about dates:

  UTC 00:00: 72 / 72 slots under the wrong label
             "today" column contained all of yesterday
  UTC 12:00: 36 / 72 wrong; every column straddled two dates
  UTC 13:37: 30 / 72 wrong
  UTC 23:59:  0 / 72 wrong (the accidental alignment case)

Anchor the six columns on UTC midnight instead. Every SatDay now covers exactly
[day 00:00, next day 00:00), split into twelve 2-hour slots newest-first so the
UI's existing first-non-gray lookup still chooses the latest daily report.

A standalone Java probe porting the old arithmetic reproduced the 72/72,
36/72 and 30/72 mismatches. Porting the new formula gives 0/72 mismatches at
00:00, 12:00, 13:37 and 23:59 UTC.

Also restore core:data's unit-test compilation. DatabaseRepoTest's fakes were
stale after IRemoteSource gained AMSAT methods and ISettingsRepo's zero-arg GPS
setter became suspend; the whole data test suite previously could not compile,
so data-layer regressions were untestable. Updated the fake members and verified
:core:data:testDebugUnitTest plus :core:data:compileReleaseKotlin BUILD
SUCCESSFUL. The product code does not use org.json in JVM tests because Android
org.json stubs throw there, so the date math remains verified by the standalone
same-JVM probe rather than a misleading mocked parser test.
2026-08-14 18:08:46 +00:00
mckero 2da7127fd3 fix(roaming): derive the 3x3 grid from qthNeighbors
The decompiled per-edge branches computing the surrounding nine squares had two
independent defects.

1. Field letters stepped past the alphabet

Every branch moved a field with raw character arithmetic (`str[0] - 1`,
`str5[0] + 1`) and Maidenhead fields only run A..R, so coordinates near the
edges of the world produced squares outside the alphabet:

  (-89.9, -179.9) -> [@A91, AA01, AA11, @A90, AA00, @A10, @@99, A@09, A@19]
  ( 89.9,  179.9) -> [RS80, RS90, SS00, RR89, RR99, SR09, RR88, RR98, SR08]

2. Some moved cells kept the old field letter

The north-edge branch advanced the latitude field for the top-centre cell only,
leaving the two top corners in the previous field:

  centre AA19 -> ported [AA00, AB10, AA20, ...]
                 correct [AB00, AB10, AB20, ...]

Cross-checked against the shared qthNeighbors helper, which is already covered
by QthConverterTest including the AA00 and RR99 wrap cases:

  before: 64,800 sampled coordinates, 6,480 disagreed (all with centre square
          digits 00 or x9, i.e. the north edge and the 00 corner)
  after:  64,800 sampled coordinates, 0 disagree

The ring is plain Maidenhead arithmetic with no QTH-Locator-specific behaviour,
so call qthNeighbors instead of keeping a second, wrong implementation. The
now-unreferenced buildGrids branches are removed (grep confirmed the definition
was the only remaining occurrence). The existing OL42 reference grid and the
four ported edge-case tests still pass unchanged.

Reverting the fix fails both new regression tests; with it
:feature:roaming:testDebugUnitTest and :core:domain:test are green.
2026-08-14 17:34:06 +00:00
mckero fed9fe188e fix(roaming): assign exact grid boundaries to the correct cell
The QTH Locator port keeps the decompiled range tables, which close both
adjacent cells (`-20.0..0.0` then `0.0..20.0`). Kotlin's `when` takes the first
match, so any coordinate landing exactly on a field, square or subsquare
boundary was attributed to the previous cell:

  (0, 0)          II99xx99  should be JJ00aa00
  (1, 1)          JJ00lx99  should be JJ01ma00
  (22, 108)       OL31xx99  should be OL42aa00
  (22.5, 108.5)   OL42fl99  should be OL42gm00
  (22.25, 108.25) OL42cf99  should be OL42dg00

At the field level the locator is wrong by a whole 20 deg x 10 deg field, and
the 3x3 neighbour grid plus the red position marker are derived from the same
characters, so the whole Roaming screen pointed at the wrong square.

Cross-checking the port against core/domain positionToQth over the grid:
  before: 65,341 sampled points, 4 agreed
  after:  65,341 sampled points, all agree

The independent converter was confirmed correct first: it reproduces the
user-verified reference sample OL42ih45, and hand-computing lon=-179.75
(0.25 deg into the field, x12 -> subsquare index 3 = 'd') and lat=-90
(subsquare 'a', extended digit 0) matches it rather than the port.

Rather than rewriting the faithful lookup tables, nudge the input by 1e-10 so
the closed ranges behave like the standard half-open [low, high) cells, keeping
+90/+180 inside the final R cell. Seven real-world city samples and all existing
ported-behaviour tests, including (90, 180) -> RR99xx99, are unchanged.

Regression tests added for the boundary cases and for cross-implementation
agreement. Reverting the fix fails both; with the fix
:feature:roaming:testDebugUnitTest is green.
2026-08-14 16:59:30 +00:00
mckero 19ca5205fb fix(cw): make waterfall revision atomic and keep clear from resurrecting old data
Two races shared the same cause: pushSamples runs on the audio capture thread
while clear() runs on the Compose main thread.

1. Lost redraw notifications

Both paths did `_revision.value += 1`. That expands to get -> add -> set and is
not atomic. A controlled two-thread probe (20k increments each, five runs)
lost up to 6,402 increments / 16%; using StateFlow.update lost zero. Since
revision is the Canvas's only redraw signal, every lost update can leave the
waterfall showing stale rows. If both writes land on the same number, StateFlow
sees no value change and notifies nobody.

Use `_revision.update { it + 1 }` in both paths.

2. Clear resurrected pre-clear audio

pushSamples copies pending audio under the lock, deliberately performs FFT
outside it, then reacquires the lock to append rows. The exact interleaving:

  audio thread: take old audio, start FFT
  main thread:  user taps Clear -> rows/pending empty
  audio thread: old FFT completes -> appends old rows again

The display becomes empty then immediately redraws the audio the user cleared.
A deterministic thread probe reproduced old rows after clear. Add a generation
counter protected by the same lock: pushSamples records it before FFT and drops
the computed rows when clear incremented it meanwhile. Fixed probe remains empty.

Verification: :feature:cw:compileReleaseKotlin + full :core:domain:test BUILD
SUCCESSFUL; grep confirms no non-atomic revision increments remain.
2026-08-14 16:31:25 +00:00
mckero a7a6d70d40 fix(aprs): keep enabled switch consistent with actual service state
AprsForegroundService refuses to run when callsign is blank and calls
stopSelf(), but it never writes enabled=false back to AprsStore. AprsCard did
the opposite: toggling Enable first persisted enabled=true, then started the
service. On a fresh install with no callsign this produced a permanent lie:

  UI switch: ON   SharedPreferences: enabled=true   service: stopped

Leaving and reopening settings still showed ON even though APRS had never sent
a packet. Startup/restore code could then repeatedly try to launch a service
that immediately stops itself.

There were two entry paths with the same root cause:
1. Turning the switch on before entering a callsign.
2. Erasing an existing callsign in the dialog while APRS was already enabled.

The switch now opens the configuration dialog without persisting or starting
anything when callsign is blank. Saving the dialog also forces enabled=false
when the callsign was erased.

State-machine simulation: old state ends ON/stopped; both fixed paths end in a
consistent OFF/stopped state. :feature:settings:compileReleaseKotlin and full
:core:domain:test BUILD SUCCESSFUL.
2026-08-14 16:10:18 +00:00
mckero d5230b3bc6 fix(qth): correct Maidenhead boundaries and longitude wrapping
A full-domain round-trip probe found three related boundary bugs.

1. Exact positive limits wrapped the square/subsquare terms to zero

positionToQth clamped only the A-R field index. At +90 latitude / +180
longitude the field saturated at R, but all later terms used modulo and wrapped
to square 0 / subsquare a:

  (90, 180) -> RR00aa00 -> (80.002083, 160.004167)
  error: -9.998 deg latitude, -19.996 deg longitude

The existing test incorrectly asserted RR00aa00 and had therefore fossilised
the defect. Clamp shifted coordinates just inside the half-open upper bound so
the limits land in the final cell RR99xx99.

2. isValidPosition allowed longitude through +360

Maidenhead covers -180..180, but 181..360 was accepted and produced plausible
locators that decoded 20-200 degrees away:

  lon 181 -> decoded 161.004167  (error -19.996)
  lon 270 -> decoded 170.004167  (error -99.996)
  lon 360 -> decoded 160.004167  (error -199.996)

Restrict the converter contract to -180..180.

3. Locator validation allowed S-X as field letters

The first pair has 18 fields A-R, while only the later subsquare pairs use
A-X. The shared [A-X]{2} regex accepted SS00aa / XX99xx and decoded them past
the poles (up to lat 149.98, lon 299.96). Use A-R for the field pair.

The SettingsRepo caller had a separate wrapping bug that masked part of this:
it mapped longitude>180 by subtracting 180 (270 -> +90, wrong hemisphere)
instead of modulo 360 (270 -> -90). Fix that at the writer too.

Verification:
- standalone JVM sweep: 519,841 points, old code had 1,441 large-error points
  with max drift 9.997917 deg lat / 19.995833 deg lon
- new Kotlin regression sweep requires every 8-char round trip <=0.01 deg
- QthConverterTest BUILD SUCCESSFUL
- full :core:domain:test + :core:data:compileReleaseKotlin BUILD SUCCESSFUL
2026-08-14 15:57:32 +00:00
mckero 7d7abeb31e fix(aprs): prevent duplicate reporters on repeated service starts
Every ACTION_START - and every null intent delivered by START_STICKY - called
startReporting(), which always constructed a new AprsReporter and overwrote the
field without stopping the old one. AprsReporter owns an independent
SupervisorJob + periodic while(isActive) loop, so every overwritten instance
kept reporting forever and could no longer be reached by ACTION_STOP.

Simulation:
  five ACTION_START events: 5 running reporters, 4 leaked -> fixed: 1 / 0
  START + 3 sticky restarts: 4 running, 3 leaked -> fixed: 1 / 0
  mixed real sequence:      4 running, 3 leaked -> fixed: 1 / 0

At the default 10-minute interval, four leaked reporters send 24 duplicate
position packets per hour and open 24 needless connections; this also amplifies
the connect-time socket leak fixed earlier.

startReporting now returns when the current reporter is active. Config changes
remain correct: AprsCard explicitly sends ACTION_STOP before ACTION_START, so
the old reporter is stopped and nulled before the new configuration starts.

:app:compileReleaseKotlin BUILD SUCCESSFUL.
2026-08-14 15:38:08 +00:00
mckero 828f720955 fix(status): show gray cell instead of crashing on an empty day
AmSatParser deliberately uses getOrNull + mapNotNull while reading each day's
12 slots, so a shortened HTML row can legitimately produce SatDay(slots=[]).
StatusRow then selected the first non-gray slot and fell back to slots.first(),
which throws NoSuchElementException and crashes the entire AMSAT status screen.

Use firstOrNull for both lookups and render a zero-count gray placeholder when
no slot exists. Real amsat.org HTML currently has all 41 satellite rows at the
full 73 cells, but the parser's own tolerance contract means the UI must handle
what it can emit.

Verified against the live page: parser matches 41/41 rows and 477/477 reports;
:feature:status:compileReleaseKotlin BUILD SUCCESSFUL.
2026-08-14 15:27:43 +00:00
mckero 5f1f90067f fix(aprs): clamp altitude and wrap course to keep fixed-width fields
Both extensions are fixed-width decimal fields, but neither value was range
checked before formatting:

  formatAltitude(-50.0)      -> /A=-00164   ('-' eats a digit slot)
  formatCourseSpeed(_, 360f) -> /360/...    (course must be 000..359)
  formatCourseSpeed(_, -1f)  -> /-01/...    (widens the field)

A negative altitude is reachable from a below-sea-level position or a poor GPS
fix, and the malformed extension corrupts everything after it in the comment
field. Altitude now clamps to 0..999999, course wraps modulo 360, and speed
clamps to three digits.

Found by the same locale probe that produced the previous commit.
:core:domain:test BUILD SUCCESSFUL.
2026-08-14 15:12:30 +00:00
mckero f4e188261d fix(aprs): format packets with Locale.ROOT so they stay ASCII
All nine String.format calls in AprsPacket used the JVM default locale. On a
device set to Arabic, Persian or Bengali the digit shapes come out as
Eastern Arabic / Bengali numerals, so every position report was malformed:

  ar_EG  lat=٣٩٥٤.٢٥N  lon=١١٦٢٤.٤٤E  alt=/A=٠٠٠٣٢٨
  fa_IR  lat=۳۹۵۴.۲۵N  lon=۱۱۶۲۴.۴۴E  alt=/A=۰۰۰۳۲۸
  bn_BD  lat=৩৯৫৪.২৫N  lon=১১৬২৪.৪৪E  alt=/A=০০০৩২৮

APRS-IS is an ASCII line protocol, so aprsc rejects these packets outright:
APRS reporting simply never worked for those users, with no clear error.
A locale using ',' as the decimal separator would corrupt the range filter
the same way.

Affected: getDMS position encoding (all five ambiguity branches), the
DDMM.MM/DDDMM.MM assembly, formatAltitude, formatCourseSpeed and
formatRangeFilter.

TDD proof:
  without Locale.ROOT: 4 of 4 AprsPacketLocaleTest cases FAILED
  with Locale.ROOT:    BUILD SUCCESSFUL, full :core:domain:test green

Ruled out by the same probe (no change made): getDMS degree/minute split
matches an independent DDMM.MM reference implementation over 1,800,000 sampled
latitudes with zero divergence; the passcode loop dropping the trailing NUL on
even-length callsigns is the standard algorithm's behaviour.
2026-08-14 15:09:18 +00:00
mckero e1233dceaa fix(wavelog): preserve six-character grids in v1 ADIF upload
WaveLog v1 truncated every grid to four characters with gridsquare.take(4),
while v2 sent the same grid at full precision. QRZ backfill provides six-character
locators (e.g. OM89ab / FN31pr), so the v1 path - the one used by the user's
server in practice - degraded position precision from roughly 4.6 km to around
100 km and stored different data depending on which API version answered.

Send the complete grid through v1 as well. The ADIF length field is already
computed from the actual value, so six/eight-character locators need no special
handling.

TDD proof:
  old take(4): v1_adif_preservesSixCharacterGrid FAILED
  fixed:       WaveLogApiPayloadTest BUILD SUCCESSFUL
  full suite:  :core:domain:test BUILD SUCCESSFUL
2026-08-14 14:56:23 +00:00
mckero 09e728fa1b fix(data): close sockets when connect() fails after the handshake
All five connect paths opened a socket, completed the TCP/RFCOMM handshake,
and only afterwards stored it in a field. Any exception in between leaked the
socket: the catch block just flipped a boolean, and disconnect() can only close
what already reached the fields.

Leak windows (statements that can throw after the handshake succeeded):
  AprsIsClient.connect        soTimeout / tcpNoDelay / getOutputStream / getInputStream
  Ic705Controller.connect     outputStream / inputStream / sendAndWaitAck
  Ft817Controller.connect     outputStream / inputStream
  BluetoothReporter x2        outputStream

AprsIsClient is the worst case because AprsReporter retries on a timer
(intervalMin, minimum 1 minute) and nulls out the client after each failure,
so every failed attempt permanently loses one fd:

  failure rate   leaked fds/hour   time to exhaust 1024 fds
       5%              3.0              ~14.2 days
      20%             12.0               ~3.6 days
      50%             30.0               ~1.4 days
     100%             60.0              ~17 hours

Typical trigger is a weak link where the TCP handshake succeeds but the peer
immediately RSTs (overloaded or rate-limiting APRS-IS server). Once fds run out
nothing in the process can open a socket or file any more: TLE updates, AMSAT
status and WaveLog uploads all start failing with no obvious cause.

Each path now keeps a local reference to the socket it opened and closes it in
the catch block, also clearing the stream/socket fields so a half-initialised
connection is not mistaken for a live one.

Verified: :core:data:compileReleaseKotlin BUILD SUCCESSFUL; grep confirms all
five close calls are present.
2026-08-14 14:09:42 +00:00
mckero c1895506e0 fix(cw): flush archive buffer inside loop to stop dropping audio
CwDeepDecoder appended evicted samples with a bare bounds check:

    for (v in overflow) {
        if (archiveSize < archiveBuffer.size) archiveBuffer[archiveSize++] = v
    }
    if (archiveSize >= ARCHIVE_THRESHOLD) { flush() }

Once archiveBuffer (64000 samples / 20 s) filled up mid-batch the remaining
samples were silently discarded, because the flush only ran after the loop.

Worst measured case: 47999 samples already accumulated (just under the 48000
flush threshold, so no flush) plus a 64000-sample overflow batch means 111999
samples pushed into a 64000 buffer -> 47999 dropped, i.e. 15 s of audio missing
from the permanently archived CW history.

Now the buffer is flushed as soon as it is full and before appending, so every
sample reaches archiveDecode. Simulation over five batch patterns: dropped
count goes 47999 -> 0 for the worst case and all 111999 samples are archived.

Bounds: single append() can evict at most capacity samples, so drainOverflow()
returns at most 64000 - archiveBuffer never needs to grow.
2026-08-14 13:28:55 +00:00
mckero 066fafbb81 fix(data): use Mutex to queue calculatePasses, not drop calls
The previous guard (if (_isCalculating.value) return) silently dropped
concurrent calls. Every call carries filter settings the user just applied,
so a dropped one left the list showing results for the previous filter:

  User clicks 'Apply' with elevation>=5
  -> UI updates to show elevation>=5
  -> calculatePasses(elevation>=5) called
  -> but if _isCalculating=true, return immediately
  -> list still shows elevation>=30 results

The guard window is wide: delay(1000) + real calculation time (hundreds
of ms to seconds), exactly when the progress indicator spins and users
naturally interact again.

Mutex serializes calls instead: the second one queues and eventually runs
with its own parameters. This also fixes the original concurrency issue
(duplicate parallel calculations) and adds finally {} so a thrown exception
cannot leave isCalculating stuck at true (frozen progress indicator).

Reverts the regression introduced in the previous attempt to add concurrency
protection.
2026-08-14 13:07:53 +00:00
mckero aedb3fee19 fix(radar): SwipeDeleteRow missing key() deletes wrong QSO
Without key(entry.id), Compose reuses component state by position.
When the list reorders mid-countdown (new QSO inserted at index 0,
or QRZ grid backfill triggers refreshTick++), the pending deletion
transfers to a different record and removes the wrong one.

Affected screens: LogTab and WavelogLogScreen.
2026-08-14 12:57:37 +00:00
mckero 77314e824e fix(radar): make pass auto-advance and duplicate-QSO guard actually work
自查上一轮修复时发现两处改动根本没生效, 属于我上一轮的误判, 这里改成真修复。

## 1. 过境结束不切换 (上一轮改动无效)

上一轮在 tick 循环里加了"过境结束就重新 findCurrentPass()"。但
findCurrentPass() 的第一级匹配是:

    passes.find { it.catNum == catNum && it.aosTime == aosTime }

其中 (catNum, aosTime) 来自 satelliteRepo.selectedPass, 而 selectPass()
只在 MainScreen 用户点击过境时调用 (grep 全仓库确认 3 处调用点全在
MainScreen), 雷达页运行期间该值不变。所以过境结束后重新查询仍然精确命中
同一个已结束的过境, nextPass != pass 恒为 false, 一次都切不过去。

模拟脚本复刻 findCurrentPass 四级回退 + tick 循环验证:
  修复前 ISS(10:00-10:10) 结束后, 到 10:19 仍在 tick ISS, 切换 0 次
  修复后 10:11 切到 NOAA-18(10:15-10:25), 切换 1 次
  边界: 最后一个过境结束后无下一个, 保持当前不崩溃

改为新增 findNextPassAfter(): 取 aosTime > current.losTime 的过境, 优先
同一颗卫星的下一圈 (雷达继续跟这颗星), 没有则退回任意卫星最早的那个。

## 2. 重复提交 QSO (上一轮改动无效)

上一轮加的 submitting 标志位没有任何作用: submit() 全程同步, 进入时置
true, 返回前置 false, 中间没有挂起点。两次 IME onDone 是两个独立事件,
第二次进来时标志早已复位。

改为记录上次入库的呼号与时间戳, 同一呼号在 2 秒内重复提交直接忽略。
这才是实际要防的场景 (误触两次回车存两条同样的 QSO)。

验证: :feature:radar:compileReleaseKotlin BUILD SUCCESSFUL
2026-08-14 12:45:33 +00:00
mckero 74902cddce fix(i18n): escape single quote in Turkish whatsnew string
Android AAPT requires single quotes in string resources to be
escaped as \' to avoid being interpreted as the start of an
escape sequence. The unescaped Ayarlar'ı triggered:
'Invalid unicode escape sequence in string'

values-tr/strings.xml:108 Ayarlar'ı → Ayarlar\'ı
2026-08-14 11:44:16 +00:00
mckero 8324903104 chore(release): bump versionCode to 462 and refresh whatsnew for v4.5.7
Increment versionCode 461 → 462 to allow reinstallation over the existing
v4.5.7 APK (required for覆盖发行版 to work on user devices).

Update whatsnew in all 4 locales (en/zh/tr/id+in) to document the 10 bug
fixes shipped in this release:
- Menu layout: Settings永久消失, AMSAT/WavelogLog forced migration
- DataParser: epoch parsing for UTC 00:00:01–00:01:26
- Radar: auto-switch to next pass, live Doppler offset
- Passes: division by zero in progress calculation
- SatelliteRepo: concurrent calculatePasses race
- WaveLog: duplicate QSO submission, grid square update race

Release notes now include both the DeepCW fp32 migration and the 10 fixes.
2026-08-14 11:38:59 +00:00
mckero a757474b06 fix(radar): 过境结束后自动切换到下一个过境
根因:
collectPassAndStartTickLoop() 启动时调用 findCurrentPass() 获取当前过境,
之后进入 while(isActive) 循环每秒 tickPass(),但从不重新检查过境是否结束。
结果:过境 LOS 后雷达页面继续显示旧卫星位置(冻结在地平线),用户必须
手动返回过境列表重新点击下一个过境。

触发条件:
1. 用户在过境进行中打开雷达页面
2. 过境结束时用户仍停留在雷达页面
3. passes 列表中存在后续过境

修复:
每次 tick 开始时检查 timeNow > pass.losTime,如果过境已结束则调用
findCurrentPass() 查找下一个过境。findCurrentPass() 的三级回退逻辑
(精确匹配 → 时间窗口 → 同卫星 → 第一个)保证能拿到合理的下一个过境。
如果找到且与当前 pass 不同,则重新 loadPassData() 加载新过境的电台和轨迹。

影响:
雷达页面现在会无缝切换到下一个过境,用户体验接近实时卫星跟踪软件。
如果 passes 列表为空(所有过境都结束),页面保持最后状态不崩溃。
2026-08-14 11:24:01 +00:00
mckero 9cfa238e5c fix(passes): 防止过境进度计算时除零崩溃
根因:
PassesViewModel.updateProgress() 计算进度时用 deltaNow / deltaTotal,
如果 TLE 损坏、轨道退化、或数据解析错误导致 losTime <= aosTime,
deltaTotal 为 0 或负数,除法触发 ArithmeticException 或产生 Infinity。

触发条件:
1. OMM/CSV 历元解析 bug(已在另一 commit 修复)导致时间错乱
2. 深空卫星 TLE 过期几十年,losTime 计算失败回退到 aosTime
3. 手动导入格式错误的 TLE

修复:
在除法前检查 deltaTotal <= 0f,跳过该过境的进度更新。
用户仍能看到过境列表,但异常过境不显示进度条(优雅降级)。

影响:
避免因单个异常 TLE 导致整个过境列表页面崩溃。
2026-08-14 11:22:54 +00:00
mckero 29ca4c29bb fix(data): 拒绝 calculatePasses 并发调用防止重复计算
根因:
SatelliteRepo.calculatePasses() 在耗时计算期间如果被重复调用,
会启动多个协程同时遍历卫星列表,导致:
1. 重复的 SGP4 轨道计算(CPU/电池浪费)
2. passes MutableStateFlow 被多次更新,触发下游 UI 重组风暴
3. _isCalculating 标志被后续调用覆盖,可能提前置 false

修复:
在 _isCalculating.value = true 之前检查当前值,如果已在计算中则
直接 return,拒绝并发调用。

影响:
防止用户快速切换过滤条件、旋转屏幕等场景下的重复计算。
_isCalculating 现在是真正的互斥信号量(简化版,无等待队列)。
2026-08-14 11:22:07 +00:00
mckero 82c8112575 fix(settings): RadioControlDialog 组合期间写状态
问题:Compose 运行时警告两次 'State write during composition' (split mode 重置 + baud rate 调整)。
根因:splitMode/baudRate 的条件写操作在组合 body 内直接执行 (if 块)。
修复:用 LaunchedEffect 隔离副作用,避免组合期间修改状态。
影响:消除运行时警告,避免潜在的组合跳帧或死循环。
2026-08-14 09:33:53 +00:00
mckero 20e5b2f617 fix(roaming): 权限授予后页面内刷新状态
问题:用户在页面内跳系统设置授予定位权限再回来,GPS 监听不启动(必须退出重进页面)。
根因:permissionLauncher 回调是空的 { },不更新 hasPermission 状态。
修复:回调里检查 FINE/COARSE 权限并更新 hasPermission,触发 DisposableEffect 启动 GPS 监听。
影响:用户授权后立即生效,无需退出重进。
2026-08-14 09:27:00 +00:00
mckero aa10d4170c fix(radar): SwipeDeleteRow 倒计时期间重新拖拽后归零偏移
问题:倒计时期间重新拖拽会取消 pending(正确),但 offsetX 仍是负值,行卡在滑开状态(要继续滑才能归位)。
根因:onDragStart 里只取消了 pending,没有归零 offsetX。
修复:onDragStart 取消 pending 的同时归零 offsetX。
影响:拖拽取消后行立即回到正常位置。
2026-08-14 09:24:26 +00:00
mckero aac3aee4bb fix(radar): QRZ 网格回填后刷新列表显示
问题:QRZ 爬虫异步回填网格后,列表里对应行不会立即显示网格(要等下次保存/删除操作才看到)。
根因:updateGridsquare 成功后没有触发 refreshTick++,UI 的 entries 列表不会重新计算。
修复:回填成功后调用 onSaved() 触发刷新。
影响:网格回填立即可见,改善用户体验。
2026-08-14 09:22:05 +00:00
mckero d749c5ab48 fix(domain): WavelogQueue.updateGridsquare 添加同步锁
问题:updateGridsquare 是唯一没有 @Synchronized 的修改方法,与 add() 并发(LogTab 主线程 add + 后台协程 updateGridsquare)会触发 read-modify-write 竞态,导致新 QSO 丢失。
修复:给 updateGridsquare 加 @Synchronized,与其他修改方法保持一致。
影响:消除数据丢失风险。
2026-08-14 09:19:41 +00:00
mckero 082e0c5bff fix(radar): 防止 WaveLog 重复提交 QSO
问题:键盘 onDone 连击会存两条相同的 QSO(时间戳/呼号/频率完全一致)。
修复:添加 submitting 状态变量,提交期间拒绝重复调用。
影响:误操作不再造成重复记录。
2026-08-14 09:14:47 +00:00
mckero e69d6dee4a fix(radar): 修复 offset slider 拖动时多普勒计算用旧值
问题:onValueChange 回调里 offsetHz 是派生状态的旧快照,拖动时计算的频率滞后一帧。
修复:在回调内立即从 newVal 计算 newOffsetHz,传给多普勒计算器。
影响:拖动 offset 时频率显示实时正确。
2026-08-14 09:11:45 +00:00
mckero cf93ca9f71 fix(ui): 修复菜单布局的三个严重 bug
Bug #1: moveToMain 误驱逐页面
- 根因:每次调用 moveToMain 都执行驱逐逻辑,即使页面本来就在主菜单
- 场景:拖拽主菜单内部顺序 → SettingsViewModel 遍历新顺序逐个调 moveToMain
  → 每次都判断 main.size > 5 → 误驱逐最后一个页面
- 修复:只在真正从 More 移到主菜单时才驱逐(加 wasInMore 标志位)

Bug #2: onReorder 传 resolve 输出污染状态
- 根因:SettingsScreen 拖拽回调传的是 resolve 输出(mainItems/subItems)
  而不是持久化输入(screenOrder/subMenuOrder)
- 场景:拖拽主菜单 → onReorder 传 [Radar, ..., Settings](完整列表)
  → Settings 被显式存入 screenOrder → 下次 resolve 当作用户手动放置 → 参与驱逐逻辑
- 修复:
  1. 拖拽主菜单时过滤掉 Settings(锁定页面用默认位置,不存持久化)
  2. 另一个菜单用输入的 screenOrder/subMenuOrder,不用 resolve 输出

Bug #3: onReorder More 菜单传错参数
- 根因:拖拽 More 菜单时传的是 mainItems(resolve 输出),不是 screenOrder
- 修复:改用输入的 screenOrder

影响:修复前,拖拽主菜单会丢页面,移页面到主菜单可能导致 Settings 消失
2026-08-14 00:43:23 +00:00
mckero 7cadded6ca fix(data): compute the OMM epoch day fraction numerically, not by string surgery
排查页面顺序问题时顺带审计发现: OMM/CSV 历元在子夜后约 86 秒内会被解析成
完全错误的值, 且不抛异常 —— 静默的错误数据。

## 根因

DataParser.parseCSV 用字符串拼接构造历元:

    val frac = ((hour + min + sec + ms) / 86400000.0).toString().substring(1)
    val epoch = "${year.substring(2)}$day$frac".toDouble()

substring(1) 的意图是切掉 "0.123" 的前导 0。但 Double.toString() 在数值
小于 1e-3 时切换为科学计数法, 于是被切掉的是【有效数字】, 剩下的指数后缀
让整个字符串重新变成一个合法但语义完全错误的 double。

Kotlin 侧实测(单测失败信息):

    00:00:01.000  期望 25001.000011574073  实得 0.2500115740740741
    00:01:00.000  期望 25001.000694444443  实得 2.5001944444444444

与 JDK 侧独立验证逐位一致。00:01:26.4 之后 frac >= 0.001, 不再用科学计数法,
所以这个 bug 只在每天前 86.4 秒的历元上出现(约占 0.1%), Celestrak OMM 数据
里整分历元并不罕见。

## 影响

runCatching 抓不到(没有异常), 该卫星的 juliandDateOfEpoch 会推出 year=2000
day≈0, tsince 偏差约 26 年 —— 方位/仰角/过境预报彻底失效, 不是精度下降。
且用户无从察觉。

## 修复

改为数值相加, 不经过字符串:

    val dayFraction = (hour + min + sec + ms) / 86400000.0
    val epoch = "${year.substring(2)}$day".toDouble() + dayFraction

"25001".toDouble() + 0.0000115 = 25001.0000115, 无科学计数法风险。

## 验证

DataParserTest 新增 5 个历元回归测试(子夜整点/子夜后 1 秒/子夜后 1 分钟/
正午/当日最后一毫秒)。先确认前两个在旧实现下失败(failures=2), 修复后:

- DataParserTest 24 个测试全绿(原有 19 个无回归)
- :core:domain:test 全量 105 个测试 0 失败 0 错误
2026-08-13 16:20:07 +00:00
mckero 6fc2f560b7 fix(nav): resolve the menu layout in core:domain so page order actually applies
用户报告"把 AMSAT 从更多菜单移到主菜单没生效"。排查后发现这是两个互相
掩盖的 bug, 其中一个会让用户永久无法进入设置页。

## Bug 1 (致命): 移任意页进主菜单 -> 设置入口从所有菜单消失

对"主菜单上限 5"的定义两处不一致:
- SettingsScreen.kt:892 判断 mainItems.filter { it != "Settings" }.size >= 5,
  上限是【不含 Settings 的 5 个】, 于是认为 [Satellites,Passes,Radar,Map]
  还有空位, 直接追加 -> 共 6 项
- MainScreen.kt:165 的 .take(5) 上限是【含 Settings 的前 5 个】, 而 Settings
  排在最后 -> 被截断丢弃

结果 Settings 既不在底栏也不在更多菜单(它不在 subMenuOrder 里), 用户再也
进不去设置页, 无法自行改回, 只能清数据或重装。

## Bug 2 (用户报告): AMSAT / WavelogLog 移到主菜单被静默撤销

MainScreen.kt:161-163 给老用户补新页面的迁移逻辑【无条件执行】:

    .let { list -> if ("AMSAT" in list) list else list + "AMSAT" }

用户把 AMSAT 移出子菜单后 subMenuOrder 里没有它, 这段又加回去, 第 165 行
filter { it.screenId !in subOrder } 于是永远过滤掉 AMSAT。

副作用: 这个 bug 恰好把主菜单拉回 5 项内, 反而掩盖了 Bug 1 —— 所以用户只
看到"AMSAT 移不过去", 没触发"设置锁死"。

## Bug 3: 溢出页面凭空消失而非落入更多菜单

.take(5) 直接丢弃超出的页面, 它们既不在底栏也不在更多菜单。

## Bug 4: 设置页展示顺序与底栏实际顺序不一致 (WYSIWYG 失效)

两处各自实现排序: 设置页不做 take(5)、用 sortedWith 把 Settings 钉最后;
MainScreen 做 take(5)、Settings 位置由 screenOrder 决定。

## Bug 5: 更多菜单里 AMSAT / Roaming 当前页不高亮

MoreMenuPopup.kt:69-79 的 when (currentKey) 缺 AmSat 与 Roaming 分支,
MainScreen.kt:188-198 缺 Roaming 分支, 靠 else -> false 兜底, 新增页面时
不会有编译错误提醒。Screen 子类都是 data object, 直接用 currentKey == screen
即可, 新增页面自动生效。

## Bug 6: 设置页主菜单区不过滤 hiddenScreens

MainScreen 会过滤隐藏页, 设置页不过滤, 于是隐藏的页面仍占据设置页的位置且
"移出主菜单"按钮可点, 与底栏实际情况不符。

## 改动

新增 core/domain/navigation/MenuLayout.kt (纯 Kotlin, 为 KMP 就绪) 作为菜单
布局的唯一入口:
- resolve(): 持久化偏好 -> 底栏 + 更多菜单。先给 Settings 预留名额再截断,
  溢出页面落入更多菜单而非丢弃; 两个列表都没提到的页面按默认归位(升级不丢页)
- moveToMain() / moveToMore(): 移动语义集中一处, 拒绝把 Settings 移出

MainScreen 与 SettingsScreen 改为共用它, 删除双份实现与无条件迁移逻辑。

## 死代码清理 (每项已 grep 全仓库确认零引用)

- SettingsAction.ResetScreenOrder: 无任何派发点, 仅定义与 when 分支
- UiSettingsCard 的 onReorder 参数: 函数体内两个 DragOrderList 的 onReorder
  实参都调 onUpdateMenu, 从未调用该参数
- SettingsAction.ReorderScreens: 唯一引用是上面那个死参数
- MainScreen 的 navigateToRadar 参数: 函数体内唯一出现是注释掉的一行
- Navigation.kt 的 defaultScreenOrder / defaultSubMenuOrder: 迁移后零引用,
  默认值已在 MenuLayout 内

保留 entry<RadarDestination> 分支不动 —— RadarDestination NavKey 被
PassDetailsMatcher deeplink 使用。

## 验证

- MenuLayoutTest 13 个新测试全绿, 每个对应上面一个 bug 场景
- :core:domain:test 全量 100 个测试 0 失败 0 错误
  (DataParser 19 / Doppler 17 / Qth 8 / Transponder 7 / CwCtc 7 /
   CwDeepBuffer 13 / CwGolden 3 / CwSpectrogram 8 / MenuLayout 13 /
   WaveLogApi 5)
- :core:domain:compileKotlin + :core:presentation + :app +
  :feature:settings compileDebugKotlin => BUILD SUCCESSFUL
- 用 Python 复刻新规则重跑当初失败的全部场景: 5 个页面逐一移入主菜单,
  设置入口全部保住、页面无丢失; 隐藏页 + 移动组合无页面丢失; 幂等性通过
2026-08-13 16:10:41 +00:00
mckero 8adf861ed7 chore(release): refresh 4.5.7 whats-new and bump versionCode to 461
版本名保持 4.5.7 不变(用户要求覆盖同一个发行版, APK 文件名仍为
Look4Sat-Pro-4.5.7.apk)。

versionCode 460 -> 461: 手机上已安装 versionCode 460 的 4.5.7, 若 code
不变则覆盖安装会被系统拒绝。versionCode 对用户不可见。

pass_whatsnew_message 五语(en/zh/tr/in/id)补全本次全部改动, 之前只写了
DeepCW 那批, 本轮 UI 改动与 fp32 模型未包含:
- 内置完整版 fp32 模型
- 更多菜单改靠右窄面板
- CW 页移除无效返回键与误导性状态提示
2026-08-13 14:49:36 +00:00
mckero f4f6ec7db5 feat(cw): ship the full fp32 DeepCW model instead of the int8 build
用户要求内置完整版模型, 不要量化版。

assets/deepcw/model.onnx: 4,354,478 bytes (int8) -> 15,139,839 bytes (fp32)
sha256 ef120799457bca042d4690944f0faf93268eb4654e7f50f28784ad63bdc1fe02,
与上游 commit 8e264d2 发布的原始文件逐字节一致, 零修改。

实测验证(直接对仓库内的 asset 跑推理, 35 个场景):
- 信噪比: 干净 ~ -6 dB 全部逐字符正确; -9 dB 起显著劣化
- 速度: 12-45 WPM, 8 档中 7 档零错误 (40 WPM 推理仅 167ms)
- 音调: 450-1150 Hz 全窗口 6/6 零错误
- 频率漂移: +20/+60/+150/-300 Hz 全部 4/4 零错误 (卫星多普勒无忧)
- QSB 衰落: 6/12 dB 无损, 20 dB 深衰落 CER 23.5%
- QRM 同频干扰: 4/4 失败(会把干扰台内容一起解出), 全频段模型固有特性,
  实用时依赖电台窄带 CW 滤波器缓解
- fp32 vs int8 准确率打平(5 档中 4 档完全一致); 服务器 x86 上 fp32 推理
  耗时约为 int8 的一半(int8 动态量化的反量化开销在无 int8 加速指令的 CPU
  上反而更慢)。手机 ARM 侧表现待装机确认。

NOTICE.md / DEEPCW.md / README.md 同步更新: 移除 int8 量化派生的记录与复现
步骤, 改为声明未修改照搬上游。

代价: APK 体积约 59MB -> 70MB, 运行内存峰值上升。此前真机闪退的根因是 R8
缺 -keep ai.onnxruntime.** 规则(已修), 与模型大小无关。
2026-08-13 14:48:56 +00:00
mckero 5d89190348 ui: slim the More menu and drop dead controls from the CW page
用户反馈三处 UI 问题, 一并处理。

1. 更多菜单风格不符 + 遮盖感重
   - 去掉全屏 scrim 遮罩(0.35 alpha 压暗整页), 改为透明点击层, 点外部仍可关闭
   - Card 限宽 232dp 靠右下角, 从"全宽卡片"变成竖长条
   - 容器色 surfaceContainerHigh -> surfaceContainer, 与导航栏一致; 加 1dp 细边框
   - 动画从全屏 expandVertically + spring 弹跳改为右下角原点 150ms scaleIn
   - Card 加 clickable(enabled=false) 吞掉点击, 避免点卡片空白区误触关闭

2. CW 页左上角退出键点击无效 -> 删除
   根因: CwDecodeScreen(navigateUp: () -> Unit = {}) 是默认空实现, 而
   MainScreen 的 entry<Screen.CwDecode> 调用 CwDecodeScreen() 从未传入
   navigateUp, 所以点击必然无反应。按 AGENTS.md 无死代码原则删除按钮 +
   navigateUp 参数 + cw_back 字符串(五语)。

3. CW 页"正在监听"状态行在停止解码后仍显示 -> 删除
   estimatedPitch 在暂停后保留上次值, 状态行不会消失, 属误导。删除该 Text
   后 estimatedPitch / lastInferenceMs 两个 collector 成为死代码, 一并清理;
   cw_status_listening / cw_status_tone 字符串(五语)同步删除。
   signalStrength(瀑布图) 与 errorMessage(错误提示) 仍在用, 保留。

验证:
- :app:compileDebugKotlin + :feature:cw:compileDebugKotlin => BUILD SUCCESSFUL
- :core:domain:test => 31 个 CW 测试全绿 (7+13+3+8)
2026-08-13 14:48:08 +00:00
mckero f9fd7a2cfa Move the LICENSING NOTICE to a separate NOTICE file so GitHub detects AGPL-3.0
GitHub 的 license 检测器(licensee gem)要求 LICENSE 文件是纯许可证原文,
顶部加说明块会导致检测失败(显示 NOASSERTION/Other)。

根 LICENSE 恢复为纯 AGPL-3.0 原文(从 DeepCW-AGPL-3.0.txt 复制),
说明块移到根目录 NOTICE 文件(GitHub 也识别 NOTICE 文件)。
2026-08-13 13:40:45 +00:00
mckero 21f14848da Merge origin/main (resolve CW fldigi vs DeepCW conflicts, keep DeepCW) 2026-08-13 13:39:13 +00:00
mckero d1668f1c27 docs(cw): update in-app "what's new" for the DeepCW release
发版漏的一步: App 内检测到新版本时弹出的更新内容
(pass_whatsnew_message) 还停留在上一版 AMSAT/WaveLog 的说明,没写进本次
DeepCW CW 解码器的改动。

补上五语 (en/zh/tr/in/id) 的更新说明:
- DeepCW 神经网络 CW 解码 (弱信号解码率大幅提升)
- CW 解码历史永久保留
- CW 瀑布图 inferno 配色 + 平滑渐变
- 恢复 64 位 (arm64)
- 暂停/恢复误报修复
2026-08-13 10:20:30 +00:00
mckero d6b61eaa4b license: switch the root LICENSE to AGPL-3.0 for the combined work
用户指出 GitHub 上显示的许可证仍是 GPL-3.0,未反映合并 AGPL 组件的事实。

根因: 之前只在 README 加了 License 章节,根 LICENSE 文件仍是 GPL-3.0 原文,
GitHub 的自动检测(只扫 LICENSE 文件)自然还是 GPL-3.0。

修复: 合并作品按 GPL-3.0 §13 / AGPL-3.0 §13 处理,根 LICENSE 改为:
- 顶部 LICENSING NOTICE 说明构成 (Look4Sat 代码 GPL-3.0 + DeepCW 模型
  AGPL-3.0-only, 合并作品按 AGPL-3.0 分发)
- 正文为 AGPL-3.0 原文 (从 DeepCW-AGPL-3.0.txt 复制)

原 GPL-3.0 原文保留在 feature/cw/licenses/Look4Sat-GPL-3.0.txt。
README License 章节同步更新,与新 LICENSE 一致。

此后 GitHub 侧边栏将识别为 AGPL-3.0。
2026-08-13 10:19:57 +00:00
mckero 26c714fc24 fix(cw): stop swallowing coroutine cancellation on pause/resume
用户反馈: 暂停再恢复时经常弹出 "CW decode failed: The coroutine scope
left the composition"。

根因: 暂停 (isListening=false) 使 LaunchedEffect 重启、旧的采集协程被
取消。若此刻 decodeWindow 正在 withContext(Dispatchers.Default) 里做 ONNX
推理, 取消传播时会抛出 LeftCompositionCancellationException
(message 即 "The coroutine scope left the composition", 是 CancellationException
的子类)。processBuffer 的 catch (Throwable) 把它当成解码失败吞掉, 既误报了
错误横幅, 又破坏了协程取消的正常传播。

修复:
- processBuffer 的 decodeWindow catch 里, CancellationException 直接
  rethrow (暂停导致的中断是正常流程, 不是错误)。
- archiveDecode 调用同样包 try-catch, CancellationException rethrow,
  其余异常只记日志不崩溃。

这是协程的标准纪律: 永远不要把 CancellationException 当业务异常吞掉。

版本: 4.5.5 -> 4.5.7 (versionCode 460)。此前多次删 v4.5.5 tag 重打导致
release 页面累积 12 个 draft 草稿, 已全部清除。
2026-08-13 09:55:15 +00:00
mckero 2e1d8b9c00 feat(cw): archive decoded history, polish the waterfall, document licensing
三个用户反馈一并解决:

1. 解码文字不再消失 (核心)
   旧实现: 20 秒环形缓冲满了就静默覆盖最旧样本, 文字随之从屏幕消失。
   新实现: CwDeepBuffer 新增 overflow —— 满时被覆盖的旧样本先进 overflow,
   解码器累积到 15 秒就单独解码一次, 结果追加到 historyText (只增不减)。
   UI 记录区显示 historyText + decodedText (历史稳定 + 当前窗口实时)。
   ICwDecoder 接口新增 historyText StateFlow。

   归档音频已离开主窗口, 不再被 CTC 修正, 故其文本是"最终版", 追加安全。
   归档窗口 15 秒: 内容已在 20 秒窗口里解过多次, 短一点几乎无损, 且推理
   开销小。

2. 瀑布图更好看
   配色从"深蓝->青->黄"换成 matplotlib inferno (黑->紫->品红->橙->黄),
   与静态频谱图保持一致。相邻 bin 之间用水平渐变做线性插值, 消除 65 列
   离散方块的像素感。

3. AGPL 合规补漏 (用户提醒: 仓库许可证没体现 AGPL 组件)
   README 新增 License 章节: 声明项目主体 GPL-3.0 + feature/cw 的 DeepCW
   模型 AGPL-3.0-only, 并说明合并作品按 GPL-3.0 §13 / AGPL-3.0 §13 处理。

验证:
- :core:domain:test => 31 个 CW 测试全绿 (CwDeepBufferTest 新增 3 个
  overflow 归档测试: 顺序/清空/reset)
- :core:domain:compileKotlin + :core:data + :feature:cw:compileDebugKotlin
  => BUILD SUCCESSFUL
2026-08-13 08:04:05 +00:00
Arty Bishop 7cdc2952dc v4.4.6 - AMSAT status page, fully customizable data sources 2026-08-13 09:47:26 +02:00
mckero f42d1f6c57 docs(cw): add DEEPCW.md recording DeepCW architecture, pitfalls, verification
记录 feature:cw 模块的完整集成知识, 供后续维护者免于重走弯路:
- 架构分层 (core:domain 纯 Kotlin 前后处理 / core:data ONNX 推理 / feature:cw UI)
- 模型规格与 int8/fp32 双版本取舍 (APK 内置 int8, fp32 作为 release 资产)
- 真机 release-only 的五个坑 (R8 keep / 惰性加载 / 线程 / 跨线程状态 / 双录音)
- 验证结果 (golden vector 79 测试 / 服务器端到端逐字符一致 / 真机 40WPM)

该文档与 skill 的 §7.55 根因坑互为参照: skill 记方法论, 这里记本模块实况。
2026-08-13 04:14:01 +00:00
mckero 3e25e1aa2f fix(cw): keep ai.onnxruntime.** through R8 to stop native crash
根因定位(确定性): release 构建开启 R8 混淆 (convention 插件的
PluginSetupUtils 设 isMinifyEnabled=true), 但 onnxruntime-android 的 AAR
不含 proguard consumer rules (仅 aar-metadata.properties)。于是 R8 把
ai.onnxruntime.* 的类重命名/裁剪, 而 ONNX Runtime 的 Java 绑定走 JNI、
native 侧按原始类名/方法名解析 —— 类名对不上即 native 崩溃, 不产生
任何 Java 堆栈, 正好解释"闪退回桌面、无任何日志"。

此前的所有内存/线程修复都无效, 因为崩溃点根本不在 Java 层。

修复:
1. app/proguard-rules.pro 新增 (ONNX Runtime 官方文档要求):
   -keep class ai.onnxruntime.** { *; }
   -dontwarn ai.onnxruntime.**
2. app/build.gradle.kts 的 release buildType 引用该规则文件。
3. onnxruntime 1.28.0 -> 1.25.1: 1.28.0 为 2026-07-25 发布(仅三周),
   1.25.1 更成熟; 同时排除 SIGILL 类骁龙 bug (该 bug 在 1.24.4 修复,
   Android AAR 对应 1.25.0+)。

验证: 服务器完整管线 (真实20s音频->频谱->ONNX->CTC) 解码逐字符正确,
与手机端同一份代码逻辑。R8 keep 规则为官方文档明确要求项。
2026-08-13 03:46:14 +00:00
mckero e0405b541f fix(cw): prevent double AudioRecord when toggling capture
CwDecodeScreen 的 LaunchedEffect 原先用内层 launch{} 启动音频采集。
isListening 在权限授予后由 false->true->(授予回调再次置 true), 加上
LaunchedEffect(isListening, permissionGranted) 的双 key 重启, 会造成
前一个 audioFlow().collect 尚未取消、新的又启动 —— 两个 AudioRecord
同时录音, 内存翻倍、音频混叠, 是低内存机 OOM 崩溃的实锤级嫌疑。

改为在 LaunchedEffect 协程体内直接 collect (取消时随父协程及时停止),
并保持 (isListening, permissionGranted) 双 key 以正确处理权限授予后
需要重启采集的情形。

同时清理不再使用的 kotlinx.coroutines.launch import。

验证: :feature:cw:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-13 03:16:36 +00:00
mckero c374058e1d perf(cw): ship int8-quantized DeepCW model (15MB -> 4MB)
用户真机闪退回桌面且无任何 Java 日志 => 高度怀疑进程被系统 LMK 杀掉
(内存不足) 或 native 层崩溃。模型加载 + ONNX 引擎初始化存在瞬时内存峰值,
fp32 模型 15MB 会放大这个峰值。

用 onnxruntime.quantization.quantize_dynamic 把模型权重动态量化为 QUInt8
(激活保持 float32):

- 体积: 15,139,839 -> 4,248,808 字节 (缩小 71%)
- 输入/输出名、形状、dtype 完全不变 -> Kotlin 代码无需改动
- 实测 CER (合成 CW 音频, fp32 vs int8 逐字符对比):
  SNR>=0dB 完全一致; -4dB 起两者一同劣化, 无显著差异
- onnx.checker 校验通过

AGPL 合规: NOTICE.md 记录派生信息 (原文件 SHA/量化后 SHA/转换步骤),
量化属模型修改, 按 AGPL 要求如实声明。复现命令已更新。

验证: :core:domain:test => 79 tests 全绿 (golden vector 测试锁定的是
频谱图前处理, 与模型文件无关)
2026-08-13 01:02:04 +00:00
mckero ac5cbbc49a fix(cw): add crash probes to localize adb-less flash-crash
闪回桌面且无任何 Java 日志 => 崩溃发生在 native 层 (ONNX 库内部段错误)
或进程被系统 LMK 直接杀掉 (内存不足) —— 两种情况 Java 的
uncaughtExceptionHandler 都不会触发, crash_log.txt 自然为空。

新增 CwProbe: 在关键节点向 files/probe_cw.txt 追加时间戳行:
  decoder_constructed -> load_begin -> load_session_ok / load_failed:<类名>
  -> infer_begin -> infer_done
进程若中途死亡, 最后一行的节点就是崩溃/被杀位置, 无需 adb 即可定位。

验证: :core:data:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-13 00:46:56 +00:00
Arty Bishop bd51044690 Added custom frequency offset setting to network reporting 2026-08-12 20:17:26 +02:00
mckero cf49dcfa01 fix(cw): persist decoder failures to files for adb-less diagnostics
在服务器上完整复现了手机端流程 (真实 20s 含噪音频 -> 重采样 -> 频谱 ->
ONNX -> 贪心 CTC), 解码逐字符正确:
  decoded: [CQ CQ DE BG7NTA BG7NTA K 5NN TU 73]   (与参考完全一致)
整条链路逻辑无问题, 闪退属环境/平台层。

应用内已有全局崩溃捕获器 (MainApplication.installCrashHandler) 会把堆栈
写入 files/crash_log.txt —— 无需 adb 即可取到崩溃原因。

本提交为加载与推理两处异常补充落盘:
- 模型加载失败 -> files/deepcw_load_error.txt
- 推理异常 -> files/deepcw_infer_error.txt

用户可在文件管理器按
Android/data/com.rtbishop.look4sat.bg7nta/files/ 路径取回这些日志。

验证: :core:data:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-12 16:43:52 +00:00
PingouinFerreux 1982c2d3dc Fixed broken star history chart in README (#240) 2026-08-12 18:22:53 +02:00
mckero 5f297f9233 fix(cw): stop the waterfall crashing and cut APK size by 87MB
三个真机实测暴露的问题:

1. 闪退 (给权限后 3-4 秒必崩, 且注入日志抓不到堆栈)
   CwWaterfallState 用 mutableIntStateOf 记录重绘版本号, 却从音频采集线程
   写入。Compose 快照状态只能在合成线程修改, 从后台线程写会在运行时崩溃 ——
   崩在 Compose 内部, 所以业务类的日志注入抓不到。
   改用 MutableStateFlow (本身线程安全), Canvas 侧 collectAsState 读取。

2. 同一状态的跨线程数据竞争
   pushSamples 在采集线程写 rows/pending, snapshot() 在绘制线程读, 而
   ArrayDeque 非线程安全 —— 并发 removeFirst()/toList() 会抛
   ConcurrentModificationException 或 IndexOutOfBoundsException。
   两侧统一加锁; FFT 计算放在锁外, 只有队列追加持锁。

3. APK 从 8.4MB 暴涨到 135MB
   onnxruntime-android 的 AAR 自带 4 个架构原生库: arm64 28M + armv7 20M +
   x86 33M + x86_64 34M = 115MB。上次提交移除 abiFilters 时把 x86 系列也
   打包了进去 (仅模拟器需要)。
   重新加上 abiFilters, 保留 arm64-v8a + armeabi-v7a 两个真机 ABI,
   预计降至约 43MB。注意这与上次"恢复 64 位"不冲突: 那次删的是只留
   armeabi-v7a 的限制, 这次是排除 x86 系列。

另外两处加固:
- CwDeepDecoder 的模型加载从 init{} 移入惰性 ensureLoaded(): 加载会触发
  ONNX Runtime 原生库装载, 失败时抛 UnsatisfiedLinkError; 在构造函数中抛出
  会连带崩掉创建它的 composable, try-catch 也救不回来。移到首次使用时执行,
  失败经 errorMessage 上报给 UI。
- ONNX 会话限制 intraOp 线程数为 (核数-1) 且上限 4, 给音频采集和 UI 留出
  余量, 默认行为会铺满所有核心。

验证:
./gradlew :feature:cw:compileDebugKotlin :core:data:compileDebugKotlin => 通过
./gradlew :core:domain:test => 79 个测试全绿
2026-08-12 13:55:03 +00:00
mckero 37300fb2a6 revert: remove build-check workflow, use release.yml for testing 2026-08-12 13:18:08 +00:00
mckero fc8096bdd5 ci: add build-check workflow asserting DeepCW packaging facts
本机 2GB 内存带不动 assembleRelease, 构建移交 GitHub Actions。
现有 release.yml 只在打 tag 时触发, 补一个可手动触发 + CW 分支推送即跑的
工作流, 便于装机实测而无需发布 tag。

断言的打包事实 (任一不满足即失败):
- lib/arm64-v8a/ 存在 —— 验证 abiFilters 解除生效, 应用恢复 64 位
- libnativedecoderjni 不存在 —— 验证被删的逆向 JNI 库未残留
- assets/deepcw/model.onnx 打包尺寸恰为 15139839 字节 —— 验证 noCompress
  生效, 未被压缩 (压缩会导致 ONNX Runtime mmap 失败)
- values-in / values-id 存在 —— 验证印尼语未被资源压缩丢弃

同时跑 :core:domain:test 与 assembleRelease (R8 检查), 产物上传为 artifact,
配置了签名 secrets 时对 release APK 签名。
2026-08-12 13:12:15 +00:00
mckero d93e3b4028 feat(settings): credit DeepCW (AGPL-3.0) in the about section
AGPL-3.0 要求署名。在设置页"关于"卡片的许可说明下方显示 DeepCW 模型的
作者 (e04)、许可证 (AGPL-3.0-only) 与上游仓库链接。

字符串标 translatable="false": 署名与许可证名称不应翻译。
完整声明见 feature/cw/licenses/NOTICE.md。

验证: ./gradlew :feature:settings:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-12 13:03:59 +00:00
mckero 9b0d543f12 refactor(cw)!: replace legacy CW engine with DeepCW in both entry points
DeepCW 成为唯一 CW 解码内核, 不保留旧引擎作兜底 (用户决定: 完全移植)。

删除旧内核 (1298 行):
- CwDecoder.kt / CwBayesianDecoder.kt / CwChannelTracker.kt / CwSpectrogram.kt
- CwDsp / CwFFT / CwSTFFT / CwGoertzel / CwFilter / CwResampler.kt
- CwDecoderTest.kt
旧内核的自动定频与 squelch 门控由 DeepCW 的 400-1200Hz 固定频窗替代 ——
模型自带定频, 不再需要频谱峰值跟踪和噪声门。

两个 CW 入口都改接 DeepCW:
1. feature:cw 独立整页 CwDecodeScreen.kt 重写为纯 Compose (瀑布图 -> 实时行
   -> 历史区), 移除 AndroidView/LayoutInflater 和被删的 activity_main 布局;
   删除 CwSettingsDialog.kt (旧引擎的手动音调/带宽面板, DeepCW 全自动无需)
2. feature:radar 内嵌可折叠面板改走 ViewModel 的 CW state/action, 移除
   Morse Expert 控制器与 cw_panel_main 布局
   (该面板此前注释写明 "no longer feeds it", ViewModel 里的 CW 通路是死代码)

新增 CwWaterfall.kt: 复用 CwDeepSpectrogram 绘制瀑布图, 显示的正是模型
分析的 400-1200Hz 频段与同一批幅值。

接口接线:
- IMainContainer.provideCwDecoder() 提供 ICwDecoder (实现需 Context 读 assets)
- RadarViewModel 构造新增 cwDecoderFactory, onCleared() 中 close() 释放
  OrtSession 避免原生内存泄漏
- 删除已无调用方的 RadarAction.CwSetToneFreq (DeepCW 定频固定, 无参数可调);
  CwSubState.cwToneFreq 语义改为只读显示检测到的音调

依赖清理:
- feature:radar 不再依赖 feature:cw 与 constraintlayout
- feature:cw 不再依赖 constraintlayout

字符串: feature:cw 清理 Morse Expert 遗留串 (premium/rate/help/
tap_back_again_to_close/purple_500), 按 en/zh/tr/in/id 五语补全新串;
core:presentation 补 radar_cw_tone / radar_cw_waiting 五语。

验证:
./gradlew :core:domain:test => 4 个测试类全绿
./gradlew :feature:cw:compileDebugKotlin => BUILD SUCCESSFUL
./gradlew :feature:radar:compileDebugKotlin => BUILD SUCCESSFUL
./gradlew :core:data:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-12 13:00:25 +00:00
mckero 57762613a8 feat(cw): add CwDeepDecoder wiring ONNX Runtime to the CW pipeline
组装完整解码链路: 麦克风 PCM -> 重采样 3200Hz -> 20 秒滚动缓冲 ->
频谱图 -> ONNX 推理 -> 贪心 CTC -> 文本。

ICwDecoder 放 core:domain (纯 Kotlin, UI 可直接依赖), 实现放 core:data
(需要 Android Context 读 assets 及 ONNX Runtime 原生库)。

关键设计:
- decodedText 是替换语义不是追加: 模型会随上下文增加改写先前字符, 追加
  会把中间态 (BM -> BG7 -> BG7NTA) 永久留在屏幕上
- 推理用 Mutex.tryLock 串行化: 上一次未完成时直接跳过本周期, 慢设备不会
  堆积任务导致 OOM
- 推理在 Dispatchers.Default, 不阻塞音频采集线程
- 模型元数据从 model.onnx.json 读取 (字符表/blank 索引/输入输出名), 不在
  代码里硬编码, 模型更新时无需改代码
- lastInferenceMs 打点: 手机实际推理耗时需真机实测 (估算系数待验证)
- estimatedPitch 由频谱峰值 bin 反算, 仅供 UI 显示 —— 模型 400-1200Hz
  固定窗自带定频, 不需要频谱峰值跟踪参与解码
- 模型加载失败时 errorMessage 置位 (旧内核已删, 无兜底可退)
- close() 释放 OrtSession, 否则原生内存泄漏

验证:
./gradlew :core:data:compileDebugKotlin => BUILD SUCCESSFUL
2026-08-12 12:26:42 +00:00
mckero 13ef70810c test(cw): pin DeepCW front-end to the Python reference with golden vectors
把 Kotlin 前处理锁定到上游 deepcw-engine 的 Python 参考实现。

golden_spec.txt 由参考实现自身的预处理代码生成 (numpy reflect padding,
np.hanning(N+1)[:-1], np.fft.rfft, log1p), 覆盖一段确定性测试音频:
700Hz 方波键控的字母 C, 20WPM, 源采样率 8000Hz。两侧用同一个确定性公式
各自合成音频, 因此只需锁定频谱图结果, 无需落盘音频。

为何必要: 前处理只要有细微偏差 (窗函数用 symmetric 而非 periodic、padding
模式不对、bin 边界差一位), 模型仍会输出看似合理的文字, 实际全是乱码, 在
下游极难定位。此测试守住整条链路的入口。

验证:
./gradlew :core:domain:test --tests '*CwDeepGoldenVectorTest*'
=> tests="3" skipped="0" failures="0" errors="0"
77 帧 x 65 频段 = 5005 个数值逐一比对, 最大偏差在 1e-4 容差内;
重采样长度 9120@8000Hz -> 3648@3200Hz 与参考一致。
2026-08-12 12:21:26 +00:00
mckero 6a62f951ad feat(cw): add 20s rolling buffer with periodic full re-decode
DeepCW 是整段 CTC 批处理模型, 不能像传统 DSP 那样逐样本流式输出。

实测否决了滑动窗口+增量拼接方案。整段批处理 CER 0.0%, 而所有窗口/步进
组合最好仅 67.6%, 最差 294.1% (呼号被重复三遍)。根因是模型每获得更多
上下文就重写已输出内容 —— 同一音频逐渐加长时 11 次采样有 6 次修正前缀
(BM -> BG7 -> BG7NTI -> BG7NTA), 任何"只追加增量"策略都会把这些中间态
永久留在屏幕上。

改为: 固定 20 秒滚动缓冲 + 每 1.5 秒重解全量 + 整体替换显示。

参数由实测定案, 是两条约束的交点:
- 准确率侧: 20s 是达到 0.0% CER 的最小窗口 (16s 仍有 5.9%)
- 算力侧: 耗时超线性增长, 60s 音频推理耗时约为 20s 的 13 倍, 实时余量
  不足; 20s 时余量约 13 倍, 安全

实现: 环形缓冲, snapshot() 返回按时序展开的副本 (调用方无法污染内部
存储), append() 返回是否该触发重解。

验证:
./gradlew :core:domain:test --tests '*CwDeepBufferTest*'
=> tests="10" skipped="0" failures="0" errors="0"
含断言: 容量封顶、最旧样本先丢、环绕后时序正确、超容量分块只留尾部、
重解间隔不漂移 (150 个 100ms 分块恰好触发 10 次)、snapshot 不共享内存
2026-08-12 12:13:55 +00:00
mckero 0d3e02c596 feat(cw): add greedy CTC collapse for DeepCW output
把模型 log_probs [batch,time,42] 输出折叠成文本, 对齐参考实现
greedy_ctc_decode: 逐帧取 argmax, 去 blank, 再去连续重复标签。

blank 的作用: 两个相同字母之间的 blank 是保住真实双字母的关键
(例如 "5NN" 的两个 N), 否则会被折叠成一个。

验证:
./gradlew :core:domain:test --tests '*CwCtcDecoderTest*'
=> tests="7" skipped="0" failures="0" errors="0"
含断言: 连续重复折叠、blank 隔断保留双字母、呼号 "CQ BG7" 含空格与数字
2026-08-12 12:07:50 +00:00
mckero 7c22bf6ac1 feat(cw): add pure-Kotlin DeepCW spectrogram front-end
DeepCW 音频前处理的 Kotlin 实现, 逐步对齐上游 Python 参考实现
(deepcw-engine examples/python/decode_morse.py):

  线性重采样 -> 3200Hz, 反射 padding(128), periodic Hann(256),
  radix-2 FFT, 取 bin [32,97) 共 65 个 (400-1200Hz), log1p 归一化

实现要点:
- Hann 窗用 periodic 变体 (numpy np.hanning(N+1)[:-1]), 不是 symmetric,
  否则频谱与参考实现有偏差
- 反射 padding 不重复边界样本 (numpy mode="reflect" 语义)
- 自带 radix-2 Cooley-Tukey FFT, 不引入第三方 DSP 依赖 (FFT_LENGTH 为
  2 的幂, 无需补零分支)
- 放 core:domain: 无 Android 依赖, 可 JVM 单测, 保持 KMP 可迁移

模型 400-1200Hz 固定频窗意味着定频内建, 无需频谱峰值跟踪与 squelch 门控 ——
这正是旧内核最大的两个坑。

验证:
./gradlew :core:domain:test --tests '*CwDeepSpectrogramTest*'
=> tests="8" skipped="0" failures="0" errors="0"
含断言: 700Hz 正弦峰值落在相对 bin 24; 8000->3200Hz 重采样后频率不变
2026-08-12 12:05:13 +00:00
mckero b8113fc757 build(cw): add onnxruntime-android 1.28.0 to core:data
DeepCW 模型推理需要 ONNX Runtime。该依赖属 Android 平台依赖 (AAR 内含
各 ABI 原生库), 因此放 core:data 而非 core:domain —— 后者按 AGENTS.md
须保持纯 Kotlin/JVM 以留 KMP 迁移余地。

版本固定为 1.28.0 不使用范围区间: release 构建走 R8, 避免依赖意外升级
引入行为变化。

验证:
./gradlew :core:data:dependencies --configuration releaseRuntimeClasspath
=> \--- com.microsoft.onnxruntime:onnxruntime-android:1.28.0
=> BUILD SUCCESSFUL in 3m 48s
2026-08-12 11:52:47 +00:00
mckero 86ab1b26b7 feat(cw): vendor DeepCW ONNX model with full AGPL-3.0 compliance
背景:
DeepCW (e04/deepcw-engine) 是基于 CTC 的神经网络 CW 解码模型。本地实测
弱信号解码率显著优于传统 DSP 方案: SNR<0dB 时 CER 16.0% vs ggmorse 52.6%;
SNR>=0dB 时两者均接近 0%。模型 400-1200Hz 固定频窗自带定频, 无需频谱峰值
跟踪与噪声门。

改动:
- assets/deepcw/model.onnx      15,139,839 字节, 原样收录未作修改
- assets/deepcw/model.onnx.json 模型元数据 (采样率 3200, FFT 256, hop 48,
  65 个频段, log1p 归一化, 42 类含 CTC blank)
- licenses/DeepCW-AGPL-3.0.txt  AGPL-3.0 许可证全文
- licenses/NOTICE.md            来源仓库/作者/取用 commit/SHA-256/
  许可证兼容性说明/复现步骤
- app/build.gradle.kts: androidResources.noCompress += "onnx"

关于 noCompress:
ONNX Runtime 通过 mmap 直接读取 assets, 压缩后无法内存映射, createSession
会失败。该配置只在打包 APK 的 app 模块生效, 在 feature 库模块声明无效。

许可证:
Look4Sat 为 GPL-3.0-or-later, DeepCW 模型为 AGPL-3.0-only。GPL v3 第 13 条
明确允许两者合并分发。推理完全在本地设备进行, 不通过网络向远程用户提供
模型功能, 故 AGPL 第 13 条的网络源码提供义务不被触发。本仓库公开, 完整
对应源码提供义务已满足。

上游取用 commit: 8e264d243bbd4467bd19f3f28292219405b47e0e
模型 SHA-256: ef120799457bca042d4690944f0faf93268eb4654e7f50f28784ad63bdc1fe02
2026-08-12 11:47:02 +00:00
mckero de6c964136 build!: drop armeabi-v7a abiFilters, restore 64-bit builds
背景:
abiFilters=armeabi-v7a 的唯一成因是 Morse Expert 的 32 位
libnativedecoderjni.so, 该 .so 已在上一提交删除。此前整个应用被迫以
32 位运行: 64 位设备走兼容层、寻址受限, 且不满足应用市场的 64 位要求。
原注释称"用户设备为 32 位软件"已与实际不符 (测试机为 64 位)。

改动:
- app/build.gradle.kts: 移除 defaultConfig.ndk.abiFilters 及相关注释
- feature/cw/build.gradle.kts: 移除 abiFilters; 移除 constraintlayout 依赖
  (仅被已删除的 activity_main.xml 使用); 移除 UTF-8 JavaCompile 配置
  (模块已无 Java 源码)
- feature/cw 改为依赖 core:domain + core:data (DeepCW 前后处理落在 core)

验证:
grep -rn 'abiFilters|jniLibs' --include=*.kts . (排除 build/) => 无匹配
APK ABI 覆盖将在 CI 产物中验证 (预期含 arm64-v8a)
2026-08-12 11:44:54 +00:00
mckero e477851adf refactor(cw)!: remove reverse-engineered Morse Expert engine and 32-bit JNI blob
背景:
feature/cw 内含 Morse Expert 1.15 (VE3NEA, 闭源免费软件) 的 jadx 反编译产物,
外加仅 armeabi-v7a 的 libnativedecoderjni.so (1.4MB)。该 .so 无 64 位版本,
迫使 app 模块设置 abiFilters=armeabi-v7a, 把整个应用锁死在 32 位。
闭源软件的反编译产物不具备任何分发授权。

改动 (共 58 项):
- 删除 pas/* (JNI 入口 nativedecoder/decoder/cwstru/system)
- 删除 com/ve3nea/morse_expert/* (MainActivity/DecodedTextView/ScaleView/
  WaterfallSurfaceView)
- 删除混淆包 B B0 D E2 F2 H2 I0 I2 J2 K1 d1 g3 i3 j1 j3 k3 s
- 删除 suncompat/* (sun.misc.Unsafe/Cleaner 存根)
- 删除 jniLibs/armeabi-v7a/libnativedecoderjni.so
- 删除配套 layout (activity_main, cw_panel_main)、menu、4 个 ic_baseline_* 图标
- proguard-rules.pro 清空 keep 规则 (已无 JNI 按类名注册依赖)

验证:
find feature/cw/src -name '*.java' | wc -l   => 0
find feature/cw/src -name '*.so'   | wc -l   => 0
git ls-files feature/cw 仅剩 build.gradle.kts, proguard-rules.pro,
CwDecodeScreen.kt, CwSettingsDialog.kt 及 5 份 app_values.xml

注意: 本提交后 CwDecodeScreen.kt 暂时无法编译 (它 inflate 了已删除的
R.layout.activity_main), 将在 DeepCW 内核接入后重写为纯 Compose。

后续: DeepCW ONNX 内核接入 (纯 Kotlin 前后处理), abiFilters 解除恢复 arm64。
2026-08-12 11:42:53 +00:00
mckero d2d4a6fe86 chore(git): ignore .keystore files and the Hermes workspace
*.jks 已被忽略, 补上 *.keystore 覆盖另一种签名库扩展名。
.hermes/ 是 agent 的本地计划目录, 不属于项目产物。

背景: BG7NTA.jks 位于仓库根目录, 此前仅依赖 *.jks 规则; 补充规则以防
其他扩展名的签名材料被误提交进公开仓库。
2026-08-12 11:40:54 +00:00
Arty Bishop 2f4e3f5802 Added the ability to fully customize data sources via import 2026-08-12 13:01:45 +02:00
Arty Bishop 24eebdef74 Consolidated app dialogs and tweaked bottom sheets 2026-08-11 14:14:14 +02:00
Arty Bishop 3f5b48f270 Integrated the AMSAT status page created by MCKero6423 2026-08-11 14:05:55 +02:00
atsunatsuandatsunatsu 060fa2dfcd Added remembering per-satellite doppler offset (#237)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
2026-08-11 14:02:15 +02:00
atsunatsuandatsunatsu 8b5960282f Broaden linear transponder detection, logic fixes (#236)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
2026-08-08 21:31:44 +02:00
mckero 10eb84690e Added AMSAT satellite status tracking page (#234) 2026-08-08 14:26:36 +02:00
bf25292bf8 Fixed recalculating Radar track on station position change (#235)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
Co-authored-by: wty2019wty <74123961+wty2019wty@users.noreply.github.com>
2026-08-08 14:10:55 +02:00
mckero 284183836e refactor(amsat): replace hand-rolled date parsing with SimpleDateFormat
Addresses @AlanCui4080's review feedback about the manual date calculation.
Uses SimpleDateFormat to eliminate the hand-written calendar math (regex +
days-from-epoch calculation). Avoids java.time since it requires desugaring
on minSdk 24, keeping dependencies minimal.

Before: 23 lines of manual day-from-epoch calculation
After: 7 lines using SimpleDateFormat

Ref: https://github.com/rt-bishop/Look4Sat/pull/233#discussion_r1868599947
2026-08-05 17:02:01 +00:00
mckero de85aa1e8b refactor(amsat): align with Material3 conventions per PR #233 review
Addresses feedback from rt-bishop/Look4Sat#233:

1. Migrate hardcoded colors to MainTheme colorScheme
   - Extend darkScheme: tertiary (Active 0xFF648FFF), tertiaryContainer (Telemetry 0xFFFFB000)
   - Extend lightScheme: tertiary (0xFF3C6FE0), tertiaryContainer (0xFFE09800) for contrast
   - Remove top-level Color() constants from SatStatusScreen.kt
   - Add statusColorOf() mapper using MaterialTheme.colorScheme

2. Move HTTP implementation from domain to data layer (Clean Architecture)
   - Delete AmSatApiClient.kt from core:domain (violates AGENTS.md: "Pure Kotlin, NO Android deps")
   - Migrate to IRemoteSource/RemoteSource in core:data (uses existing OkHttp3)
   - AmSatRepository now depends on IRemoteSource instead of AmSatApiClient

3. Inline JSON parsing (prepare for java.time migration)
   - Parse AMSAT API responses (names, reports) in AmSatRepository
   - Time parsing still uses manual logic (java.time desugaring in follow-up)

Before:
  - Hardcoded Color(0xFFXXXXXX) in UI + Repository (no theme support)
  - HttpURLConnection in domain layer (architecture violation)
  - AMSAT colors duplicated across modules

After:
  - MaterialTheme.colorScheme.tertiary/tertiaryContainer (light/dark adaptive)
  - HTTP via data layer RemoteSource (follows AGENTS.md architecture)
  - Single source of truth for AMSAT colors

Ref: https://github.com/rt-bishop/Look4Sat/pull/233#discussion_r1868599947
Ref: AGENTS.md "core:domain - Pure Kotlin (JVM). NO Android dependencies."
2026-08-05 15:26:42 +00:00
Arty Bishop 8fbfcb3712 v4.4.5 - Pass progress hotfix, swapped modes/filter dialogs 2026-08-05 13:14:50 +02:00
Arty Bishop 602b1553a2 v4.4.4 - Icom CAT, components, filters and sources tweaks 2026-08-04 20:51:22 +02:00
atsunatsuandatsunatsu bd0881fb4b Added linear transponder Doppler calculator (#232)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
2026-08-04 18:45:12 +02:00
atsunatsuandatsunatsu a9dd3e6e55 Localized pass date and time formats for Chinese (#231)
Co-authored-by: atsunatsu <atsunatsu@users.noreply.github.com>
2026-08-04 18:12:10 +02:00
Lukas 905995ab44 Added configurable Radar offset to the sensors output (#230) 2026-08-04 18:08:44 +02:00
Arty Bishop f9806d7f7f Replaced the types selection dialog with modes selection 2026-07-31 16:04:39 +02:00
Arty Bishop 2d3adfc6a6 Added small tweaks to Sources, Components and strings 2026-07-31 12:27:25 +02:00
252 changed files with 18434 additions and 6533 deletions

No files matched your search

+4
View File
@@ -4,3 +4,7 @@ updates:
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "bundler"
directory: "/"
schedule:
interval: "never"
+58
View File
@@ -0,0 +1,58 @@
# 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/
+7
View File
@@ -40,10 +40,14 @@ captures/
# Keystore files
*.jks
*.keystore
/*.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
@@ -66,3 +70,6 @@ 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/
+75 -52
View File
@@ -8,16 +8,15 @@ All assistant-specific files (`CLAUDE.md`, `.github/copilot-instructions.md`) po
## Project Overview
Look4Sat is an open-source, fully offline Android satellite tracker and pass predictor. It tracks 9000+ active
satellites using TLE/OMM data from Celestrak/SatNOGS, calculates orbital positions via SGP4/SDP4 models, and displays
passes relative to the user's location. Features include polar radar visualization, SSTV image decoding, satellite
ground track mapping, and pass predictions up to 10 days ahead. No ads, no tracking, no network required after initial
data download.
satellites using Celestrak/SatNOGS orbital data, calculates positions via SGP4/SDP4, and predicts passes relative to
the user's location. Features include polar radar visualization, SSTV image decoding, and ground track mapping. No ads,
no tracking, no network required after initial data download.
## Architecture
## Architecture & Design
**MVI (Model-View-Intent)** with unidirectional data flow:
- `State` data class → exposed via `StateFlow` from ViewModel
- `Action` sealed interface → user intents dispatched to ViewModel's `onAction()`
- `State` data class (named `<Feature>State`) exposed via `StateFlow` from ViewModel
- `Action` sealed interface (named `<Feature>Action`) dispatched to ViewModel's `onAction()`
- Jetpack Compose UI observes state and recomposes reactively
**Clean Architecture layers:**
@@ -26,7 +25,7 @@ data download.
|----------------------|---------------------------------------------------------------------|
| `app` | Entry point. Aggregates all modules |
| `core:data` | Android library. Room DB, OkHttp networking, repo implementations |
| `core:domain` | Pure Kotlin (JVM). Orbital math (SGP4/SDP4), models, repo contracts |
| `core:domain` | Multiplatform: JVM + iOS. Orbital math (SGP4/SDP4), models, 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 |
@@ -34,9 +33,11 @@ data download.
| `feature:satellites` | Satellite list, filtering, selection |
| `feature:settings` | User preferences |
- `feature:*` modules depend only on `core:domain` + `core:presentation`. Features never depend on each other.
**Feature isolation:**
- `feature:*` modules depend only on `core:domain` and `core:presentation`.
- No feature-to-feature dependencies; cross-feature communication goes through core layers.
## Build & Run
## Build & Platform
```shell
# Debug build
@@ -49,68 +50,90 @@ data download.
./gradlew test
```
- **Min SDK**: 24 | **Target SDK**: 36 | **JDK**: 17
- **Gradle**: Uses version catalog (`gradle/libs.versions.toml`) + convention plugins in `build-logic/`
- **Min SDK**: 24 | **Target SDK**: 36 | **JDK**: 21 (`jdkVersion` in the version catalog)
- **Gradle**: Version catalog in `gradle/libs.versions.toml` + convention plugins in `build-logic/`
## Key Libraries
## Tech Stack
- **Compose** (BOM 2026.05.01) + Material3 Adaptive
- **Navigation3** (type-safe, uses `@Serializable` NavKeys)
- **Room** (KSP code generation) for local satellite/TLE storage
- **OkHttp** 5.x for TLE downloads
- **Navigation3**: Type-safe navigation with `@Serializable` nav keys
- **Room** (KSP code generation) for local satellite/orbital storage
- **OkHttp** 5.x for data downloads
- **OSMDroid** for map rendering
- **Kotlin Serialization** for navigation args and data parsing
- **Kotlin Serialization** for navigation args and parsing
- **Coroutines** + `StateFlow` for async/reactive patterns
## Conventions
- **Minimal dependencies**: Avoid adding libraries when a simple manual solution exists. Fewer deps = less maintenance.
- **DI**: Manual — ViewModels use companion `factory()` methods with `IMainContainer` interface.
- **Navigation**: Type-safe Compose Navigation3 with `@Serializable` data classes as nav keys.
- **State naming**: `<Feature>State` data class + `<Feature>Action` sealed interface per feature.
- **No feature-to-feature deps**: All cross-feature communication goes through core layers.
- **Localization**: 7 languages (en, es, ru, si, tr, uk, zh).
- **Localization**: 7 languages (en, es, ru, si, tr, uk, zh)
## Data Formats & Migration
**TLE vs. OMM/CSV format:**
Look4Sat supports both TLE and OMM (Orbit Mean-Elements Message) CSV formats:
Look4Sat supports both TLE and OMM (Orbit Mean-Elements Message) formats for backward compatibility:
- **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
- 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)
- **TLE format**: Traditional 3-line element format (deprecated). NORAD catalog numbers are 5-digit integers, which
are running out of space. Celestrak has signaled that TLE format will eventually be phased out.
- **OMM/CSV format**: The future standard. CSV files contain the same orbital parameters as TLE but use ISO 8601
timestamps and support larger NORAD IDs. Celestrak and SatNOGS already provide OMM data in CSV format.
## Engineering Heuristics (Lazy = Efficient)
**Current implementation:**
- `DataParser.kt` handles both `parseTLEStream()` and `parseCSVStream()` seamlessly
- TLE data is downloaded from configured sources and stored in Room database
- When downloading satellite data, the app automatically detects format and parses accordingly
- Both formats produce identical `OrbitalData` objects, ensuring transparent format switching
- Treat "lazy" as efficient, not careless: the best code is the code never written.
- First understand the task and trace the real flow end-to-end, then climb this ladder:
1. Does this need to be built now? (YAGNI)
2. Does it already exist in this codebase? Reuse helpers/patterns before rewriting.
3. Does Kotlin/Java stdlib already solve it?
4. Does the Android/platform API already solve it?
5. Does an already-installed dependency solve it?
6. Can this be simpler (including one-liner simple)?
7. Only then: write the minimum code that works.
- Prefer deletion to addition, boring over clever, and the fewest touched files.
- Avoid new abstractions, dependencies, and boilerplate unless explicitly requested.
- Manual DI only: ViewModels use companion `factory()` methods with `IMainContainer`.
- Release builds use ProGuard: avoid reflection-heavy libraries unless explicitly approved.
- When two options are similar in size, choose the edge-case-correct one.
- If you keep a deliberate simplification (for example O(n^2) scan or global lock), leave a short comment with the ceiling and upgrade path.
- For complex asks, challenge scope when appropriate: "Do you need X, or does Y already cover it?"
**Migration path:**
As NORAD catalog space becomes constrained, OMM/CSV will become the primary format. Look4Sat is already positioned
to handle this transition without code changes — existing users can continue using TLE files while new sources
transition to OMM/CSV automatically.
## Bug-Fix Policy
## Code Style
- Prefer **short, focused functions** — single responsibility, easy to read.
- **Exceptions**: Composable functions and math-heavy algorithms (SGP4/SDP4) may be longer.
- Strict code style — no dead code, no unused imports, consistent formatting.
- Fix root cause, not just the reported symptom.
- If touching a shared function, inspect callers and prefer one shared fix over per-caller patches.
- The smallest correct diff wins only after behavior is understood.
## Roadmap
- **KMP migration**: `core:domain` is to become a fully shareable KMM module. Keep it pure Kotlin/JVM.
- **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).
## Gotchas
- Orbital math lives in `core:domain/predict/` — it's dense vector math (SGP4/SDP4). Tread carefully.
- TLE/OMM data must be refreshed weekly for accurate predictions (satellite orbits decay). TLE format is legacy and
will eventually be deprecated in favor of OMM/CSV as NORAD catalog numbers approach the 5-digit limit.
- 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 all shared Gradle configuration — edit there, not in individual modules.
- ProGuard is enabled for release builds — don't add reflection-based libs or any other dependencies without asking.
- `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
+64 -77
View File
@@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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 licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are 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. 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.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ 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.
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.
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.
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.
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.
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.
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.
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.
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.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -72,7 +60,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -549,35 +537,45 @@ 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. Use with the GNU Affero General Public License.
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.
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 Affero General Public License into a single
under version 3 of the GNU 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
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
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
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 General
Program specifies that a certain numbered version of the GNU Affero 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 General Public License, you may choose any version ever published
GNU Affero 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 General Public License can be used, that proxy's
versions of the GNU Affero 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.
@@ -635,40 +633,29 @@ 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 General Public License as published by
it under the terms of the GNU Affero 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.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero 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 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".
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.
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 GPL, see
For more information on this, and how to apply and follow the GNU AGPL, 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
@@ -0,0 +1,24 @@
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.
--------------------------------------------------------------------------------
+19 -4
View File
@@ -34,12 +34,27 @@ 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://www.star-history.com/?repos=rt-bishop%2FLook4Sat&type=timeline&legend=top-left">
<a href="https://star-history.dera.page/#rt-bishop/Look4Sat&type=timeline&legend=top-left">
<picture>
<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" />
<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" />
</picture>
</a>
+13 -2
View File
@@ -11,15 +11,23 @@ val keystoreProperties = Properties().apply {
}
android {
// CW 解码已迁移为纯 Kotlin fldigi 引擎, 不再有 native 库;
// 取消 armeabi-v7a 强制, 按设备 ABI 打包(含 x86_64 模拟器)
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) {
@@ -34,6 +42,9 @@ android {
buildTypes {
release {
signingConfig = signingConfigs.findByName("release")
// ONNX Runtime 走 JNI, R8 混淆会重命名 ai.onnxruntime.* 类导致 native
// 崩溃。convention 插件已开启 isMinifyEnabled, 必须补 keep 规则。
proguardFiles("proguard-rules.pro")
}
}
}
+13
View File
@@ -0,0 +1,13 @@
# 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.**
+15
View File
@@ -15,7 +15,22 @@
<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"
@@ -1,5 +1,6 @@
package com.rtbishop.look4sat.app
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
@@ -11,7 +12,10 @@ 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
@@ -35,10 +39,25 @@ class AprsForegroundService : Service() {
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
@@ -51,6 +70,12 @@ class AprsForegroundService : Service() {
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)
@@ -64,6 +89,16 @@ class AprsForegroundService : Service() {
}
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 {
@@ -75,18 +110,33 @@ class AprsForegroundService : Service() {
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
val msg = if (report.ok) {
getString(R.string.aprs_toast_ok)
} else {
getString(R.string.aprs_toast_fail, report.detail)
// 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)
}
runCatching {
mainHandler.post {
Toast.makeText(this, msg,
if (report.ok) Toast.LENGTH_SHORT else Toast.LENGTH_LONG).show()
}
@@ -94,9 +144,12 @@ class AprsForegroundService : Service() {
)
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)
@@ -107,6 +160,11 @@ class AprsForegroundService : Service() {
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)
@@ -187,4 +245,43 @@ class AprsForegroundService : Service() {
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) { MainScreen() }
MainTheme(isDarkTheme = true) { NavRoot() }
}
}
@@ -20,20 +20,18 @@ package com.rtbishop.look4sat
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
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.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
@@ -51,7 +49,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.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteDefaults
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold
@@ -67,6 +65,7 @@ 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
@@ -83,6 +82,7 @@ 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
@@ -97,41 +97,45 @@ 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.status.SatStatusScreen
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 {
val destination = deeplinkResolver.resolve(it) // rootBackStack.clear()
rootBackStack.add(destination)
}
deeplink?.let { rootBackStack.add(deeplinkResolver.resolve(it)) }
}
val navigateBack: () -> Unit = { rootBackStack.removeLastOrNull() }
val slideInTransition = slideInHorizontally(initialOffsetX = { it }) togetherWith scaleOut(targetScale = 0.9f)
val slideOutTransition = scaleIn(initialScale = 0.9f) togetherWith slideOutHorizontally(targetOffsetX = { it })
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 }
NavDisplay(
modifier = Modifier.fillMaxSize(),
backStack = rootBackStack,
onBack = navigateBack,
transitionSpec = { slideInTransition },
popTransitionSpec = { slideOutTransition },
predictivePopTransitionSpec = { slideOutTransition },
transitionSpec = { pushTransition },
popTransitionSpec = { popTransition },
predictivePopTransitionSpec = { popTransition },
entryDecorators = listOf(
rememberSaveableStateHolderNavEntryDecorator(), // Required for saving Compose state per entry
rememberViewModelStoreNavEntryDecorator() // Required for ViewModel scoping per entry
rememberSaveableStateHolderNavEntryDecorator(),
rememberViewModelStoreNavEntryDecorator()
),
entryProvider = entryProvider {
entry<Screen.Passes> { MainScreen(navigateToRadar = { rootBackStack.add(RadarDestination) }) }
entry<Screen.Passes> { MainScreen() }
entry<RadarDestination> {
Scaffold { innerPadding ->
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
RadarDestination(navigateUp = navigateBack)
innerPadding.calculateTopPadding()
}
}
}
@@ -139,7 +143,7 @@ fun NavRoot(deeplink: String? = null) {
}
@Composable
fun MainScreen(navigateToRadar: () -> Unit = {}) {
fun MainScreen() {
val backStack = rememberNavBackStack(Screen.Passes)
val currentKey = backStack.lastOrNull()
val navigateBack: () -> Unit = { backStack.removeLastOrNull() }
@@ -148,27 +152,27 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
val container = (context.applicationContext as IContainerProvider).getMainContainer()
val trackingState by container.radioTrackingService.state.collectAsStateWithLifecycle()
val otherSettings by container.settingsRepo.otherSettings.collectAsStateWithLifecycle()
// UI settings: sort by screenOrder (empty = default order), then filter by hiddenScreens (Settings always kept)
val allNavItems = listOf(Screen.Satellites, Screen.Passes, Screen.Radar, Screen.Mutual, Screen.Roaming, Screen.CwDecode, Screen.WavelogLog, Screen.AmSat, Screen.Map, Screen.Settings)
.sortedBy { screen ->
// Unknown pages (e.g. CwDecode not in old persisted order): use default-order position (Roaming<->Map), then fall back to last
val idx = otherSettings.screenOrder.indexOf(screen.screenId)
if (idx != -1) idx
else com.rtbishop.look4sat.core.presentation.defaultScreenOrder.indexOf(screen.screenId).let {
if (it != -1) it else Int.MAX_VALUE
}
}
.filter { it.screenId !in otherSettings.hiddenScreens || it is Screen.Settings }
// 4.5.1 foldable menu: main menu (5 bottom-bar slots) + More menu (overflow page)
// Legacy migration: persisted subMenuOrder lacks new pages (WavelogLog) -> append to the sub-menu tail
val subOrder = (otherSettings.subMenuOrder.ifEmpty { com.rtbishop.look4sat.core.presentation.defaultSubMenuOrder })
.let { list -> if ("WavelogLog" in list) list else list + "WavelogLog" }
.let { list -> if ("AMSAT" in list) list else list + "AMSAT" }
val mainNavItems = remember(allNavItems, subOrder) {
allNavItems.filter { it.screenId !in subOrder }.take(5)
// 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 moreNavItems = remember(allNavItems, subOrder) {
subOrder.mapNotNull { id -> allNavItems.find { it.screenId == id } }
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
@@ -188,20 +192,16 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
NavigationSuiteScaffold(
navigationSuiteItems = {
mainNavItems.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.Mutual -> screen is Screen.Mutual
is Screen.CwDecode -> screen is Screen.CwDecode
is Screen.WavelogLog -> screen is Screen.WavelogLog
is Screen.AmSat -> screen is Screen.AmSat
is Screen.Map -> screen is Screen.Map
is Screen.Settings -> screen is Screen.Settings
else -> false
}
// Screen subclasses are data objects, so identity is enough and
// newly added pages highlight without touching this call site.
val isSelected = currentKey == screen
item(
icon = { Icon(painterResource(screen.iconResId), stringResource(screen.titleResId)) },
icon = {
Icon(
painter = painterResource(screen.iconResId),
contentDescription = stringResource(screen.titleResId)
)
},
label = { Text(stringResource(screen.titleResId)) },
selected = isSelected,
onClick = {
@@ -260,7 +260,6 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
container.setMutualPassData(MutualPassData())
container.satelliteRepo.selectPass(catNum, aosTime)
backStack.add(Screen.Radar)
// navigateToRadar()
}
}
entry<Screen.Radar> {
@@ -287,7 +286,7 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
CwDecodeScreen()
}
entry<Screen.AmSat> {
SatStatusScreen(container = container)
SatStatusDestination()
}
entry<Screen.WavelogLog> {
WavelogLogScreen(queue = container.wavelogQueue)
@@ -346,14 +345,18 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
}
}
}
// More-menu popup panel (overlays content above the bottom bar; spring bounce)
// More-menu popup panel (slim strip anchored to the bottom-right corner)
AnimatedVisibility(
visible = moreExpanded,
modifier = Modifier.fillMaxSize(),
enter = expandVertically(
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)
) + fadeIn(),
exit = shrinkVertically() + fadeOut()
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,
@@ -369,4 +372,4 @@ fun MainScreen(navigateToRadar: () -> Unit = {}) {
}
}
}
}
}
@@ -1,13 +1,13 @@
/*
* MoreMenuPopup.kt - bottom-nav "More" second-level menu popup panel (4.5.1).
*
* Overlays the content area (above the bottom bar, right-aligned), vertical menu items (icon+text+arrow),
* current page highlighted; tap the scrim to close, tap an item to navigate. Open/close animation is driven by the caller
* (MainScreen's AnimatedVisibility + spring).
* 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.background
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -18,6 +18,7 @@ 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
@@ -45,31 +46,30 @@ fun MoreMenuPopup(
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.35f))
// 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),
.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.surfaceContainerHigh
containerColor = MaterialTheme.colorScheme.surfaceContainer
)
) {
Column(modifier = Modifier.padding(vertical = 4.dp)) {
items.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.Mutual -> screen is Screen.Mutual
is Screen.CwDecode -> screen is Screen.CwDecode
is Screen.WavelogLog -> screen is Screen.WavelogLog
is Screen.Map -> screen is Screen.Map
is Screen.Settings -> screen is Screen.Settings
else -> false
}
// 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
@@ -19,17 +19,50 @@ package com.rtbishop.look4sat.convention
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.configure
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
/**
* 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.jvm)
applyPlugin(libs.plugins.kotlin.multiplatform)
applyPlugin(libs.plugins.kotlin.serialization)
setupKotlin()
dependencies {
implementation(libs.kotlin.coroutines)
implementation(libs.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 {
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)
}
}
}
}
@@ -62,6 +62,12 @@ internal fun Project.setupAndroidApp() {
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,3 +5,9 @@ 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,16 +1,23 @@
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 (reverse-ported from APRSdroid TcpUploader.scala).
* Plain-text protocol: one login line + one packet per line; 30 s reconnect after drop.
* 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,
@@ -18,6 +25,7 @@ class AprsIsClient(
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
@@ -27,70 +35,188 @@ class AprsIsClient(
private var reader: BufferedReader? = null
private val lock = Any()
val isConnected: Boolean
get() = synchronized(lock) { socket?.isConnected == true && !socket!!.isClosed }
/**
* 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
/** Connect + login (synchronous/blocking; call from a background thread) */
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()
s.connect(InetSocketAddress(host, port), 30_000)
s.soTimeout = timeoutSec * 1000
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)
}
// Login line
val login = AprsPacket.formatLogin(callsign, ssid, passcode, version) + filter
writer?.println(login)
// Read the login response (aprsc replies # logresp ... verified/unverified)
runCatching {
s.soTimeout = 8000
val resp = reader?.readLine()
if (resp != null && (resp.contains("Invalid", ignoreCase = true) ||
resp.contains("unverified", ignoreCase = true))) {
throw IllegalArgumentException(resp.trim())
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)
}
// Restore timeout
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
}
}
/**
* Sends one APRS packet (one line) and tries to read the server ack.
* Returns null=failed to send; Pair(ok, detail)=result (server error text lives in detail)
* 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
w.println(packetLine)
// 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")
}
// Try to read the server response (short 3 s timeout; APRS-IS replies with an error line on bad format)
return runCatching {
val s = socket ?: return@runCatching Pair(true, "OK")
val oldTimeout = s.soTimeout
s.soTimeout = 3000
try {
val resp = reader?.readLine()
if (resp != null && (resp.contains("Invalid", ignoreCase = true) ||
resp.contains("error", ignoreCase = true))) {
Pair(false, resp.trim())
} else {
Pair(true, if (resp.isNullOrBlank()) "OK" else resp.trim())
}
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 {
s.soTimeout = oldTimeout
runCatching { s.soTimeout = previousTimeout }
}
}.getOrElse { Pair(true, "OK") }
}
}
/** Read one line (server response; throws on timeout) */
fun readLine(): String? {
return reader?.readLine()
/**
* 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() {
@@ -103,4 +229,16 @@ class AprsIsClient(
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,12 +1,11 @@
package com.rtbishop.look4sat.core.data.aprs
import com.rtbishop.look4sat.core.domain.aprs.AprsPacket
import com.rtbishop.look4sat.core.domain.aprs.AprsPosition
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.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
@@ -34,12 +33,39 @@ data class AprsReport(
val timestamp: Long,
val packet: String,
val ok: Boolean,
val detail: String
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 = {}
@@ -59,12 +85,11 @@ class AprsReporter(
onState(AprsState.Error)
return
}
job = scope.launch {
while (isActive) {
reportOnce()
delay(cfg.intervalMin.coerceAtLeast(1) * 60_000L)
}
}
// 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() {
@@ -86,41 +111,92 @@ class AprsReporter(
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,
passcode = cfg.passcode.toIntOrNull()?.takeIf { it >= 0 } ?: AprsPacket.passcode(cfg.callsign),
version = "Look4Sat 4.5.4"
// 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 pos = positionProvider()
val packetLine = buildPositionPacket(cfg, pos?.first, pos?.second)
val result = c.sendPacket(packetLine)
val ok = result?.first == true
val sent = result?.first == true
val detail = result?.second ?: "no connection"
onReport(AprsReport(System.currentTimeMillis(), packetLine, ok, detail))
// 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"))
onReport(AprsReport(System.currentTimeMillis(), "", false, e.message ?: "error", false))
}
}
/** Build position packet: BG7NTA-5>APRS:=DDMM.MMN/DDDMM.MME<status text */
private fun buildPositionPacket(cfg: AprsConfig, lat: Double? = null, lon: Double? = null): String {
val source = AprsPacket.formatCallSsid(cfg.callsign, cfg.ssid)
val pos = AprsPosition(
latitude = lat ?: 0.0,
longitude = lon ?: 0.0,
symbolTable = cfg.symbolTable.firstOrNull() ?: '/',
symbolCode = cfg.symbolCode.firstOrNull() ?: '>'
)
return "$source>APRS:=${pos.toUncompressedString()}${cfg.statusText}"
/** 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
}
}
@@ -24,6 +24,15 @@ object AprsStore {
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"
@@ -41,7 +50,7 @@ object AprsStore {
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, ">") ?: ">"
symbolCode = p.getString(KEY_SYMBOL_CODE, DEFAULT_SYMBOL_CODE) ?: DEFAULT_SYMBOL_CODE
)
}
@@ -0,0 +1,771 @@
/*
* 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
}
}
@@ -0,0 +1,53 @@
/*
* 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)
}
}
}
@@ -45,7 +45,12 @@ interface Look4SatDao {
@Query("DELETE FROM entries")
suspend fun deleteEntries()
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes)")
@Query(
"""
SELECT DISTINCT catnum FROM radios WHERE isAlive = 1
AND (downlinkMode IN (:modes) OR uplinkMode IN (:modes))
"""
)
suspend fun getIdsWithModes(modes: List<String>): List<Int>
@Query("SELECT COUNT(*) FROM radios")
@@ -76,10 +76,12 @@ 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
@@ -87,6 +89,11 @@ 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
@@ -97,10 +104,12 @@ 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
@@ -108,6 +117,11 @@ 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,6 +42,9 @@ 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
@@ -53,9 +56,11 @@ 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
@@ -66,6 +71,13 @@ 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
}
@@ -91,6 +103,16 @@ 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,9 +67,11 @@ 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
@@ -84,6 +86,13 @@ 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,14 +71,19 @@ class NetworkReporter(
private fun ensureRotatorConnected() {
if (rotatorConnected || rotatorConnecting || rotatorServer.isBlank()) return
reporterScope.launch {
var opened: SocketChannel? = null
try {
rotatorConnecting = true
rotatorSocket = SocketChannel.open(InetSocketAddress(rotatorServer, rotatorPort))
opened = SocketChannel.open(InetSocketAddress(rotatorServer, rotatorPort))
rotatorSocket = opened
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
}
@@ -88,14 +93,17 @@ class NetworkReporter(
private fun ensureFrequencyConnected() {
if (frequencyConnected || frequencyConnecting || frequencyServer.isBlank()) return
reporterScope.launch {
var opened: SocketChannel? = null
try {
frequencyConnecting = true
frequencySocket = SocketChannel.open(InetSocketAddress(frequencyServer, frequencyPort))
opened = SocketChannel.open(InetSocketAddress(frequencyServer, frequencyPort))
frequencySocket = opened
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
}
@@ -111,6 +119,17 @@ 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,12 +267,18 @@ class RadioTrackingService(
if (tuningRadio.isEmpty()) {
if (txNow != null && txNow.isConnected && txRadioFreq != null) {
txNow.setFrequency(txRadioFreq)
lastSetTxFreq = txRadioFreq.toDouble()
// 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)) {
lastSetTxFreq = txRadioFreq.toDouble()
}
}
if (rxNow != null && rxNow.isConnected && rxRadioFreq != null) {
rxNow.setFrequency(rxRadioFreq)
lastSetRxFreq = rxRadioFreq.toDouble()
if (rxNow.setFrequency(rxRadioFreq)) {
lastSetRxFreq = rxRadioFreq.toDouble()
}
}
}
@@ -450,13 +456,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")
radio.setWorkingFrequency(rxRadioFreq)
lastSetRxFreq = rxRadioFreq.toDouble()
if (radio.setWorkingFrequency(rxRadioFreq)) {
lastSetRxFreq = rxRadioFreq.toDouble()
}
}
if (txRadioFreq != null) {
Log.d(tag, "Split loop TX (0x25/01): ${txRadioFreq}Hz")
radio.setTxVfoFrequency(txRadioFreq)
lastSetTxFreq = txRadioFreq.toDouble()
if (radio.setTxVfoFrequency(txRadioFreq)) {
lastSetTxFreq = txRadioFreq.toDouble()
}
}
}
@@ -30,13 +30,13 @@ import com.rtbishop.look4sat.core.data.framework.Ic705Controller
import com.rtbishop.look4sat.core.data.framework.NetworkReporter
import com.rtbishop.look4sat.core.data.framework.RadioTrackingService
import com.rtbishop.look4sat.core.data.repository.AmSatRepository
import com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient
import com.rtbishop.look4sat.core.data.repository.DatabaseRepo
import com.rtbishop.look4sat.core.data.repository.SatelliteRepo
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
@@ -70,20 +70,32 @@ 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 mainHandler = CoroutineExceptionHandler { _, error -> println("MainHandler: $error") }
override val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + mainHandler)
override val settingsRepo = provideSettingsRepo()
override val selectionRepo = provideSelectionRepo()
override val satelliteRepo = provideSatelliteRepo()
override val databaseRepo = provideDatabaseRepo()
override val amSatRepo = AmSatRepository(com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient())
override val amSatRepo by lazy { AmSatRepository(remoteSource) }
override val radioTrackingService: IRadioTrackingService by lazy {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
RadioTrackingService(appScope, manager, satelliteRepo, settingsRepo)
@@ -98,10 +110,25 @@ class MainContainer(private val context: Context) : IMainContainer {
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)
@@ -120,6 +147,22 @@ class MainContainer(private val context: Context) : IMainContainer {
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
@@ -0,0 +1,61 @@
/*
* 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"
}
}
@@ -0,0 +1,112 @@
/*
* 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)
}
}
@@ -1,58 +1,206 @@
package com.rtbishop.look4sat.core.data.repository
import com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient
import com.rtbishop.look4sat.core.domain.amsat.ApiReport
import com.rtbishop.look4sat.core.domain.model.SatDay
import com.rtbishop.look4sat.core.domain.model.SatReport
import com.rtbishop.look4sat.core.domain.model.SatSlot
import com.rtbishop.look4sat.core.domain.model.SatStatus
import com.rtbishop.look4sat.core.domain.model.SatStatusPage
import com.rtbishop.look4sat.core.domain.repository.IAmSatRepository
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
/** AMSAT status repository: official API v1 -> SatStatusPage (replaces the HTML parser). */
class AmSatRepository(private val apiClient: AmSatApiClient) : IAmSatRepository {
/**
* 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(
val id: String,
val name: String,
val callsign: String,
val report: String,
val gridSquare: String,
val reportedTimeUtcSec: Long
)
/** AMSAT status repository using RemoteSource (Clean Architecture: data layer handles HTTP). */
class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepository {
private val isoUtcFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
override suspend fun fetchStatus(): SatStatusPage? = withContext(Dispatchers.IO) {
val nowSec = System.currentTimeMillis() / 1000
val names = apiClient.fetchCatalog()
val reports = apiClient.fetchAllReports(hours = 168)
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 names = parseCatalog(catalogJson)
val reports = parseReports(reportsJson)
if (names.isEmpty() && reports.isEmpty()) return@withContext null
val statuses = buildStatuses(names, reports, nowSec)
val reportMap = reports.associate { it.id to toSatReport(it) }
SatStatusPage(System.currentTimeMillis(), statuses, reportMap)
// 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)
}
/** 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> {
/** Parse catalog JSON to list of satellite names */
private fun parseCatalog(json: String): List<String> {
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).map { arr.getJSONObject(it).getString("name") }
} catch (_: Exception) {
emptyList()
}
}
/** Parse reports JSON to list of ApiReport domain objects */
private fun parseReports(json: String): List<ApiReport> {
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i)
val iso = o.optString("reported_time", "")
if (iso.isEmpty()) null else ApiReport(
id = o.optString("id", ""),
name = o.optString("name", ""),
callsign = o.optString("callsign", ""),
report = o.optString("report", ""),
gridSquare = o.optString("grid_square", ""),
reportedTimeUtcSec = parseIsoUtcSec(iso)
)
}
} catch (_: 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) {
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> {
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"))
val labels = (0 until 6).map { d ->
utc.timeInMillis = (nowSec - d * 86400L) * 1000
// 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
"${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 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()) {
SatSlot(statusColor = NoReportGray, count = 0)
} else {
val newest = inSlot.maxByOrNull { it.reportedTimeUtcSec }!!
SatSlot(
statusColor = statusColorOf(newest.report),
count = inSlot.size,
reportIds = inSlot.map { it.id }
)
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 }
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)
} else {
val newest = inSlot.maxByOrNull { it.reportedTimeUtcSec }!!
SatSlot(
statusColor = statusColorOf(newest.report),
count = inSlot.size,
reportIds = inSlot.map { it.id }
)
}
}
}
val days = (0 until 6).map { d ->
SatDay(dateLabel = labels[d], slots = slots.subList(d * 12, (d + 1) * 12))
SatDay(dateLabel = labels[dayIdx], slots = slots)
}
SatStatus(name = name, days = days)
}
@@ -76,18 +224,30 @@ class AmSatRepository(private val apiClient: AmSatApiClient) : IAmSatRepository
)
}
/** Map status text to color value (for UI rendering). */
private fun statusColorOf(report: String): Long = when (report.lowercase()) {
"heard", "crew active" -> ActiveBlue
"telemetry only" -> TlmOrange
"not heard" -> NotHeardPink
else -> ConflictDeepOrange
"heard", "crew active" -> ACTIVE_BLUE
"telemetry only" -> TLM_ORANGE
"not heard" -> NOT_HEARD_PINK
else -> CONFLICT_DEEP_ORANGE
}
companion object {
private const val ActiveBlue = 0xFF648FFF
private const val TlmOrange = 0xFFFFB000
private const val NotHeardPink = 0xFFDC267F
private const val ConflictDeepOrange = 0xFFFE6100
private const val NoReportGray = 0xFFC0C0C0
// AMSAT official status colors (from amsat.org/status)
private const val ACTIVE_BLUE = 0xFF648FFF
private const val TLM_ORANGE = 0xFFFFB000
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.InputStream
import java.io.ByteArrayInputStream
import java.util.zip.ZipInputStream
class DatabaseRepo(
@@ -42,10 +42,21 @@ 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.getFileStream(uri)?.let { stream ->
val entries = parseSatelliteStream(uri, unwrapIfZipped(uri, stream))
remoteSource.getFileBytes(uri)?.let { data ->
val entries = parseSatelliteData(uri, unwrapIfZipped(uri, data))
localSource.insertEntries(entries)
settingsRepo.setSatelliteTypeIds(customSourceType, entries.map { it.catnum })
importedCount = entries.size
@@ -56,8 +67,8 @@ class DatabaseRepo(
override suspend fun updateTransceiversFromFile(uri: String): Int = withContext(dispatcher) {
var importedCount = 0
remoteSource.getFileStream(uri)?.let { stream ->
val transceivers = dataParser.parseJSONStream(unwrapIfZipped(uri, stream))
remoteSource.getFileBytes(uri)?.let { data ->
val transceivers = dataParser.parseJSON(unwrapIfZipped(uri, data).decodeToString())
localSource.insertRadios(transceivers)
importedCount = transceivers.size
}
@@ -67,36 +78,56 @@ class DatabaseRepo(
override suspend fun updateFromRemote() = withContext(dispatcher) {
val dataSourcesSettings = settingsRepo.dataSourcesSettings.value
val tleUrls = buildMap {
putAll(Sources.satelliteDataUrls)
// Switch on + non-empty URL -> All uses the custom URL; otherwise the default URL (online-update default source)
put("All", if (dataSourcesSettings.useCustomTLE && dataSourcesSettings.tleUrl.isNotBlank())
dataSourcesSettings.tleUrl else Sources.defaultTleUrl)
}.filterValues { it.isNotBlank() }
val radioUrls = buildMap {
putAll(Sources.transceiversDataUrls)
put("SatNOGS", if (dataSourcesSettings.useCustomTransceivers && dataSourcesSettings.transceiversUrl.isNotBlank())
dataSourcesSettings.transceiversUrl else Sources.defaultTransceiversUrl)
}.filterValues { it.isNotBlank() }
// 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() }
}
// launch all network requests concurrently
val tleJobs = tleUrls.values.map { url -> async { url to remoteSource.getNetworkStream(url) } }
val radioJobs = radioUrls.values.map { url -> async { url to remoteSource.getNetworkStream(url) } }
// Count successful sources: zero successes = update failed (timestamp untouched, exception surfaced in the UI)
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()
val successCount = tleResults.count { it.second != null } + radioResults.count { it.second != null }
if (successCount == 0) {
throw java.io.IOException("All data sources failed to download")
// 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")
}
// parse fetched data concurrently and associate with types
val importedEntries = tleResults.flatMap { (url, stream) ->
val importedEntries = tleResults.flatMap { (url, data) ->
val type = tleUrls.entries.find { it.value == url }?.key ?: customSourceType
stream?.let { parseSatelliteStream(url, unwrapIfZipped(url, it)) }.orEmpty().also { entries ->
data?.let { parseSatelliteData(url, unwrapIfZipped(url, it)) }.orEmpty().also { entries ->
settingsRepo.setSatelliteTypeIds(type, entries.map { it.catnum })
}
}
val importedRadios = radioResults.flatMap { (url, stream) ->
stream?.let { dataParser.parseJSONStream(unwrapIfZipped(url, it)) }.orEmpty()
val importedRadios = radioResults.flatMap { (url, data) ->
data?.let { dataParser.parseJSON(unwrapIfZipped(url, it).decodeToString()) }.orEmpty()
}
// insert parsed data into the database
localSource.insertEntries(importedEntries)
@@ -110,11 +141,11 @@ class DatabaseRepo(
setUpdateSuccessful(0L)
}
private suspend fun parseSatelliteStream(url: String, stream: InputStream): List<OrbitalData> {
val bufferedStream = stream.buffered()
private suspend fun parseSatelliteData(url: String, data: ByteArray): List<OrbitalData> {
val text = data.decodeToString()
return when {
hasCsvHint(url) || looksLikeCsv(bufferedStream) -> dataParser.parseCSVStream(bufferedStream)
else -> dataParser.parseTLEStream(bufferedStream)
hasCsvHint(url) || looksLikeCsv(text) -> dataParser.parseCSV(text)
else -> dataParser.parseTLE(text)
}
}
@@ -124,14 +155,9 @@ class DatabaseRepo(
url.endsWith(".csv.zip", ignoreCase = true)
}
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()
private fun looksLikeCsv(text: String): Boolean {
val line = text.lineSequence().firstOrNull()?.trim().orEmpty()
if (line.isEmpty()) return false
return line.contains("OBJECT_NAME", ignoreCase = true) ||
line.contains("NORAD_CAT_ID", ignoreCase = true) ||
line.count { it == ',' } >= 4
@@ -143,6 +169,10 @@ class DatabaseRepo(
)
}
private fun unwrapIfZipped(url: String, stream: InputStream): InputStream =
if (url.endsWith(".zip", ignoreCase = true)) ZipInputStream(stream).apply { nextEntry } else stream
private fun unwrapIfZipped(url: String, data: ByteArray): ByteArray =
if (url.endsWith(".zip", ignoreCase = true)) {
ZipInputStream(ByteArrayInputStream(data)).apply { nextEntry }.readBytes()
} else {
data
}
}
@@ -34,9 +34,13 @@ 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
class SatelliteRepo(
private val dispatcher: CoroutineDispatcher,
@@ -50,6 +54,10 @@ 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
@@ -63,19 +71,23 @@ class SatelliteRepo(
override suspend fun getRadiosWithId(id: Int) = localStorage.getRadiosWithId(id)
override suspend fun initRepository() = withContext(dispatcher) {
settingsRepo.selectedIds.collect { selectedIds ->
_satellites.update { localStorage.getEntriesWithIds(selectedIds) }
val settings = settingsRepo.passesSettings.value
calculatePasses(
time = System.currentTimeMillis(),
hoursAhead = settings.hoursAhead,
minElevation = settings.minElevation,
aosStartMinute = settings.aosStartMinute,
aosEndMinute = settings.aosEndMinute,
invertAosTimeWindow = settings.invertAosTimeWindow,
modes = settings.selectedModes
)
}
combine(
settingsRepo.selectedIds,
settingsRepo.stationPosition
) { selectedIds, _ -> selectedIds }
.collect { selectedIds ->
_satellites.update { localStorage.getEntriesWithIds(selectedIds) }
val settings = settingsRepo.passesSettings.value
calculatePasses(
time = System.currentTimeMillis(),
hoursAhead = settings.hoursAhead,
minElevation = settings.minElevation,
aosStartMinute = settings.aosStartMinute,
aosEndMinute = settings.aosEndMinute,
invertAosTimeWindow = settings.invertAosTimeWindow,
modes = settingsRepo.selectedSatModes.value
)
}
}
override suspend fun getPosition(sat: OrbitalObject, pos: GeoPos, time: Long): OrbitalPos {
@@ -117,45 +129,55 @@ class SatelliteRepo(
invertAosTimeWindow: Boolean,
modes: List<String>
) {
_isCalculating.value = true
// 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
val currentSatellites = _satellites.value
withContext(dispatcher) {
val idsWithModes = localStorage.getIdsWithModes(modes)
val stationPos = settingsRepo.stationPosition.value
val filteredSatellites = if (idsWithModes.isEmpty()) {
currentSatellites
} else {
currentSatellites.filter { it.data.catnum in idsWithModes }
}
// Compute passes for each satellite in parallel
val passLists = coroutineScope {
filteredSatellites.map { satellite ->
async { satellite.getPasses(stationPos, normalizedTime, hoursAhead) }
}.awaitAll()
}
// Flatten and filter in a single pass
val timeFuture = normalizedTime + (hoursAhead * 60L * 60L * 1000L)
val newPasses = ArrayList<OrbitalPass>()
for (list in passLists) {
for (pass in list) {
if (
pass.losTime > time
&& pass.aosTime < timeFuture
&& pass.maxElevation > minElevation
&& (pass.isDeepSpace || isAosInRange(pass.aosTime, aosStartMinute, aosEndMinute, invertAosTimeWindow))
) {
newPasses.add(pass)
// 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
val currentSatellites = _satellites.value
withContext(dispatcher) {
val idsWithModes = localStorage.getIdsWithModes(modes)
val stationPos = settingsRepo.stationPosition.value
val filteredSatellites = if (idsWithModes.isEmpty()) {
currentSatellites
} else {
currentSatellites.filter { it.data.catnum in idsWithModes }
}
// Compute passes for each satellite in parallel
val passLists = coroutineScope {
filteredSatellites.map { satellite ->
async { satellite.getPasses(stationPos, normalizedTime, hoursAhead) }
}.awaitAll()
}
// Flatten and filter in a single pass
val timeFuture = normalizedTime + (hoursAhead * 60L * 60L * 1000L)
val newPasses = ArrayList<OrbitalPass>()
for (list in passLists) {
for (pass in list) {
if (
pass.losTime > time
&& pass.aosTime < timeFuture
&& pass.maxElevation > minElevation
&& (pass.isDeepSpace || isAosInRange(pass.aosTime, aosStartMinute, aosEndMinute, invertAosTimeWindow))
) {
newPasses.add(pass)
}
}
}
newPasses.sortBy { it.aosTime }
delay(1000) // 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
}
newPasses.sortBy { it.aosTime }
delay(1000) // Simulate loading time for better UX
_passes.update { newPasses }
}
_isCalculating.value = false
}
private fun isAosInRange(
@@ -170,7 +192,7 @@ class SatelliteRepo(
val inRange = if (aosStartMinute <= aosEndMinute) {
aosMinute in aosStartMinute..aosEndMinute
} else {
aosMinute >= aosStartMinute || aosMinute <= aosEndMinute
aosMinute !in (aosEndMinute + 1)..<aosStartMinute
}
return if (invertAosTimeWindow) !inRange else inRange
}
@@ -38,16 +38,16 @@ class SelectionRepo(
) : ISelectionRepo {
private val currentItems = MutableStateFlow<List<SatItem>>(emptyList())
private val currentTypes = MutableStateFlow(settingsRepo.selectedTypes.value)
private val currentQuery = MutableStateFlow("")
// Resolve type IDs once when types change, then filter items reactively.
// Resolve sat IDs once when modes change, then filter items reactively.
// The HashSet gives O(1) catnum lookups instead of O(n) with a List.
private val itemsWithTypes = currentTypes.flatMapLatest { types: List<String> ->
val catnumSet: Set<Int>? = if (types.isEmpty()) {
// Directly observe settingsRepo.selectedSatModes to ensure real-time sync across screens.
private val itemsWithModes = settingsRepo.selectedSatModes.flatMapLatest { list: List<String> ->
val catnumSet: Set<Int>? = if (list.isEmpty()) {
null // null = no filtering
} else {
val ids = settingsRepo.getSatelliteTypesIds(types)
val ids = localSource.getIdsWithModes(list)
if (ids.isEmpty()) null else ids.toHashSet()
}
currentItems.map { items ->
@@ -56,14 +56,18 @@ class SelectionRepo(
}
private val itemsWithQuery = currentQuery.flatMapLatest { query ->
itemsWithTypes.map { items -> filterByQuery(items, query) }
itemsWithModes.map { items ->
filterByQuery(items, query).sortedWith(
compareByDescending<SatItem> { it.isSelected }
.thenBy { it.name }
.thenBy { it.catnum }
)
}
}
override fun getCurrentTypes() = currentTypes.value
override fun getCurrentModes() = settingsRepo.selectedSatModes.value
override fun getTypesList() = Sources.satelliteDataUrls.keys.sorted().toMutableList().apply {
removeAt(0)
}
override fun getModesList() = Sources.satelliteModes
override suspend fun getEntriesFlow() = withContext(dispatcher) {
val selectedIds = settingsRepo.selectedIds.value.toHashSet()
@@ -73,9 +77,8 @@ class SelectionRepo(
return@withContext itemsWithQuery
}
override suspend fun setTypes(types: List<String>) {
currentTypes.value = types
settingsRepo.setSelectedTypes(types)
override suspend fun setModes(modes: List<String>) {
settingsRepo.setSelectedSatModes(modes)
}
override suspend fun setQuery(query: String) {
@@ -29,15 +29,18 @@ 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.source.Sources
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,
@@ -69,9 +72,9 @@ class SettingsRepo(
private val keyFrequencyAddress = "frequencyAddress"
private val keyFrequencyPort = "frequencyPort"
private val keyFrequencyFormat = "frequencyFormat"
private val keyFrequencyOffsetHz = "frequencyOffsetHz"
private val keySelectedIds = "selectedIds"
private val keySelectedTypes = "selectedTypes"
private val keySelectedModes = "selectedModes"
private val keySelectedSatModes = "selectedSatModes"
private val keyStateOfAutoUpdate = "stateOfAutoUpdate"
private val keyStateOfSensors = "stateOfSensors"
private val keyStateOfSweep = "stateOfSweep"
@@ -100,13 +103,18 @@ class SettingsRepo(
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
private val _satelliteSelection = MutableStateFlow(getSelectedIds())
private val _typesSelection = MutableStateFlow(getSelectedTypes())
private val _satelliteModeSelection = MutableStateFlow(getSelectedSatModes())
override val selectedIds: StateFlow<List<Int>> = _satelliteSelection
override val selectedTypes: StateFlow<List<String>> = _typesSelection
override val selectedSatModes: StateFlow<List<String>> = _satelliteModeSelection
override fun setSelectedIds(ids: List<Int>) {
val selectionString = ids.joinToString(separatorComma)
@@ -114,10 +122,10 @@ class SettingsRepo(
_satelliteSelection.value = ids
}
override fun setSelectedTypes(types: List<String>) {
val typesString = types.joinToString(separatorComma)
preferences.edit { putString(keySelectedTypes, typesString) }
_typesSelection.value = types
override fun setSelectedSatModes(modes: List<String>) {
val modesString = modes.joinToString(separatorComma)
preferences.edit { putString(keySelectedSatModes, modesString) }
_satelliteModeSelection.value = modes
}
private fun getSelectedIds(): List<Int> {
@@ -126,10 +134,10 @@ class SettingsRepo(
return selectionString.split(separatorComma).map { it.toInt() }
}
private fun getSelectedTypes(): List<String> {
val typesString = preferences.getString(keySelectedTypes, "Amateur")
if (typesString.isNullOrEmpty()) return emptyList()
return typesString.split(separatorComma)
private fun getSelectedSatModes(): List<String> {
val modesString = preferences.getString(keySelectedSatModes, null)
if (modesString.isNullOrEmpty()) return emptyList()
return modesString.split(separatorComma).sorted()
}
//endregion
@@ -144,7 +152,6 @@ class SettingsRepo(
putInt(keyFilterAosStartMinute, settings.aosStartMinute)
putInt(keyFilterAosEndMinute, settings.aosEndMinute)
putBoolean(keyFilterAosInvert, settings.invertAosTimeWindow)
putString(keySelectedModes, settings.selectedModes.joinToString(separatorComma))
_passesSettings.value = settings
}
@@ -155,16 +162,13 @@ class SettingsRepo(
val aosStartMinute = preferences.getInt(keyFilterAosStartMinute, 0).coerceIn(0, 23 * 60 + 59)
val aosEndMinute = preferences.getInt(keyFilterAosEndMinute, 23 * 60 + 59).coerceIn(0, 23 * 60 + 59)
val invertAosTimeWindow = preferences.getBoolean(keyFilterAosInvert, false)
val selectedModesString = preferences.getString(keySelectedModes, null)
val selectedModes = selectedModesString?.split(separatorComma)?.sorted() ?: emptyList()
return PassesSettings(
showDeepSpace,
hoursAhead,
minElevation,
aosStartMinute,
aosEndMinute,
invertAosTimeWindow,
selectedModes
invertAosTimeWindow
)
}
//endregion
@@ -181,7 +185,10 @@ class SettingsRepo(
}
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean {
val newLongitude = if (longitude > 180.0) longitude - 180 else longitude
// 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 locator = positionToQth(latitude, newLongitude) ?: return false
setStationPosition(latitude, newLongitude, altitude, locator)
return true
@@ -262,6 +269,7 @@ class SettingsRepo(
private val _databaseState = MutableStateFlow(getDatabaseState())
override val databaseState: StateFlow<DatabaseState> = _databaseState
override fun getSatelliteTypesIds(types: List<String>): List<Int> {
val idsSet = mutableSetOf<Int>()
types.forEach { type ->
@@ -325,6 +333,10 @@ 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)
@@ -334,6 +346,7 @@ 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)
@@ -342,7 +355,7 @@ class SettingsRepo(
putString(keyBluetoothFrequencyFormat, settings.bluetoothFrequencyFormat)
putString(keyBluetoothFrequencyAddress, settings.bluetoothFrequencyAddress)
}
_rcSettings.value = settings
_rcSettings.value = settings.copy(frequencyOffsetHz = clampedFreqOffsetHz)
}
private fun getRCSettings(): RCSettings = RCSettings(
@@ -354,6 +367,8 @@ 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",
@@ -390,6 +405,11 @@ class SettingsRepo(
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
}
@@ -413,7 +433,11 @@ class SettingsRepo(
wavelogUrl = preferences.getString(keyWavelogUrl, null) ?: "",
wavelogApiKey = preferences.getString(keyWavelogApiKey, null) ?: "",
wavelogStationId = preferences.getString(keyWavelogStationId, null) ?: "",
wavelogAutoUpload = preferences.getBoolean(keyWavelogAutoUpload, false)
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)
)
//endregion
@@ -431,20 +455,47 @@ 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 {
// 4.4.8 fix: legacy example.com placeholder URLs count as unconfigured -> replaced with the real default URL and the switch forced off,
// otherwise the online All/SatNOGS sources would point at the wrong address and fail to update
val storedTleUrl = preferences.getString(keyTleUrl, Sources.defaultTleUrl) ?: Sources.defaultTleUrl
val storedTxUrl = preferences.getString(keyTransceiversUrl, Sources.defaultTransceiversUrl) ?: Sources.defaultTransceiversUrl
val tleUrl = if (storedTleUrl == "https://example.com/tle.txt") Sources.defaultTleUrl else storedTleUrl
val txUrl = if (storedTxUrl == "https://example.com/radio.json") Sources.defaultTransceiversUrl else storedTxUrl
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(
useCustomTLE = preferences.getBoolean(keyUseCustomTle, false) && tleUrl != Sources.defaultTleUrl,
useCustomTransceivers = preferences.getBoolean(keyUseCustomTransceivers, false) && txUrl != Sources.defaultTransceiversUrl,
tleUrl = tleUrl,
transceiversUrl = txUrl
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
)
}
//endregion
//region # Radio control settings
@@ -484,5 +535,27 @@ class SettingsRepo(
baudRate = preferences.getInt(keyRadioBaudRate, 4800),
splitMode = preferences.getBoolean(keyRadioSplitMode, false)
)
//endregion
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) }
}
}
@@ -1,136 +0,0 @@
package com.rtbishop.look4sat.core.data.source
import com.rtbishop.look4sat.core.domain.model.SatDay
import com.rtbishop.look4sat.core.domain.model.SatReport
import com.rtbishop.look4sat.core.domain.model.SatSlot
import com.rtbishop.look4sat.core.domain.model.SatStatus
import com.rtbishop.look4sat.core.domain.model.SatStatusPage
import java.util.regex.Pattern
/**
* AMSAT satellite status page parser (https://amsat.org/status/)
*
* Page structure (static HTML, verified 2026-08):
* - Status table: 48 rows in <table>, header = Name + 6 days (each colspan=12)
* Data row has 73 cells: [0]=satellite name, [1..72] = 6 days x 12 two-hour slots (new->old)
* Each cell: <td width=9 bgcolor="color">count</td>; when reports exist the count carries a
* docTips.show('id') link
* - Report details live in the page's inline JS:
* tips.a885153 = new Array(5,5,120,'status<br>callsign<br>grid<br>date<br>time span UTC')
*
* Status colors: #648fff=active, #ffb000=telemetry only, #dc267f=not heard, #fe6100=conflicting
*/
object AmSatParser {
private val STATUS_COLORS = mapOf(
"#648fff" to 0xFF648FFF.toLong(),
"#ffb000" to 0xFFFFB000.toLong(),
"#dc267f" to 0xFFDC267F.toLong(),
"#fe6100" to 0xFFFE6100.toLong()
)
private val GRAY = 0xFFC0C0C0.toLong()
private val rowRe = Pattern.compile("<tr>(.*?)</tr>", Pattern.DOTALL)
private val cellRe = Pattern.compile("(<t[dh][^>]*>.*?</t[dh]>)", Pattern.DOTALL)
private val bgRe = Pattern.compile("bgcolor=\"?(#[0-9a-fA-F]{6}|C0C0C0)\"?")
private val linkRe = Pattern.compile("docTips\\.show\\('(a\\d+)'\\)")
private val tipRe = Pattern.compile(
"tips\\.(a\\d+)\\s*=\\s*new\\s+Array\\(\\s*\\d+,\\s*\\d+,\\s*\\d+,\\s*'([^']*)'"
)
/** Parse the full page */
fun parse(html: String, fetchedAtUtcMs: Long): SatStatusPage {
val reports = parseReports(html)
val statuses = parseStatusTable(html, reports)
return SatStatusPage(fetchedAtUtcMs, statuses, reports)
}
/** Extract all reports (tips.* JS arrays) */
fun parseReports(html: String): Map<String, SatReport> {
val map = mutableMapOf<String, SatReport>()
val m = tipRe.matcher(html)
while (m.find()) {
val id = m.group(1)
val parts = m.group(2).split("<br>")
map[id] = SatReport(
id = id,
statusText = parts.getOrElse(0) { "" }.trim(),
call = parts.getOrElse(1) { "" }.trim(),
grid = parts.getOrElse(2) { "" }.trim(),
dateUtc = parts.getOrElse(3) { "" }.trim(),
timeUtc = parts.getOrElse(4) { "" }.trim()
)
}
return map
}
/** Parse the status table (48 satellite rows) */
fun parseStatusTable(html: String, reports: Map<String, SatReport>): List<SatStatus> {
val result = mutableListOf<SatStatus>()
val tables = extractTables(html)
for (table in tables) {
val rows = rowRe.matcher(table)
val parsed = mutableListOf<SatStatus>()
var rowIndex = 0
var dayHeaders: List<String> = emptyList()
while (rows.find()) {
val rowHtml = rows.group(1)
val cells = cellRe.matcher(rowHtml)
val cellList = mutableListOf<String>()
while (cells.find()) cellList.add(cells.group(1))
if (rowIndex == 0) {
// Header: Name + 6 days (each colspan=12)
dayHeaders = cellList.drop(1).take(6).map { stripHtml(it) }
rowIndex++
continue
}
if (cellList.size < 7) { rowIndex++; continue }
val name = stripHtml(cellList[0])
if (name.isBlank()) { rowIndex++; continue }
val days = mutableListOf<SatDay>()
for (d in 0 until 6) {
val start = 1 + d * 12
val end = start + 12
val slots = (start until end).mapNotNull { i ->
cellList.getOrNull(i)?.let { cell ->
val bg = bgRe.matcher(cell)
val color = if (bg.find()) {
STATUS_COLORS[bg.group(1).lowercase()] ?: GRAY
} else GRAY
val link = linkRe.matcher(cell)
val ids = mutableListOf<String>()
while (link.find()) ids.add(link.group(1))
val hasReport = ids.isNotEmpty()
val count = if (hasReport) {
stripHtml(cell).trim().toIntOrNull() ?: ids.size
} else 0
SatSlot(
statusColor = if (hasReport) color else GRAY,
count = count,
reportIds = ids
)
}
}
days.add(SatDay(dayHeaders.getOrElse(d) { "" }, slots))
}
parsed.add(SatStatus(name, days))
rowIndex++
}
if (parsed.isNotEmpty()) {
result.addAll(parsed)
break
}
}
return result
}
private fun extractTables(html: String): List<String> {
val result = mutableListOf<String>()
val m = Pattern.compile("<table.*?</table>", Pattern.DOTALL).matcher(html)
while (m.find()) result.add(m.group())
return result
}
private fun stripHtml(s: String): String =
s.replace(Regex("<[^>]+>"), "").trim()
}
@@ -0,0 +1,89 @@
/*
* 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,12 +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.ByteArrayInputStream
import java.io.InputStream
class RemoteSource(
private val dispatcher: CoroutineDispatcher,
@@ -33,42 +32,87 @@ class RemoteSource(
private val httpClient: OkHttpClient
) : IRemoteSource {
override suspend fun getFileStream(uri: String): InputStream? = withContext(dispatcher) {
override suspend fun getFileBytes(uri: String): ByteArray? = withContext(dispatcher) {
try {
val fileUri = uri.toUri()
contentResolver.openInputStream(fileUri)?.buffered()
contentResolver.openInputStream(fileUri)?.use { it.readBytes() }
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("RemoteSource file stream exception: $exception")
null
}
}
override suspend fun getStatusHtml(): String? = withContext(dispatcher) {
try {
val request = Request.Builder()
.url("https://amsat.org/status/")
.header("User-Agent", "Mozilla/5.0 (Linux; Android 13) Look4Sat/4.5")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
}
} catch (exception: Exception) {
println("RemoteSource amsat status exception: $exception")
null
}
}
override suspend fun getNetworkStream(url: String): InputStream? = withContext(dispatcher) {
override suspend fun getNetworkBytes(url: String): ByteArray? = 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@withContext null
ByteArrayInputStream(response.body.bytes())
if (!response.isSuccessful) return@use null
response.body.bytes()
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
println("RemoteSource network stream exception: $exception")
null
}
}
override suspend fun getAmSatCatalog(): String? = withContext(dispatcher) {
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/catalog.php")
.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 catalog exception: $exception")
null
}
}
override suspend fun getAmSatReports(hours: Int, limit: Int): String? = withContext(dispatcher) {
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")
.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 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")
null
}
}
}
@@ -56,8 +56,14 @@ class AudioCapture : IAudioCapture {
if (read > 0) emit(if (read == chunkSize) buffer.copyOf() else buffer.copyOfRange(0, read))
}
} finally {
recorder.stop()
recorder.release()
// 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() }
}
}.flowOn(Dispatchers.IO)
}
@@ -29,4 +29,8 @@ class ShowToast(private val context: Context) : IShowToast {
override fun invoke(resId: Int) {
invoke(context.getString(resId))
}
override fun invoke(resId: Int, vararg formatArgs: Any) {
invoke(context.getString(resId, *formatArgs))
}
}
@@ -0,0 +1,307 @@
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)
}
}
@@ -0,0 +1,150 @@
/*
* 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
)
}
}
@@ -0,0 +1,130 @@
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
)
}
}
@@ -0,0 +1,407 @@
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)
}
}
}
@@ -0,0 +1,365 @@
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,6 +18,7 @@
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
@@ -40,7 +41,6 @@ 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 {
fileStreams[uri] = { validCsvStream() }
fileData[uri] = { validCsvBytes() }
}
val settingsRepo = FakeSettingsRepo()
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
@@ -71,7 +71,7 @@ class DatabaseRepoTest {
val uri = "content://look4sat/import/legacy"
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
fileStreams[uri] = { validTleStream() }
fileData[uri] = { validTleBytes() }
}
val settingsRepo = FakeSettingsRepo()
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
@@ -87,7 +87,7 @@ class DatabaseRepoTest {
val customCsvUrl = "https://example.com/custom-omm.csv"
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[customCsvUrl] = { validCsvStream() }
networkData[customCsvUrl] = { validCsvBytes() }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
@@ -102,29 +102,129 @@ class DatabaseRepoTest {
repository.updateFromRemote()
assertTrue(localSource.insertedEntries.any { it.catnum == 25544 })
// New semantics: switch on + non-empty URL -> the All source uses the custom URL, data lands in the All type
assertEquals(listOf(25544), settingsRepo.satelliteTypeIdsByType["All"])
// 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"])
}
private fun validCsvStream(): InputStream = """
/** 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 = """
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().byteInputStream()
""".trimIndent().encodeToByteArray()
private fun validTleStream(): InputStream = """
private fun validTleBytes(): ByteArray = """
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().byteInputStream()
""".trimIndent().encodeToByteArray()
}
private class FakeRemoteSource : IRemoteSource {
val fileStreams: MutableMap<String, () -> InputStream> = mutableMapOf()
val networkStreams: MutableMap<String, () -> InputStream> = mutableMapOf()
val fileData: MutableMap<String, () -> ByteArray> = mutableMapOf()
val networkData: MutableMap<String, () -> ByteArray> = mutableMapOf()
override suspend fun getFileStream(uri: String): InputStream? = fileStreams[uri]?.invoke()
/** Every URL asked for, so a test can assert WHICH sources were fetched, not just the result. */
val requestedUrls = mutableListOf<String>()
override suspend fun getNetworkStream(url: String): InputStream? = networkStreams[url]?.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
}
private class FakeLocalSource : ILocalSource {
@@ -166,10 +266,10 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
override val selectedIds: StateFlow<List<Int>> = MutableStateFlow(emptyList())
override val selectedTypes: StateFlow<List<String>> = MutableStateFlow(emptyList())
override val selectedSatModes: StateFlow<List<String>> = MutableStateFlow(emptyList())
override val passesSettings: StateFlow<PassesSettings> = MutableStateFlow(
PassesSettings(hoursAhead = 24, minElevation = 0.0, selectedModes = emptyList())
PassesSettings(hoursAhead = 24, minElevation = 0.0)
)
override val stationPosition: StateFlow<GeoPos> = MutableStateFlow(GeoPos(0.0, 0.0))
@@ -177,7 +277,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, "", "", "", false, "", "", "", false, "", "")
RCSettings(false, "", "", "", false, "", "", "", 0L, false, "", "", "", false, "", "")
)
override val otherSettings: StateFlow<OtherSettings> = MutableStateFlow(
@@ -194,13 +294,13 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
override fun setSelectedIds(ids: List<Int>) = Unit
override fun setSelectedTypes(types: List<String>) = Unit
override fun setSelectedSatModes(modes: List<String>) = Unit
override fun setPassesSettings(settings: PassesSettings) = Unit
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
override fun setStationPosition(): Boolean = true
override suspend fun setStationPosition(): Boolean = true
override fun setStationPosition(locator: String): Boolean = true
@@ -223,6 +323,10 @@ 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 {
@@ -0,0 +1,181 @@
/*
* 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.repository
import com.rtbishop.look4sat.core.domain.model.DataSourcesSettings
import com.rtbishop.look4sat.core.domain.model.DatabaseState
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.SatItem
import com.rtbishop.look4sat.core.domain.model.SatRadio
import com.rtbishop.look4sat.core.domain.predict.GeoPos
import com.rtbishop.look4sat.core.domain.predict.OrbitalObject
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import com.rtbishop.look4sat.core.domain.source.ILocalSource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class SelectionRepoTest {
private val dispatcher = StandardTestDispatcher()
@Test
fun `unknown mode values do not crash and do not filter out entries`() = runTest(dispatcher) {
val localSource = FakeLocalSource(
entries = listOf(
SatItem(25544, "ISS (ZARYA)", false),
SatItem(40967, "TIANGONG", false)
)
)
val settingsRepo = FakeSettingsRepo(selectedModes = listOf("REMOVED_MODE"))
val repository = SelectionRepo(dispatcher, localSource, settingsRepo)
val flow = repository.getEntriesFlow()
repository.setModes(listOf("REMOVED_MODE"))
val items = flow.first()
assertEquals(listOf(25544, 40967), items.map { it.catnum })
assertEquals(listOf("REMOVED_MODE"), repository.getCurrentModes())
}
@Test
fun `selected satellites are shown first`() = runTest(dispatcher) {
val localSource = FakeLocalSource(
entries = listOf(
SatItem(44444, "Zeta", false),
SatItem(25544, "Alpha", false),
SatItem(40967, "Beta", false)
)
)
val settingsRepo = FakeSettingsRepo(selectedModes = emptyList())
val repository = SelectionRepo(dispatcher, localSource, settingsRepo)
val flow = repository.getEntriesFlow()
repository.setSelection(listOf(40967), true)
val items = flow.first()
assertEquals(listOf(40967, 25544, 44444), items.map { it.catnum })
assertEquals(listOf(true, false, false), items.map { it.isSelected })
}
private class FakeLocalSource(
private val entries: List<SatItem>
) : ILocalSource {
override suspend fun getEntriesTotal(): Int = entries.size
override suspend fun getEntriesList(): List<SatItem> = entries
override suspend fun getEntriesWithIds(ids: List<Int>): List<OrbitalObject> = emptyList()
override suspend fun insertEntries(entries: List<com.rtbishop.look4sat.core.domain.predict.OrbitalData>) = Unit
override suspend fun deleteEntries() = Unit
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = emptyList()
override suspend fun getRadiosTotal(): Int = 0
override suspend fun getRadiosWithId(id: Int): List<SatRadio> = emptyList()
override suspend fun insertRadios(radios: List<SatRadio>) = Unit
override suspend fun deleteRadios() = Unit
}
private class FakeSettingsRepo(
selectedModes: List<String>
) : ISettingsRepo {
override val appVersionName: String = "test"
override val selectedIds: StateFlow<List<Int>> = MutableStateFlow(emptyList())
override val selectedSatModes: MutableStateFlow<List<String>> = MutableStateFlow(selectedModes)
override val passesSettings: StateFlow<PassesSettings> = MutableStateFlow(
PassesSettings(hoursAhead = 24, minElevation = 0.0)
)
override val stationPosition: StateFlow<GeoPos> = MutableStateFlow(GeoPos(0.0, 0.0))
override val databaseState: MutableStateFlow<DatabaseState> = MutableStateFlow(DatabaseState(0, 0, 0L))
override val rcSettings: StateFlow<RCSettings> = MutableStateFlow(
RCSettings(false, "", "", "", false, "", "", "", 0L, false, "", "", "", false, "", "")
)
override val otherSettings: StateFlow<OtherSettings> = MutableStateFlow(
OtherSettings(false, false, false, false, false, false, false, false)
)
override val dataSourcesSettings: StateFlow<DataSourcesSettings> = MutableStateFlow(
DataSourcesSettings(false, false, "", "")
)
override val radioControlSettings: StateFlow<RadioControlSettings> = MutableStateFlow(
RadioControlSettings(false, RadioControlSettings.MODEL_YAESU_FT817, "", "", "", "", 9600)
)
override fun setSelectedIds(ids: List<Int>) = Unit
override fun setSelectedSatModes(modes: List<String>) {
selectedSatModes.value = modes
}
override fun setPassesSettings(settings: PassesSettings) = Unit
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
override suspend 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
}
override fun updateRCSettings(settings: RCSettings) = Unit
override fun updateOtherSettings(transform: (OtherSettings) -> OtherSettings) = Unit
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
}
}
-5
View File
@@ -1,8 +1,3 @@
plugins {
alias(libs.plugins.convention.coreDomainPlugin)
}
dependencies {
// 编译期使用 org.json(构造/解析 WaveLog API 请求体); 运行时用 Android 系统自带的 org.json
compileOnly("org.json:json:20240303")
}
@@ -0,0 +1,156 @@
/*
* 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 = '-'
}
@@ -0,0 +1,140 @@
/*
* 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(',') ?: ""
}
}
@@ -2,6 +2,7 @@ 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).
@@ -21,12 +22,6 @@ object AprsPacket {
return hash and 0x7FFF
}
/** Login line: user CALL-SSID pass XXXX vers XXXX */
fun formatLogin(callsign: String, ssid: String, passcode: Int, version: String): String {
val callSsid = formatCallSsid(callsign, ssid)
return "user $callSsid pass $passcode vers $version"
}
/** Callsign-SSID join (BG7NTA + 5 -> BG7NTA-5) */
fun formatCallSsid(callsign: String, ssid: String): String {
if (ssid.isNullOrEmpty()) return callsign
@@ -35,20 +30,31 @@ object AprsPacket {
/** Optional distance filter: filter r/lat/lon/dist */
fun formatRangeFilter(latitude: Double, longitude: Double, distKm: Int): String {
return String.format("r/%.3f/%.3f/%d", latitude, longitude, distKm)
return formatString("r/%.3f/%.3f/%d", latitude, longitude, distKm)
}
/** Altitude extension /A=00000 (feet) */
/**
* 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 ""
return String.format("/A=%06d", (altitudeMeters * 3.2808399).toInt())
val feet = (altitudeMeters * 3.2808399).toInt().coerceIn(0, 999999)
return formatString("/A=%06d", feet)
}
/** Speed/course extension (knots/degrees) */
/**
* 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()
return String.format("/%03d/%03d", bearing.toInt(), knots)
val knots = (speedMps * 1.94384449).toInt().coerceIn(0, 999)
val course = ((bearing.toInt() % 360) + 360) % 360
return formatString("/%03d/%03d", course, knots)
}
}
@@ -100,17 +106,17 @@ class AprsPosition(
val hundredths = iRound % 100
val frac = when (positionAmbiguity) {
1 -> " . "
2 -> String.format("%d . ", minutes / 10)
3 -> String.format("%02d. ", minutes)
4 -> String.format("%02d.%d ", minutes, hundredths / 10)
else -> String.format("%02d.%02d", minutes, hundredths)
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'
String.format("%02d%s%c", degrees, frac, ns)
formatString("%02d%s%c", degrees, frac, ns)
} else {
val ew = if (value >= 0) 'E' else 'W'
String.format("%03d%s%c", degrees, frac, ew)
formatString("%03d%s%c", degrees, frac, ew)
}
}
}
@@ -0,0 +1,101 @@
/*
* 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
}
@@ -0,0 +1,81 @@
/*
* 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)
}
}
@@ -0,0 +1,195 @@
/*
* 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)
}
}
}
@@ -0,0 +1,61 @@
/*
* 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()
}
}
@@ -0,0 +1,140 @@
/*
* 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)
}
}
@@ -0,0 +1,242 @@
/*
* 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
}
}
}
@@ -0,0 +1,88 @@
/*
* 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
}
}
@@ -0,0 +1,115 @@
/*
* 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
}
}
@@ -0,0 +1,323 @@
/*
* 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
}
@@ -0,0 +1,98 @@
/*
* 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()
}
@@ -15,11 +15,9 @@
* 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
package com.rtbishop.look4sat.core.domain.model
interface IShowToast {
operator fun invoke(message: String)
/** Show by resource ID (four-language text) */
operator fun invoke(resId: Int)
object Constants {
const val FREQ_OFFSET_MIN_HZ = -50_000L
const val FREQ_OFFSET_MAX_HZ = 50_000L
}
@@ -23,10 +23,11 @@ data class SatDay(
val slots: List<SatSlot> // 12 槽(00-02 ... 22-24)
)
/** One satellite, 6 days of state */
/** One satellite, 3 days of state */
data class SatStatus(
val name: String, // "AO-123_[FM]"
val days: List<SatDay> // 6 天(新→旧)
val days: List<SatDay>, // 3 天(新→旧)
val summaryCount: Int = 0 // 0 means unknown; used for data-completeness marking
)
/** Overall page parse result */
@@ -29,8 +29,7 @@ data class PassesSettings(
val minElevation: Double,
val aosStartMinute: Int = 0,
val aosEndMinute: Int = 23 * 60 + 59,
val invertAosTimeWindow: Boolean = false,
val selectedModes: List<String>
val invertAosTimeWindow: Boolean = false
)
data class RCSettings(
@@ -42,6 +41,7 @@ data class RCSettings(
val frequencyAddress: String,
val frequencyPort: String,
val frequencyFormat: String,
val frequencyOffsetHz: Long = 0L,
val bluetoothRotatorState: Boolean,
val bluetoothRotatorFormat: String,
val bluetoothRotatorName: String,
@@ -73,7 +73,25 @@ data class OtherSettings(
val wavelogUrl: String = "",
val wavelogApiKey: String = "",
val wavelogStationId: String = "",
val wavelogAutoUpload: Boolean = false
val wavelogAutoUpload: Boolean = false,
// Upstream radar compass offset (merged from rt-bishop)
val radarCompassOffset: Float = 0f,
val radarCompassOffsetElev: Float = 0f,
/**
* Shift a CW tone that sits outside the model's 400-1200 Hz analysis window into
* it before decoding. Off by default: when disabled the audio path is unchanged,
* and a tone already inside the window is never touched either way.
*/
val cwToneShiftEnabled: Boolean = false,
/**
* Draw each AMSAT day as twelve two-hour stripes rather than one colour.
*
* On by default: a single colour is taken from the first slot with a report, so a
* satellite that worked all morning and failed all afternoon looks identical to one
* that worked once. Some operators prefer the older, simpler tile, hence the switch.
*/
val amsatDayStripes: Boolean = true
)
data class DataSourcesSettings(
@@ -0,0 +1,143 @@
/*
* 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
}
}
@@ -424,8 +424,12 @@ object CelestialComputer {
}
if (sunrise == 0.0) sunrise = daynum
// Phase 4: fast-forward through the day until sun drops back below threshold
daynum = sunrise
// Phase 4: fast-forward through the day until sun drops back below threshold.
// Start from just after sunrise (small offset) so the sun is clearly above
// the threshold. This prevents a bug where Phase 3 converges to a point
// slightly below -threshold, causing Phase 4 to skip and Phase 5 to converge
// to the same time as sunrise, producing identical sunrise/sunset times.
daynum = sunrise + 0.001
sunPos = getSunPosition(observer, daynumToMillis(daynum))
guard = 0
while (sunPos.elevation > -threshold && guard++ < 500) {
@@ -0,0 +1,45 @@
/*
* 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?
}
@@ -0,0 +1,106 @@
/*
* 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}" }
}
}
@@ -35,6 +35,7 @@ interface IMainContainer {
val mutualPassData: StateFlow<MutualPassData>
fun setMutualPassData(data: MutualPassData)
fun provideAddToCalendar(): IAddToCalendar
fun providePairedBluetoothDevices(): List<Pair<String, String>>
fun provideShowToast(): IShowToast
fun provideBluetoothReporter(): IReporter
fun provideNetworkReporter(): IReporter
@@ -42,12 +43,16 @@ interface IMainContainer {
fun provideTxRadioController(): IRadioController
fun provideRxRadioController(): IRadioController
fun provideAudioCapture(): IAudioCapture
fun provideCwDecoder(): com.rtbishop.look4sat.core.domain.cw.ICwDecoder
fun provideSaveImage(): ISaveImage
// WaveLog logging (4.5.2)
val wavelogQueue: com.rtbishop.look4sat.core.domain.wavelog.WavelogQueue
fun provideWavelogUploader(): com.rtbishop.look4sat.core.domain.wavelog.WavelogUploader
fun provideLotwSatellitesRepo(): com.rtbishop.look4sat.core.domain.wavelog.ILotwSatellitesRepo
/** QRZ grid lookup, so the log screen never touches the stored cookie itself. */
fun provideQrzGridLookup(): com.rtbishop.look4sat.core.domain.qrz.IQrzGridLookup
}
data class MutualPassData(
@@ -21,10 +21,10 @@ import com.rtbishop.look4sat.core.domain.model.SatItem
import kotlinx.coroutines.flow.Flow
interface ISelectionRepo {
fun getCurrentTypes(): List<String>
fun getTypesList(): List<String>
fun getCurrentModes(): List<String>
fun getModesList(): List<String>
suspend fun getEntriesFlow(): Flow<List<SatItem>>
suspend fun setTypes(types: List<String>)
suspend fun setModes(modes: List<String>)
suspend fun setQuery(query: String)
suspend fun setSelection(selectAll: Boolean)
suspend fun setSelection(ids: List<Int>, isTicked: Boolean)
@@ -19,10 +19,16 @@ package com.rtbishop.look4sat.core.domain.repository
import com.rtbishop.look4sat.core.domain.predict.GeoPos
import kotlinx.coroutines.flow.StateFlow
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
@OptIn(ExperimentalTime::class)
interface ISensorsRepo {
val sensorData: StateFlow<Pair<Float, Float>>
fun getMagDeclination(geoPos: GeoPos, time: Long = System.currentTimeMillis()): Float
// The default used to be System.currentTimeMillis(), which Kotlin/Native does not have;
// kotlin.time.Clock is the multiplatform equivalent.
fun getMagDeclination(geoPos: GeoPos, time: Long = Clock.System.now().toEpochMilliseconds()): Float
fun enableSensor()
fun disableSensor()
}
@@ -32,9 +32,9 @@ interface ISettingsRepo {
//region # Satellites selection settings
val selectedIds: StateFlow<List<Int>>
val selectedTypes: StateFlow<List<String>>
val selectedSatModes: StateFlow<List<String>>
fun setSelectedIds(ids: List<Int>)
fun setSelectedTypes(types: List<String>)
fun setSelectedSatModes(modes: List<String>)
//endregion
//region # Passes filter settings
@@ -78,4 +78,9 @@ interface ISettingsRepo {
val radioControlSettings: StateFlow<RadioControlSettings>
fun updateRadioControlSettings(settings: RadioControlSettings)
//endregion
//region # Per-satellite calculator offset settings
fun getSatelliteOffset(catnum: Int): String
fun setSatelliteOffset(catnum: Int, offset: String)
//endregion
}
@@ -17,12 +17,12 @@
*/
package com.rtbishop.look4sat.core.domain.source
import java.io.InputStream
interface IRemoteSource {
suspend fun getFileStream(uri: String): InputStream?
suspend fun getNetworkStream(url: String): InputStream?
/** Fetch AMSAT status page HTML (with UA; null = failure) */
suspend fun getStatusHtml(): String?
/** 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)
@@ -0,0 +1,34 @@
/*
* 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?
}
@@ -52,6 +52,15 @@ object Sources {
"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"
)
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff. Show more