Author SHA1 Message Date
piotr 903c5c69b6 feat: add bounded display_diag journal diagnostics for the OSD (#3) 2026-11-24 15:24:39 +01:00
piotr 5d067ee82d fix: bound the event drain so the OSD timer punch survives storms (#3) 2026-11-06 16:37:39 +01:00
piotr b7e054e949 fix: build blank cursor from depth-1 bitmaps and check window creation (#3) 2026-11-05 14:56:16 +01:00
piotr 296569232e fix: hide cursor natively, keep OSD on top, pin codec extension contract (#3) 2026-11-03 22:49:36 +01:00
piotr 3d6d146007 feat: keep OSD always visible with pre-map fullscreen states (#3) 2026-11-03 13:11:15 +01:00
piotr 79ea5d62b7 feat: publish adaptive-link OSD contract and keep overlay above video (#3) 2026-10-18 08:02:18 +02:00
piotr f0d5052ccb feat: render minimal flight OSD from supervisor snapshots (#3) 2026-10-17 08:49:01 +02:00
piotr ffae3560c4 fix: resolve reply-bearing X11 liveness cookies with Reply (#2)
Build Ground Station / build (push) Successful in 26s
2026-10-02 10:42:07 +02:00
piotr 2ced44b47b feat: log structured reconnect diagnostics for kiosk display layers (#2)
Build Ground Station / build (push) Successful in 1m2s
2026-10-02 10:23:28 +02:00
piotr 41552b4797 feat: split kiosk into fallback canvas and OSD overlay layers (#8)
Build Ground Station / build (push) Successful in 37s
Drive two independent visual layers per display target from one shared
video presence signal: the fullscreen fallback/menu canvas below video
and a transparent, input-transparent OSD overlay above video, reserved
as the future flight OSD rendering surface. WFB and video decode stay
out of the UI process; pilot video keeps rendering priority.
2026-10-02 10:02:34 +02:00
piotr 056cd5440a docs: explain Ground Station artifact components
Build Ground Station / build (push) Successful in 35s
2026-10-01 15:40:23 +02:00
piotr d3bc369164 fix: set 115200 baud via CBAUD bits and verify readback on UART open (#10)
Build Ground Station / build (push) Successful in 38s
2026-10-01 15:26:24 +02:00
piotr b169a64ad5 feat: show no-WFB kiosk fallback only while video absent (#2)
Build Ground Station / build (push) Successful in 44s
2026-10-01 14:40:24 +02:00
31 changed files with 5419 additions and 117 deletions
+81 -25
View File
@@ -1,44 +1,100 @@
# Ground Station
Orange Pi Zero 3W application for the custom OpenIPC/WFB ground station.
Orange Pi Zero 3W supervisor and kiosk display for the custom OpenIPC/WFB ground station.
## Current baseline
## Components
- receives framed GX12 RC channel data over the dedicated AUX1 UART at 115200 8N1;
The ARM64 artifact intentionally contains two executables:
- `groundstation-linux-arm64` — the long-running root supervisor. It owns the GX12 UART, logging, RC state, video lifecycle, and starts the display process.
- `groundstation-display-linux-arm64` — the unprivileged X11 kiosk renderer. It runs as `orangepi` on `DISPLAY=:0`; the supervisor owns it during normal use.
Current capabilities:
- receives framed GX12 RC channel data at 115200 8N1;
- validates protocol version, frame length and CRC-16;
- logs final mixed channel values;
- starts an independent kiosk display process that maps a fullscreen black canvas on `DISPLAY=:0` before video, tolerates X11 downtime without restarting the supervisor, and stops deterministically on shutdown;
- video keeps rendering priority: the kiosk canvas stays below the `fpv-video` window, and future display targets (MIPI/touch) get their own target-specific templates instead of one global layout.
- logs channel changes instead of every frame;
- starts/stops `fpv-video` from the configured CH6 power/lifecycle control;
- publishes immutable flight OSD snapshots — final RC channels, arm state
derived from the configured arm channel, the adaptive-link contract values
(operator target table, temporary CH6 maxPower ceiling, requested runtime
level, VTX acknowledgment, observed link — pending/unknown until their
producers exist) and decoded-video presence — to a tmpfs state file
without ever blocking the UART, WFB or video paths; unchanged state is
republished as a heartbeat and the file is removed on shutdown;
- starts an independent kiosk display before video, tolerates temporary X11 downtime without restarting the supervisor, and stops deterministically on shutdown;
- keeps the fullscreen fallback/menu canvas below `fpv-video`, showing `Brak połączenia WFB` only while video is absent;
- maps a transparent, input-transparent OSD overlay above `fpv-video` as the flight OSD rendering surface: it never intercepts video input, and it punches its output shape only around the text it draws;
- renders the flight OSD from startup on the transparent overlay — on top of the no-video fallback presentation and above fullscreen video alike: the arm state, the compact adaptive-link line, and an explicit VIDEO ON/OFF line sourced from the display-observed video lifecycle; before any snapshot has arrived it shows explicit NO DATA / unknown marks, and a snapshot beyond the freshness window stays visible marked DATA STALE instead of being presented as current — refreshing on a slower cadence than the video so the pilot stream keeps priority.
The first baseline is intentionally small. It does **not** yet control an AUX, manipulate the flight-control link, or replace the primary video pipeline.
Future MIPI/touch targets use their own templates rather than sharing one global layout. The flight OSD renders on the existing transparent layer above video, preserving the pilot stream's priority.
## Run
## Installation on Orange Pi
Extract the artifact and install **both** files:
```bash
# Supervisor (YAML configuration, default /etc/groundstation/config.yml;
# hardware UART paths live in the config file)
groundstation -config /etc/groundstation/config.yml
sudo install -m 0755 groundstation-linux-arm64 /usr/local/bin/groundstation
sudo install -m 0755 groundstation-display-linux-arm64 /usr/local/bin/groundstation-display
sudo systemctl restart groundstation
```
# Test input mode
groundstation -stdin
Check logs:
# Kiosk canvas alone (the supervisor starts it; standalone for debugging)
```bash
systemctl status groundstation --no-pager
journalctl -u groundstation -b --no-pager -n 80
```
Do not run `groundstation-display` by hand during normal operation. It needs the X11 user/session environment and is managed by the supervisor. For isolated renderer debugging it supports:
```bash
groundstation-display -target x11
```
## Configuration
The service reads `/etc/groundstation/config.yml`. For the verified permanent GX12 connection, use:
```yaml
serial:
path: /dev/ttyS2
```
`/dev/ttyS0` is the Orange Pi boot/debug UART and must not be used for the permanently connected GX12.
The flight OSD is configured alongside:
```yaml
osd:
state_path: /run/groundstation/osd-state.bin
arm_index: 4 # CH5/AUX1, zero-based
armed_threshold: 0 # armed while the arm channel stays above this
vtx_table_gen: 0 # operator-selected VTX table (0 = none selected)
vtx_table_hash: 0
```
CH6 acts only as the temporary operator maxPower ceiling and static
configuration is never applied VTX state. `groundstation-display` reads the
same state file; both sides must agree on
the path (override the renderer's with `groundstation-display -osd-state
<path>` if you change `osd.state_path`). The state file carries only flight
telemetry and never any credentials or keys.
## Runtime dependencies
- an X11 session on `:0` owned by the `orangepi` desktop user (the kiosk waits for X11 to appear and reconnects after display-manager restarts);
- `wmctrl` for the fullscreen/below kiosk window state — without it the canvas still maps but stays a plain window (logged);
- `runuser` from util-linux (base install) for the unprivileged kiosk launch.
- X11 session on `:0` owned by `orangepi`; the kiosk waits for X11 and reconnects after display-manager restarts;
- `wmctrl` for the fullscreen/stacking kiosk window states; without it the kiosk windows map as normal windows and the condition is logged;
- `runuser` from util-linux for the unprivileged kiosk launch.
## Protocol
## Diagnostics
The v1 protocol is described in `AGENTS.md` once the repository policy file is approved. It carries 16 final EdgeTX channel outputs as a binary framed message with CRC.
The display process emits a bounded, state-transition-driven `display_diag`
journal stream (open, first redraw, actual shape/geometry/stacking query,
snapshot/video/stack transitions, reconnects, one close summary) — never
per-frame or per-refresh spam, never RC channel values or telemetry
payloads. To collect the current boot's diagnostic lines for a bug report:
## Project direction
1. GX12 Ground Station UART mode sends final RC/switch state to Orange Pi.
2. Orange Pi logs and renders state while supervising the FPV video launcher.
3. Add WFB quality, recorder state, and MIPI touch display independently of pilot video.
4. Add a watchdog-protected override of exactly one reserved `SAFE/NORMAL/HIGH` AUX.
```bash
journalctl -u groundstation -b --no-pager | grep display_diag | tail -60
```
+79 -12
View File
@@ -1,4 +1,4 @@
// Command groundstation-display renders the Ground Station kiosk canvas. It
// Command groundstation-display renders the Ground Station kiosk layers. It
// owns its display lifecycle independently of WFB, the transmitter and the
// video launcher: it waits for its target to appear, redraws as needed, and
// stops only when it receives SIGINT or SIGTERM.
@@ -11,37 +11,104 @@ import (
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"git.piksar.eu/piotr/groundstation/internal/display"
"git.piksar.eu/piotr/groundstation/internal/osd"
)
// buildTarget selects the target-specific opener and template. Each target
// owns its own backend and layouts; there is no shared global template.
func buildTarget(name string) (display.Opener, display.Template, error) {
// osdRefresh is the OSD overlay's redraw cadence, deliberately slower than
// the video: newly published flight snapshots appear without waiting for X
// events while the video window keeps rendering priority.
const osdRefresh = time.Second
// buildTarget selects the target-specific layers. Each target owns its own
// backend and layouts; there is no shared global template. The Viture target
// builds two independent layers — the fullscreen fallback/menu canvas below
// video and the transparent OSD overlay above it — wired to one shared video
// presence signal: the sessions observe the video output lifecycle on the
// display server and the templates draw or hide from it. The OSD layer also
// consumes the supervisor-published flight snapshots and refreshes on its
// own slower cadence. WFB and video decode never move into this process.
func buildTarget(name string, osdState string, diag *display.Diag) ([]display.Layer, error) {
switch name {
case "x11":
return display.X11Opener{}, display.NewStatusTemplate("Brak polaczenia WFB"), nil
video := display.NewVideoPresence()
return []display.Layer{
{
Name: "fallback-canvas",
Opener: display.X11Opener{Video: video, Diag: diag},
Template: display.NewFallbackTemplate(video, "Brak połączenia WFB"),
},
{
Name: "osd-overlay",
Opener: display.X11Opener{
Video: video,
Diag: diag,
Role: display.RoleAbove,
RefreshInterval: osdRefresh,
},
Template: display.NewOSDTemplate(video, osd.NewFileSource(osdState)),
},
}, nil
default:
return nil, nil, fmt.Errorf("unknown display target %q (supported: x11)", name)
return nil, fmt.Errorf("unknown display target %q (supported: x11)", name)
}
}
// wireDiagnostics gives every layer the shared structured reconnect hook so
// each layer reports its own reconnect boundaries, identified by target and
// layer name.
func wireDiagnostics(target string, layers []display.Layer) {
for i := range layers {
layers[i].Options = display.Options{
Target: target,
Layer: layers[i].Name,
Diagnostic: func(d display.Diagnostic) {
log.Printf("%s", formatDiagnostic(d))
},
}
}
}
// formatDiagnostic renders one reconnect boundary as a display_diag
// journal record in the shared bounded schema.
func formatDiagnostic(d display.Diagnostic) string {
return display.FormatDiagLine("reconnect", d.Layer,
"target="+d.Target,
"event="+d.Event,
fmt.Sprintf("retry_delay=%s", d.RetryDelay),
fmt.Sprintf("error=%q", d.Err))
}
func main() {
target := flag.String("target", "x11", "display target: x11 (Viture) today; mipi planned")
osdState := flag.String("osd-state", osd.DefaultStatePath,
"OSD snapshot state file published by the groundstation supervisor")
flag.Parse()
opener, template, err := buildTarget(*target)
// The bounded display_diag journal stream: process start with PID and
// embedded VCS revision, then per-role open, first redraw, query,
// state-transition and summary records. Written to standard output,
// which the systemd unit carries into the journal.
diag := display.NewDiag(os.Stdout)
diag.EmitForced("start", "",
"pid="+strconv.Itoa(os.Getpid()),
"vcs="+display.VCSRevision())
layers, err := buildTarget(*target, *osdState, diag)
if err != nil {
log.Fatal(err)
}
wireDiagnostics(*target, layers)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Temporary X11 unavailability never exits this process; display.Run
// keeps retrying internally until the context is cancelled.
if err := display.Run(ctx, opener, template, display.Options{}); err != nil {
log.Fatalf("display: %v", err)
}
// Temporary X11 unavailability never exits this process; every layer
// keeps retrying internally until the context is cancelled, reporting
// each reconnect boundary through the structured diagnostic hook.
display.RunLayers(ctx, layers)
}
+187
View File
@@ -0,0 +1,187 @@
package main
import (
"errors"
"path/filepath"
"testing"
"time"
"git.piksar.eu/piotr/groundstation/internal/display"
"git.piksar.eu/piotr/groundstation/internal/osd"
)
type recordingCanvas struct {
width, height int
lines []string
clears, flushes int
}
func (c *recordingCanvas) Size() (int, int) { return c.width, c.height }
func (c *recordingCanvas) Clear() { c.clears++ }
func (c *recordingCanvas) Text(_, _ int, message string) {
c.lines = append(c.lines, message)
}
func (c *recordingCanvas) Flush() { c.flushes++ }
func TestBuildTargetBuildsIndependentVitureLayers(t *testing.T) {
layers, err := buildTarget("x11", filepath.Join(t.TempDir(), "osd-state.bin"), nil)
if err != nil {
t.Fatal(err)
}
if len(layers) != 2 {
t.Fatalf("layers=%d want the fallback canvas and the OSD overlay", len(layers))
}
canvas, osdLayer := layers[0], layers[1]
if canvas.Name != "fallback-canvas" || osdLayer.Name != "osd-overlay" {
t.Fatalf("layer names %q/%q want fallback-canvas/osd-overlay", canvas.Name, osdLayer.Name)
}
canvasOpener, ok := canvas.Opener.(display.X11Opener)
if !ok {
t.Fatalf("canvas opener %T must be the X11 target", canvas.Opener)
}
if canvasOpener.Role != display.RoleBelow {
t.Fatalf("canvas layer role %v must stay below video", canvasOpener.Role)
}
osdOpener, ok := osdLayer.Opener.(display.X11Opener)
if !ok {
t.Fatalf("OSD opener %T must be the X11 target", osdLayer.Opener)
}
if osdOpener.Role != display.RoleAbove {
t.Fatalf("OSD layer role %v must stay above video", osdOpener.Role)
}
// The OSD refreshes on its own slower cadence; the canvas stays purely
// event-driven.
if osdOpener.RefreshInterval <= 0 {
t.Fatal("the OSD overlay must redraw on its own refresh interval")
}
if canvasOpener.RefreshInterval != 0 {
t.Fatal("the fallback canvas must keep its event-driven redraws")
}
// Both layers must share one presence signal so the video lifecycle
// observed by either session drives both templates.
if canvasOpener.Video == nil || osdOpener.Video == nil || canvasOpener.Video != osdOpener.Video {
t.Fatal("layers must share one video presence signal")
}
// The canvas layer keeps the target-specific fallback template with the
// exact fallback text; the OSD layer shows explicit state without a
// snapshot. Both layers are fullscreen at startup with no video — the
// canvas below (RoleBelow) and the OSD above (RoleAbove), per the
// display package's fullscreen-args contract.
canvasSurface := &recordingCanvas{width: 800, height: 600}
canvas.Template.Draw(canvasSurface)
if len(canvasSurface.lines) != 1 || canvasSurface.lines[0] != "Brak połączenia WFB" {
t.Fatalf("canvas lines=%q want the exact fallback text", canvasSurface.lines)
}
osdSurface := &recordingCanvas{width: 800, height: 600}
osdLayer.Template.Draw(osdSurface)
wantStartup := []string{"NO DATA", "VTX tbl:-- ceil:-- req:-- ack:--", "VIDEO OFF"}
if len(osdSurface.lines) != len(wantStartup) {
t.Fatalf("OSD lines=%q want the explicit startup state %q", osdSurface.lines, wantStartup)
}
for i := range wantStartup {
if osdSurface.lines[i] != wantStartup[i] {
t.Fatalf("line %d=%q want %q", i, osdSurface.lines[i], wantStartup[i])
}
}
// Video presence hides the fallback on the canvas layer only.
canvasOpener.Video.SetActive(true)
canvasSurface.lines = nil
canvas.Template.Draw(canvasSurface)
if len(canvasSurface.lines) != 0 {
t.Fatalf("canvas lines=%q must disappear while video is present", canvasSurface.lines)
}
canvasOpener.Video.SetActive(false)
}
func TestBuildTargetOSDLayerRendersPublishedSnapshots(t *testing.T) {
state := filepath.Join(t.TempDir(), "run", "osd-state.bin")
publisher := osd.NewFilePublisher(state, nil)
defer publisher.Close()
snapshot := osd.Snapshot{
Sequence: 11,
Armed: true,
OpConfig: osd.OperatorConfig{MaxPower: 95},
Policy: osd.GSPolicy{Pending: true},
Ack: osd.VTXAck{Pending: true, Lifecycle: osd.VTXLifecyclePending},
Link: osd.GSObservedLink{Known: false},
}
publisher.Publish(snapshot)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if _, err := osd.DecodeFile(state); err == nil {
break
}
time.Sleep(time.Millisecond)
}
layers, err := buildTarget("x11", state, nil)
if err != nil {
t.Fatal(err)
}
osdLayer := layers[1]
osdOpener := osdLayer.Opener.(display.X11Opener)
osdOpener.Video.SetActive(true)
surface := &recordingCanvas{width: 800, height: 600}
osdLayer.Template.Draw(surface)
want := []string{"ARM ARMED", "VTX tbl:-- ceil:95 req:-- ack:--", "VIDEO ON"}
if len(surface.lines) != len(want) {
t.Fatalf("OSD lines=%q want %q from the supervisor-published snapshot", surface.lines, want)
}
for i := range want {
if surface.lines[i] != want[i] {
t.Fatalf("line %d=%q want %q", i, surface.lines[i], want[i])
}
}
}
func TestBuildTargetRejectsUnknownTarget(t *testing.T) {
if _, err := buildTarget("hdmi-mirror", "", nil); err == nil {
t.Fatal("unknown target must fail")
}
}
func TestFormatDiagnosticRendersStructuredFields(t *testing.T) {
got := formatDiagnostic(display.Diagnostic{
Target: "x11",
Layer: "fallback-canvas",
Event: display.EventOpenFailed,
Err: errors.New("connect X11: refused"),
RetryDelay: 500 * time.Millisecond,
})
want := `display_diag kind=reconnect role=fallback-canvas target=x11 event=open_failed retry_delay=500ms error="connect X11: refused"`
if got != want {
t.Fatalf("formatDiagnostic=%q want %q", got, want)
}
}
func TestWireDiagnosticsTagsEveryLayerWithItsName(t *testing.T) {
layers, err := buildTarget("x11", filepath.Join(t.TempDir(), "osd-state.bin"), nil)
if err != nil {
t.Fatal(err)
}
wireDiagnostics("x11", layers)
for _, layer := range layers {
if layer.Options.Target != "x11" {
t.Fatalf("layer %q target=%q want x11", layer.Name, layer.Options.Target)
}
if layer.Options.Layer != layer.Name {
t.Fatalf("layer %q diagnostic layer=%q", layer.Name, layer.Options.Layer)
}
if layer.Options.Diagnostic == nil {
t.Fatalf("layer %q must carry the reconnect diagnostic hook", layer.Name)
}
}
// The shared hook must be safe to call from any layer goroutine.
layers[0].Options.Diagnostic(display.Diagnostic{Target: "x11", Layer: layers[0].Name})
}
+25 -4
View File
@@ -15,6 +15,7 @@ import (
"time"
"git.piksar.eu/piotr/groundstation/internal/config"
"git.piksar.eu/piotr/groundstation/internal/osd"
"git.piksar.eu/piotr/groundstation/internal/protocol"
"git.piksar.eu/piotr/groundstation/internal/serialport"
)
@@ -68,8 +69,21 @@ func runMain() int {
defer func() { _ = video.Stop() }()
}
// The flight OSD snapshot publisher survives UART reconnects: the
// display keeps seeing the last state, refreshed as a heartbeat, and
// the state file is removed on shutdown so nothing stale renders.
var publisher *osd.Publisher
if cfg.OSD.StatePath != "" {
if err := os.MkdirAll(filepath.Dir(cfg.OSD.StatePath), 0755); err != nil {
logger.Printf("osd state dir: %v", err)
return 1
}
publisher = osd.NewFilePublisher(cfg.OSD.StatePath, logger)
defer publisher.Close()
}
if *stdin {
if err := run(ctx, os.Stdin, logger, video, cfg); err != nil && !errors.Is(err, context.Canceled) {
if err := run(ctx, os.Stdin, logger, video, cfg, publisher); err != nil && !errors.Is(err, context.Canceled) {
logger.Printf("stdin run: %v", err)
return 1
}
@@ -85,7 +99,7 @@ func runMain() int {
}
logger.Printf("UART connected: %s", cfg.Serial.Path)
err = run(ctx, port, logger, video, cfg)
err = run(ctx, port, logger, video, cfg, publisher)
_ = port.Close()
if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.EOF) {
logger.Printf("UART disconnected: %v", err)
@@ -121,7 +135,7 @@ func wait(ctx context.Context, duration time.Duration) {
}
}
func run(ctx context.Context, input io.Reader, logger *log.Logger, video *videoController, cfg config.Config) error {
func run(ctx context.Context, input io.Reader, logger *log.Logger, video *videoController, cfg config.Config, publisher *osd.Publisher) error {
buf := make([]byte, protocol.RCSize)
var previous *protocol.RCFrame
for {
@@ -134,11 +148,18 @@ func run(ctx context.Context, input io.Reader, logger *log.Logger, video *videoC
continue
}
active := frame.Channels[cfg.Video.AuxIndex] > cfg.Video.Threshold
if video != nil {
if err := video.Set(frame.Channels[cfg.Video.AuxIndex] > cfg.Video.Threshold); err != nil {
if err := video.Set(active); err != nil {
return err
}
}
// Publish the OSD snapshot after the video decision so the
// snapshot carries the launcher presence that resulted from it.
// Publish never blocks: the UART loop only stores and wakes.
if publisher != nil {
publisher.Publish(newSnapshot(frame, cfg, video))
}
if previous == nil || previous.Channels != frame.Channels {
logger.Printf("RC seq=%d t=%d channels=%v", frame.Sequence, frame.Timestamp, frame.Channels)
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"git.piksar.eu/piotr/groundstation/internal/config"
"git.piksar.eu/piotr/groundstation/internal/osd"
"git.piksar.eu/piotr/groundstation/internal/protocol"
)
// newSnapshot builds the immutable flight OSD snapshot from the latest
// valid RC frame: the final RC channels, the arm state derived from the
// configured arm channel, and the adaptive-link contract values. CH6 feeds
// only the temporary operator maxPower ceiling — it constrains what may be
// requested and is never proof of applied VTX power. The policy,
// acknowledgment and link producers (adaptive control, the VTX ack
// transport, WFB RX metrics) do not exist yet, so the snapshot carries
// their explicit pending/unknown states instead of fabricated data. The
// supervisor's decoded-video presence stays its launcher ownership.
// Building the snapshot is pure computation: publication never blocks the
// UART loop.
func newSnapshot(frame protocol.RCFrame, cfg config.Config, video *videoController) osd.Snapshot {
snapshot := osd.Snapshot{
Sequence: frame.Sequence,
TimestampMS: frame.Timestamp,
Channels: frame.Channels,
Armed: frame.Channels[cfg.OSD.ArmIndex] > cfg.OSD.ArmedThreshold,
OpConfig: osd.OperatorConfig{
Table: osd.Table{Gen: cfg.OSD.VtxTableGen, Hash: cfg.OSD.VtxTableHash},
MaxPower: osd.CeilingFromChannel(frame.Channels[cfg.Video.AuxIndex]),
},
Policy: osd.GSPolicy{Pending: true},
Ack: osd.VTXAck{Pending: true, Lifecycle: osd.VTXLifecyclePending},
Link: osd.GSObservedLink{Known: false},
}
if video != nil {
snapshot.Video = video.Running()
}
return snapshot
}
+207
View File
@@ -0,0 +1,207 @@
package main
import (
"bytes"
"context"
"errors"
"io"
"log"
"os/exec"
"testing"
"time"
"git.piksar.eu/piotr/groundstation/internal/config"
"git.piksar.eu/piotr/groundstation/internal/osd"
"git.piksar.eu/piotr/groundstation/internal/protocol"
)
func TestNewSnapshotDerivesArmCeilingAndContractStates(t *testing.T) {
cfg := config.Default()
cfg.OSD.VtxTableGen = 3
cfg.OSD.VtxTableHash = 0xcafe
frame := protocol.RCFrame{Sequence: 3, Timestamp: 42}
frame.Channels[4] = 512 // arm channel above the armed threshold
frame.Channels[5] = 100 // CH6 knob mid-range
frame.Channels[15] = -999 // untouched channel must stay unchanged
snapshot := newSnapshot(frame, cfg, nil)
if snapshot.Sequence != 3 || snapshot.TimestampMS != 42 {
t.Fatalf("snapshot=%+v must carry the frame provenance", snapshot)
}
if snapshot.Channels != frame.Channels {
t.Fatal("the snapshot must carry the final RC state unchanged")
}
if !snapshot.Armed {
t.Fatal("arm channel above the threshold must derive armed")
}
// CH6 is only the temporary operator maxPower ceiling, never applied
// VTX power.
if snapshot.OpConfig.MaxPower != osd.CeilingFromChannel(100) {
t.Fatalf("maxPower=%d want the CH6-derived ceiling", snapshot.OpConfig.MaxPower)
}
if snapshot.OpConfig.Table != (osd.Table{Gen: 3, Hash: 0xcafe}) {
t.Fatalf("table=%+v want the operator-selected table", snapshot.OpConfig.Table)
}
// No policy, acknowledgment or link producer exists yet: the snapshot
// must carry explicit pending/unknown states, never fabricated data.
if !snapshot.Policy.Pending || snapshot.Policy.Level != 0 {
t.Fatalf("policy=%+v must stay explicitly pending", snapshot.Policy)
}
if !snapshot.Ack.Pending || snapshot.Ack.Lifecycle != osd.VTXLifecyclePending {
t.Fatalf("ack=%+v must stay explicitly pending", snapshot.Ack)
}
if snapshot.Link.Known {
t.Fatalf("link=%+v must stay explicitly unknown", snapshot.Link)
}
if snapshot.Video {
t.Fatal("without a video launcher there is no decoded-video presence")
}
frame.Channels[4] = -256
frame.Channels[5] = -1000
snapshot = newSnapshot(frame, cfg, &videoController{cmd: &exec.Cmd{}, done: make(chan error, 1)})
if snapshot.Armed {
t.Fatal("arm channel below the threshold must derive disarmed")
}
if snapshot.OpConfig.MaxPower != osd.CeilingFromChannel(-1000) {
t.Fatalf("maxPower=%d must follow the CH6 knob", snapshot.OpConfig.MaxPower)
}
if !snapshot.Video {
t.Fatal("a running video launcher is the supervisor's decoded-video presence")
}
}
func TestRunningReportsVideoLauncherPresence(t *testing.T) {
video := newVideoController("fpv-video")
if video.Running() {
t.Fatal("a launcher never started must not report running")
}
video.cmd = &exec.Cmd{}
video.done = make(chan error, 1)
if !video.Running() {
t.Fatal("a live launcher must report running")
}
// A launcher that exited on its own stays recorded until the next Set;
// its completed wait must end its decoded-video presence.
video.done <- errors.New("exited")
if video.Running() {
t.Fatal("a launcher with a completed wait must not report running")
}
}
func TestRunningEndsWhenTheLauncherExitsOnItsOwn(t *testing.T) {
video := newVideoController("true")
if err := video.Set(true); err != nil {
t.Fatal(err)
}
// The launcher exits on its own; its pending wait result must end its
// decoded-video presence without anyone consuming the stop path's
// done signal.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if !video.Running() {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("a launcher that exited on its own must not report running")
}
func TestRunPublishesSnapshotsForValidFramesOnly(t *testing.T) {
cfg := config.Default()
first := protocol.RCFrame{Sequence: 1}
first.Channels[4] = 512
second := protocol.RCFrame{Sequence: 2}
second.Channels[4] = -256
second.Channels[5] = 100
var input bytes.Buffer
input.Write(protocol.EncodeRC(first))
input.Write([]byte("junk frame bytes that fail the CRC"))
input.Write(protocol.EncodeRC(second))
publisher := osd.NewPublisher()
if err := run(context.Background(), &input, log.New(io.Discard, "", 0), nil, cfg, publisher); !errors.Is(err, io.EOF) {
t.Fatalf("run=%v want clean EOF after the input ends", err)
}
got, ok := publisher.Latest()
if !ok {
t.Fatal("valid frames must publish snapshots")
}
if got.Sequence != 2 {
t.Fatalf("sequence=%d want the latest valid frame 2", got.Sequence)
}
if got.Armed {
t.Fatal("the latest frame's arm state must be disarmed")
}
if got.OpConfig.MaxPower != osd.CeilingFromChannel(100) {
t.Fatalf("maxPower=%d must follow the latest frame's CH6 knob", got.OpConfig.MaxPower)
}
if !got.Policy.Pending || !got.Ack.Pending || got.Link.Known {
t.Fatalf("contract values %+v/%+v/%+v must stay pending/unknown", got.Policy, got.Ack, got.Link)
}
if got.PublishedMS == 0 {
t.Fatal("the publisher must stamp the publication time")
}
}
func TestRunPublishesWithoutAConfiguredVideoLauncher(t *testing.T) {
cfg := config.Default()
frame := protocol.RCFrame{Sequence: 5}
frame.Channels[5] = 0
publisher := osd.NewPublisher()
if err := run(context.Background(),
bytes.NewReader(protocol.EncodeRC(frame)),
log.New(io.Discard, "", 0), nil, cfg, publisher); !errors.Is(err, io.EOF) {
t.Fatalf("run=%v want clean EOF", err)
}
got, ok := publisher.Latest()
if !ok {
t.Fatal("frames must publish even without a video launcher")
}
if got.OpConfig.MaxPower != osd.CeilingFromChannel(0) || got.Video {
t.Fatalf("snapshot=%+v must derive the ceiling without video presence", got)
}
}
func TestRunPublishNeverBlocksTheUARTPath(t *testing.T) {
// A burst of frames must be read and published with no waiting on the
// state-file writer: the publisher's Publish is non-blocking by design,
// so the loop over a large input returns promptly.
cfg := config.Default()
publisher := osd.NewFilePublisher("/proc/nonexistent/osd-state.bin", log.New(io.Discard, "", 0))
defer publisher.Close()
frame := protocol.RCFrame{Sequence: 1}
var input bytes.Buffer
for i := 0; i < 500; i++ {
frame.Sequence = uint16(i)
input.Write(protocol.EncodeRC(frame))
}
if err := run(context.Background(), &input, log.New(io.Discard, "", 0), nil, cfg, publisher); !errors.Is(err, io.EOF) {
t.Fatalf("run=%v want clean EOF", err)
}
if got, _ := publisher.Latest(); got.Sequence != 499 {
t.Fatalf("sequence=%d want the last frame", got.Sequence)
}
}
func TestNewSnapshotArmChannelConfigurationIsApplied(t *testing.T) {
cfg := config.Default()
cfg.OSD.ArmIndex = 6
cfg.OSD.ArmedThreshold = 256
frame := protocol.RCFrame{}
frame.Channels[6] = 257
if snapshot := newSnapshot(frame, cfg, nil); !snapshot.Armed {
t.Fatal("the configured arm index and threshold must drive the arm state")
}
}
+16
View File
@@ -51,6 +51,22 @@ func (v *videoController) Set(active bool) error {
return nil
}
// Running reports whether the video launcher is currently alive. It is the
// supervisor's decoded-video presence for the OSD snapshot: the launcher is
// the only video decoder this process knows about. A launcher that exited
// on its own stays recorded until the next Set; its pending wait result
// proves it is no longer alive without consuming the signal the stop path
// relies on. Reading this never signals or waits on the launcher, so it
// never disturbs the video path.
func (v *videoController) Running() bool {
v.mu.Lock()
defer v.mu.Unlock()
if v.cmd == nil {
return false
}
return len(v.done) == 0
}
func (v *videoController) Stop() error {
return v.Set(false)
}
+16
View File
@@ -16,6 +16,22 @@ video:
threshold: -922 # first 5% of CH6 knob remains management/off
command: fpv-video
osd:
# Flight OSD snapshots for the kiosk overlay: final RC channels, arm
# state, the adaptive-link contract values and decoded-video presence,
# published to tmpfs without blocking the UART path. The display process
# must read the same path (its -osd-state flag defaults to the value
# below).
state_path: /run/groundstation/osd-state.bin
arm_index: 4 # CH5/AUX1, zero-based
armed_threshold: 0
# Operator-selected VTX power table identifiers (0 = none selected yet).
# Static configuration is operator intent only: it is never rendered or
# serialized as applied VTX state, and CH6 acts only as the temporary
# maxPower ceiling.
vtx_table_gen: 0
vtx_table_hash: 0
logging:
enabled: true
path: /var/log/groundstation/groundstation.log
+46 -2
View File
@@ -1,8 +1,11 @@
package config
import (
"fmt"
"os"
"git.piksar.eu/piotr/groundstation/internal/osd"
"git.piksar.eu/piotr/groundstation/internal/protocol"
"gopkg.in/yaml.v3"
)
@@ -15,6 +18,21 @@ type DisplayConfig struct {
Xauthority string `yaml:"xauthority"`
}
// OSDConfig configures the supervisor's flight OSD snapshot publication.
type OSDConfig struct {
// StatePath is the snapshot state file the display process reads.
StatePath string `yaml:"state_path"`
// ArmIndex and ArmedThreshold derive the arm state from the final RC
// channels: armed while that channel stays above the threshold.
ArmIndex int `yaml:"arm_index"`
ArmedThreshold int16 `yaml:"armed_threshold"`
// VtxTableGen and VtxTableHash are the operator-selected VTX power
// table identifiers. Zero means no table is selected yet; a static
// selection is operator intent and never applied VTX state.
VtxTableGen uint32 `yaml:"vtx_table_gen"`
VtxTableHash uint64 `yaml:"vtx_table_hash"`
}
type Config struct {
Display DisplayConfig `yaml:"display"`
Serial struct {
@@ -26,6 +44,7 @@ type Config struct {
Threshold int16 `yaml:"threshold"`
Command string `yaml:"command"`
} `yaml:"video"`
OSD OSDConfig `yaml:"osd"`
Logging struct {
Enabled bool `yaml:"enabled"`
Path string `yaml:"path"`
@@ -40,6 +59,7 @@ func Default() Config {
c.Video.AuxIndex = 5 // AUX2, zero-based
c.Video.Threshold = -512
c.Video.Command = "fpv-video"
c.OSD = DefaultOSD()
c.Logging.Enabled = true
return c
}
@@ -56,17 +76,41 @@ func DefaultDisplay() DisplayConfig {
}
}
// DefaultOSD publishes snapshots to the default tmpfs path and derives the
// arm state from CH5/AUX1, armed above the midpoint.
func DefaultOSD() OSDConfig {
return OSDConfig{
StatePath: osd.DefaultStatePath,
ArmIndex: 4,
ArmedThreshold: 0,
}
}
func Load(path string) (Config, error) {
config := Default()
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return config, nil
return config, config.validate()
}
return config, err
}
if err := yaml.Unmarshal(data, &config); err != nil {
return config, err
}
return config, nil
return config, config.validate()
}
// validate rejects channel indexes outside the final RC channel range: an
// out-of-range index would panic on the first decoded frame.
func (c Config) validate() error {
for name, index := range map[string]int{
"video.aux_index": c.Video.AuxIndex,
"osd.arm_index": c.OSD.ArmIndex,
} {
if index < 0 || index >= protocol.Channels {
return fmt.Errorf("%s %d outside the RC channel range 0..%d", name, index, protocol.Channels-1)
}
}
return nil
}
+66
View File
@@ -48,3 +48,69 @@ func TestLoadOverridesDisplaySettings(t *testing.T) {
t.Fatalf("display=%q want default :0", cfg.Display.Display)
}
}
func TestDefaultConfigPublishesOSDSnapshotsFromAUX1(t *testing.T) {
cfg := Default()
if cfg.OSD.StatePath != "/run/groundstation/osd-state.bin" {
t.Fatalf("state_path=%q want the default tmpfs path", cfg.OSD.StatePath)
}
// CH5/AUX1 is the arming channel; the fail-closed convention reads it
// armed above the midpoint.
if cfg.OSD.ArmIndex != 4 {
t.Fatalf("arm_index=%d want 4 (CH5/AUX1, zero-based)", cfg.OSD.ArmIndex)
}
if cfg.OSD.ArmedThreshold != 0 {
t.Fatalf("armed_threshold=%d want 0", cfg.OSD.ArmedThreshold)
}
}
func TestLoadOverridesOSDSettings(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yml")
body := "osd:\n state_path: /tmp/osd-state.bin\n arm_index: 6\n armed_threshold: 256\n vtx_table_gen: 3\n vtx_table_hash: 9\n"
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
t.Fatal(err)
}
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
if cfg.OSD.StatePath != "/tmp/osd-state.bin" {
t.Fatalf("state_path=%q want the override", cfg.OSD.StatePath)
}
if cfg.OSD.ArmIndex != 6 || cfg.OSD.ArmedThreshold != 256 {
t.Fatalf("arm config=%+v want the overrides", cfg.OSD)
}
if cfg.OSD.VtxTableGen != 3 || cfg.OSD.VtxTableHash != 9 {
t.Fatalf("table config=%+v want the selected table", cfg.OSD)
}
}
func TestDefaultConfigSelectsNoVtxTable(t *testing.T) {
// No table exists yet: the operator selection defaults to none, so the
// OSD shows an explicit pending table instead of static configuration
// dressed up as applied VTX state.
cfg := Default()
if cfg.OSD.VtxTableGen != 0 || cfg.OSD.VtxTableHash != 0 {
t.Fatalf("table config=%+v must default to no selection", cfg.OSD)
}
}
func TestLoadRejectsArmAndVideoIndexesOutsideTheChannelRange(t *testing.T) {
for name, body := range map[string]string{
"arm index below range": "osd:\n arm_index: -1\n",
"arm index above range": "osd:\n arm_index: 16\n",
"video index below range": "video:\n aux_index: -1\n",
"video index above range": "video:\n aux_index: 16\n",
} {
path := filepath.Join(t.TempDir(), "config.yml")
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil {
t.Fatalf("%s must be rejected: an out-of-range index would panic on the first frame", name)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
package display
import (
"fmt"
"io"
"runtime/debug"
"strings"
"sync"
)
const (
// DiagTag prefixes every diagnostic line so the journal can be
// filtered to the stream with a plain grep.
DiagTag = "display_diag"
// DiagCap bounds the unique diagnostic records a process emits: the
// stream is small by construction, and only the close summary passes
// once the cap is reached.
DiagCap = 64
// DiagCollectCommand is the documented collection command: current
// boot, only diagnostic lines, capped output.
DiagCollectCommand = "journalctl -u groundstation -b --no-pager | grep " + DiagTag + " | tail -60"
)
// Diag emits compact, stable key=value diagnostics into the systemd
// journal stream (standard output of the display process). The schema is a
// fixed whitelist — process metadata, role and window identifiers,
// geometry and shape extents, state enums, stack position, bounded
// counters and operation errors — so diagnostics can never carry RC
// channel values, telemetry payloads, file contents, environment or
// credentials. Records are state-transition-driven: identical consecutive
// transitions are deduplicated, the total number of records is capped,
// and only the close summary bypasses the cap.
type Diag struct {
mu sync.Mutex
out io.Writer
cap int
last map[string]string
count int
}
// NewDiag builds a diagnostics emitter writing to out.
func NewDiag(out io.Writer) *Diag {
return &Diag{out: out, cap: DiagCap, last: map[string]string{}}
}
// FormatDiagLine renders one diagnostic record in the exact stable schema.
func FormatDiagLine(kind, role string, fields ...string) string {
b := &strings.Builder{}
b.WriteString(DiagTag)
b.WriteString(" kind=")
b.WriteString(kind)
if role != "" {
b.WriteString(" role=")
b.WriteString(role)
}
for _, field := range fields {
if field != "" {
b.WriteString(" ")
b.WriteString(field)
}
}
return b.String()
}
// Emit records a state transition or event; identical consecutive records
// are deduplicated and the total is capped.
func (d *Diag) Emit(kind, role string, fields ...string) {
d.emit(kind, role, false, fields...)
}
// EmitForced records a record that must never be dropped by the cap, such
// as the close summary.
func (d *Diag) EmitForced(kind, role string, fields ...string) {
d.emit(kind, role, true, fields...)
}
func (d *Diag) emit(kind, role string, forced bool, fields ...string) {
if d == nil {
return
}
line := FormatDiagLine(kind, role, fields...)
d.mu.Lock()
defer d.mu.Unlock()
if !forced {
if d.count >= d.cap {
return
}
key := kind + "|" + role
if d.last[key] == line {
return
}
d.last[key] = line
}
d.count++
if d.out != nil {
fmt.Fprintln(d.out, line)
}
}
// diagValue sanitizes a free-text diagnostic value: line breaks are
// collapsed so a hostile or multiline error can never inject journal lines
// into the display_diag stream, and the value is length-bounded. Values
// without free text (identifiers, dimensions, enums) bypass this and are
// formatted from trusted numeric sources only.
func diagValue(text string) string {
if text == "" {
return text
}
if len(text) > diagValueMaxLen {
text = text[:diagValueMaxLen]
}
return strings.ReplaceAll(strings.ReplaceAll(text, "\n", " "), "\r", " ")
}
// diagValueMaxLen bounds free-text diagnostic values so a chatty error can
// never bloat the journal stream.
const diagValueMaxLen = 160
// VCSRevision returns the VCS revision the binary was built from, or
// unknown when the build carried none. No other build or environment
// metadata is exposed.
func VCSRevision() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" && setting.Value != "" {
return setting.Value
}
}
}
return "unknown"
}
+150
View File
@@ -0,0 +1,150 @@
package display
import (
"bytes"
"regexp"
"strings"
"testing"
)
func TestFormatDiagLineRendersTheExactStableSchema(t *testing.T) {
got := FormatDiagLine("first_redraw", "osd",
"trigger=initial", "ops=3", "regions=3", "bounds=196x106+28+15",
"snap=none", "video=off", "stack=top")
want := "display_diag kind=first_redraw role=osd trigger=initial ops=3 regions=3 bounds=196x106+28+15 snap=none video=off stack=top"
if got != want {
t.Fatalf("line=%q want %q", got, want)
}
// A start record has no role: the role field is omitted entirely.
got = FormatDiagLine("start", "", "pid=123", "vcs=unknown")
want = "display_diag kind=start pid=123 vcs=unknown"
if got != want {
t.Fatalf("line=%q want %q", got, want)
}
}
func TestDiagCollectCommandTargetsTheStableTagWithATailCap(t *testing.T) {
// The documented collection command must filter the journal on the
// stable tag and cap the output, so it stays pasteable.
if !strings.Contains(DiagCollectCommand, DiagTag) {
t.Fatalf("collect command %q must target the stable tag %q", DiagCollectCommand, DiagTag)
}
if !strings.Contains(DiagCollectCommand, "tail") || !strings.Contains(DiagCollectCommand, "--no-pager") {
t.Fatalf("collect command %q must cap with tail and disable paging", DiagCollectCommand)
}
}
func TestDiagDeduplicatesIdenticalStateTransitions(t *testing.T) {
var buf bytes.Buffer
d := NewDiag(&buf)
for i := 0; i < 3; i++ {
d.Emit("snap", "osd", "state=fresh")
}
d.Emit("snap", "osd", "state=stale")
d.Emit("snap", "osd", "state=stale")
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 2 {
t.Fatalf("lines=%d (%v) want one fresh and one stale record", len(lines), lines)
}
if !strings.Contains(lines[0], "state=fresh") || !strings.Contains(lines[1], "state=stale") {
t.Fatalf("lines=%v want state transitions only", lines)
}
}
func TestDiagCapsRecordsAndForcesOnlyTheSummary(t *testing.T) {
var buf bytes.Buffer
d := NewDiag(&buf)
d.cap = 3
for i := 0; i < 10; i++ {
d.Emit("snap", "osd", "state="+[]string{"fresh", "stale"}[i%2])
}
d.EmitForced("summary", "osd", "flushes=1")
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 4 {
t.Fatalf("lines=%d (%v) want the cap plus one forced summary", len(lines), lines)
}
if !strings.Contains(lines[len(lines)-1], "kind=summary") {
t.Fatalf("last line=%q want the forced summary", lines[len(lines)-1])
}
}
func TestDiagNilReceiverIsSafe(t *testing.T) {
var d *Diag
d.Emit("snap", "osd", "state=fresh")
d.EmitForced("summary", "osd", "flushes=0")
}
func TestDiagValueSanitizesNewlinesAndBoundsLength(t *testing.T) {
// A hostile or multiline error can never inject journal lines into the
// display_diag stream: line breaks collapse to spaces and the value is
// length-bounded.
hostile := "line one\nline two\rinjected line\n" + strings.Repeat("x", 400)
got := diagValue(hostile)
if strings.ContainsAny(got, "\n\r") {
t.Fatalf("sanitized value=%q still carries line breaks", got)
}
if len(got) != diagValueMaxLen {
t.Fatalf("len=%d want the %d-byte bound", len(got), diagValueMaxLen)
}
if !strings.HasPrefix(got, "line one line two injected line ") {
t.Fatalf("sanitized value=%q must preserve content with spaces", got)
}
if diagValue("") != "" {
t.Fatal("an empty value stays empty")
}
}
func TestVCSRevisionReturnsASafeSingleToken(t *testing.T) {
// The revision is either the embedded build revision or the explicit
// unknown marker: a single token without whitespace either way, safe
// for the key=value schema under any build mode.
got := VCSRevision()
if got == "" || strings.ContainsAny(got, " \t\n\r") {
t.Fatalf("vcs revision=%q must be a single safe token", got)
}
}
func TestDiagLinesCarryNoSensitiveValues(t *testing.T) {
var buf bytes.Buffer
d := NewDiag(&buf)
// Everything the diagnostics can ever emit: process metadata, role and
// window identifiers, geometry and shape extents, state enums, stack
// position, bounded counters and operation errors. No RC channel
// values, telemetry payloads, file contents, environment or
// credentials have a field in the schema.
d.EmitForced("start", "", "pid=4321", "vcs=0123abcd")
d.Emit("open", "osd", "window=0x600001", "root=0x2a0", "cfg=1920x1080",
"root_geom=1920x1080", "client_geom=1920x1080", "refresh=1s",
"type=DOCK", "wm_state=FULLSCREEN+ABOVE", "shape_init=empty/empty")
d.Emit("first_redraw", "osd", "trigger=initial", "ops=3", "regions=3",
"bounds=196x106+28+15", "snap=none", "video=off", "stack=top")
d.Emit("query", "osd", "shape=196x106+28+15", "geom=1920x1080+0+26",
"parent=0x1a00001", "stack=1/3")
d.Emit("snap", "osd", "state=stale")
d.Emit("video", "osd", "state=on")
d.Emit("stack", "osd", "target=video/0x2c00002")
d.Emit("reconnect", "osd", "event=open_failed", "error=connect refused", "retry_delay=500ms")
d.Emit("error", "osd", "op=shape", "err=bounding shape: BadWindow")
d.EmitForced("summary", "osd", "redraws=12", "flushes=12", "errors=1", "snap=stale", "video=on")
schema := regexp.MustCompile(`^display_diag kind=[a-z_]+( role=[a-z]+)?( [a-z_0-9]+="?[^\s"]+( [^\s"]+)*"?)?$`)
for _, line := range strings.Split(strings.TrimSpace(buf.String()), "\n") {
if !strings.HasPrefix(line, DiagTag+" ") {
t.Fatalf("line=%q must carry the stable tag", line)
}
if !schema.MatchString(line) {
t.Fatalf("line=%q does not match the whitelisted schema", line)
}
for _, forbidden := range []string{"channel", "channels", "gps", "battery", "attitude", "Xauthority", "env", "password"} {
if strings.Contains(strings.ToLower(line), forbidden+"=") {
t.Fatalf("line=%q must never carry a %q field", line, forbidden)
}
}
}
}
+182
View File
@@ -0,0 +1,182 @@
package display
import (
"context"
"errors"
"sync"
"testing"
"time"
)
// diagnosticCapture collects structured reconnect records from Run.
type diagnosticCapture struct {
mu sync.Mutex
records []Diagnostic
}
func (c *diagnosticCapture) record(d Diagnostic) {
c.mu.Lock()
defer c.mu.Unlock()
c.records = append(c.records, d)
}
func (c *diagnosticCapture) all() []Diagnostic {
c.mu.Lock()
defer c.mu.Unlock()
return append([]Diagnostic(nil), c.records...)
}
func TestRunDiagnosesEachFailedOpenWithStructuredFields(t *testing.T) {
session := newFakeSession()
var opens int
opener := fakeOpener{open: func(int) (Session, error) {
opens++
if opens <= 2 {
return nil, errors.New("x11 down")
}
return session, nil
}}
capture := &diagnosticCapture{}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- Run(ctx, opener, NewStatusTemplate("hello"), Options{
Target: "x11",
Layer: "fallback-canvas",
Diagnostic: capture.record,
RetryDelay: time.Millisecond,
MaxDelay: 2 * time.Millisecond,
})
}()
waitFor(t, func() bool { return session.canvas.lineCount() > 0 }, "connect after retries")
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("run: %v", err)
}
case <-time.After(time.Second):
t.Fatal("run did not stop after cancel")
}
records := capture.all()
if len(records) != 2 {
t.Fatalf("records=%d want exactly one per failed open (2)", len(records))
}
first, second := records[0], records[1]
if first.Target != "x11" {
t.Fatalf("target=%q want x11", first.Target)
}
if first.Layer != "fallback-canvas" {
t.Fatalf("layer=%q want fallback-canvas", first.Layer)
}
if first.Event != EventOpenFailed {
t.Fatalf("event=%q want %q", first.Event, EventOpenFailed)
}
if first.Err == nil || first.Err.Error() != "x11 down" {
t.Fatalf("underlying error %v must be carried in the record", first.Err)
}
if first.RetryDelay != time.Millisecond {
t.Fatalf("first retry delay=%v want %v", first.RetryDelay, time.Millisecond)
}
if second.RetryDelay != 2*time.Millisecond {
t.Fatalf("backed-off retry delay=%v want %v", second.RetryDelay, 2*time.Millisecond)
}
}
func TestRunDiagnosesBrokenSessionOnceAndRecovers(t *testing.T) {
first := newFakeSession()
second := newFakeSession()
var opens int
opener := fakeOpener{open: func(int) (Session, error) {
opens++
if opens == 1 {
return first, nil
}
return second, nil
}}
capture := &diagnosticCapture{}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- Run(ctx, opener, NewStatusTemplate("hello"), Options{
Target: "x11",
Diagnostic: capture.record,
RetryDelay: time.Millisecond,
MaxDelay: 2 * time.Millisecond,
})
}()
waitFor(t, func() bool { return first.canvas.lineCount() == 1 }, "draw on first session")
first.events <- eventResult{err: errors.New("connection lost")}
waitFor(t, func() bool { return second.canvas.lineCount() == 1 }, "recover on reconnected session")
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("run: %v", err)
}
case <-time.After(time.Second):
t.Fatal("run did not stop after cancel")
}
records := capture.all()
if len(records) != 1 {
t.Fatalf("records=%d want exactly one per broken session (1)", len(records))
}
record := records[0]
if record.Target != "x11" {
t.Fatalf("target=%q want x11", record.Target)
}
if record.Event != EventSessionEnded {
t.Fatalf("event=%q want %q", record.Event, EventSessionEnded)
}
if record.Err == nil || record.Err.Error() != "connection lost" {
t.Fatalf("underlying error %v must be carried in the record", record.Err)
}
if record.RetryDelay != time.Millisecond {
t.Fatalf("retry delay=%v want the reset %v", record.RetryDelay, time.Millisecond)
}
}
// blockingOpener fails only after the context is done, so cancellation is
// the sole reason Run stops: no diagnostic may fire for shutdown.
type blockingOpener struct{}
func (blockingOpener) Open(ctx context.Context) (Session, error) {
<-ctx.Done()
return nil, ctx.Err()
}
func TestRunStaysSilentWhenCancellationEndsTheLoop(t *testing.T) {
capture := &diagnosticCapture{}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- Run(ctx, blockingOpener{}, NewStatusTemplate("hello"), Options{
Target: "x11",
Diagnostic: capture.record,
RetryDelay: time.Millisecond,
MaxDelay: 2 * time.Millisecond,
})
}()
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("run: %v", err)
}
case <-time.After(time.Second):
t.Fatal("run did not stop after cancel")
}
if records := capture.all(); len(records) != 0 {
t.Fatalf("records=%v must stay empty: shutdown is not a reconnect boundary", records)
}
}
+117 -8
View File
@@ -1,12 +1,24 @@
// Package display owns the Ground Station kiosk canvas lifecycle. The kiosk
// runs independently of WFB, the transmitter and the RC video knob: it waits
// for its rendering target to appear, keeps a fullscreen black canvas alive
// and stops only when told to. Each target (X11/Viture today, MIPI/touch
// later) provides its own opener and templates instead of one global layout.
// Package display owns the Ground Station kiosk layers. The kiosk runs
// independently of WFB, the transmitter and the RC video knob: it waits for
// its rendering target to appear, keeps its windows alive and stops only
// when told to. Each target drives two independent visual layers: a
// fullscreen fallback/menu canvas below video, visible while decoded pilot
// video is absent, and a transparent, input-transparent OSD overlay above
// video that renders deliberately minimal flight telemetry from
// supervisor-published OSD snapshots from startup — on top of the fallback
// presentation and above fullscreen video alike, with the observed video
// lifecycle shown as an explicit VIDEO line. When video
// output is presented the video window takes rendering priority and the
// fallback disappears, returning when video ends. Presence is observed from
// the video output itself on the display server, never from WFB or launcher
// processes, and the video pipeline is never moved into, coupled to or
// touched by this package. Each target (X11/Viture today, MIPI/touch later)
// provides its own openers and templates instead of one global layout.
package display
import (
"context"
"sync"
"time"
)
@@ -40,12 +52,47 @@ type Opener interface {
Open(ctx context.Context) (Session, error)
}
// Reconnect-boundary diagnostic events.
const (
// EventOpenFailed marks a failed attempt to open the display target.
EventOpenFailed = "open_failed"
// EventSessionEnded marks a session broken by a target failure.
EventSessionEnded = "session_ended"
)
// Diagnostic is one structured record from a reconnect boundary of the
// kiosk loop. Exactly one record is emitted per failed open or broken
// session; cancellation and shutdown stay silent.
type Diagnostic struct {
// Target is the display target name, for example "x11".
Target string
// Layer is the display layer name within the target, for example
// "fallback-canvas"; empty for single-layer runs.
Layer string
// Event names the boundary: EventOpenFailed or EventSessionEnded.
Event string
// Err is the underlying error from Opener.Open or Session.WaitEvent.
Err error
// RetryDelay is the wait scheduled after this boundary.
RetryDelay time.Duration
}
// Options tune the kiosk lifecycle loop. Zero values select the defaults.
type Options struct {
// RetryDelay is the first wait after a failed connect or lost session.
RetryDelay time.Duration
// MaxDelay bounds the exponential reconnect backoff.
MaxDelay time.Duration
// Target names the display target in diagnostics. Empty selects
// "unknown".
Target string
// Layer names the kiosk layer in diagnostics; empty for single-layer
// runs.
Layer string
// Diagnostic receives one structured record per reconnect boundary.
// Nil disables diagnostics. It runs on the loop goroutine and must not
// block.
Diagnostic func(Diagnostic)
}
func (o Options) withDefaults() Options {
@@ -58,10 +105,35 @@ func (o Options) withDefaults() Options {
return o
}
func (o Options) targetName() string {
if o.Target == "" {
return "unknown"
}
return o.Target
}
// diagnose emits one reconnect-boundary record. Cancellation is shutdown,
// not a failure, so it stays silent; so does a nil hook.
func (o Options) diagnose(ctx context.Context, event string, err error, retryDelay time.Duration) {
if o.Diagnostic == nil || err == nil || ctx.Err() != nil {
return
}
o.Diagnostic(Diagnostic{
Target: o.targetName(),
Layer: o.Layer,
Event: event,
Err: err,
RetryDelay: retryDelay,
})
}
// Run owns the kiosk display lifecycle until ctx is cancelled. Temporary
// unavailability of the target, for example X11 not being up yet, never
// returns an error: Run retries with bounded backoff and only stops when the
// context is cancelled, so the Ground Station supervisor stays up.
// context is cancelled, so the Ground Station supervisor stays up. Each
// reconnect boundary (failed open, broken session) emits one structured
// Diagnostic record through Options.Diagnostic, never through an error
// return; cancellation stays silent.
func Run(ctx context.Context, opener Opener, template Template, options Options) error {
opts := options.withDefaults()
delay := opts.RetryDelay
@@ -72,6 +144,7 @@ func Run(ctx context.Context, opener Opener, template Template, options Options)
session, err := opener.Open(ctx)
if err != nil {
opts.diagnose(ctx, EventOpenFailed, err, delay)
if !sleep(ctx, delay) {
return nil
}
@@ -82,9 +155,11 @@ func Run(ctx context.Context, opener Opener, template Template, options Options)
delay = opts.RetryDelay
canvas := session.Canvas()
template.Draw(canvas)
var sessionErr error
for ctx.Err() == nil {
redraw, err := session.WaitEvent(ctx)
if err != nil {
var redraw bool
redraw, sessionErr = session.WaitEvent(ctx)
if sessionErr != nil {
break
}
if redraw {
@@ -96,6 +171,7 @@ func Run(ctx context.Context, opener Opener, template Template, options Options)
if ctx.Err() != nil {
return nil
}
opts.diagnose(ctx, EventSessionEnded, sessionErr, delay)
if !sleep(ctx, delay) {
return nil
}
@@ -103,6 +179,39 @@ func Run(ctx context.Context, opener Opener, template Template, options Options)
}
}
// Layer is one independent visual layer of a display target: its own
// connection, window role and template. A lost or degraded layer never
// affects the others, so a missing overlay cannot disturb the fallback
// canvas and neither can disturb pilot video.
type Layer struct {
// Name identifies the layer in diagnostics.
Name string
// Opener connects to the layer's own window on the target.
Opener Opener
// Template renders the layer's target-specific layout.
Template Template
// Options tune the layer's lifecycle loop. Zero values select the
// defaults.
Options Options
}
// RunLayers drives every layer of a display target until ctx is cancelled,
// each on its own connection with its own reconnect backoff. A layer whose
// target keeps failing keeps retrying and never stops the other layers, so
// the Ground Station supervisor stays up. RunLayers returns only after every
// layer has stopped.
func RunLayers(ctx context.Context, layers []Layer) {
var wg sync.WaitGroup
for _, layer := range layers {
wg.Add(1)
go func(layer Layer) {
defer wg.Done()
_ = Run(ctx, layer.Opener, layer.Template, layer.Options)
}(layer)
}
wg.Wait()
}
func nextDelay(delay, max time.Duration) time.Duration {
delay *= 2
if delay > max {
+81
View File
@@ -242,6 +242,87 @@ func TestRunReconnectsAfterSessionFailure(t *testing.T) {
}
}
func TestRunLayersDrawsEveryLayerOnItsOwnCanvas(t *testing.T) {
canvasSession := newFakeSession()
osdSession := newFakeSession()
layers := []Layer{
{
Name: "fallback-canvas",
Opener: fakeOpener{open: func(int) (Session, error) { return canvasSession, nil }},
Template: NewStatusTemplate("canvas"),
},
{
Name: "osd-overlay",
Opener: fakeOpener{open: func(int) (Session, error) { return osdSession, nil }},
Template: NewOSDTemplate(NewVideoPresence(), stubSource{}),
},
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
RunLayers(ctx, layers)
close(done)
}()
waitFor(t, func() bool { return canvasSession.canvas.lineCount() == 1 }, "canvas layer draw")
waitFor(t, func() bool {
clears, _ := osdSession.canvas.drawCounts()
return clears == 1
}, "osd layer transparent clear")
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("run layers did not stop after cancel")
}
if got := canvasSession.closeCount(); got != 1 {
t.Fatalf("canvas session closed %d times, want 1", got)
}
if got := osdSession.closeCount(); got != 1 {
t.Fatalf("osd session closed %d times, want 1", got)
}
}
func TestRunLayersKeepsOtherLayerAliveWhenOneTargetFails(t *testing.T) {
alive := newFakeSession()
layers := []Layer{
{
Name: "dead",
Opener: fakeOpener{open: func(int) (Session, error) { return nil, errors.New("target down") }},
Template: NewStatusTemplate("never drawn"),
},
{
Name: "alive",
Opener: fakeOpener{open: func(int) (Session, error) { return alive, nil }},
Template: NewOSDTemplate(NewVideoPresence(), stubSource{}),
},
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
RunLayers(ctx, layers)
close(done)
}()
waitFor(t, func() bool {
clears, _ := alive.canvas.drawCounts()
return clears == 1
}, "alive layer keeps drawing while the other target fails")
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("run layers did not stop after cancel")
}
if got := alive.closeCount(); got != 1 {
t.Fatalf("alive session closed %d times, want 1", got)
}
}
func TestRunStopsWithoutConnectingWhenContextAlreadyCancelled(t *testing.T) {
var opens int32
opener := fakeOpener{open: func(int) (Session, error) {
+25
View File
@@ -0,0 +1,25 @@
package display
// FallbackTemplate is the no-video kiosk layout: a cleared black canvas with
// the fallback lines. While decoded video is present the fallback
// disappears: the canvas stays plain black so the video window keeps
// rendering priority without stale text around or behind it, and the exact
// fallback lines return when video ends.
type FallbackTemplate struct {
fallback StatusTemplate
video *VideoPresence
}
// NewFallbackTemplate builds a template that draws the given fallback lines
// only while the shared presence reports no video.
func NewFallbackTemplate(video *VideoPresence, lines ...string) FallbackTemplate {
return FallbackTemplate{fallback: NewStatusTemplate(lines...), video: video}
}
func (t FallbackTemplate) Draw(canvas Canvas) {
canvas.Clear()
if !t.video.Active() {
drawLines(canvas, t.fallback.lines)
}
canvas.Flush()
}
+57
View File
@@ -0,0 +1,57 @@
package display
import "testing"
const wantFallbackText = "Brak połączenia WFB"
func TestFallbackTemplateShowsExactTextWhileVideoAbsent(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewFallbackTemplate(presence, wantFallbackText).Draw(canvas)
clears, flushes := canvas.drawCounts()
if clears != 1 || flushes != 1 {
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
}
lines := canvas.lines()
if len(lines) != 1 || lines[0] != wantFallbackText {
t.Fatalf("lines=%q want [%q]", lines, wantFallbackText)
}
}
func TestFallbackTemplateDisappearsWhileVideoPresent(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
presence.SetActive(true)
NewFallbackTemplate(presence, wantFallbackText).Draw(canvas)
clears, flushes := canvas.drawCounts()
if clears != 1 || flushes != 1 {
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
}
if lines := canvas.lines(); len(lines) != 0 {
t.Fatalf("video has priority: fallback lines %q must disappear", lines)
}
}
func TestFallbackTemplateReturnsWhenVideoEnds(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
presence.SetActive(true)
template := NewFallbackTemplate(presence, wantFallbackText)
template.Draw(canvas)
if lines := canvas.lines(); len(lines) != 0 {
t.Fatalf("lines=%q must stay empty while video is present", lines)
}
presence.SetActive(false)
template.Draw(canvas)
lines := canvas.lines()
if len(lines) != 1 || lines[0] != wantFallbackText {
t.Fatalf("lines=%q want fallback [%q] after video end", lines, wantFallbackText)
}
}
+145
View File
@@ -0,0 +1,145 @@
package display
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
)
func TestConfirmMappedSucceedsWhenLivenessReplySucceeds(t *testing.T) {
// Open's post-map liveness stage must succeed when the reply-bearing
// round trip succeeds, so the mapped window proceeds to a live session.
probes := 0
probe := func() error {
probes++
return nil
}
if err := confirmMapped(probe); err != nil {
t.Fatalf("confirmMapped=%v want success when the liveness reply arrives", err)
}
if probes != 1 {
t.Fatalf("probes=%d want exactly one liveness round trip", probes)
}
}
func TestConfirmMappedWrapsLivenessFailureForMappedWindowCleanup(t *testing.T) {
sentinel := errors.New("connection reset")
err := confirmMapped(func() error { return sentinel })
if err == nil {
t.Fatal("confirmMapped must propagate a failed liveness round trip")
}
if !strings.Contains(err.Error(), "map kiosk window") {
t.Fatalf("error %v must be wrapped as the map-kiosk-window failure so Open closes the connection", err)
}
if !errors.Is(err, sentinel) {
t.Fatalf("error %v must carry the underlying liveness error", err)
}
}
func TestX11SessionWaitEventKeepsPollingWhileLivenessRepliesSucceed(t *testing.T) {
probes := 0
session := &x11Session{
poll: time.Millisecond,
pollEvent: func() (xgb.Event, xgb.Error) {
return nil, nil
},
probe: func() error {
probes++
return nil
},
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
_, err := session.WaitEvent(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("WaitEvent=%v want clean cancellation while liveness replies succeed", err)
}
if probes == 0 {
t.Fatal("WaitEvent must perform liveness round trips while idle")
}
}
func TestX11SessionWaitEventPropagatesLivenessError(t *testing.T) {
sentinel := errors.New("X server went away")
session := &x11Session{
poll: time.Millisecond,
pollEvent: func() (xgb.Event, xgb.Error) { return nil, nil },
probe: func() error { return sentinel },
}
// The propagated error is what makes Run close the mapped window and
// reconnect, keeping the failure contained in the display loop.
_, err := session.WaitEvent(context.Background())
if !errors.Is(err, sentinel) {
t.Fatalf("WaitEvent=%v want the underlying liveness error", err)
}
}
func TestX11SessionWaitEventStillHandlesEventsBeforeLiveness(t *testing.T) {
session := &x11Session{
poll: time.Millisecond,
pollEvent: func() (xgb.Event, xgb.Error) {
return xproto.ExposeEvent{}, nil
},
probe: func() error {
t.Fatal("liveness must not run when an event is already handled")
return nil
},
}
redraw, err := session.WaitEvent(context.Background())
if err != nil {
t.Fatalf("WaitEvent=%v", err)
}
if !redraw {
t.Fatal("an expose event must request a redraw")
}
}
// TestResolveLivenessWaitsForReplyOnReplyBearingCookie is the behavioral
// guard for the hardware-proven root cause. GetInputFocus issues a
// reply-bearing cookie (NewCookie(true, true)); resolveLiveness must
// consume it with Reply — meaning it blocks awaiting the server's reply —
// never with Check, which would return the XGB reply-cookie error on every
// call regardless of server health. A reply-bearing cookie can be built
// without a server because xgb's NewCookie does not touch the connection.
func TestResolveLivenessWaitsForReplyOnReplyBearingCookie(t *testing.T) {
conn := &xgb.Conn{}
cookie := xproto.GetInputFocusCookie{Cookie: conn.NewCookie(true, true)}
done := make(chan error, 1)
go func() { done <- resolveLiveness(cookie) }()
select {
case err := <-done:
t.Fatalf("resolveLiveness returned %v without any server reply; the cookie was not resolved with Reply", err)
case <-time.After(100 * time.Millisecond):
// Still waiting for the reply: Reply-resolution semantics intact.
}
}
// TestCheckOnReplyBearingCookieIsTheDeviceRootCause pins the exact xgb
// behavior the fix depends on, using the real cookie API: Check on a
// reply-bearing cookie returns the device-proven error immediately, while
// Reply is the only resolution that waits for the server. This is the
// behavioral contrast proving connLivenessProbe/resolveLiveness cannot
// reintroduce the open_failed reconnect loop.
func TestCheckOnReplyBearingCookieIsTheDeviceRootCause(t *testing.T) {
conn := &xgb.Conn{}
cookie := xproto.GetInputFocusCookie{Cookie: conn.NewCookie(true, true)}
err := cookie.Check()
if err == nil {
t.Fatal("Check on a reply-bearing cookie must fail; the device root cause would be reintroduced")
}
const deviceError = "Cannot call 'Check' on a cookie that is expecting a *reply*. Use 'Reply' instead."
if err.Error() != deviceError {
t.Fatalf("Check error=%q want the device-proven %q", err.Error(), deviceError)
}
}
+133
View File
@@ -0,0 +1,133 @@
package display
import (
"strconv"
"git.piksar.eu/piotr/groundstation/internal/osd"
)
// SnapshotSource serves the latest supervisor-published OSD snapshot and its
// state (none / fresh / stale). The file-backed implementation lives in the
// osd package; the template only consumes the contract.
type SnapshotSource interface {
Latest() (osd.Snapshot, osd.SnapshotState)
}
// OSDTemplate is the flight OSD layout of a display target: a transparent,
// input-transparent surface above everything else on the screen. It renders
// from startup — on top of the no-video fallback presentation and above
// fullscreen video alike — and never gates on video presence: the video
// lifecycle the display observes on the display server is itself displayed
// as the VIDEO line, never the snapshot's Video field. ARM and the compact
// adaptive-link line come from the latest snapshot; a stale last-known
// snapshot stays visible and marked DATA STALE, and before any snapshot has
// existed the OSD shows explicit NO DATA / unknown marks. The OSD never
// draws the fallback: it is a telemetry surface, not a video substitute,
// and WFB or video decode never move into the UI process to feed it. The
// OSD refreshes on its own slower cadence than the video and the video
// window keeps rendering priority.
type OSDTemplate struct {
video *VideoPresence
source SnapshotSource
}
// NewOSDTemplate builds the OSD surface for a target from the shared
// display-observed video presence and the supervisor-published snapshot
// source.
func NewOSDTemplate(video *VideoPresence, source SnapshotSource) OSDTemplate {
return OSDTemplate{video: video, source: source}
}
func (t OSDTemplate) Draw(canvas Canvas) {
canvas.Clear()
snapshot, state := t.source.Latest()
// Report the snapshot state into the layer's diagnostic stream when
// the canvas supports it; transitions are deduplicated there.
if reporter, ok := canvas.(interface{ SetDiagSnapshot(string) }); ok {
reporter.SetDiagSnapshot(snapshotStateName(state))
}
t.draw(canvas, snapshot, state)
canvas.Flush()
}
// draw renders the deliberately minimal telemetry lines in the top-left
// corner: arm state, the adaptive-link contract, an optional staleness or
// no-data marker, and the observed video state. The full final RC state
// stays in the snapshot; the pilot-facing overlay stays terse.
func (t OSDTemplate) draw(canvas Canvas, snapshot osd.Snapshot, state osd.SnapshotState) {
y := 32
switch state {
case osd.SnapshotNone:
canvas.Text(32, y, "NO DATA")
y += 32
canvas.Text(32, y, "VTX tbl:-- ceil:-- req:-- ack:--")
y += 32
default:
canvas.Text(32, y, armLine(snapshot))
y += 32
canvas.Text(32, y, vtxLine(snapshot))
y += 32
if state == osd.SnapshotStale {
canvas.Text(32, y, "DATA STALE")
y += 32
}
}
canvas.Text(32, y, "VIDEO "+videoState(t.video.Active()))
}
func armLine(snapshot osd.Snapshot) string {
if snapshot.Armed {
return "ARM ARMED"
}
return "ARM OFF"
}
// snapshotStateName names a snapshot state in diagnostics.
func snapshotStateName(state osd.SnapshotState) string {
switch state {
case osd.SnapshotFresh:
return "fresh"
case osd.SnapshotStale:
return "stale"
}
return "none"
}
func videoState(active bool) string {
if active {
return "ON"
}
return "OFF"
}
// vtxLine is the compact adaptive-link contract line.
func vtxLine(snapshot osd.Snapshot) string {
return "VTX tbl:" + vtxTable(snapshot.OpConfig.Table) +
" ceil:" + strconv.FormatUint(uint64(snapshot.OpConfig.MaxPower), 10) +
" req:" + vtxLevel(snapshot.Policy.Pending, snapshot.Policy.Level) +
" ack:" + vtxAck(snapshot.Ack)
}
func vtxTable(table osd.Table) string {
if !table.Selected() {
return "--"
}
return strconv.FormatUint(uint64(table.Gen), 10)
}
func vtxLevel(pending bool, level uint8) string {
if pending {
return "--"
}
return strconv.FormatUint(uint64(level), 10)
}
func vtxAck(ack osd.VTXAck) string {
if ack.Pending {
return "--"
}
if ack.Lifecycle == osd.VTXLifecycleError {
return "ERR"
}
return vtxLevel(false, ack.Level)
}
+227
View File
@@ -0,0 +1,227 @@
package display
import (
"strings"
"testing"
"git.piksar.eu/piotr/groundstation/internal/osd"
)
// stubSource serves one fixed snapshot state, or none.
type stubSource struct {
snapshot osd.Snapshot
state osd.SnapshotState
}
func (s stubSource) Latest() (osd.Snapshot, osd.SnapshotState) { return s.snapshot, s.state }
// pendingSource is the contract state while the adaptive-link producers do
// not exist: arm state and CH6 ceiling from the snapshot, everything else
// explicitly pending.
func pendingSource(armed bool, ceiling uint8) stubSource {
return stubSource{snapshot: osd.Snapshot{
Armed: armed,
OpConfig: osd.OperatorConfig{MaxPower: ceiling},
Policy: osd.GSPolicy{Pending: true},
Ack: osd.VTXAck{Pending: true, Lifecycle: osd.VTXLifecyclePending},
Link: osd.GSObservedLink{Known: false},
}, state: osd.SnapshotFresh}
}
func assertLines(t *testing.T, canvas *fakeCanvas, want []string) {
t.Helper()
lines := canvas.lines()
if len(lines) < len(want) {
t.Fatalf("lines=%q want at least %q", lines, want)
}
// Compare only the most recent draw pass: the canvas accumulates lines
// across passes.
lines = lines[len(lines)-len(want):]
for i := range want {
if lines[i] != want[i] {
t.Fatalf("line %d=%q want %q", i, lines[i], want[i])
}
}
}
func TestOSDTemplateRendersExplicitNoDataState(t *testing.T) {
// Before any snapshot has ever existed the overlay must show explicit
// unknown state plus the authoritative video state instead of a blank
// overlay — including over the no-video fallback presentation.
canvas := &fakeCanvas{width: 800, height: 600}
NewOSDTemplate(NewVideoPresence(), stubSource{}).Draw(canvas)
clears, flushes := canvas.drawCounts()
if clears != 1 || flushes != 1 {
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
}
assertLines(t, canvas, []string{
"NO DATA",
"VTX tbl:-- ceil:-- req:-- ack:--",
"VIDEO OFF",
})
}
func TestOSDTemplateDrawsFreshSnapshotWithVideoOff(t *testing.T) {
// Fresh snapshot data renders on top of the no-video fallback
// presentation; the observed video lifecycle shows as VIDEO OFF.
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewOSDTemplate(presence, pendingSource(true, 63)).Draw(canvas)
assertLines(t, canvas, []string{
"ARM ARMED",
"VTX tbl:-- ceil:63 req:-- ack:--",
"VIDEO OFF",
})
}
func TestOSDTemplateMarksStaleLastKnownData(t *testing.T) {
// A snapshot beyond the freshness window stays visible as last-known
// data, explicitly marked stale — never presented as current.
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewOSDTemplate(presence, stubSource{snapshot: osd.Snapshot{
Armed: true,
OpConfig: osd.OperatorConfig{
Table: osd.Table{Gen: 3, Hash: 0xcafe},
MaxPower: 63,
},
Policy: osd.GSPolicy{Level: 42},
Ack: osd.VTXAck{
Table: osd.Table{Gen: 3},
Level: 40,
Lifecycle: osd.VTXLifecycleApplied,
},
}, state: osd.SnapshotStale}).Draw(canvas)
assertLines(t, canvas, []string{
"ARM ARMED",
"VTX tbl:3 ceil:63 req:42 ack:40",
"DATA STALE",
"VIDEO OFF",
})
}
func TestOSDTemplateStaysVisibleAcrossVideoTransition(t *testing.T) {
// Video appearing fullscreen must not hide the OSD: the data lines stay
// and only the authoritative VIDEO line flips.
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
template := NewOSDTemplate(presence, pendingSource(true, 63))
template.Draw(canvas)
assertLines(t, canvas, []string{
"ARM ARMED",
"VTX tbl:-- ceil:63 req:-- ack:--",
"VIDEO OFF",
})
presence.SetActive(true)
template.Draw(canvas)
assertLines(t, canvas, []string{
"ARM ARMED",
"VTX tbl:-- ceil:63 req:-- ack:--",
"VIDEO ON",
})
}
func TestOSDTemplateRendersSelectedTableRequestedAndAppliedStates(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
presence.SetActive(true)
NewOSDTemplate(presence, stubSource{snapshot: osd.Snapshot{
Armed: true,
OpConfig: osd.OperatorConfig{
Table: osd.Table{Gen: 3, Hash: 0xcafe},
MaxPower: 127,
},
Policy: osd.GSPolicy{Level: 42},
Ack: osd.VTXAck{
Table: osd.Table{Gen: 3},
Level: 40,
Lifecycle: osd.VTXLifecycleApplied,
},
}, state: osd.SnapshotFresh}).Draw(canvas)
assertLines(t, canvas, []string{
"ARM ARMED",
"VTX tbl:3 ceil:127 req:42 ack:40",
"VIDEO ON",
})
}
func TestOSDTemplateRendersAckErrorState(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewOSDTemplate(presence, stubSource{snapshot: osd.Snapshot{
OpConfig: osd.OperatorConfig{MaxPower: 10},
Policy: osd.GSPolicy{Pending: true},
Ack: osd.VTXAck{Lifecycle: osd.VTXLifecycleError},
}, state: osd.SnapshotFresh}).Draw(canvas)
assertLines(t, canvas, []string{
"ARM OFF",
"VTX tbl:-- ceil:10 req:-- ack:ERR",
"VIDEO OFF",
})
}
func TestOSDTemplateRendersLevelZeroAsExplicitOff(t *testing.T) {
// Level 0 in an available policy or acknowledgment is an explicit
// off / no-runtime-command state and must render as 0; only a pending
// value — no producer yet — renders as the pending mark.
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewOSDTemplate(presence, stubSource{snapshot: osd.Snapshot{
OpConfig: osd.OperatorConfig{MaxPower: 0},
Policy: osd.GSPolicy{Level: 0},
Ack: osd.VTXAck{Level: 0, Lifecycle: osd.VTXLifecycleApplied},
}, state: osd.SnapshotFresh}).Draw(canvas)
assertLines(t, canvas, []string{
"ARM OFF",
"VTX tbl:-- ceil:0 req:0 ack:0",
"VIDEO OFF",
})
}
func TestOSDTemplateVideoLineUsesOnlyObservedLifecycle(t *testing.T) {
// The VIDEO line is sourced from the video lifecycle the display
// observes on the display server, never from the snapshot's Video
// field (the supervisor's launcher knowledge).
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
NewOSDTemplate(presence, stubSource{snapshot: osd.Snapshot{
Video: true,
}, state: osd.SnapshotFresh}).Draw(canvas)
for _, line := range canvas.lines() {
if strings.HasPrefix(line, "VIDEO") && line != "VIDEO OFF" {
t.Fatalf("line=%q: snapshot presence must never replace the observed lifecycle", line)
}
}
}
func TestOSDTemplateNeverDrawsTheFallbackText(t *testing.T) {
canvas := &fakeCanvas{width: 800, height: 600}
presence := NewVideoPresence()
template := NewOSDTemplate(presence, pendingSource(true, 63))
for _, active := range []bool{false, true, false} {
presence.SetActive(active)
template.Draw(canvas)
for _, line := range canvas.lines() {
if line == wantFallbackText {
t.Fatalf("the OSD is a telemetry surface, not a fallback: drew %q", line)
}
}
}
}
+6 -2
View File
@@ -13,11 +13,15 @@ func NewStatusTemplate(lines ...string) StatusTemplate {
func (t StatusTemplate) Draw(canvas Canvas) {
canvas.Clear()
drawLines(canvas, t.lines)
canvas.Flush()
}
func drawLines(canvas Canvas, lines []string) {
_, height := canvas.Size()
y := height / 2
for _, line := range t.lines {
for _, line := range lines {
canvas.Text(32, y, line)
y += 32
}
canvas.Flush()
}
+30
View File
@@ -0,0 +1,30 @@
package display
import "sync/atomic"
// VideoPresence is the shared decoded-video signal between a display target
// session and the templates it drives. Sessions update it from
// display-server events about the video output itself: a presented video
// window is presence, its unmap or destroy is video end. Nothing here
// inspects WFB or launcher processes, so a running-but-silent receiver never
// hides the fallback and the video pipeline is never touched.
type VideoPresence struct {
active atomic.Bool
}
// NewVideoPresence starts with video absent, so the fallback is visible
// before the first presented video output.
func NewVideoPresence() *VideoPresence {
return &VideoPresence{}
}
// Active reports whether decoded video output is being presented.
func (p *VideoPresence) Active() bool {
return p.active.Load()
}
// SetActive records video presence and reports whether the state changed, so
// callers can trigger exactly one redraw per lifecycle transition.
func (p *VideoPresence) SetActive(active bool) bool {
return p.active.Swap(active) != active
}
+26
View File
@@ -0,0 +1,26 @@
package display
import "testing"
func TestVideoPresenceTransitionsReportChange(t *testing.T) {
presence := NewVideoPresence()
if presence.Active() {
t.Fatal("video must be absent before any signal")
}
if !presence.SetActive(true) {
t.Fatal("first video appearance must report a change")
}
if !presence.Active() {
t.Fatal("video must be active after appearance")
}
if presence.SetActive(true) {
t.Fatal("repeated appearance must not report a change")
}
if !presence.SetActive(false) {
t.Fatal("video end must report a change")
}
if presence.Active() {
t.Fatal("video must be inactive after end")
}
}
+1334 -46
View File
File diff suppressed because it is too large Load Diff
+783 -9
View File
@@ -1,22 +1,36 @@
package display
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/shape"
"github.com/BurntSushi/xgb/xproto"
)
func TestX11FullscreenArgsKeepCanvasBelowVideo(t *testing.T) {
args := x11FullscreenArgs(0x1a2b)
joined := strings.Join(args, " ")
if !strings.Contains(joined, "add,fullscreen,below") {
t.Fatalf("args %v must request fullscreen with below stacking", args)
func TestX11FullscreenArgsOrderByRole(t *testing.T) {
below := strings.Join(x11FullscreenArgs(0x1a2b, RoleBelow), " ")
if !strings.Contains(below, "add,fullscreen,below") {
t.Fatalf("args %q must request fullscreen with below stacking", below)
}
if !strings.Contains(joined, "0x00001a2b") {
t.Fatalf("args %v must reference the kiosk window id", args)
if !strings.Contains(below, "0x00001a2b") {
t.Fatalf("args %q must reference the kiosk window id", below)
}
above := strings.Join(x11FullscreenArgs(0x1a2b, RoleAbove), " ")
if strings.Contains(above, "below") {
t.Fatalf("args %q must never stack the OSD overlay below video", above)
}
if !strings.Contains(above, "add,fullscreen,above") {
t.Fatalf("args %q must request fullscreen with above stacking", above)
}
}
@@ -36,10 +50,770 @@ func TestX11OpenerAppliesFullscreenArgsThroughHook(t *testing.T) {
return errors.New("wmctrl missing")
}}
if err := opener.applyFullscreen(x11FullscreenArgs(0x42)); err == nil {
if err := opener.applyFullscreen(x11FullscreenArgs(0x42, RoleBelow)); err == nil {
t.Fatal("hook error must propagate for logging")
}
if len(got) != 1 || !strings.Contains(strings.Join(got[0], " "), "add,fullscreen,below") {
t.Fatalf("hook args %v must request fullscreen with below stacking", got)
}
}
func TestClassifyVideoChangeTracksVideoWindowLifecycle(t *testing.T) {
const own = xproto.Window(0x10)
const video = xproto.Window(0x20)
const other = xproto.Window(0x30)
change, w := classifyVideoChange(xproto.MapNotifyEvent{Window: video}, own)
if change != videoAppeared || w != video {
t.Fatalf("map of a foreign window must announce video, got %v %v", change, w)
}
change, _ = classifyVideoChange(xproto.MapNotifyEvent{Window: own}, own)
if change != videoUnrelated {
t.Fatalf("map of the kiosk window must be unrelated, got %v", change)
}
change, w = classifyVideoChange(xproto.UnmapNotifyEvent{Window: video}, own)
if change != videoDisappeared || w != video {
t.Fatalf("unmap must announce a video end candidate, got %v %v", change, w)
}
change, _ = classifyVideoChange(xproto.UnmapNotifyEvent{Window: own}, own)
if change != videoUnrelated {
t.Fatalf("unmap of the kiosk window must be unrelated, got %v", change)
}
change, w = classifyVideoChange(xproto.UnmapNotifyEvent{Window: other}, own)
if change != videoDisappeared || w != other {
t.Fatalf("unmap of a foreign window must be an end candidate, got %v %v", change, w)
}
change, w = classifyVideoChange(xproto.DestroyNotifyEvent{Window: video}, own)
if change != videoDisappeared || w != video {
t.Fatalf("destroy must announce a video end candidate, got %v %v", change, w)
}
change, _ = classifyVideoChange(xproto.ExposeEvent{}, own)
if change != videoUnrelated {
t.Fatalf("expose must not change video presence, got %v", change)
}
}
func TestAddAndRemoveVideoWindowTrackPresenceTransitions(t *testing.T) {
const video = xproto.Window(0x20)
const second = xproto.Window(0x30)
windows := make(map[xproto.Window]struct{})
if !addVideoWindow(windows, video) {
t.Fatal("first video window must change presence")
}
if addVideoWindow(windows, video) {
t.Fatal("re-adding the tracked window must not change presence")
}
if addVideoWindow(windows, second) {
t.Fatal("a second video window must not change presence")
}
if removeVideoWindow(windows, second) {
t.Fatal("removing one of two video windows must not change presence")
}
if !removeVideoWindow(windows, video) {
t.Fatal("removing the last video window must change presence")
}
if removeVideoWindow(windows, video) {
t.Fatal("removing an untracked window must not change presence")
}
if len(windows) != 0 {
t.Fatalf("set %v must be empty after all video ended", windows)
}
}
func TestEWMHNonVideoWindowTypesExcludeDesktopHelpers(t *testing.T) {
for _, name := range []string{"DOCK", "DESKTOP", "TOOLBAR", "MENU", "UTILITY", "SPLASH", "DIALOG", "NOTIFICATION", "TOOLTIP"} {
if !ewmhNonVideoTypes[name] {
t.Fatalf("window type %q must not count as video", name)
}
}
for _, name := range []string{"NORMAL", "", "VIDEO_PLAY"} {
if ewmhNonVideoTypes[name] {
t.Fatalf("window type %q must count as video", name)
}
}
}
func TestUTF16Char2bEncodesPolishFallbackText(t *testing.T) {
chars := utf16Char2b(wantFallbackText, maxImageText16Units)
want := []xproto.Char2b{
{Byte1: 0, Byte2: 'B'}, {Byte1: 0, Byte2: 'r'}, {Byte1: 0, Byte2: 'a'}, {Byte1: 0, Byte2: 'k'}, {Byte1: 0, Byte2: ' '},
{Byte1: 0, Byte2: 'p'}, {Byte1: 0, Byte2: 'o'},
{Byte1: 0x01, Byte2: 0x42}, // ł
{Byte1: 0x01, Byte2: 0x05}, // ą
{Byte1: 0, Byte2: 'c'}, {Byte1: 0, Byte2: 'z'}, {Byte1: 0, Byte2: 'e'}, {Byte1: 0, Byte2: 'n'}, {Byte1: 0, Byte2: 'i'}, {Byte1: 0, Byte2: 'a'}, {Byte1: 0, Byte2: ' '},
{Byte1: 0, Byte2: 'W'}, {Byte1: 0, Byte2: 'F'}, {Byte1: 0, Byte2: 'B'},
}
if len(chars) != len(want) {
t.Fatalf("units=%v want %v", chars, want)
}
for i := range want {
if chars[i] != want[i] {
t.Fatalf("unit %d=%v want %v", i, chars[i], want[i])
}
}
}
func TestUTF16Char2bTruncatesToOneRequestLength(t *testing.T) {
if chars := utf16Char2b(wantFallbackText, 10); len(chars) != 10 {
t.Fatalf("units=%d want 10", len(chars))
}
}
func TestUTF16Char2bNeverSplitsSurrogatePairs(t *testing.T) {
// U+1F3A5 encodes as a surrogate pair (0xD83C, 0xDFA5): a cut that would
// land between the two units must back off instead of splitting it.
if chars := utf16Char2b("a🎥", 2); len(chars) != 1 || chars[0].Byte2 != 'a' {
t.Fatalf("units=%v want only the leading ASCII unit", chars)
}
if chars := utf16Char2b("🎥", 1); len(chars) != 0 {
t.Fatalf("units=%v want none, the pair does not fit", chars)
}
if chars := utf16Char2b("🎥", 2); len(chars) != 2 {
t.Fatalf("units=%v want the intact pair", chars)
}
if chars := utf16Char2b(wantFallbackText, 0); len(chars) != 0 {
t.Fatalf("units=%v want none for a zero limit", chars)
}
}
func TestFoldToASCIIStripsPolishDiacritics(t *testing.T) {
if got := foldToASCII(wantFallbackText); got != "Brak polaczenia WFB" {
t.Fatalf("foldToASCII=%q want %q", got, "Brak polaczenia WFB")
}
}
func TestFoldToASCIIKeepsPlainASCIIUntouched(t *testing.T) {
if got := foldToASCII("plain text"); got != "plain text" {
t.Fatalf("foldToASCII=%q want %q", got, "plain text")
}
}
func TestX11FontPatternRequestsUnicodeFixedFont(t *testing.T) {
if !strings.Contains(iso10646FontPattern, "fixed") {
t.Fatalf("font pattern %q must select a fixed font", iso10646FontPattern)
}
if !strings.Contains(iso10646FontPattern, "iso10646") {
t.Fatalf("font pattern %q must select a Unicode encoding for the exact fallback text", iso10646FontPattern)
}
}
func TestLayerMarkerIdentifiesOwnLayerWindows(t *testing.T) {
if layerMarkerValue(RoleBelow) == layerMarkerValue(RoleAbove) {
t.Fatal("roles must carry distinct marker payloads")
}
for _, role := range []LayerRole{RoleBelow, RoleAbove} {
if !markerIsGroundstation(layerMarkerValue(role)) {
t.Fatalf("marker %q must identify our own window", layerMarkerValue(role))
}
}
for _, foreign := range []string{"", "video", "desktop", "groundstation-fake"} {
if markerIsGroundstation(foreign) {
t.Fatalf("foreign marker payload %q must not identify our windows", foreign)
}
}
}
func TestMarkerWalkBoundsStayBoundedAndCoverFrameDepth(t *testing.T) {
depth, nodes := markerWalkBounds()
if depth <= 0 || nodes <= 0 {
t.Fatalf("marker walk bounds depth=%d nodes=%d must be positive", depth, nodes)
}
if nodes < depth {
t.Fatalf("node budget %d must cover at least a depth-%d ancestor chain", nodes, depth)
}
// A reparenting window manager puts each of our two layer windows inside
// its own frame, so the walk must reach our window below one frame.
if depth < 2 {
t.Fatalf("marker walk depth %d must cover our window below a window-manager frame", depth)
}
}
func TestEWMHWindowTypeAnnouncesOverlayRoleOnly(t *testing.T) {
if name := ewmhWindowTypeName(RoleAbove); !strings.Contains(name, "DOCK") {
t.Fatalf("OSD overlay window type %q must be the always-above helper role", name)
}
if name := ewmhWindowTypeName(RoleBelow); name != "" {
t.Fatalf("fallback canvas must keep announcing no window type, got %q", name)
}
}
func TestPresentedVideoDecisionExcludesOwnLayersAndHelpers(t *testing.T) {
video := windowFacts{inputOutput: true, viewable: true}
if !isPresentedVideoWindow(video) {
t.Fatal("a presented output window must count as video")
}
for name, facts := range map[string]windowFacts{
"input-only": {viewable: true},
"override-redirect": {inputOutput: true, viewable: true, overrideRedirect: true},
"unmapped": {inputOutput: true},
"auxiliary": {inputOutput: true, viewable: true, auxiliary: true},
"groundstation-canvas": {inputOutput: true, viewable: true, groundstation: true},
"groundstation-osd": {inputOutput: true, viewable: true, groundstation: true},
} {
if isPresentedVideoWindow(facts) {
t.Fatalf("%s window must never count as video", name)
}
}
// Window-manager frames around our layer windows carry no marker of
// their own; groundstationLayerWindow finds the marker below the frame,
// so framed Ground Station layers land in these same excluded facts.
}
func TestStackOrderByRoleKeepsLayersOnTheirSideOfVideo(t *testing.T) {
if mode := stackModeForVideoAppear(RoleBelow); mode != xproto.StackModeBelow {
t.Fatalf("canvas must park below appearing video, got %v", mode)
}
if mode := stackModeForVideoAppear(RoleAbove); mode != xproto.StackModeAbove {
t.Fatalf("OSD overlay must rise above appearing video, got %v", mode)
}
if !raisesOnVideoEnd(RoleBelow) {
t.Fatal("canvas must raise itself when video ends so the fallback returns")
}
if raisesOnVideoEnd(RoleAbove) {
t.Fatal("OSD overlay is already above video and must not restack on video end")
}
}
func TestOSDEventMaskNeverSelectsDeviceInput(t *testing.T) {
if osdEventMask&deviceInputEventMask != 0 {
t.Fatalf("OSD event mask must not select pointer or key input: %b", osdEventMask)
}
if osdEventMask&xproto.EventMaskExposure == 0 {
t.Fatal("OSD event mask must still select exposure for redraws")
}
}
func TestStackReassertKeepsTheOSDOnTop(t *testing.T) {
// While video is live the overlay must sit above the tracked video
// window; while video is absent the overlay must rise to the top,
// because the fallback canvas raises itself to the top when video ends
// and would otherwise bury the overlay's text. Only the OSD overlay
// re-asserts; the canvas and video windows are never moved by this.
windows := map[xproto.Window]struct{}{0x20: {}}
if sibling, mode, ok := stackReassert(RoleAbove, true, 0x20, windows); !ok || sibling != 0x20 || mode != xproto.StackModeAbove {
t.Fatalf("sibling=%v mode=%v ok=%v want above the tracked video window", sibling, mode, ok)
}
if sibling, mode, ok := stackReassert(RoleAbove, false, 0, nil); !ok || sibling != 0 || mode != xproto.StackModeAbove {
t.Fatalf("sibling=%v mode=%v ok=%v want a top raise while video is absent", sibling, mode, ok)
}
if _, _, ok := stackReassert(RoleBelow, true, 0x20, windows); ok {
t.Fatal("the fallback canvas must never re-assert stacking")
}
if _, _, ok := stackReassert(RoleAbove, true, 0x30, windows); ok {
t.Fatal("a stale top video window must not be restacked against")
}
if _, _, ok := stackReassert(RoleAbove, true, 0, windows); ok {
t.Fatal("no tracked video window means no video-relative restack")
}
}
func TestCreateWindowValuesOrderMatchesTheValueMask(t *testing.T) {
// The CreateWindow values must follow the mask bit order (back pixel,
// event mask, cursor) so the server reads each value correctly; the
// blank cursor hides the pointer over the layer from its first frame.
mask, values := createWindowValues(0x100, 0x200, 0xc0de)
if mask != xproto.CwBackPixel|xproto.CwEventMask|xproto.CwCursor {
t.Fatalf("mask=%b want back pixel, event mask and cursor bits", mask)
}
if len(values) != 3 || values[0] != 0x100 || values[1] != 0x200 || values[2] != 0xc0de {
t.Fatalf("values=%v want [backPixel eventMask cursor]", values)
}
}
func TestFullscreenStateAtomsOrderByRole(t *testing.T) {
// Fullscreen is requested as a pre-map _NET_WM_STATE property so a
// compliant window manager maps each layer genuinely fullscreen and
// undecorated from its first frame; a post-map client message alone
// leaves a decorated, repositioned window on the screen at startup.
below := fullscreenStateAtoms(RoleBelow)
if len(below) != 2 || below[0] != "_NET_WM_STATE_FULLSCREEN" || below[1] != "_NET_WM_STATE_BELOW" {
t.Fatalf("canvas state atoms=%v want fullscreen below", below)
}
above := fullscreenStateAtoms(RoleAbove)
if len(above) != 2 || above[0] != "_NET_WM_STATE_FULLSCREEN" || above[1] != "_NET_WM_STATE_ABOVE" {
t.Fatalf("OSD state atoms=%v want fullscreen above", above)
}
}
// scriptedCursorX scripts the checked blank-cursor request surface: it
// records every operation in order, can fail any single operation, and
// records reclaim calls — reproducing the production request-order and
// resource-lifecycle discipline without a server.
type scriptedCursorX struct {
failAt string
ops []string
freed []string
depths []uint8
}
func (s *scriptedCursorX) CreatePixmapChecked(pid xproto.Pixmap, _ xproto.Drawable, depth uint8, _, _ uint16) error {
s.depths = append(s.depths, depth)
s.ops = append(s.ops, "pixmap:"+strconv.FormatUint(uint64(pid), 10))
if s.failAt == s.ops[len(s.ops)-1] {
return fmt.Errorf("bad pixmap request")
}
if s.failAt == "bitmap-depth" && depth != 1 {
return fmt.Errorf("cursor bitmaps must be depth 1")
}
return nil
}
func (s *scriptedCursorX) CreateGCChecked(gc xproto.Gcontext, _ xproto.Drawable) error {
s.ops = append(s.ops, "gc")
if s.failAt == "gc" {
return fmt.Errorf("bad gc request")
}
return nil
}
func (s *scriptedCursorX) PolyFillRectangleChecked(drawable xproto.Drawable, _ xproto.Gcontext, _ []xproto.Rectangle) error {
s.ops = append(s.ops, "fill:"+strconv.FormatUint(uint64(drawable), 10))
if s.failAt == s.ops[len(s.ops)-1] {
return fmt.Errorf("bad fill request")
}
return nil
}
func (s *scriptedCursorX) FreeGC(gc xproto.Gcontext) {
s.ops = append(s.ops, "free-gc")
s.freed = append(s.freed, "gc")
}
func (s *scriptedCursorX) CreateCursorChecked(cid xproto.Cursor, _, _ xproto.Pixmap) error {
s.ops = append(s.ops, "cursor")
if s.failAt == "cursor" {
return fmt.Errorf("bad cursor request")
}
return nil
}
func (s *scriptedCursorX) FreePixmap(pid xproto.Pixmap) {
s.freed = append(s.freed, "pixmap:"+strconv.FormatUint(uint64(pid), 10))
}
func TestBlankCursorBuildsCheckedDepthOneBitmapsInOrder(t *testing.T) {
// Cursor source and mask must be 1-bit bitmaps — the depth mismatch of
// the previous implementation is what made CreateCursor fail on the
// device and poisoned the window id. Every request is checked at its
// own operation, in order, and the pixmaps and context are reclaimed
// once the cursor exists.
x := &scriptedCursorX{}
cursor, err := blankCursorOver(x, 0x1, 1, 0x20, 0x21, 0x30, 0x40)
if err != nil {
t.Fatal(err)
}
if cursor != 0x40 {
t.Fatalf("cursor=%d want 0x40", cursor)
}
want := []string{"pixmap:32", "pixmap:33", "gc", "fill:32", "fill:33", "free-gc", "cursor"}
if strings.Join(x.ops, ",") != strings.Join(want, ",") {
t.Fatalf("ops=%v want %v", x.ops, want)
}
for _, depth := range x.depths {
if depth != 1 {
t.Fatalf("cursor bitmap depth=%d want 1", depth)
}
}
if strings.Join(x.freed, ",") != "gc,pixmap:32,pixmap:33" {
t.Fatalf("freed=%v want the context and both bitmaps reclaimed", x.freed)
}
}
func TestBlankCursorRejectsNonBitmapDepths(t *testing.T) {
// The device regression: cursor bitmaps created at the root depth made
// the unchecked CreateCursor fail asynchronously, which poisoned the
// window id and surfaced only later as BadWindow on the shape request.
// The checked sequence must reject such a depth at its own operation.
x := &scriptedCursorX{failAt: "bitmap-depth"}
cursor, err := blankCursorOver(x, 0x1, 24, 0x20, 0x21, 0x30, 0x40)
if err == nil {
t.Fatal("a non-bitmap depth must fail the cursor sequence")
}
if cursor != 0 {
t.Fatal("a failed sequence must not return a cursor")
}
if len(x.ops) != 1 || x.ops[0] != "pixmap:32" {
t.Fatalf("ops=%v want the failure to stop the sequence at the first request", x.ops)
}
}
func TestBlankCursorAttributesFailureToItsOwnOperation(t *testing.T) {
cases := []struct {
failAt string
want string
}{
{"pixmap:32", "create cursor source bitmap"},
{"pixmap:33", "create cursor mask bitmap"},
{"gc", "create cursor graphics context"},
{"fill:32", "clear cursor source bitmap"},
{"fill:33", "clear cursor mask bitmap"},
{"cursor", "create blank cursor"},
}
for _, c := range cases {
x := &scriptedCursorX{failAt: c.failAt}
cursor, err := blankCursorOver(x, 0x1, 1, 0x20, 0x21, 0x30, 0x40)
if err == nil {
t.Fatalf("failAt=%q must fail", c.failAt)
}
if cursor != 0 {
t.Fatalf("failAt=%q must not return a cursor", c.failAt)
}
if !strings.Contains(err.Error(), c.want) {
t.Fatalf("failAt=%q error=%v want attribution %q", c.failAt, err, c.want)
}
// No operation after the failed one may run — resource reclamation
// (free-gc, pixmap frees) is the expected cleanup, not a dependent
// request.
for i, op := range x.ops {
if op == c.failAt {
for _, later := range x.ops[i+1:] {
if strings.HasPrefix(later, "free-") || strings.HasPrefix(later, "pixmap:") {
continue
}
t.Fatalf("failAt=%q: dependent operation ran after failure: %v", c.failAt, later)
}
break
}
}
}
}
func TestCreateWindowValuesOmitCursorWhenUnavailable(t *testing.T) {
// A failed cursor setup must never poison the window: with no cursor,
// the window maps with the default cursor and the value list drops the
// cursor bit entirely.
mask, values := createWindowValues(0x100, 0x200, 0)
if mask != xproto.CwBackPixel|xproto.CwEventMask {
t.Fatalf("mask=%b want back pixel and event mask only", mask)
}
if len(values) != 2 || values[0] != 0x100 || values[1] != 0x200 {
t.Fatalf("values=%v want [backPixel eventMask]", values)
}
}
// scriptedQueries scripts the one-time query bundle: fixed answers for
// shape extents, geometry, parent and stacking position, with an optional
// shape query error.
type scriptedQueries struct {
shape string
geom string
parent string
pos string
of string
shapeErr error
}
func (q *scriptedQueries) ShapeExtents(xproto.Window) (string, error) {
return q.shape, q.shapeErr
}
func (q *scriptedQueries) Geometry(xproto.Window) (string, error) {
return q.geom, nil
}
func (q *scriptedQueries) Parent(xproto.Window) (string, error) {
return q.parent, nil
}
func (q *scriptedQueries) StackPosition(xproto.Window) (string, string, error) {
return q.pos, q.of, nil
}
func TestRecordFlushEmitsFirstRedrawAndQueryBundleOnce(t *testing.T) {
var buf bytes.Buffer
presence := NewVideoPresence()
session := &x11Session{
role: RoleAbove,
diag: NewDiag(&buf),
video: presence,
width: 1920,
height: 1080,
lastTrigger: "initial",
queries: &scriptedQueries{
shape: "196x106+28+15", geom: "1920x1080+0+26",
parent: "0x1a00001", pos: "1", of: "3",
},
}
session.drawn = []xproto.Rectangle{
{X: 30, Y: 19, Width: 58, Height: 18},
{X: 30, Y: 51, Width: 196, Height: 18},
{X: 30, Y: 83, Width: 120, Height: 18},
}
session.recordFlush(nil)
session.recordFlush(nil) // the bundle and the first-redraw record are once-only
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 2 {
t.Fatalf("lines=%v want exactly the first_redraw and query records", lines)
}
wantFirst := "display_diag kind=first_redraw role=osd trigger=initial ops=0 regions=3 bounds=196x82+30+19 snap=none video=off stack=top ok"
if lines[0] != wantFirst {
t.Fatalf("first_redraw=%q want %q", lines[0], wantFirst)
}
wantQuery := "display_diag kind=query role=osd shape=196x106+28+15 geom=1920x1080+0+26 parent=0x1a00001 stack=1/3"
if lines[1] != wantQuery {
t.Fatalf("query=%q want %q", lines[1], wantQuery)
}
}
func TestRecordFlushReportsShapeErrorsWithoutBlockingTheLayer(t *testing.T) {
var buf bytes.Buffer
session := &x11Session{
role: RoleAbove,
diag: NewDiag(&buf),
video: NewVideoPresence(),
lastTrigger: "refresh",
queries: &scriptedQueries{shapeErr: errors.New("BadWindow")},
}
// The shape error arrives with the first flush: it must be carried by
// the first_redraw record and the query bundle reports its own query
// failure alongside.
session.recordFlush(errors.New("bounding shape: BadWindow"))
session.recordFlush(nil)
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 2 {
t.Fatalf("lines=%v want the first_redraw error record and the query error record", lines)
}
if !strings.Contains(lines[0], "ok=no") || !strings.Contains(lines[0], "err=bounding shape: BadWindow") {
t.Fatalf("first_redraw=%q must carry the shape error", lines[0])
}
if !strings.Contains(lines[1], "err=") {
t.Fatalf("query=%q must carry the query error", lines[1])
}
}
func TestSetDiagSnapshotEmitsTransitionsOnly(t *testing.T) {
var buf bytes.Buffer
session := &x11Session{role: RoleAbove, diag: NewDiag(&buf)}
session.SetDiagSnapshot("none")
session.SetDiagSnapshot("none")
session.SetDiagSnapshot("fresh")
session.SetDiagSnapshot("fresh")
session.SetDiagSnapshot("stale")
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 3 {
t.Fatalf("lines=%v want none, fresh and stale transitions only", lines)
}
for i, want := range []string{"none", "fresh", "stale"} {
if !strings.Contains(lines[i], "kind=snap") || !strings.Contains(lines[i], "state="+want) {
t.Fatalf("line %d=%q want the %s transition", i, lines[i], want)
}
}
}
func TestTransparentShapesEmptyInputAndOutput(t *testing.T) {
var input, output bool
for _, kind := range transparentShapeKinds() {
switch kind {
case shape.SkInput:
input = true
case shape.SkBounding:
output = true
}
}
if !input || !output {
t.Fatalf("shape kinds %v must empty both the input and the bounding region", transparentShapeKinds())
}
}
// stormSession builds an OSD layer session whose event source never runs
// dry: it serves an endless stream of non-Expose root events (the video
// fullscreen repaint storm), so the drain loop can only exit through its
// bound — never through an empty queue.
func stormSession(refresh time.Duration) *x11Session {
return &x11Session{
poll: time.Millisecond,
refresh: refresh,
pollEvent: func() (xgb.Event, xgb.Error) {
return xproto.ConfigureNotifyEvent{}, nil
},
probe: func() error { return nil },
}
}
func TestWaitEventRefreshesDuringContinuousEventStorm(t *testing.T) {
// The initially empty bounding shape is punched only by redraws: an
// endless stream of unrelated events must never starve the timer that
// drives the OSD refresh cadence.
session := stormSession(3 * time.Millisecond)
session.topVideo = 0
done := make(chan eventResult, 1)
go func() {
redraw, err := session.WaitEvent(context.Background())
done <- eventResult{redraw: redraw, err: err}
}()
select {
case result := <-done:
if result.err != nil {
t.Fatalf("WaitEvent=%v", result.err)
}
if !result.redraw {
t.Fatal("the refresh must request a redraw during an event storm")
}
case <-time.After(2 * time.Second):
t.Fatal("WaitEvent starved: the timer redraw never fired during the storm")
}
}
func TestWaitEventHonorsCancellationDuringEventStorm(t *testing.T) {
session := stormSession(time.Hour)
ctx, cancel := context.WithCancel(context.Background())
cancel()
done := make(chan eventResult, 1)
go func() {
redraw, err := session.WaitEvent(ctx)
done <- eventResult{redraw: redraw, err: err}
}()
select {
case result := <-done:
if result.redraw {
t.Fatal("cancellation must not be reported as a redraw")
}
if !errors.Is(result.err, context.Canceled) {
t.Fatalf("err=%v want clean cancellation during the storm", result.err)
}
case <-time.After(2 * time.Second):
t.Fatal("WaitEvent did not terminate on cancellation during the storm")
}
}
func TestWaitEventStillRedrawsOnExposeDuringEventStorm(t *testing.T) {
var served atomic.Bool
session := stormSession(0)
session.pollEvent = func() (xgb.Event, xgb.Error) {
if served.CompareAndSwap(false, true) {
return xproto.ExposeEvent{}, nil
}
return xproto.ConfigureNotifyEvent{}, nil
}
redraw, err := session.WaitEvent(context.Background())
if err != nil {
t.Fatal(err)
}
if !redraw {
t.Fatal("an expose event must still trigger a redraw during a storm")
}
}
func TestRoleBelowCanvasStaysEventDrivenDuringEventStorm(t *testing.T) {
// The fallback canvas has no refresh interval: an endless unrelated
// event stream must never produce refresh redraws, and only
// cancellation ends the wait.
session := stormSession(0)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
redraw, err := session.WaitEvent(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err=%v want clean cancellation without a refresh interval", err)
}
if redraw {
t.Fatal("the canvas must stay event-driven with no refresh redraws")
}
}
func TestOSDTextRectCoversTheGlyphCellAroundTheBaseline(t *testing.T) {
rect := osdTextRect(32, 32, 9, 6, 11, 3)
if rect.X != 30 || rect.Y != 19 {
t.Fatalf("origin=(%d,%d) want (30,19): the region must start left of and above the baseline", rect.X, rect.Y)
}
if rect.Width != 9*6+4 || rect.Height != 11+3+4 {
t.Fatalf("size=%dx%d want %dx%d with padding", rect.Width, rect.Height, 9*6+4, 11+3+4)
}
if osdTextRect(0, 0, 1, 6, 11, 3).Width == 0 {
t.Fatal("a one-unit text must still produce a visible region")
}
}
func TestX11SessionRecordsOSDTextRegionsOnlyAboveVideo(t *testing.T) {
above := &x11Session{role: RoleAbove, fontCell: 6, fontAscent: 11, fontDescent: 3}
above.recordOSDText(32, 32, 9)
above.recordOSDText(32, 64, 5)
if len(above.drawn) != 2 {
t.Fatalf("drawn=%v want one region per OSD text", above.drawn)
}
if above.drawn[0] != osdTextRect(32, 32, 9, 6, 11, 3) {
t.Fatalf("first region=%v want the glyph cell of the first text", above.drawn[0])
}
above.resetOSDRegions()
if len(above.drawn) != 0 {
t.Fatalf("drawn=%v want the recorded regions reset on clear", above.drawn)
}
below := &x11Session{role: RoleBelow, fontCell: 6, fontAscent: 11, fontDescent: 3}
below.recordOSDText(32, 32, 9)
if len(below.drawn) != 0 {
t.Fatalf("drawn=%v want none: the fallback canvas never punches output shapes", below.drawn)
}
}
func TestX11SessionWaitEventRefreshesOnItsInterval(t *testing.T) {
// The OSD layer redraws on its own slower cadence: refresh must return
// redraw even with no X events pending, so template data — the latest
// published snapshot — appears without video or exposure churn.
session := &x11Session{
poll: time.Millisecond,
refresh: 2 * time.Millisecond,
pollEvent: func() (xgb.Event, xgb.Error) { return nil, nil },
probe: func() error { return nil },
}
done := make(chan eventResult, 1)
go func() {
redraw, err := session.WaitEvent(context.Background())
done <- eventResult{redraw: redraw, err: err}
}()
select {
case result := <-done:
if result.err != nil {
t.Fatalf("WaitEvent=%v", result.err)
}
if !result.redraw {
t.Fatal("the refresh interval must request a redraw")
}
case <-time.After(2 * time.Second):
t.Fatal("WaitEvent never returned the refresh redraw")
}
}
func TestX11SessionWaitEventWithoutRefreshKeepsWaiting(t *testing.T) {
probes := 0
session := &x11Session{
poll: time.Millisecond,
pollEvent: func() (xgb.Event, xgb.Error) { return nil, nil },
probe: func() error {
probes++
return nil
},
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
redraw, err := session.WaitEvent(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("WaitEvent=%v want clean cancellation without a refresh interval", err)
}
if redraw {
t.Fatal("no refresh interval must mean no refresh redraws")
}
if probes == 0 {
t.Fatal("liveness probes must continue while idle")
}
}
+275
View File
@@ -0,0 +1,275 @@
package osd
import (
"os"
"path/filepath"
"testing"
"time"
"git.piksar.eu/piotr/groundstation/internal/protocol"
)
func TestTableSelectionRequiresAnIdentifier(t *testing.T) {
if (Table{}).Selected() {
t.Fatal("zero generation and hash mean no table is selected yet")
}
if !(Table{Gen: 3}).Selected() || !(Table{Hash: 9}).Selected() {
t.Fatal("either identifier alone selects a table")
}
}
func TestCeilingFromChannelScalesTheKnobLinearly(t *testing.T) {
// The temporary operator maxPower ceiling maps the full CH6 channel
// range onto the 0..127 level domain. It is operator intent only.
cases := []struct {
channel int16
want uint8
}{
{-1024, 0},
{-1023, 0},
{0, 63},
{512, 95},
{1023, 126},
{1024, 127},
}
for _, c := range cases {
if got := CeilingFromChannel(c.channel); got != c.want {
t.Fatalf("CeilingFromChannel(%d)=%d want %d", c.channel, got, c.want)
}
}
if CeilingFromChannel(-2000) != 0 || CeilingFromChannel(2000) != 127 {
t.Fatal("out-of-range channels must clamp to the level domain")
}
}
func TestSnapshotCarriesFourDistinctContractValues(t *testing.T) {
// The four contract values must stay distinct: every field survives a
// roundtrip at its own offset, so no value can silently alias another
// (for example a mode/power collapse of CH6 ceiling and applied VTX
// state).
snapshot := Snapshot{
Sequence: 7,
TimestampMS: 99,
Armed: true,
Video: true,
OpConfig: OperatorConfig{
Table: Table{Gen: 3, Hash: 0xdeadbeefcafe},
MaxPower: 95,
},
Policy: GSPolicy{
Pending: false,
Level: 42,
Reason: [8]byte{'a', 'd', 'a', 'p', 't'},
TimestampMS: 1234,
},
Ack: VTXAck{
Pending: false,
Table: Table{Gen: 2, Hash: 0xfeed},
Level: 40,
Lifecycle: VTXLifecycleApplied,
},
Link: GSObservedLink{
Known: true,
AgeMS: 250,
},
PublishedMS: 555,
}
snapshot.Channels[5] = 100
got, err := Decode(Encode(snapshot))
if err != nil {
t.Fatal(err)
}
if got != snapshot {
t.Fatalf("roundtrip lost contract state: %+v != %+v", got, snapshot)
}
}
func TestSnapshotCarriesExplicitPendingStates(t *testing.T) {
// Until the policy, acknowledgment and link producers exist the
// snapshot must carry their explicit pending/unknown states, never
// fabricated levels or metrics.
snapshot := Snapshot{
Armed: true,
OpConfig: OperatorConfig{
MaxPower: 63,
},
Policy: GSPolicy{Pending: true},
Ack: VTXAck{Pending: true, Lifecycle: VTXLifecyclePending},
Link: GSObservedLink{Known: false},
}
got, err := Decode(Encode(snapshot))
if err != nil {
t.Fatal(err)
}
if !got.Policy.Pending || got.Policy.Level != 0 {
t.Fatalf("policy=%+v must stay explicitly pending", got.Policy)
}
if !got.Ack.Pending || got.Ack.Level != 0 || got.Ack.Lifecycle != VTXLifecyclePending {
t.Fatalf("ack=%+v must stay explicitly pending", got.Ack)
}
if got.Link.Known || got.Link.AgeMS != 0 {
t.Fatalf("link=%+v must stay explicitly unknown", got.Link)
}
if got.OpConfig != snapshot.OpConfig {
t.Fatalf("operator config=%+v must survive", got.OpConfig)
}
}
func TestDecodeRejectsV1Snapshots(t *testing.T) {
// A v1-sized record cannot carry the contract; a v2-sized record that
// claims v1 must be rejected by version, not parsed loosely.
v1Shaped := make([]byte, Size)
v1Shaped[0], v1Shaped[1], v1Shaped[2] = Magic0, Magic1, Version-1
if _, err := Decode(v1Shaped); err == nil {
t.Fatal("a v1-marked record must be rejected")
}
}
func TestVTXLifecycleStatesAreDistinct(t *testing.T) {
if VTXLifecyclePending == VTXLifecycleApplied ||
VTXLifecycleApplied == VTXLifecycleError ||
VTXLifecyclePending == VTXLifecycleError {
t.Fatal("pending, applied and error must be distinct lifecycle states")
}
}
func TestSnapshotDomainsAreEncodedInDisjointByteRanges(t *testing.T) {
// The four contract domains — operator configuration (table identity
// and ceiling), the requested policy level, the applied acknowledgment
// level and the observed link — must occupy disjoint byte ranges: a
// change to one domain may never alias another domain's bytes, so
// future extensions land behind a version bump instead of colliding.
base := Snapshot{
Sequence: 1,
TimestampMS: 2,
Channels: [protocol.Channels]int16{},
Armed: false,
Video: false,
OpConfig: OperatorConfig{
Table: Table{Gen: 1, Hash: 1},
MaxPower: 1,
},
Policy: GSPolicy{Level: 1},
Ack: VTXAck{
Table: Table{Gen: 1},
Level: 1,
Lifecycle: VTXLifecycleApplied,
},
Link: GSObservedLink{Known: false},
}
deltas := map[string]struct {
rangeStart, rangeEnd int
mutate func(*Snapshot)
}{
"operator-config": {opMaxPowerOffset, policyLevelOffset, func(s *Snapshot) { s.OpConfig.MaxPower = 2 }},
"policy-level": {policyLevelOffset, ackTableGenOffset, func(s *Snapshot) { s.Policy.Level = 2 }},
"ack-level": {ackTableGenOffset, linkAgeOffset, func(s *Snapshot) { s.Ack.Level = 2 }},
"observed-link": {linkAgeOffset, crcOffset, func(s *Snapshot) { s.Link.AgeMS = 2 }},
}
reference := Encode(base)
for name, delta := range deltas {
modified := base
delta.mutate(&modified)
encoded := Encode(modified)
if len(encoded) != len(reference) {
t.Fatalf("%s: encoded length changed", name)
}
for i := range encoded {
if encoded[i] == reference[i] {
continue
}
// The CRC covers the whole record and necessarily changes with
// any domain change; every payload byte must stay inside the
// domain's own range.
if i >= crcOffset {
continue
}
if i < delta.rangeStart || i >= delta.rangeEnd {
t.Fatalf("%s: byte %d changed outside the domain range [%d,%d)",
name, i, delta.rangeStart, delta.rangeEnd)
}
}
if _, err := Decode(encoded); err != nil {
t.Fatalf("%s: modified snapshot must still decode: %v", name, err)
}
}
}
func TestDecodeRejectsCorruptionAtomically(t *testing.T) {
// Malformed input must never yield a partially decoded snapshot that
// could clear or corrupt one domain while keeping others: any flipped
// byte anywhere in the record rejects the whole snapshot, and the
// publisher keeps its last valid state until a new valid one arrives.
encoded := Encode(Snapshot{
OpConfig: OperatorConfig{Table: Table{Gen: 5, Hash: 5}, MaxPower: 5},
Policy: GSPolicy{Level: 5},
Ack: VTXAck{Level: 5, Lifecycle: VTXLifecycleApplied},
Link: GSObservedLink{Known: true, AgeMS: 5},
})
// Sample corruption positions across the whole record — magic, body
// regions and CRC — derived from the actual encoded length, so the
// atomicity contract holds across future version bumps and layout
// extensions without coupling to today's offsets.
positions := []int{
0,
len(encoded) / 4,
len(encoded) / 2,
3 * len(encoded) / 4,
len(encoded) - 1,
}
for _, offset := range positions {
corrupt := append([]byte(nil), encoded...)
corrupt[offset] ^= 0xff
got, err := Decode(corrupt)
if err == nil {
t.Fatalf("flipped byte at %d must reject the record", offset)
}
if got != (Snapshot{}) {
t.Fatalf("flipped byte at %d must not emit a partial snapshot", offset)
}
}
}
func TestFileCorruptionDoesNotClearLastValidSnapshot(t *testing.T) {
// A corrupted state file reports no snapshot for the moment, but the
// publisher retains its last valid snapshot and the next heartbeat
// rewrite restores exactly those values: corruption never clears
// last valid data, and nothing is fabricated in between.
path := filepath.Join(t.TempDir(), "osd-state.bin")
now := time.UnixMilli(10_000_000)
source := NewFileSource(path)
source.now = func() time.Time { return now }
want := testSnapshot()
want.PublishedMS = now.UnixMilli()
if err := os.WriteFile(path, Encode(want), 0644); err != nil {
t.Fatal(err)
}
if _, state := source.Latest(); state != SnapshotFresh {
t.Fatalf("state=%v want fresh before corruption", state)
}
corrupt := append([]byte(nil), Encode(want)...)
corrupt[len(corrupt)/2] ^= 0xff
if err := os.WriteFile(path, corrupt, 0644); err != nil {
t.Fatal(err)
}
if _, state := source.Latest(); state != SnapshotNone {
t.Fatalf("state=%v want none while the file is corrupt", state)
}
// The publisher's heartbeat rewrites its retained last valid snapshot.
if err := os.WriteFile(path, Encode(want), 0644); err != nil {
t.Fatal(err)
}
got, state := source.Latest()
if state != SnapshotFresh {
t.Fatalf("state=%v want fresh after the heartbeat restore", state)
}
if got != want {
t.Fatalf("restored snapshot=%+v want the untouched last valid %+v", got, want)
}
}
+523
View File
@@ -0,0 +1,523 @@
// Package osd is the shared flight OSD snapshot contract between the Ground
// Station supervisor and the kiosk display process. The supervisor owns the
// RC, arming, video and operator-configuration state and publishes immutable
// snapshots; the display renders the latest fresh snapshot on the transparent
// OSD overlay. The snapshot is a plain value: everything published is copied,
// so a reader can never observe or mutate a half-written state.
//
// The adaptive-link contract is modeled as four distinct values that must
// never be collapsed into one another: the operator configuration (selected
// power table plus the temporary CH6 maxPower ceiling), the ground-station
// policy (requested runtime level), the aircraft VTX acknowledgment (applied
// level and lifecycle) and the observed receiver link. Their producers —
// adaptive control, the VTX ack transport and WFB RX metric ingestion — do
// not exist yet and stay out of scope; until they arrive the snapshot carries
// explicit pending/unknown states instead of fabricated data. CH6 is operator
// intent only: it constrains what may be requested and is never proof of
// applied VTX power, and static configuration is never rendered or serialized
// as applied VTX state.
//
// Extension contract for future domains: the snapshot is an explicit,
// extensible foundation of independent domains — operator table identity,
// requested level, applied level, observed link, and flight telemetry
// (versioned WFB-derived battery/GPS/arm/flight-mode/attitude with source
// and freshness, future work). Telemetry domains land as new typed nested
// structs with their own explicit pending/unknown states, appended at fixed
// offsets before the CRC behind a version bump; the typed fields plus the
// versioned all-or-nothing codec are the extension seam, and no runtime
// placeholder fields exist before a domain is actually modeled. Domains are
// independent by construction: each occupies a disjoint byte range (pinned
// by contract tests), decoding is atomic — malformed or damaged records are
// rejected whole and can never clear one domain while keeping others — and
// the publisher retains its last valid snapshot, republishing it until a
// new valid snapshot replaces it. Flight telemetry stays independent of
// video and policy; battery, GPS and similar aircraft state must never be
// inferred from RC channels, and the only RC-derived flight state remains
// the already-defined CH5/AUX1 arm indication.
package osd
import (
"encoding/binary"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"git.piksar.eu/piotr/groundstation/internal/protocol"
)
const (
Magic0 byte = 'G'
Magic1 byte = 'O'
Version byte = 2
// Size is the fixed encoded snapshot length: magic and version, frame
// sequence and timestamp, all 16 final RC channels, one flags byte,
// the publish time, the four adaptive-link contract values and the CRC.
Size = 3 + 2 + 4 + protocol.Channels*2 + 1 + 8 + // 50: v2 header block
1 + // operator maxPower ceiling
4 + 8 + // operator table generation + hash
1 + 8 + 8 + // policy level + reason + timestamp
4 + 8 + 1 + 1 + // ack table generation + hash + level + lifecycle
8 + // link freshness age
2 // CRC
// DefaultStatePath is where the supervisor publishes snapshots and
// where the display reads them unless configured otherwise. It lives
// in tmpfs: snapshots are runtime telemetry, not persistent state.
DefaultStatePath = "/run/groundstation/osd-state.bin"
// Heartbeat is how often an unchanged snapshot is republished, so the
// display keeps seeing it as fresh while the UART stays healthy.
Heartbeat = 500 * time.Millisecond
// writeInterval is the minimum gap between two state-file writes. It
// bounds the write rate when RC channels change on every frame without
// delaying an arm or power transition noticeably.
writeInterval = 50 * time.Millisecond
// Freshness is the display-side maximum age of a rendered snapshot: a
// dead UART must end OSD rendering instead of freezing stale telemetry
// over live video.
Freshness = 2 * time.Second
// MaxVTXLevel is the upper bound of the VTX power level domain shared
// by the operator ceiling, the ground-station policy and the applied
// acknowledgment.
MaxVTXLevel uint8 = 127
)
// VTX acknowledgment lifecycle states.
const (
// VTXLifecyclePending means no acknowledgment has arrived yet.
VTXLifecyclePending uint8 = 0
// VTXLifecycleApplied means the VTX acknowledged applying the level.
VTXLifecycleApplied uint8 = 1
// VTXLifecycleError means the acknowledgment reported a lifecycle error.
VTXLifecycleError uint8 = 2
)
// Snapshot flag bits in the encoded record.
const (
flagArmed byte = 1 << iota
flagVideo
flagTableSelected
flagPolicyPending
flagAckPending
flagLinkKnown
)
// Fixed field offsets of the encoded record.
const (
publishedOffset = 42
opMaxPowerOffset = 50
opTableGenOffset = 51
opTableHashOffset = 55
policyLevelOffset = 63
policyReasonOffset = 64
policyTimeOffset = 72
ackTableGenOffset = 80
ackTableHashOffset = 84
ackLevelOffset = 92
ackLifecycleOffset = 93
linkAgeOffset = 94
crcOffset = Size - 2
)
var (
ErrLength = errors.New("groundstation/osd: invalid snapshot length")
ErrMagic = errors.New("groundstation/osd: invalid snapshot magic")
ErrVersion = errors.New("groundstation/osd: unsupported snapshot version")
ErrCRC = errors.New("groundstation/osd: invalid snapshot crc")
)
// Table identifies a selectable VTX power table by generation and content
// hash. Zero generation and hash mean no table is selected yet. The
// identifiers are the operator's opaque selection of a table target — the
// table generator (future work) owns real identity — and a statically
// configured selection is operator intent: it is never applied VTX state.
type Table struct {
Gen uint32
Hash uint64
}
// Selected reports whether a table has been selected at all.
func (t Table) Selected() bool { return t.Gen != 0 || t.Hash != 0 }
// OperatorConfig is the operator's configuration intent: the selected power
// table plus the temporary CH6 maxPower ceiling. It is never proof of
// applied VTX power: the ceiling constrains what the system may request,
// while the applied state comes only from a VTX acknowledgment.
type OperatorConfig struct {
Table Table
MaxPower uint8 // maxPower ceiling in the 0..127 level domain
}
// GSPolicy is the ground station's requested runtime VTX power level with
// the reason and time of the request. No policy producer exists yet (the
// adaptive controller is future work), so published policies stay Pending
// rather than fabricating a level. Within the 0..127 domain, level 0 is an
// explicit off / no-runtime-command request; only Pending marks the absent
// producer.
type GSPolicy struct {
Pending bool
Level uint8 // requested level, 0..127; 0 is explicit off
Reason [8]byte // producer-defined short reason tag
TimestampMS int64
}
// VTXAck is the aircraft VTX's acknowledgment: the table it accepted, the
// level it applied and its lifecycle/error state. No acknowledgment
// transport exists yet, so published acks stay Pending. Applied level 0 is
// an explicit applied-off state; only Pending marks the absent transport.
type VTXAck struct {
Pending bool
Table Table
Level uint8 // applied level, 0..127; 0 is explicit off
Lifecycle uint8
}
// GSObservedLink is the ground-station receiver's link observation with its
// freshness. WFB RX metrics are out of scope until that producer exists, so
// the observation stays explicitly UNKNOWN instead of carrying fabricated
// numbers.
type GSObservedLink struct {
Known bool // false = explicitly unknown
AgeMS int64 // freshness of the metrics at publication; 0 while unknown
}
// Snapshot is one immutable flight state: the final RC channels, the arm
// state derived from the configured arm channel, the supervisor's
// decoded-video presence knowledge and the four adaptive-link contract
// values, plus the provenance of the RC frame it was built from. The display
// never renders from the Video field: it gates on the video lifecycle it
// observes on the display server itself. PublishedMS is stamped at
// publication and is what the display uses to reject stale snapshots.
type Snapshot struct {
Sequence uint16
TimestampMS uint32
Channels [protocol.Channels]int16
Armed bool
Video bool
OpConfig OperatorConfig
Policy GSPolicy
Ack VTXAck
Link GSObservedLink
PublishedMS int64
}
// CeilingFromChannel maps the final CH6 channel onto the temporary operator
// maxPower ceiling: the full channel range -1024..1024 scales linearly onto
// the 0..127 level domain with clamping. The ceiling is operator intent
// only and never proof of applied VTX power.
func CeilingFromChannel(channel int16) uint8 {
if channel <= -1024 {
return 0
}
if channel >= 1024 {
return MaxVTXLevel
}
return uint8((int32(channel) + 1024) * int32(MaxVTXLevel) / 2048)
}
func Encode(snapshot Snapshot) []byte {
buf := make([]byte, Size)
buf[0], buf[1], buf[2] = Magic0, Magic1, Version
binary.LittleEndian.PutUint16(buf[3:5], snapshot.Sequence)
binary.LittleEndian.PutUint32(buf[5:9], snapshot.TimestampMS)
for i, value := range snapshot.Channels {
binary.LittleEndian.PutUint16(buf[9+i*2:9+i*2+2], uint16(value))
}
var flags byte
if snapshot.Armed {
flags |= flagArmed
}
if snapshot.Video {
flags |= flagVideo
}
if snapshot.OpConfig.Table.Selected() {
flags |= flagTableSelected
}
if snapshot.Policy.Pending {
flags |= flagPolicyPending
}
if snapshot.Ack.Pending {
flags |= flagAckPending
}
if snapshot.Link.Known {
flags |= flagLinkKnown
}
buf[41] = flags
binary.LittleEndian.PutUint64(buf[publishedOffset:opMaxPowerOffset], uint64(snapshot.PublishedMS))
buf[opMaxPowerOffset] = snapshot.OpConfig.MaxPower
binary.LittleEndian.PutUint32(buf[opTableGenOffset:opTableHashOffset], snapshot.OpConfig.Table.Gen)
binary.LittleEndian.PutUint64(buf[opTableHashOffset:policyLevelOffset], snapshot.OpConfig.Table.Hash)
buf[policyLevelOffset] = snapshot.Policy.Level
copy(buf[policyReasonOffset:policyTimeOffset], snapshot.Policy.Reason[:])
binary.LittleEndian.PutUint64(buf[policyTimeOffset:ackTableGenOffset], uint64(snapshot.Policy.TimestampMS))
binary.LittleEndian.PutUint32(buf[ackTableGenOffset:ackTableHashOffset], snapshot.Ack.Table.Gen)
binary.LittleEndian.PutUint64(buf[ackTableHashOffset:ackLevelOffset], snapshot.Ack.Table.Hash)
buf[ackLevelOffset] = snapshot.Ack.Level
buf[ackLifecycleOffset] = snapshot.Ack.Lifecycle
binary.LittleEndian.PutUint64(buf[linkAgeOffset:crcOffset], uint64(snapshot.Link.AgeMS))
binary.LittleEndian.PutUint16(buf[crcOffset:], protocol.CRC16CCITT(buf[:crcOffset]))
return buf
}
func Decode(buf []byte) (Snapshot, error) {
var snapshot Snapshot
if len(buf) != Size {
return snapshot, ErrLength
}
if buf[0] != Magic0 || buf[1] != Magic1 {
return snapshot, ErrMagic
}
if buf[2] != Version {
return snapshot, ErrVersion
}
if got, want := binary.LittleEndian.Uint16(buf[crcOffset:]), protocol.CRC16CCITT(buf[:crcOffset]); got != want {
return snapshot, fmt.Errorf("%w: got %04x want %04x", ErrCRC, got, want)
}
snapshot.Sequence = binary.LittleEndian.Uint16(buf[3:5])
snapshot.TimestampMS = binary.LittleEndian.Uint32(buf[5:9])
for i := range snapshot.Channels {
snapshot.Channels[i] = int16(binary.LittleEndian.Uint16(buf[9+i*2 : 9+i*2+2]))
}
flags := buf[41]
snapshot.Armed = flags&flagArmed != 0
snapshot.Video = flags&flagVideo != 0
snapshot.OpConfig.MaxPower = buf[opMaxPowerOffset]
snapshot.OpConfig.Table.Gen = binary.LittleEndian.Uint32(buf[opTableGenOffset:opTableHashOffset])
snapshot.OpConfig.Table.Hash = binary.LittleEndian.Uint64(buf[opTableHashOffset:policyLevelOffset])
snapshot.Policy.Level = buf[policyLevelOffset]
copy(snapshot.Policy.Reason[:], buf[policyReasonOffset:policyTimeOffset])
snapshot.Policy.TimestampMS = int64(binary.LittleEndian.Uint64(buf[policyTimeOffset:ackTableGenOffset]))
snapshot.Ack.Table.Gen = binary.LittleEndian.Uint32(buf[ackTableGenOffset:ackTableHashOffset])
snapshot.Ack.Table.Hash = binary.LittleEndian.Uint64(buf[ackTableHashOffset:ackLevelOffset])
snapshot.Ack.Level = buf[ackLevelOffset]
snapshot.Ack.Lifecycle = buf[ackLifecycleOffset]
snapshot.Link.AgeMS = int64(binary.LittleEndian.Uint64(buf[linkAgeOffset:crcOffset]))
snapshot.Policy.Pending = flags&flagPolicyPending != 0
snapshot.Ack.Pending = flags&flagAckPending != 0
snapshot.Link.Known = flags&flagLinkKnown != 0
snapshot.PublishedMS = int64(binary.LittleEndian.Uint64(buf[publishedOffset:opMaxPowerOffset]))
return snapshot, nil
}
// DecodeFile reads and decodes one snapshot from its state file.
func DecodeFile(path string) (Snapshot, error) {
data, err := os.ReadFile(path)
if err != nil {
return Snapshot{}, err
}
return Decode(data)
}
// Publisher publishes immutable snapshots latest-wins. Publish never blocks:
// it stores the snapshot atomically and only wakes the writer, so the UART,
// WFB and video paths never wait on state-file I/O. The writer persists the
// latest snapshot whenever it changes and republishes it as a heartbeat so
// the display keeps seeing it as fresh.
type Publisher struct {
latest atomic.Pointer[Snapshot]
wake chan struct{}
done chan struct{}
stopped chan struct{}
closeOnce sync.Once
path string
heartbeat time.Duration
writeInterval time.Duration
write func(path string, data []byte) error
logger *log.Logger
}
// NewPublisher builds an in-memory publisher without a writer goroutine.
func NewPublisher() *Publisher {
return newFilePublisher("", nil, Heartbeat, writeInterval, nil)
}
// NewFilePublisher builds a publisher that persists snapshots to path for
// the display process. Failures are logged and retried; they never block
// Publish.
func NewFilePublisher(path string, logger *log.Logger) *Publisher {
return newFilePublisher(path, writeStateFile, Heartbeat, writeInterval, logger)
}
func newFilePublisher(path string, write func(string, []byte) error, heartbeat, interval time.Duration, logger *log.Logger) *Publisher {
p := &Publisher{
wake: make(chan struct{}, 1),
done: make(chan struct{}),
stopped: make(chan struct{}),
path: path,
heartbeat: heartbeat,
writeInterval: interval,
write: write,
logger: logger,
}
if path != "" {
go p.loop()
}
return p
}
// Publish records the snapshot and wakes the writer. The published value is
// stamped with the publication time and stored as an immutable copy.
func (p *Publisher) Publish(snapshot Snapshot) {
snapshot.PublishedMS = time.Now().UnixMilli()
p.latest.Store(&snapshot)
if p.path == "" {
return
}
select {
case p.wake <- struct{}{}:
default:
}
}
// Latest reports the most recently published snapshot, if any.
func (p *Publisher) Latest() (Snapshot, bool) {
snapshot := p.latest.Load()
if snapshot == nil {
return Snapshot{}, false
}
return *snapshot, true
}
// Close stops the writer and removes the state file, so a stopped
// supervisor never leaves stale telemetry for the display to render.
// It is safe to call more than once and on an in-memory publisher.
func (p *Publisher) Close() {
p.closeOnce.Do(func() {
if p.path == "" {
return
}
close(p.done)
<-p.stopped
_ = os.Remove(p.path)
})
}
func (p *Publisher) loop() {
defer close(p.stopped)
ticker := time.NewTicker(p.writeInterval)
defer ticker.Stop()
var last Snapshot
have := false
var lastWrite time.Time
var lastErrLog time.Time
for {
select {
case <-p.wake:
case <-ticker.C:
case <-p.done:
return
}
snapshot := p.latest.Load()
if snapshot == nil {
continue
}
// Changed states go out as soon as the write floor allows; an
// unchanged state goes out on the heartbeat so the display keeps
// seeing it as fresh.
now := time.Now()
if have {
if *snapshot == last {
if now.Sub(lastWrite) < p.heartbeat {
continue
}
} else if now.Sub(lastWrite) < p.writeInterval {
continue
}
}
if err := p.write(p.path, Encode(*snapshot)); err != nil {
// Failures are retried on every tick, so a persistently
// broken state path is logged at most once per heartbeat
// instead of flooding the journal.
if p.logger != nil && now.Sub(lastErrLog) >= p.heartbeat {
p.logger.Printf("osd state write %s: %v", p.path, err)
lastErrLog = now
}
continue
}
last, have, lastWrite = *snapshot, true, now
}
}
// writeStateFile replaces the state file atomically: readers either see the
// previous complete snapshot or the new one, never a partial write. The file
// stays world-readable so the unprivileged display user can read it; it
// carries only flight telemetry.
func writeStateFile(path string, data []byte) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
temp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*")
if err != nil {
return err
}
tmpPath := temp.Name()
defer os.Remove(tmpPath)
if _, err := temp.Write(data); err != nil {
temp.Close()
return err
}
if err := temp.Chmod(0644); err != nil {
temp.Close()
return err
}
if err := temp.Close(); err != nil {
return err
}
return os.Rename(tmpPath, path)
}
// SnapshotState tells the display how to treat the latest snapshot.
type SnapshotState int
const (
// SnapshotNone means no snapshot has ever been decoded: the display
// renders explicit unknown state instead of last-known values.
SnapshotNone SnapshotState = iota
// SnapshotFresh means the snapshot is within the freshness window and
// its values are current.
SnapshotFresh
// SnapshotStale means the last successfully decoded snapshot is older
// than the freshness window: the display keeps showing its values
// marked as stale, never as current.
SnapshotStale
)
// FileSource reads the supervisor-published snapshot from its state file.
// It is the display-side end of the snapshot contract: missing or corrupt
// records report none, and a record beyond the freshness window is reported
// as stale last-known data rather than hidden, so the display can mark it
// visibly instead of freezing it as current.
type FileSource struct {
path string
// now is the clock used for freshness checks; tests replace it.
now func() time.Time
}
// NewFileSource builds a source reading the given state file.
func NewFileSource(path string) *FileSource {
return &FileSource{path: path, now: time.Now}
}
// Latest reports the current snapshot and its state.
func (s *FileSource) Latest() (Snapshot, SnapshotState) {
snapshot, err := DecodeFile(s.path)
if err != nil {
return Snapshot{}, SnapshotNone
}
if age := s.now().Sub(time.UnixMilli(snapshot.PublishedMS)); age > Freshness {
return snapshot, SnapshotStale
}
return snapshot, SnapshotFresh
}
+183
View File
@@ -0,0 +1,183 @@
package osd
import (
"bytes"
"errors"
"log"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestPublisherKeepsOnlyTheLatestSnapshot(t *testing.T) {
publisher := NewPublisher()
if _, ok := publisher.Latest(); ok {
t.Fatal("a publisher without snapshots must report none")
}
first := testSnapshot()
publisher.Publish(first)
got, ok := publisher.Latest()
if !ok {
t.Fatal("a published snapshot must be readable")
}
if got.Sequence != first.Sequence || got.PublishedMS == 0 {
t.Fatalf("latest=%+v must carry the published state with a publish timestamp", got)
}
second := first
second.Sequence = 7
second.Video = false
publisher.Publish(second)
got, _ = publisher.Latest()
if got.Sequence != 7 || got.Video {
t.Fatalf("latest=%+v must be the most recent snapshot", got)
}
}
func TestPublishNeverBlocksOnASlowWriter(t *testing.T) {
release := make(chan struct{})
var writes atomic.Int32
publisher := newFilePublisher(filepath.Join(t.TempDir(), "osd-state.bin"), func(string, []byte) error {
writes.Add(1)
<-release
return errors.New("unreachable")
}, Heartbeat, time.Millisecond, nil)
done := make(chan struct{})
go func() {
defer close(done)
for i := 0; i < 100; i++ {
snapshot := testSnapshot()
snapshot.Sequence = uint16(i)
publisher.Publish(snapshot)
}
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("publish must never wait for the state file writer")
}
close(release)
}
func TestFilePublisherPublishesSnapshotsToTheStateFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "run", "osd-state.bin")
publisher := NewFilePublisher(path, nil)
defer publisher.Close()
want := testSnapshot()
publisher.Publish(want)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if got, err := DecodeFile(path); err == nil && got == want {
if info, statErr := os.Stat(path); statErr != nil || info.Mode().Perm() != 0644 {
t.Fatalf("state file mode=%v want 0644 for the unprivileged display user", info.Mode())
}
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("the published snapshot never reached the state file")
}
func TestFilePublisherRewritesUnchangedStateAsHeartbeat(t *testing.T) {
var writes sync.Mutex
count := 0
publisher := newFilePublisher(filepath.Join(t.TempDir(), "osd-state.bin"),
func(path string, data []byte) error {
if err := os.WriteFile(path, data, 0644); err != nil {
return err
}
writes.Lock()
count++
writes.Unlock()
return nil
}, 10*time.Millisecond, 5*time.Millisecond, nil)
publisher.Publish(testSnapshot())
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
writes.Lock()
got := count
writes.Unlock()
if got >= 3 {
publisher.Close()
return
}
time.Sleep(time.Millisecond)
}
publisher.Close()
t.Fatal("an unchanged snapshot must keep being republished so it stays fresh")
}
func TestFilePublisherCloseRemovesTheStateFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "osd-state.bin")
publisher := NewFilePublisher(path, nil)
publisher.Publish(testSnapshot())
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(path); err == nil {
break
}
time.Sleep(time.Millisecond)
}
publisher.Close()
publisher.Close() // must be idempotent
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("state file stat=%v want removed after close", err)
}
}
func TestFilePublisherKeepsRetryingAfterAWriteFailure(t *testing.T) {
var attempts atomic.Int32
path := filepath.Join(t.TempDir(), "osd-state.bin")
publisher := newFilePublisher(path, func(path string, data []byte) error {
if attempts.Add(1) == 1 {
return errors.New("transient write failure")
}
return os.WriteFile(path, data, 0644)
}, time.Second, 5*time.Millisecond, log.New(os.Stderr, "", 0))
defer publisher.Close()
publisher.Publish(testSnapshot())
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if _, err := DecodeFile(path); err == nil {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("a failed state write must be retried, not dropped")
}
func TestFilePublisherThrottlesPersistentFailureLogs(t *testing.T) {
var logs sync.Mutex
var buffer bytes.Buffer
publisher := newFilePublisher(filepath.Join(t.TempDir(), "missing-dir", "osd-state.bin"),
func(string, []byte) error {
return errors.New("state path is broken")
}, 20*time.Millisecond, 5*time.Millisecond, log.New(&buffer, "", 0))
publisher.Publish(testSnapshot())
time.Sleep(150 * time.Millisecond)
publisher.Close()
logs.Lock()
defer logs.Unlock()
lines := strings.Count(buffer.String(), "\n")
// The write retries on every tick but must log at most once per
// heartbeat: about 150ms/20ms plus the first line, never per attempt.
if lines == 0 || lines > 8 {
t.Fatalf("failure log lines=%d want throttled reporting (1..8)", lines)
}
}
+156
View File
@@ -0,0 +1,156 @@
package osd
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
)
func testSnapshot() Snapshot {
var snapshot Snapshot
snapshot.Sequence = 0xbEEF
snapshot.TimestampMS = 123456
for i := range snapshot.Channels {
snapshot.Channels[i] = int16(-1024 + i*137)
}
snapshot.Armed = true
snapshot.Video = true
snapshot.OpConfig = OperatorConfig{Table: Table{Gen: 1}, MaxPower: 95}
snapshot.Policy = GSPolicy{Pending: true}
snapshot.Ack = VTXAck{Pending: true}
snapshot.Link = GSObservedLink{Known: false}
snapshot.PublishedMS = time.Now().UnixMilli()
return snapshot
}
func TestSnapshotSizeMatchesLayout(t *testing.T) {
// Header (magic, version, sequence, timestamp) + all 16 channels +
// flags + publish time + the four contract values + CRC must stay a
// small fixed record.
if Size != 50+1+12+17+14+8+2 {
t.Fatalf("Size=%d must match the documented layout", Size)
}
if encoded := Encode(testSnapshot()); len(encoded) != Size {
t.Fatalf("encoded=%d bytes want %d", len(encoded), Size)
}
}
func TestEncodeDecodeSnapshotRoundtrip(t *testing.T) {
want := testSnapshot()
got, err := Decode(Encode(want))
if err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("decoded=%+v want %+v", got, want)
}
}
func TestDecodeRejectsDamagedSnapshots(t *testing.T) {
encoded := Encode(testSnapshot())
if _, err := Decode(encoded[:len(encoded)-1]); !errors.Is(err, ErrLength) {
t.Fatalf("truncated decode=%v want ErrLength", err)
}
magic := append([]byte(nil), encoded...)
magic[1] = 'X'
if _, err := Decode(magic); !errors.Is(err, ErrMagic) {
t.Fatalf("magic decode=%v want ErrMagic", err)
}
version := append([]byte(nil), encoded...)
version[2] = Version + 1
if _, err := Decode(version); !errors.Is(err, ErrVersion) {
t.Fatalf("version decode=%v want ErrVersion", err)
}
corrupt := append([]byte(nil), encoded...)
corrupt[10] ^= 0xff
if _, err := Decode(corrupt); !errors.Is(err, ErrCRC) {
t.Fatalf("corrupt payload decode=%v want ErrCRC", err)
}
corruptCRC := append([]byte(nil), encoded...)
corruptCRC[len(corruptCRC)-1] ^= 0xff
if _, err := Decode(corruptCRC); !errors.Is(err, ErrCRC) {
t.Fatalf("corrupt crc decode=%v want ErrCRC", err)
}
}
func TestFileSourceAgeIsNotResetByRewritingIdenticalBytes(t *testing.T) {
// Publisher heartbeats rewrite the last snapshot's identical bytes; the
// display's staleness must key on the snapshot's own publish time, so a
// rewrite can never present stale data as current.
path := filepath.Join(t.TempDir(), "osd-state.bin")
now := time.UnixMilli(10_000_000)
source := NewFileSource(path)
source.now = func() time.Time { return now }
want := testSnapshot()
want.PublishedMS = now.UnixMilli()
if err := os.WriteFile(path, Encode(want), 0644); err != nil {
t.Fatal(err)
}
if _, state := source.Latest(); state != SnapshotFresh {
t.Fatalf("state=%v want fresh at publish time", state)
}
// Heartbeat rewrite of identical bytes at a later wall-clock time.
if err := os.WriteFile(path, Encode(want), 0644); err != nil {
t.Fatal(err)
}
source.now = func() time.Time { return now.Add(2 * Freshness) }
got, state := source.Latest()
if state != SnapshotStale {
t.Fatalf("state=%v want stale despite the heartbeat rewrite", state)
}
if got != want {
t.Fatalf("last-known snapshot=%+v want %+v", got, want)
}
}
func TestFileSourceReportsFreshStaleAndMissingStates(t *testing.T) {
path := filepath.Join(t.TempDir(), "osd-state.bin")
source := NewFileSource(path)
fixed := time.UnixMilli(10_000_000)
source.now = func() time.Time { return fixed }
if _, state := source.Latest(); state != SnapshotNone {
t.Fatalf("a missing state file must report state %v, got %v", SnapshotNone, state)
}
if err := os.WriteFile(path, []byte("garbage that is not a snapshot"), 0644); err != nil {
t.Fatal(err)
}
if _, state := source.Latest(); state != SnapshotNone {
t.Fatalf("a corrupt state file must report state %v, got %v", SnapshotNone, state)
}
want := testSnapshot()
want.PublishedMS = fixed.UnixMilli()
if err := os.WriteFile(path, Encode(want), 0644); err != nil {
t.Fatal(err)
}
got, state := source.Latest()
if state != SnapshotFresh {
t.Fatalf("a fresh snapshot must report state %v, got %v", SnapshotFresh, state)
}
if got != want {
t.Fatalf("got=%+v want %+v", got, want)
}
// The last successfully decoded snapshot must survive past the
// freshness window, marked stale instead of being hidden: the display
// shows last-known values as explicitly stale.
stale := want
stale.PublishedMS = fixed.Add(-Freshness - time.Second).UnixMilli()
if err := os.WriteFile(path, Encode(stale), 0644); err != nil {
t.Fatal(err)
}
got, state = source.Latest()
if state != SnapshotStale {
t.Fatalf("a snapshot beyond the freshness window must report state %v, got %v", SnapshotStale, state)
}
if got != stale {
t.Fatalf("last-known snapshot=%+v want %+v", got, stale)
}
}
+35 -9
View File
@@ -19,19 +19,45 @@ func Open115200(path string) (*os.File, error) {
return nil, err
}
termios.Iflag = 0
termios.Oflag = 0
termios.Lflag = 0
termios.Cflag &^= unix.CSIZE | unix.PARENB | unix.CSTOPB | unix.CRTSCTS
termios.Cflag |= unix.CS8 | unix.CREAD | unix.CLOCAL
termios.Ispeed = unix.B115200
termios.Ospeed = unix.B115200
termios.Cc[unix.VMIN] = 1
termios.Cc[unix.VTIME] = 0
configureRaw115200(termios)
if err := unix.IoctlSetTermios(int(file.Fd()), unix.TCSETS, termios); err != nil {
file.Close()
return nil, fmt.Errorf("configure %s: %w", path, err)
}
effective, err := unix.IoctlGetTermios(int(file.Fd()), unix.TCGETS)
if err != nil {
file.Close()
return nil, fmt.Errorf("read back %s: %w", path, err)
}
if err := verifyBaud(*effective, unix.B115200); err != nil {
file.Close()
return nil, fmt.Errorf("verify %s: %w", path, err)
}
return file, nil
}
// configureRaw115200 keeps the raw 115200 8N1 blocking-read configuration.
// On Linux TCSETS takes the line speed from the CBAUD bits in Cflag, so
// CBAUD must be cleared and B115200 selected there; Ispeed/Ospeed alone
// leave an inherited baud (for example 9600 from boot defaults) in effect.
func configureRaw115200(termios *unix.Termios) {
termios.Iflag = 0
termios.Oflag = 0
termios.Lflag = 0
termios.Cflag &^= unix.CSIZE | unix.PARENB | unix.CSTOPB | unix.CRTSCTS | unix.CBAUD
termios.Cflag |= unix.B115200
termios.Cflag |= unix.CS8 | unix.CREAD | unix.CLOCAL
termios.Ispeed = unix.B115200
termios.Ospeed = unix.B115200
termios.Cc[unix.VMIN] = 1
termios.Cc[unix.VTIME] = 0
}
func verifyBaud(termios unix.Termios, baud uint32) error {
if got := termios.Cflag & unix.CBAUD; got != baud {
return fmt.Errorf("effective baud bits %#o, want %#o", got, baud)
}
return nil
}
+59
View File
@@ -0,0 +1,59 @@
package serialport
import (
"testing"
"golang.org/x/sys/unix"
)
func TestConfigureRaw115200OverridesInheritedBaud(t *testing.T) {
var termios unix.Termios
termios.Iflag = unix.IGNBRK | unix.ICRNL
termios.Oflag = unix.OPOST
termios.Lflag = unix.ICANON | unix.ECHO
termios.Cflag = unix.B9600 | unix.CS8 | unix.CREAD | unix.CLOCAL | unix.HUPCL
termios.Ispeed = unix.B9600
termios.Ospeed = unix.B9600
configureRaw115200(&termios)
if got := termios.Cflag & unix.CBAUD; got != unix.B115200 {
t.Fatalf("effective baud bits=%#o want %#o", got, unix.B115200)
}
if got := termios.Cflag & unix.CSIZE; got != unix.CS8 {
t.Fatalf("character size bits=%#o want %#o", got, unix.CS8)
}
for _, flag := range []uint32{unix.CREAD, unix.CLOCAL} {
if termios.Cflag&flag == 0 {
t.Fatalf("flag %#o lost", flag)
}
}
for _, flag := range []uint32{unix.PARENB, unix.CSTOPB, unix.CRTSCTS} {
if termios.Cflag&flag != 0 {
t.Fatalf("flag %#o must be cleared", flag)
}
}
if termios.Iflag != 0 || termios.Oflag != 0 || termios.Lflag != 0 {
t.Fatal("raw mode must clear Iflag, Oflag and Lflag")
}
if termios.Ispeed != unix.B115200 || termios.Ospeed != unix.B115200 {
t.Fatalf("speed fields=%d/%d want 115200/115200", termios.Ispeed, termios.Ospeed)
}
if termios.Cc[unix.VMIN] != 1 || termios.Cc[unix.VTIME] != 0 {
t.Fatalf("VMIN=%d VTIME=%d want 1/0", termios.Cc[unix.VMIN], termios.Cc[unix.VTIME])
}
}
func TestVerifyBaudAcceptsOnlyConfiguredLineSpeed(t *testing.T) {
var inherited unix.Termios
inherited.Cflag = unix.B9600 | unix.CS8
if err := verifyBaud(inherited, unix.B115200); err == nil {
t.Fatal("inherited 9600 line speed must fail verification")
}
var configured unix.Termios
configured.Cflag = unix.B115200 | unix.CS8 | unix.CREAD
if err := verifyBaud(configured, unix.B115200); err != nil {
t.Fatalf("115200 line speed must verify: %v", err)
}
}