Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ automatisch mit [git-cliff](https://git-cliff.org) aus den Commit-Messages gener
- Tags nur noch für festgehaltene Versionen
- Schichtzeiten mit Minuten in den Projektregeln
- Temperaturdiagramm in den Projektregeln
- Kamera-Wächter und go2rtc-Abgleich in den Projektregeln

### Fixed

- **icons**: Hochgeladene SVG-Symbole nehmen die Textfarbe an
- **calendar**: Schichtzeiten immer mit Minuten
- **weather**: Temperaturdiagramm so scharf wie der übrige Text
- **bring**: Kacheln schneiden Symbole und Namen nicht mehr ab
- **camera**: Eingefrorenes Kamerabild startet den Player neu
- **camera**: Stream bei go2rtc nicht mehr alle 5 Minuten neu anlegen

## [0.9.1] - 2026-11-14

Expand Down
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ Pi 5 · Ubuntu 26.04 Server · Host: nur Docker
4. Feature-API-Funktion im Frontend über den erzeugten Client schreiben.
- **Jeder Frontend-API-Aufruf läuft über den erzeugten Client** (`web/src/shared/api/client.ts`). Rohes `fetch` auf `/api/*` ist verboten.
- **Einzige Ausnahme: der Kamera-Stream** `GET /api/v1/camera/stream`. Er ist ein WebSocket-Proxy (`httputil.ReverseProxy`) und kein Strict-Server-Endpunkt. Er steht im Vertrag (101/404/426/502), ist per `exclude-operation-ids` von der Erzeugung ausgenommen und wird in `api.Register` von Hand registriert, bewusst öffentlich wie das Dashboard. Er leitet nur zur festen Quelle `mirror-camera` weiter, nichts aus der Anfrage des Browsers bestimmt die Quelle. Der Player `web/src/vendor/go2rtc/video-rtc.js` (MIT, unverändert bis auf den Herkunftskopf) öffnet ihn direkt.
- Der Player verbindet sich nur neu, wenn der Socket schließt oder `<video>` einen Fehler meldet. Eine hängende MSE-Wiedergabe bliebe stehen (go2rtc#1102). Deshalb baut ihn ein Wächter im Widget neu auf (`camera/stall.ts`): wenn 10 s lang kein neues Bild gezeigt wurde bzw. 20 s nach dem Start noch keins. Maßgeblich sind die gezeigten Bilder aus `getVideoPlaybackQuality()`, nicht `currentTime`, das der Player auch ohne Bild vorschiebt.
- Der Server meldet den Stream beim Start und nach jeder Änderung der Einstellungen per PUT an, danach prüft er nur per GET, ob go2rtc ihn noch kennt. Jedes PUT legt in go2rtc ein neues Stream-Objekt an und schreibt dessen Konfigurationsdatei neu.
- **Keine Datenbank.**
- Persistenter Zustand liegt unter `MIRROR_DATA_DIR` (Container: `/data`, ein Docker-Volume).
- Einstellungen liegen in `settings.json` mit `schemaVersion`.
Expand Down
81 changes: 69 additions & 12 deletions server/internal/camera/camera.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ type Options struct {
// Backoff is the wait before retry number attempt (0-based) while go2rtc
// is not reachable; nil uses 1 s doubling up to 30 s.
Backoff func(attempt int) time.Duration
// Resync is how often a successful registration is repeated, so a camera
// service that lost its state gets the stream again; 0 means 5 minutes.
// Resync is how often a successful registration is checked (Ensure, a
// read-only GET), so a camera service that lost its state gets the
// stream again; 0 means 5 minutes. It is not re-registered while go2rtc
// still knows it: every PUT puts a new stream object
// in go2rtc's map (a running consumer stays on the orphaned old one) and
// rewrites its config file on the SD card.
Resync time.Duration
}

Expand Down Expand Up @@ -104,13 +108,23 @@ func (s *Service) Apply() {
}

// Run keeps go2rtc in step with the settings until ctx ends. It registers on
// start and after every Apply, retries with backoff while go2rtc is down and
// repeats a successful registration now and then.
// start and after every Apply (Sync), retries with backoff while go2rtc is
// down (Sync again) and, once a pass succeeded and Resync has passed, only
// checks that go2rtc still knows the stream (Ensure). A failed check is
// followed by backoff and a full Sync.
func (s *Service) Run(ctx context.Context) {
attempt := 0
checkOnly := false // the next pass is the periodic check, not a registration
for {
wait := s.resync
if err := s.Sync(ctx); err != nil && !s.config().configured() {
var err error
if checkOnly {
err = s.Ensure(ctx)
} else {
err = s.Sync(ctx)
}
checkOnly = false
if err != nil && !s.config().configured() {
// Nothing to register and go2rtc is not running: that is the normal
// state for a mirror without the camera service, so no backoff and no warning.
s.log.Debug("camera service not reachable, camera is not configured", "error", err)
Expand All @@ -121,6 +135,7 @@ func (s *Service) Run(ctx context.Context) {
s.log.Warn("camera service not updated, will retry", "error", err, "retryIn", wait.String())
} else {
attempt = 0
checkOnly = true
}
timer := time.NewTimer(wait)
select {
Expand All @@ -130,6 +145,7 @@ func (s *Service) Run(ctx context.Context) {
case <-s.notify:
timer.Stop()
attempt = 0
checkOnly = false
case <-timer.C:
}
}
Expand All @@ -148,6 +164,36 @@ func (s *Service) Sync(ctx context.Context) error {
return s.request(ctx, http.MethodPut, url.Values{"name": {StreamName}, "src": {go2rtcSource(cfg.StreamURL)}})
}

// Ensure is the read-only counterpart of Sync: it asks go2rtc whether it
// knows the stream and only acts when that disagrees with the settings,
// registering a missing stream or removing one that is no longer wanted.
// Unlike a repeated PUT it leaves a running stream and go2rtc's config file
// alone.
func (s *Service) Ensure(ctx context.Context) error {
cfg := s.config()
if cfg.configured() && !supportedScheme(cfg.StreamURL) {
return ErrUnsupportedURL
}
status, err := s.do(ctx, http.MethodGet, url.Values{"src": {StreamName}})
if err != nil {
return err
}
switch status {
case http.StatusOK:
if cfg.configured() {
return nil
}
return s.request(ctx, http.MethodDelete, url.Values{"src": {StreamName}})
case http.StatusNotFound:
if cfg.configured() {
return s.Sync(ctx)
}
return nil
default:
return fmt.Errorf("GET camera stream: camera service answered %d", status)
}
}

func supportedScheme(raw string) bool {
lower := strings.ToLower(raw)
return strings.HasPrefix(lower, "rtsp://") || strings.HasPrefix(lower, "rtsps://") || strings.HasPrefix(lower, "rtspx://")
Expand Down Expand Up @@ -189,27 +235,38 @@ func (s *Service) endpoint(apiPath string, query url.Values) *url.URL {
return &u
}

// request calls go2rtc's /api/streams. Errors carry the status code or the
// do calls go2rtc's /api/streams and returns the status code. Errors carry the
// transport cause only: the request URL holds the stream address in its query
// and url.Error would print it.
func (s *Service) request(ctx context.Context, method string, query url.Values) error {
// and url.Error would print it. The body (which may echo the address) is read
// in a bounded way and dropped.
func (s *Service) do(ctx context.Context, method string, query url.Values) (int, error) {
u := s.endpoint("api/streams", query)
req, err := http.NewRequestWithContext(ctx, method, u.String(), nil)
if err != nil {
return errors.New("build camera service request")
return 0, errors.New("build camera service request")
}
resp, err := s.client.Do(req)
if err != nil {
var ue *url.Error
if errors.As(err, &ue) {
err = ue.Err
}
return fmt.Errorf("%s camera stream: %w", method, err)
return 0, fmt.Errorf("%s camera stream: %w", method, err)
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
if resp.StatusCode/100 != 2 {
return fmt.Errorf("%s camera stream: camera service answered %d", method, resp.StatusCode)
return resp.StatusCode, nil
}

// request calls go2rtc and treats anything but 2xx as an error carrying the
// method and status code only.
func (s *Service) request(ctx context.Context, method string, query url.Values) error {
status, err := s.do(ctx, method, query)
if err != nil {
return err
}
if status/100 != 2 {
return fmt.Errorf("%s camera stream: camera service answered %d", method, status)
}
return nil
}
Expand Down
185 changes: 185 additions & 0 deletions server/internal/camera/camera_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,3 +646,188 @@ func TestRunWhileConfiguredWarnsAndBacksOff(t *testing.T) {
t.Errorf("no warning while configured:\n%s", logs)
}
}

// methodFake answers per HTTP method and records every call; the body echoes
// an address like go2rtc does for a known stream.
type methodFake struct {
*fakeGo2RTC
statuses map[string]int
}

func newMethodFake(t *testing.T, statuses map[string]int) *methodFake {
t.Helper()
m := &methodFake{fakeGo2RTC: &fakeGo2RTC{}, statuses: statuses}
m.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
m.calls = append(m.calls, recorded{r.Method, r.URL.RawQuery, r.URL.Path})
st, ok := m.statuses[r.Method]
m.mu.Unlock()
if !ok {
st = http.StatusOK
}
w.WriteHeader(st)
_, _ = w.Write([]byte(`{"producers":[{"url":"rtsp://admin:geheim-passwort@192.168.1.20:554/stream1"}]}`))
}))
t.Cleanup(m.server.Close)
return m
}

func count(calls []recorded, method string) int {
n := 0
for _, c := range calls {
if c.method == method {
n++
}
}
return n
}

func TestEnsure(t *testing.T) {
configured := Config{Enabled: true, StreamURL: "rtspx://10.10.1.1:7441/Tok?enableSrtp"}
tests := []struct {
name string
cfg Config
get int
methods []string // expected methods in order
wantErr string
}{
{"configured, stream exists", configured, 200, []string{"GET"}, ""},
{"configured, stream missing", configured, 404, []string{"GET", "PUT"}, ""},
{"not configured, stream exists", Config{}, 200, []string{"GET", "DELETE"}, ""},
{"not configured, stream missing", Config{}, 404, []string{"GET"}, ""},
{"configured, go2rtc fails", configured, 500, []string{"GET"}, "500"},
{"not configured, go2rtc fails", Config{}, 500, []string{"GET"}, "500"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newMethodFake(t, map[string]int{"GET": tt.get})
s := newService(t, f.server.URL, fixed(tt.cfg), io.Discard)
err := s.Ensure(context.Background())
if tt.wantErr == "" && err != nil {
t.Fatal(err)
}
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr)
}
for _, part := range []string{"geheim", "admin", "Tok", "192.168.1.20", "10.10.1.1", "src="} {
if strings.Contains(err.Error(), part) {
t.Errorf("error leaks %q: %v", part, err)
}
}
}
calls := f.got()
if len(calls) != len(tt.methods) {
t.Fatalf("calls = %+v, want methods %v", calls, tt.methods)
}
for i, m := range tt.methods {
if calls[i].method != m {
t.Errorf("call %d = %s, want %s", i, calls[i].method, m)
}
}
if calls[0].query != "src=mirror-camera" {
t.Errorf("GET query = %q, want src=mirror-camera", calls[0].query)
}
if tt.name == "configured, stream missing" {
want := url.Values{"name": {StreamName}, "src": {"rtspx://10.10.1.1:7441/Tok"}}.Encode()
if calls[1].query != want {
t.Errorf("PUT query = %s, want %s", calls[1].query, want)
}
}
})
}
}

func TestEnsureNeverReachesGo2RTCWithAnUnsupportedAddress(t *testing.T) {
f := newMethodFake(t, nil)
s := newService(t, f.server.URL, fixed(Config{Enabled: true, StreamURL: "exec:ffmpeg"}), io.Discard)
if err := s.Ensure(context.Background()); !errors.Is(err, ErrUnsupportedURL) {
t.Errorf("err = %v, want ErrUnsupportedURL", err)
}
if n := len(f.got()); n != 0 {
t.Errorf("%d calls reached go2rtc", n)
}
}

func TestRunOnlyChecksAfterTheFirstRegistration(t *testing.T) {
f := newMethodFake(t, nil) // everything answers 200: the stream exists
logs := &logBuf{}
s, err := New(Options{
HTTPClient: &http.Client{Timeout: 2 * time.Second},
BaseURL: f.server.URL,
Config: fixed(Config{Enabled: true, StreamURL: secretURL}),
Logger: slog.New(slog.NewTextHandler(logs, nil)),
Backoff: func(int) time.Duration { return time.Millisecond },
Resync: 20 * time.Millisecond,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { s.Run(ctx); close(done) }()
t.Cleanup(func() { cancel(); <-done })

waitFor(t, func() bool { return count(f.got(), "GET") >= 4 }, "several periodic checks")
calls := f.got()
if calls[0].method != http.MethodPut {
t.Errorf("first call = %s, want PUT", calls[0].method)
}
if n := count(calls, "PUT"); n != 1 {
t.Errorf("PUTs = %d over several resync periods, want 1", n)
}

// A changed setting registers again.
s.Apply()
waitFor(t, func() bool { return count(f.got(), "PUT") == 2 }, "PUT after Apply")
if strings.Contains(logs.String(), "geheim") {
t.Errorf("log leaks the address: %s", logs)
}
}

func TestRunRegistersAgainWhenTheStreamIsGone(t *testing.T) {
f := newMethodFake(t, map[string]int{"GET": 404})
s, err := New(Options{
HTTPClient: &http.Client{Timeout: 2 * time.Second},
BaseURL: f.server.URL,
Config: fixed(Config{Enabled: true, StreamURL: "rtsp://cam/x"}),
Backoff: func(int) time.Duration { return time.Millisecond },
Resync: 20 * time.Millisecond,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { s.Run(ctx); close(done) }()
t.Cleanup(func() { cancel(); <-done })
// PUT (start), GET 404 -> PUT (the check found nothing).
waitFor(t, func() bool { return count(f.got(), "PUT") >= 2 }, "re-registration after a 404 check")
}

func TestRunFailedCheckBacksOffAndThenSyncs(t *testing.T) {
f := newMethodFake(t, map[string]int{"GET": 500})
a := &attempts{wait: time.Millisecond}
s, err := New(Options{
HTTPClient: &http.Client{Timeout: 2 * time.Second},
BaseURL: f.server.URL,
Config: fixed(Config{Enabled: true, StreamURL: "rtsp://cam/x"}),
Backoff: a.backoff,
Resync: 20 * time.Millisecond,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { s.Run(ctx); close(done) }()
t.Cleanup(func() { cancel(); <-done })
waitFor(t, func() bool { return count(f.got(), "PUT") >= 2 }, "full Sync after a failed check")
if got := a.got(); len(got) == 0 || got[0] != 0 {
t.Errorf("backoff attempts = %v, want to start with 0", got)
}
calls := f.got()
if len(calls) < 3 || calls[0].method != "PUT" || calls[1].method != "GET" || calls[2].method != "PUT" {
t.Errorf("calls = %+v, want PUT, GET, PUT", calls)
}
}
Loading
Loading