feat(daemon): run/events commands wiring log, config, controller and hub

Tails controller.txt, hot-reloads the active config, reconnects to the
controller, supervises the QML overlay with a tokenised ws:// URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013UzjWSBjtVZ2zi8fJxS2hH
This commit is contained in:
ziadarafatandClaude Opus 5.5 committed 2026-10-30 16:08:01 -06:00
1 parent 729c941fed
commit b71266ff17
4 files changed
+356 -1

No files matched your search

+22 -1
View File
@@ -23,6 +23,9 @@ import (
const usage = `usage: deckhudd <command>
commands:
run [ui-dir] run the daemon and launch the overlay from ui-dir
(default: ../share/deckhud/ui next to the binary)
events run without the overlay, printing events as JSON lines
find print the Deck controller hidraw device
dump print the active Steam Input config as deckhud sees it
monitor print button changes and stick angles live
@@ -39,6 +42,14 @@ func main() {
var err error
switch os.Args[1] {
case "run":
dir := defaultUIDir()
if len(os.Args) > 2 {
dir = os.Args[2]
}
err = run(ctx, runOpts{uiDir: dir})
case "events":
err = run(ctx, runOpts{print: true})
case "find":
var dev string
if dev, err = hid.Find("/sys"); err == nil {
@@ -145,7 +156,7 @@ func activeConfig() (*steamcfg.Config, string, appwatch.State, error) {
if err != nil {
return nil, "", st, err
}
for _, line := range strings.Split(string(log), "\n") {
for _, line := range splitLines(string(log)) {
st.Feed(line)
}
st.Flush()
@@ -203,3 +214,13 @@ func dump() error {
}
return nil
}
func splitLines(s string) []string { return strings.Split(s, "\n") }
func defaultUIDir() string {
exe, err := os.Executable()
if err != nil {
return "ui"
}
return filepath.Join(filepath.Dir(exe), "..", "share", "deckhud", "ui")
}
+217
View File
@@ -0,0 +1,217 @@
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/RustyRaptor/deckhud/internal/appwatch"
"github.com/RustyRaptor/deckhud/internal/engine"
"github.com/RustyRaptor/deckhud/internal/hid"
"github.com/RustyRaptor/deckhud/internal/ipc"
"github.com/RustyRaptor/deckhud/internal/steamcfg"
)
const protocolVersion = 1
type runOpts struct {
uiDir string // directory holding main.qml; empty = don't launch the UI
print bool // print events as JSON lines on stdout
}
// daemon owns the engine and the config it was built from.
type daemon struct {
opts runOpts
hub *ipc.Hub
mu sync.Mutex
eng *engine.Engine
cfg *steamcfg.Config
cfgPath string
cfgMod time.Time
app appwatch.State
}
func run(ctx context.Context, opts runOpts) error {
d := &daemon{opts: opts}
token := randomToken()
d.hub = ipc.NewHub(token, d.greeting)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
srv := &http.Server{Handler: d.hub}
go srv.Serve(ln)
defer srv.Close()
url := fmt.Sprintf("ws://%s/%s", ln.Addr(), token)
if err := d.reload(true); err != nil {
fmt.Fprintln(os.Stderr, "deckhudd: config:", err)
}
go d.watchConfig(ctx)
if opts.uiDir != "" {
go superviseUI(ctx, opts.uiDir, url)
}
d.readController(ctx)
return nil
}
func randomToken() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return hex.EncodeToString(b)
}
func (d *daemon) greeting() []any {
d.mu.Lock()
defer d.mu.Unlock()
msgs := []any{map[string]any{"type": "hello", "version": protocolVersion}}
if d.eng != nil {
msgs = append(msgs, d.configMsg())
st := d.eng.State()
msgs = append(msgs, engine.Event{Type: "state", State: &st})
}
return msgs
}
func (d *daemon) configMsg() map[string]any {
return map[string]any{"type": "config", "app": d.app.App, "title": d.cfg.Title}
}
func (d *daemon) emit(v any) {
d.hub.Broadcast(v)
if d.opts.print {
if data, err := json.Marshal(v); err == nil {
fmt.Println(string(data))
}
}
}
// reload re-reads Steam's log and the config it points at. With full=false it
// only follows log lines appended since the last call.
func (d *daemon) reload(full bool) error {
d.mu.Lock()
defer d.mu.Unlock()
changed := false
if full {
d.app = appwatch.State{}
data, err := os.ReadFile(logPath())
if err != nil {
return err
}
for _, line := range splitLines(string(data)) {
d.app.Feed(line)
}
d.app.Flush()
changed = true
}
path, err := steamcfg.Locator{SteamRoot: steamRoot()}.Resolve(d.app.App, d.app.ConfigSets)
if err != nil {
return err
}
st, err := os.Stat(path)
if err != nil {
return err
}
if !changed && path == d.cfgPath && st.ModTime().Equal(d.cfgMod) {
return nil
}
cfg, err := steamcfg.LoadFile(path)
if err != nil {
return err
}
d.cfg, d.cfgPath, d.cfgMod = cfg, path, st.ModTime()
d.eng = engine.New(cfg, engine.Options{})
st2 := d.eng.State()
go func(cfgMsg map[string]any, state engine.Event) { // emit outside the lock
d.emit(cfgMsg)
d.emit(state)
}(d.configMsg(), engine.Event{Type: "state", State: &st2})
return nil
}
func (d *daemon) watchConfig(ctx context.Context) {
tail := &appwatch.Tail{Path: logPath()}
tail.Poll() // skip history; reload(true) already replayed it
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
lines, _ := tail.Poll()
d.mu.Lock()
for _, l := range lines {
d.app.Feed(l)
}
d.app.Flush()
d.mu.Unlock()
if err := d.reload(false); err != nil {
fmt.Fprintln(os.Stderr, "deckhudd: config:", err)
}
}
}
// readController streams controller states into the engine, reopening the
// device after errors (e.g. suspend/resume).
func (d *daemon) readController(ctx context.Context) {
for ctx.Err() == nil {
f, err := openDevice(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "deckhudd: controller:", err)
} else {
err = hid.Stream(f, func(s hid.State) {
d.mu.Lock()
var evs []engine.Event
if d.eng != nil {
evs = d.eng.Update(s, time.Now())
}
d.mu.Unlock()
for _, e := range evs {
d.emit(e)
}
})
f.Close()
if err != nil && ctx.Err() == nil {
fmt.Fprintln(os.Stderr, "deckhudd: controller:", err)
}
}
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
}
}
}
// superviseUI keeps the QML overlay running, restarting it if it exits.
func superviseUI(ctx context.Context, dir, url string) {
qml := "/usr/lib/qt6/bin/qml"
for ctx.Err() == nil {
cmd := exec.CommandContext(ctx, qml, filepath.Join(dir, "main.qml"), "--", url)
cmd.Env = append(os.Environ(), "QT_FORCE_STDERR_LOGGING=1")
cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
if err := cmd.Run(); err != nil && ctx.Err() == nil {
fmt.Fprintln(os.Stderr, "deckhudd: ui exited:", err)
}
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
}
}
}
func logPath() string { return filepath.Join(steamRoot(), "logs", "controller.txt") }
+53
View File
@@ -0,0 +1,53 @@
package appwatch
import (
"bytes"
"io"
"os"
)
// Tail reads lines appended to a file between polls. If the file shrinks
// (Steam restarted and rewrote its log) it starts again from the top.
type Tail struct {
Path string
off int64
partial []byte
}
// Poll returns the complete lines added since the last call.
func (t *Tail) Poll() ([]string, error) {
f, err := os.Open(t.Path)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.Size() < t.off {
t.off, t.partial = 0, nil
}
if st.Size() == t.off {
return nil, nil
}
data, err := io.ReadAll(io.NewSectionReader(f, t.off, st.Size()-t.off))
if err != nil {
return nil, err
}
t.off += int64(len(data))
data = append(t.partial, data...)
var lines []string
for {
i := bytes.IndexByte(data, '\n')
if i < 0 {
break
}
lines = append(lines, string(bytes.TrimRight(data[:i], "\r")))
data = data[i+1:]
}
t.partial = append([]byte(nil), data...)
return lines, nil
}
+64
View File
@@ -0,0 +1,64 @@
package appwatch
import (
"os"
"path/filepath"
"reflect"
"testing"
)
func appendFile(t *testing.T, path, s string) {
t.Helper()
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteString(s); err != nil {
t.Fatal(err)
}
}
func TestTailReturnsOnlyNewCompleteLines(t *testing.T) {
path := filepath.Join(t.TempDir(), "controller.txt")
appendFile(t, path, "a\nb\n")
tl := &Tail{Path: path}
lines, err := tl.Poll()
if err != nil || !reflect.DeepEqual(lines, []string{"a", "b"}) {
t.Fatalf("first poll = %q, %v", lines, err)
}
if lines, _ := tl.Poll(); len(lines) != 0 {
t.Errorf("no growth should yield nothing, got %q", lines)
}
appendFile(t, path, "c\npart")
if lines, _ := tl.Poll(); !reflect.DeepEqual(lines, []string{"c"}) {
t.Errorf("partial line must wait, got %q", lines)
}
appendFile(t, path, "ial\n")
if lines, _ := tl.Poll(); !reflect.DeepEqual(lines, []string{"partial"}) {
t.Errorf("got %q", lines)
}
}
func TestTailRestartsAfterTruncationOrRotation(t *testing.T) {
path := filepath.Join(t.TempDir(), "controller.txt")
appendFile(t, path, "old line one\nold line two\n")
tl := &Tail{Path: path}
tl.Poll()
if err := os.WriteFile(path, []byte("new\n"), 0o644); err != nil { // Steam restarted
t.Fatal(err)
}
if lines, _ := tl.Poll(); !reflect.DeepEqual(lines, []string{"new"}) {
t.Errorf("got %q", lines)
}
}
func TestTailMissingFile(t *testing.T) {
tl := &Tail{Path: filepath.Join(t.TempDir(), "nope.txt")}
if _, err := tl.Poll(); err == nil {
t.Error("expected error for missing file")
}
}