feat(hid): Deck report decoder, device discovery, monitor/record CLI

Decodes report 0x09 (buttons, sticks, pads, triggers) per hid-steam's
layout, verified against a real idle capture. Finds the vendor
interface via sysfs, maps buttons to Steam config source/input names.

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 15:57:29 -06:00
1 parent 73795c6dd7
commit 3d2789e6a6
6 files changed
+601

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
// Command deckhudd is the deckhud daemon. During early development it also
// carries diagnostic subcommands.
package main
import (
"context"
"fmt"
"io"
"math"
"os"
"os/signal"
"time"
"github.com/RustyRaptor/deckhud/internal/hid"
)
const usage = `usage: deckhudd <command>
commands:
find print the Deck controller hidraw device
monitor print button changes and stick angles live
record <file> save raw controller reports to <file> (Ctrl+C to stop)
`
func main() {
if len(os.Args) < 2 {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
var err error
switch os.Args[1] {
case "find":
var dev string
if dev, err = hid.Find("/sys"); err == nil {
fmt.Println(dev)
}
case "monitor":
err = monitor(ctx)
case "record":
if len(os.Args) < 3 {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
err = record(ctx, os.Args[2])
default:
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "deckhudd:", err)
os.Exit(1)
}
}
// openDevice opens the controller and closes it when ctx ends, which unblocks
// any pending read.
func openDevice(ctx context.Context) (*os.File, error) {
dev, err := hid.Find("/sys")
if err != nil {
return nil, err
}
f, err := os.Open(dev)
if err != nil {
return nil, err
}
go func() { <-ctx.Done(); f.Close() }()
return f, nil
}
func monitor(ctx context.Context) error {
f, err := openDevice(ctx)
if err != nil {
return err
}
fmt.Println("press buttons / move sticks; Ctrl+C to quit")
var prev hid.State
var lastStick time.Time
err = hid.Stream(f, func(s hid.State) {
if pressed, released := prev.Buttons.Diff(s.Buttons); pressed|released != 0 {
pressed.Each(func(b hid.Button) {
in, _ := b.SteamInput()
fmt.Printf("down %-12s steam=%s/%s\n", b, in.Source, in.Name)
})
released.Each(func(b hid.Button) { fmt.Printf("up %s\n", b) })
}
if time.Since(lastStick) > 150*time.Millisecond {
for _, st := range []struct {
name string
v hid.Vec
}{{"left", s.LeftStick}, {"right", s.RightStick}} {
if mag := math.Hypot(float64(st.v.X), float64(st.v.Y)); mag > 8000 {
deg := math.Atan2(float64(st.v.X), float64(st.v.Y)) * 180 / math.Pi
fmt.Printf("%s stick: %4.0f° (0=up, clockwise) mag %5.0f\n", st.name, math.Mod(deg+360, 360), mag)
lastStick = time.Now()
}
}
}
prev = s
})
if ctx.Err() != nil {
return nil
}
return err
}
func record(ctx context.Context, path string) error {
f, err := openDevice(ctx)
if err != nil {
return err
}
out, err := os.Create(path)
if err != nil {
return err
}
defer out.Close()
n, err := io.Copy(out, f)
fmt.Fprintf(os.Stderr, "recorded %d reports\n", n/hid.ReportSize)
if ctx.Err() != nil {
return nil
}
return err
}
+62
View File
@@ -0,0 +1,62 @@
package hid
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Valve's USB IDs for the Steam Deck's built-in controller.
const deckHIDID = "000028DE:00001205"
// vendorUsagePage is the report-descriptor prefix of the interface that
// carries controller state (Usage Page 0xFFFF). The other two interfaces are
// the "lizard mode" mouse and keyboard.
var vendorUsagePage = []byte{0x06, 0xff, 0xff}
// Find returns the /dev path of the Deck controller's state interface.
// sysRoot is normally "/sys".
func Find(sysRoot string) (string, error) {
dirs, err := filepath.Glob(filepath.Join(sysRoot, "class", "hidraw", "hidraw*"))
if err != nil {
return "", err
}
for _, d := range dirs {
uevent, err := os.ReadFile(filepath.Join(d, "device", "uevent"))
if err != nil || !strings.Contains(strings.ToUpper(string(uevent)), "HID_ID=0003:"+deckHIDID) {
continue
}
desc, err := os.ReadFile(filepath.Join(d, "device", "report_descriptor"))
if err != nil || !bytes.HasPrefix(desc, vendorUsagePage) {
continue
}
return "/dev/" + filepath.Base(d), nil
}
return "", fmt.Errorf("hid: no Steam Deck controller found under %s", sysRoot)
}
// Stream reads reports from r until EOF or error, calling f for every decoded
// controller state. Non-state reports are skipped. A clean EOF returns nil.
func Stream(r io.Reader, f func(State)) error {
buf := make([]byte, ReportSize)
for {
if _, err := io.ReadFull(r, buf); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
s, err := Decode(buf)
if errors.Is(err, ErrNotInput) {
continue
}
if err != nil {
return err
}
f(s)
}
}
+66
View File
@@ -0,0 +1,66 @@
package hid
import (
"os"
"path/filepath"
"testing"
)
func fakeHidraw(t *testing.T, root, name, hidID string, desc []byte) {
t.Helper()
dir := filepath.Join(root, "class", "hidraw", name, "device")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
uevent := "DRIVER=hid-steam\nHID_ID=" + hidID + "\nHID_NAME=Valve Software Steam Controller\n"
if err := os.WriteFile(filepath.Join(dir, "uevent"), []byte(uevent), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "report_descriptor"), desc, 0o644); err != nil {
t.Fatal(err)
}
}
func TestFindPicksVendorInterfaceOfDeck(t *testing.T) {
sys := t.TempDir()
deck := "0003:000028DE:00001205"
fakeHidraw(t, sys, "hidraw0", deck, []byte{0x05, 0x01, 0x09, 0x02}) // lizard mouse
fakeHidraw(t, sys, "hidraw1", deck, []byte{0x05, 0x01, 0x09, 0x06}) // lizard keyboard
fakeHidraw(t, sys, "hidraw3", "0003:0000046D:0000C077", []byte{0x06, 0xff, 0xff, 0x09})
fakeHidraw(t, sys, "hidraw2", deck, []byte{0x06, 0xff, 0xff, 0x09}) // controller
got, err := Find(sys)
if err != nil {
t.Fatal(err)
}
if got != "/dev/hidraw2" {
t.Errorf("Find = %q, want /dev/hidraw2", got)
}
}
func TestFindNoDeck(t *testing.T) {
sys := t.TempDir()
fakeHidraw(t, sys, "hidraw0", "0003:0000046D:0000C077", []byte{0x05, 0x01})
if _, err := Find(sys); err == nil {
t.Fatal("expected error when no Deck controller is present")
}
}
func TestStreamSkipsNonInputAndStopsAtEOF(t *testing.T) {
a, b, status := blank(), blank(), blank()
a[8] = 0x80 // A
status[2] = 0x04
b[13] = 0x02 // L4
var buf []byte
for _, r := range [][]byte{a, status, b} {
buf = append(buf, r...)
}
var got []Button
err := Stream(bytesReader(buf), func(s State) { got = append(got, s.Buttons) })
if err != nil {
t.Fatalf("Stream: %v", err)
}
if len(got) != 2 || got[0] != A || got[1] != L4 {
t.Errorf("got %v", got)
}
}
+8
View File
@@ -0,0 +1,8 @@
package hid
import (
"bytes"
"io"
)
func bytesReader(b []byte) io.Reader { return bytes.NewReader(b) }
+181
View File
@@ -0,0 +1,181 @@
// Package hid decodes the Steam Deck ("Neptune") controller's raw HID input
// reports, which can be read from /dev/hidrawN alongside Steam without
// disturbing it.
//
// Layout follows the Linux hid-steam driver (steam_do_deck_input_event): a
// 4-byte header (version u16, type u8 = 0x09, length u8 = 0x40), then a
// little-endian payload.
package hid
import (
"encoding/binary"
"errors"
"fmt"
"math/bits"
"strings"
)
// ReportSize is the size of one Deck input report in bytes.
const ReportSize = 64
const typeDeckState = 0x09
// ErrNotInput is returned for well-formed reports that aren't controller state
// (battery/status reports share the same endpoint).
var ErrNotInput = errors.New("hid: not a deck state report")
// Vec is a raw signed 2D axis. Y is positive up for sticks and pads.
type Vec struct{ X, Y int16 }
// State is one decoded controller snapshot.
type State struct {
Seq uint32
Buttons Button
LeftPad, RightPad Vec
LeftTrigger, RightTrigger uint16 // 0..32767
LeftStick, RightStick Vec
LeftPadPressure, RightPadPressure uint16
}
// Decode parses a single report.
func Decode(r []byte) (State, error) {
if len(r) < 60 {
return State{}, fmt.Errorf("hid: short report (%d bytes)", len(r))
}
if r[2] != typeDeckState {
return State{}, ErrNotInput
}
le := binary.LittleEndian
i16 := func(off int) int16 { return int16(le.Uint16(r[off:])) }
return State{
Seq: le.Uint32(r[4:]),
Buttons: Button(le.Uint64(r[8:])) & allButtons,
LeftPad: Vec{i16(16), i16(18)},
RightPad: Vec{i16(20), i16(22)},
LeftTrigger: le.Uint16(r[44:]),
RightTrigger: le.Uint16(r[46:]),
LeftStick: Vec{i16(48), i16(50)},
RightStick: Vec{i16(52), i16(54)},
LeftPadPressure: le.Uint16(r[56:]),
RightPadPressure: le.Uint16(r[58:]),
}, nil
}
// Button is a bit set of physical controls. Bit n is bit (n%8) of report byte
// 8+n/8.
type Button uint64
const (
R2 Button = 1 << 0 // digital full pull
L2 Button = 1 << 1
R1 Button = 1 << 2
L1 Button = 1 << 3
Y Button = 1 << 4
B Button = 1 << 5
X Button = 1 << 6
A Button = 1 << 7
DpadUp Button = 1 << 8
DpadRight Button = 1 << 9
DpadLeft Button = 1 << 10
DpadDown Button = 1 << 11
View Button = 1 << 12
Steam Button = 1 << 13
Menu Button = 1 << 14
L5 Button = 1 << 15 // lower left back button
R5 Button = 1 << 16 // lower right back button
LeftPadClick Button = 1 << 17
RightPadClick Button = 1 << 18
LeftPadTouch Button = 1 << 19
RightPadTouch Button = 1 << 20
L3 Button = 1 << 22
R3 Button = 1 << 26
L4 Button = 1 << 41 // upper left back button
R4 Button = 1 << 42 // upper right back button
LeftStickTouch Button = 1 << 46
RightStickTouch Button = 1 << 47
QAM Button = 1 << 50 // quick access ("...") button
)
var buttonNames = []struct {
b Button
name string
}{
{A, "A"}, {B, "B"}, {X, "X"}, {Y, "Y"},
{L1, "L1"}, {R1, "R1"}, {L2, "L2"}, {R2, "R2"}, {L3, "L3"}, {R3, "R3"},
{L4, "L4"}, {R4, "R4"}, {L5, "L5"}, {R5, "R5"},
{DpadUp, "Up"}, {DpadDown, "Down"}, {DpadLeft, "Left"}, {DpadRight, "Right"},
{View, "View"}, {Menu, "Menu"}, {Steam, "Steam"}, {QAM, "QAM"},
{LeftPadClick, "LPadClick"}, {RightPadClick, "RPadClick"},
{LeftPadTouch, "LPadTouch"}, {RightPadTouch, "RPadTouch"},
{LeftStickTouch, "LStickTouch"}, {RightStickTouch, "RStickTouch"},
}
var allButtons = func() Button {
var all Button
for _, n := range buttonNames {
all |= n.b
}
return all
}()
// Has reports whether every button in o is in b.
func (b Button) Has(o Button) bool { return b&o == o }
// Diff returns the buttons newly pressed and newly released going from b to next.
func (b Button) Diff(next Button) (pressed, released Button) {
return next &^ b, b &^ next
}
// Each calls f for every single button in b, in stable order.
func (b Button) Each(f func(Button)) {
for _, n := range buttonNames {
if b.Has(n.b) {
f(n.b)
}
}
}
func (b Button) String() string {
if b == 0 {
return "none"
}
var parts []string
b.Each(func(o Button) {
for _, n := range buttonNames {
if n.b == o {
parts = append(parts, n.name)
}
}
})
return strings.Join(parts, "+")
}
// Input names a control the way Steam Input configs do: Source is the key used
// in a preset's group_source_bindings, Name is the input inside the group.
type Input struct {
Source string
Name string
}
var steamInputs = map[Button]Input{
A: {"button_diamond", "button_a"}, B: {"button_diamond", "button_b"},
X: {"button_diamond", "button_x"}, Y: {"button_diamond", "button_y"},
L1: {"switch", "left_bumper"}, R1: {"switch", "right_bumper"},
View: {"switch", "button_escape"}, Menu: {"switch", "button_menu"},
L5: {"switch", "button_back_left"}, R5: {"switch", "button_back_right"},
L4: {"switch", "button_back_left_upper"}, R4: {"switch", "button_back_right_upper"},
DpadUp: {"dpad", "dpad_north"}, DpadDown: {"dpad", "dpad_south"},
DpadLeft: {"dpad", "dpad_west"}, DpadRight: {"dpad", "dpad_east"},
L3: {"joystick", "click"}, R3: {"right_joystick", "click"},
L2: {"left_trigger", "click"}, R2: {"right_trigger", "click"},
LeftPadClick: {"left_trackpad", "click"}, RightPadClick: {"right_trackpad", "click"},
}
// SteamInput maps a single button to its Steam config source and input name.
func (b Button) SteamInput() (Input, bool) {
if bits.OnesCount64(uint64(b)) != 1 {
return Input{}, false
}
in, ok := steamInputs[b]
return in, ok
}
+159
View File
@@ -0,0 +1,159 @@
package hid
import (
"encoding/binary"
"encoding/hex"
"strings"
"testing"
)
// idle is a real report captured from a Steam Deck (LCD) with Steam running.
const idle = "0100094059 5f0e01 0000000000000000 0000000000000000 0000000000000000 0000000000000000" +
"0000000000000000 aa01cbfdadffc5ff 0000000008000200"
func mustHex(t *testing.T, s string) []byte {
t.Helper()
b, err := hex.DecodeString(strings.ReplaceAll(s, " ", ""))
if err != nil {
t.Fatal(err)
}
return b
}
func blank() []byte {
b := make([]byte, ReportSize)
b[0], b[1], b[2], b[3] = 0x01, 0x00, 0x09, 0x40
return b
}
func TestDecodeRealIdleReport(t *testing.T) {
s, err := Decode(mustHex(t, idle))
if err != nil {
t.Fatal(err)
}
if s.Seq != 0x010e5f59 {
t.Errorf("Seq = %#x", s.Seq)
}
if s.Buttons != 0 {
t.Errorf("Buttons = %v, want none", s.Buttons)
}
if s.LeftStick != (Vec{426, -565}) || s.RightStick != (Vec{-83, -59}) {
t.Errorf("sticks = %v %v", s.LeftStick, s.RightStick)
}
}
func TestDecodeButtonBits(t *testing.T) {
cases := []struct {
byteIdx, bit int
want Button
}{
{8, 0, R2}, {8, 1, L2}, {8, 2, R1}, {8, 3, L1},
{8, 4, Y}, {8, 5, B}, {8, 6, X}, {8, 7, A},
{9, 0, DpadUp}, {9, 1, DpadRight}, {9, 2, DpadLeft}, {9, 3, DpadDown},
{9, 4, View}, {9, 5, Steam}, {9, 6, Menu}, {9, 7, L5},
{10, 0, R5}, {10, 1, LeftPadClick}, {10, 2, RightPadClick},
{10, 3, LeftPadTouch}, {10, 4, RightPadTouch}, {10, 6, L3},
{11, 2, R3},
{13, 1, L4}, {13, 2, R4}, {13, 6, LeftStickTouch}, {13, 7, RightStickTouch},
{14, 2, QAM},
}
for _, c := range cases {
r := blank()
r[c.byteIdx] = 1 << c.bit
s, err := Decode(r)
if err != nil {
t.Fatal(err)
}
if s.Buttons != c.want {
t.Errorf("byte %d bit %d: got %v, want %v", c.byteIdx, c.bit, s.Buttons, c.want)
}
}
}
func TestDecodeAxes(t *testing.T) {
r := blank()
put := func(off int, v int16) { binary.LittleEndian.PutUint16(r[off:], uint16(v)) }
put(16, -100)
put(18, 200)
put(20, 300)
put(22, -400)
put(44, 32767)
put(46, 1000)
put(48, -32767)
put(50, 32767)
put(52, 12345)
put(54, -12345)
put(56, 50)
put(58, 60)
s, err := Decode(r)
if err != nil {
t.Fatal(err)
}
want := State{
LeftPad: Vec{-100, 200}, RightPad: Vec{300, -400},
LeftTrigger: 32767, RightTrigger: 1000,
LeftStick: Vec{-32767, 32767}, RightStick: Vec{12345, -12345},
LeftPadPressure: 50, RightPadPressure: 60,
}
if s != want {
t.Errorf("got %+v\nwant %+v", s, want)
}
}
func TestDecodeRejectsOtherReports(t *testing.T) {
short := blank()[:20]
other := blank()
other[2] = 0x04 // battery/status report
for name, r := range map[string][]byte{"short": short, "other type": other} {
if _, err := Decode(r); err == nil {
t.Errorf("%s: expected error", name)
}
}
if _, err := Decode(other); err != ErrNotInput {
t.Errorf("other type should return ErrNotInput, got %v", err)
}
}
func TestButtonSetHelpers(t *testing.T) {
set := A | L4 | QAM
if !set.Has(A) || !set.Has(L4) || set.Has(B) {
t.Error("Has wrong")
}
if got := set.String(); got != "A+L4+QAM" {
t.Errorf("String = %q", got)
}
pressed, released := (A | B).Diff(B | X)
if pressed != X || released != A {
t.Errorf("Diff: pressed %v released %v", pressed, released)
}
if got := Button(0).String(); got != "none" {
t.Errorf("empty String = %q", got)
}
}
func TestSteamInputNames(t *testing.T) {
// Source (group_source_bindings key) and input name used in Steam configs.
cases := map[Button]Input{
A: {"button_diamond", "button_a"}, B: {"button_diamond", "button_b"},
X: {"button_diamond", "button_x"}, Y: {"button_diamond", "button_y"},
L1: {"switch", "left_bumper"}, R1: {"switch", "right_bumper"},
View: {"switch", "button_escape"}, Menu: {"switch", "button_menu"},
L5: {"switch", "button_back_left"}, R5: {"switch", "button_back_right"},
L4: {"switch", "button_back_left_upper"}, R4: {"switch", "button_back_right_upper"},
DpadUp: {"dpad", "dpad_north"}, DpadDown: {"dpad", "dpad_south"},
DpadLeft: {"dpad", "dpad_west"}, DpadRight: {"dpad", "dpad_east"},
L3: {"joystick", "click"}, R3: {"right_joystick", "click"},
L2: {"left_trigger", "click"}, R2: {"right_trigger", "click"},
LeftPadClick: {"left_trackpad", "click"}, RightPadClick: {"right_trackpad", "click"},
}
for b, want := range cases {
if got, ok := b.SteamInput(); !ok || got != want {
t.Errorf("%v.SteamInput() = %v,%v want %v", b, got, ok, want)
}
}
for _, b := range []Button{Steam, QAM, LeftPadTouch, A | B} {
if _, ok := b.SteamInput(); ok {
t.Errorf("%v should have no Steam input mapping", b)
}
}
}