Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.
#!/usr/bin/env python
# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Nintendo Switch Joy-Con teleop input for the Tom Cartesian controller.
This is the gamepad sibling of the keyboard/intent layer in ``-m tomctl.control``. It reads one
or two Joy-Cons through pygame's joystick API and turns them into the SAME ``command_delta`` /
named-pose intents the keyboard uses — so the Joy-Cons drive the shared ``CartesianController`` with
no new control path. Two Joy-Cons map to the two sim arms (one each); one Joy-Con drives the single
real arm. The sim's web runner (``--web --gamepad``) and the real-arm runner (``--gamepad``) both
poll a ``GamepadSet`` built here once per control tick.
WHY A MAPPING WIZARD (and not a hardcoded layout): a *single* Joy-Con held sideways exposes its
sticks/buttons/d-pad differently across SDL versions and across the L vs R shell, so a fixed
axis/button table is unreliable. Instead we capture the layout interactively (``--map``) and persist
it to ``gamepad_profile.json`` (the same per-arm, JSON-on-disk pattern as ``ik_calibration.json``).
``--list`` shows connected devices; ``--probe`` is a live raw readout for debugging a mapping.
CONTROL MODEL (velocity, not per-press steps): the analog stick is continuous, so the stick drives a
bounded Cartesian *velocity* — each tick adds ``stick * max_speed * dt`` to the commanded tip target
via ``command_delta``; the controller's own slew/IK in ``control_step`` then follows smoothly. Z and
the gripper are on buttons (digital), applied as a held rate. Pose buttons (home/rest/save/custom)
and quit are edge-triggered (fire once per press); the deadman is level (held = freeze).
Quick start:
.venv/bin/python -m tomctl.gamepad --list # see connected Joy-Cons
.venv/bin/python -m tomctl.gamepad --map # capture the button/stick layout
.venv/bin/python -m tomctl.gamepad --probe # live raw axis/button readout
Then drive:
.venv/bin/python -m tomctl.control --web --gamepad # sim, two arms
.venv/bin/python -m tomctl.real --gamepad --dry-run # real, offline check
"""
from __future__ import annotations
import json
import time
from dataclasses import dataclass, field
from pathlib import Path
from tomctl import ASSETS
DEFAULT_PROFILE_PATH = ASSETS / "gamepad_profile.json"
# Velocity model (CALIBRATABLE via the profile's "motion" block). The stick maps to a bounded tip
# speed; Z/gripper buttons apply a held rate. Keep XY/Z speeds <= CartesianController.CART_MAX_SPEED_MPS
# (0.18) so the IK slew keeps up with the commanded target instead of lagging it.
DEFAULT_MOTION = {
"xy_speed_mps": 0.084, # max tip speed in the surface plane at full stick (30% slower than 0.12)
"z_speed_mps": 0.056, # tip speed along world Z while a Z button is held (30% slower than 0.08)
"grip_speed_pps": 56.0, # gripper command units/s while a grip button is held (30% slower than 80)
"deadzone": 0.15, # stick magnitude below this reads as zero (kills resting drift)
"expo": 0.35, # 0 = linear stick, 1 = full cubic (finer control near centre)
}
# The intents a controller can drive. Sticks are analog (xy_x/xy_y); the rest are digital (button /
# hat / trigger-as-button). Pose + quit are edge-triggered; deadman is level-held.
STICK_FUNCS = ("xy_x", "xy_y")
HELD_FUNCS = ("z_up", "z_down", "grip_open", "grip_close", "deadman")
EDGE_FUNCS = ("home", "rest", "save", "custom", "quit")
DIGITAL_FUNCS = HELD_FUNCS + EDGE_FUNCS
# Human-facing prompts for the mapping wizard. xy_x/xy_y are grounded in the gripper's intended motion
# (not "stick up/left") so the sign is correct regardless of how the shell is held.
FUNC_PROMPTS = {
"xy_x": "STICK: push the way you want the gripper to move OUT over the table (away from the arm)",
"xy_y": "STICK: push the way you want the gripper to move to its LEFT",
"z_up": "BUTTON: raise the gripper (Z up)",
"z_down": "BUTTON: lower the gripper (Z down)",
"grip_open": "BUTTON: open the gripper",
"grip_close": "BUTTON: close the gripper",
"home": "BUTTON: go to HOME (ready) pose",
"rest": "BUTTON: go to REST (stow) pose [optional — press Enter to skip]",
"save": "BUTTON: save current pose as CUSTOM [optional — press Enter to skip]",
"custom": "BUTTON: recall the CUSTOM pose [optional — press Enter to skip]",
"deadman": "BUTTON (hold): DEADMAN freeze [optional — press Enter to skip]",
"quit": "BUTTON: quit / stop teleop",
}
OPTIONAL_FUNCS = {"rest", "save", "custom", "deadman"}
def _require_pygame():
try:
import pygame # noqa: PLC0415
except ImportError as e: # pragma: no cover - environment guard
raise SystemExit(
"pygame is required for Joy-Con teleop. Install the gamepad extra:\n"
" uv sync --extra gamepad (or: .venv/bin/python -m pip install 'pygame>=2.5.1,<2.7.0')"
) from e
return pygame
# --- SDL / libudev workaround (Linux) --------------------------------------------------------------
# pip's Linux pygame wheels (including the aarch64 / Raspberry Pi build) bundle their OWN libSDL2,
# and that bundle is compiled WITHOUT libudev. SDL enumerates joysticks on Linux through libudev, so
# the bundled SDL reports ZERO controllers even when Joy-Cons are connected and readable (kernel
# js0/js1 + evdev nodes present) — the exact "No controllers detected" dead end on this rig. The
# system libSDL2 (apt) IS built with udev and enumerates them fine. ensure_udev_sdl() re-execs the
# process with that system SDL LD_PRELOADed, so pygame loads the working one.
_SDL_PRELOAD_SENTINEL = "_TOMCTL_SDL_PRELOADED" # set on the re-exec so we never loop
def _sdl_has_udev(path: str) -> bool:
"""Whether an SDL2 shared object was built WITH udev support. SDL dlopen()s libudev at runtime
(it never appears in ldd/DT_NEEDED), so the reliable tell is the embedded "libudev.so" dlopen
string — present only when SDL was compiled with udev, which is what enumerates /dev/input
joysticks on Linux."""
try:
with open(path, "rb") as f:
return b"libudev.so" in f.read()
except OSError:
return False
def _system_sdl2_with_udev() -> str | None:
"""Path to a SYSTEM libSDL2 built with udev (can enumerate /dev/input joysticks), or None."""
import glob # noqa: PLC0415
for pat in (
"/usr/lib/*/libSDL2-2.0.so.0", # multiarch (e.g. /usr/lib/aarch64-linux-gnu/...)
"/lib/*/libSDL2-2.0.so.0",
"/usr/lib/libSDL2-2.0.so.0",
"/usr/local/lib/libSDL2-2.0.so.0",
):
for p in sorted(glob.glob(pat)):
if _sdl_has_udev(p):
return p
return None
def _pygame_bundles_udevless_sdl() -> bool:
"""True if the pygame that WILL be imported bundles an SDL built WITHOUT udev (so it can't see
joysticks). Inspects the wheel's bundled libSDL2 on disk WITHOUT importing pygame (importing would
load SDL and defeat the LD_PRELOAD that follows)."""
import glob # noqa: PLC0415
import importlib.util # noqa: PLC0415
import os # noqa: PLC0415
try:
spec = importlib.util.find_spec("pygame")
except (ImportError, ValueError):
return False
if spec is None or not spec.submodule_search_locations:
return False
pkg = list(spec.submodule_search_locations)[0]
cands: list[str] = []
for d in (os.path.join(os.path.dirname(pkg), "pygame.libs"), os.path.join(pkg, ".libs"), pkg):
cands += glob.glob(os.path.join(d, "libSDL2-*.so*"))
if not cands:
return False # no bundled SDL -> pygame links the system SDL; nothing to fix
return not any(_sdl_has_udev(c) for c in cands)
def ensure_udev_sdl() -> None:
"""Make SDL able to enumerate joysticks on Linux (see the note above).
If pygame's bundled SDL lacks udev AND a udev-enabled system SDL exists, re-exec this process with
that system SDL LD_PRELOADed. No-op otherwise (non-Linux, already-good SDL, no system SDL, or
already re-exec'd). MUST be called BEFORE pygame is imported and BEFORE any hardware is opened,
because it replaces the process."""
import os # noqa: PLC0415
import sys # noqa: PLC0415
if sys.platform != "linux" or os.environ.get(_SDL_PRELOAD_SENTINEL):
return
if not _pygame_bundles_udevless_sdl():
return
sys_sdl = _system_sdl2_with_udev()
if not sys_sdl:
return # can't fix transparently; build_gamepad_set's error explains the manual remedy
existing = os.environ.get("LD_PRELOAD", "")
os.environ["LD_PRELOAD"] = f"{sys_sdl}:{existing}" if existing else sys_sdl
os.environ[_SDL_PRELOAD_SENTINEL] = "1"
print(
"[gamepad] pygame's bundled SDL has no libudev (joysticks are invisible to it) — "
f"relaunching with the system SDL preloaded:\n {sys_sdl}",
flush=True,
)
argv = list(getattr(sys, "orig_argv", [sys.executable, *sys.argv]))
try:
os.execv(sys.executable, [sys.executable, *argv[1:]])
except OSError as e: # re-exec failed: don't wedge — drop the sentinel and fall through
os.environ.pop(_SDL_PRELOAD_SENTINEL, None)
print(f"[gamepad] SDL preload re-exec failed ({e}); continuing as-is.", flush=True)
# ----------------------------------------------------------------------------------------
# Binding evaluation. A binding is a small dict describing one physical input; the same shapes are
# produced by the wizard and consumed at runtime, so the two never drift.
# stick : {"type":"axis","index":i,"invert":bool} -> float in [-1, 1]
# digital : {"type":"button","index":i} -> bool pressed
# {"type":"hat","index":i,"value":[x,y]} (matches the nonzero component)
# {"type":"axis","index":i,"sign":+1|-1,"threshold":t} (a trigger/stick used as a button)
# ----------------------------------------------------------------------------------------
def _eval_stick(js, b) -> float:
try:
v = float(js.get_axis(int(b["index"])))
except Exception:
return 0.0
return -v if b.get("invert") else v
def _eval_digital(js, b) -> bool:
if b is None:
return False
try:
t = b["type"]
if t == "button":
return bool(js.get_button(int(b["index"])))
if t == "hat":
hx, hy = js.get_hat(int(b["index"]))
wx, wy = b["value"]
return (wx != 0 and hx == wx) or (wy != 0 and hy == wy)
if t == "axis":
v = float(js.get_axis(int(b["index"])))
return v * float(b.get("sign", 1.0)) > float(b.get("threshold", 0.5))
except Exception:
return False
return False
def _expo(v: float, k: float) -> float:
"""Blend linear and cubic response so small stick deflections give fine control (k in [0,1])."""
return (1.0 - k) * v + k * v * v * v
@dataclass
class GamepadCommand:
"""One tick of intent from a single controller. dx/dy/dz/dgrip are already scaled by dt (ready to
hand to ``command_delta``). Pose flags + quit are edge-triggered (true only on the press tick);
deadman is level (true while held)."""
role: str
dx: float = 0.0
dy: float = 0.0
dz: float = 0.0
dgrip: float = 0.0
home: bool = False
rest: bool = False
save: bool = False
custom: bool = False
deadman: bool = False
quit: bool = False
def has_motion(self) -> bool:
return bool(self.dx or self.dy or self.dz or self.dgrip)
@dataclass
class Gamepad:
"""A single connected controller bound to one arm role, plus its mapping + motion config."""
role: str
joystick: object
bindings: dict
motion: dict
name: str = ""
_prev: dict = field(default_factory=dict) # edge-detection state per function
def poll(self, dt: float) -> GamepadCommand:
js, b, m = self.joystick, self.bindings, self.motion
cmd = GamepadCommand(role=self.role)
# --- analog stick -> bounded XY velocity (deadzone + expo, radial so diagonals aren't fast) ---
sx = _eval_stick(js, b["xy_x"]) if "xy_x" in b else 0.0
sy = _eval_stick(js, b["xy_y"]) if "xy_y" in b else 0.0
mag = (sx * sx + sy * sy) ** 0.5
dz_band = float(m["deadzone"])
if mag > dz_band:
# rescale past the deadzone to keep full range, then shape with expo
scale = _expo((mag - dz_band) / (1.0 - dz_band), float(m["expo"])) / mag
cmd.dx = sx * scale * float(m["xy_speed_mps"]) * dt
cmd.dy = sy * scale * float(m["xy_speed_mps"]) * dt
# --- digital held axes: Z + gripper as a constant rate while pressed ---
zsp = float(m["z_speed_mps"]) * dt
if _eval_digital(js, b.get("z_up")):
cmd.dz += zsp
if _eval_digital(js, b.get("z_down")):
cmd.dz -= zsp
gsp = float(m["grip_speed_pps"]) * dt
if _eval_digital(js, b.get("grip_open")):
cmd.dgrip += gsp
if _eval_digital(js, b.get("grip_close")):
cmd.dgrip -= gsp
cmd.deadman = _eval_digital(js, b.get("deadman"))
# --- edge-triggered: fire once on the press transition ---
for func in EDGE_FUNCS:
pressed = _eval_digital(js, b.get(func))
if pressed and not self._prev.get(func, False):
setattr(cmd, func, True)
self._prev[func] = pressed
return cmd
def freeze_controller(ctrl) -> None:
"""DEADMAN: stop all motion and pin every intent to the CURRENT solved pose (mirrors the real
runner's _freeze) so the slew, any named-pose move, and the gripper all halt, and the next jog
starts from here with no stale-target snap-back."""
from tomctl import control as cc # noqa: PLC0415 the shared control core
ctrl._cancel_path()
ctrl.target_pos = cc._tool_point(ctrl.kin.forward_kinematics(ctrl.joints_deg)).copy()
ctrl.commanded_pos = ctrl.target_pos.copy()
ctrl.commanded_gripper = ctrl.gripper
ctrl._cart_speed = 0.0
def apply_command(cmd: GamepadCommand, ctrl) -> None:
"""Route one ``GamepadCommand`` into a ``CartesianController`` using the SAME intent API the
keyboard uses. Deadman wins (freeze + ignore motion); otherwise a named-pose press takes the arm
over (cancels manual slew), and stick/Z/grip add to the commanded target."""
if cmd.deadman:
freeze_controller(ctrl)
return
if cmd.home:
ctrl.go_home()
elif cmd.rest:
ctrl.go_rest()
elif cmd.save:
ctrl.save_custom()
elif cmd.custom:
ctrl.go_custom()
if cmd.has_motion():
ctrl.command_delta(cmd.dx, cmd.dy, cmd.dz, cmd.dgrip)
# ----------------------------------------------------------------------------------------
# Profile load / save + device discovery.
# ----------------------------------------------------------------------------------------
def load_profile(path: str | Path = DEFAULT_PROFILE_PATH) -> dict | None:
path = Path(path)
if not path.exists():
return None
with open(path) as f:
return json.load(f)
def save_profile(profile: dict, path: str | Path = DEFAULT_PROFILE_PATH) -> None:
with open(path, "w") as f:
json.dump(profile, f, indent=2)
print(f"Saved gamepad profile -> {path}")
def init_joysticks():
"""Init pygame's joystick subsystem and return the list of connected joystick objects."""
import os # noqa: PLC0415
# Keep two paired Joy-Cons as SEPARATE devices (one per arm). SDL otherwise merges a connected
# L+R pair into a single combined controller, which would collapse our two-arm mapping. Must be
# set before pygame/SDL init. (Harmless with a single Joy-Con.)
os.environ.setdefault("SDL_JOYSTICK_HIDAPI_COMBINE_JOY_CONS", "0")
pygame = _require_pygame()
pygame.init()
pygame.joystick.init()
sticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
for js in sticks:
js.init()
return pygame, sticks
def _match_joystick(sticks, spec: dict, used: set) -> object | None:
"""Pick the connected joystick for a role: prefer a name-substring match, else first unused.
(Two Joy-Cons of the same shell share a GUID, so we match on the name, e.g. 'Joy-Con (L)'.)"""
want = (spec.get("name") or "").lower()
if want:
for i, js in enumerate(sticks):
if i not in used and want in js.get_name().lower():
used.add(i)
return js
for i, js in enumerate(sticks): # fall back to assignment order
if i not in used:
used.add(i)
return js
return None
def build_gamepad_set(
roles: list[str], profile: dict | None = None, profile_path: str | Path = DEFAULT_PROFILE_PATH
) -> list[Gamepad]:
"""Build the active ``Gamepad`` objects for the requested roles from the saved profile + the
currently-connected devices. Skips (with a warning) any role that has no mapping or no device."""
if profile is None:
profile = load_profile(profile_path)
if not profile or "controllers" not in profile:
raise SystemExit(
f"No gamepad profile found at {profile_path}.\n"
"Map your Joy-Con(s) first: .venv/bin/python -m tomctl.gamepad --map"
)
_, sticks = init_joysticks()
if not sticks:
raise SystemExit(
"No controllers detected. Pair the Joy-Con(s) over Bluetooth (bluetoothctl devices "
"Connected), then retry.\n"
" If they ARE connected but still invisible, pygame's SDL may lack libudev; retry with "
"the system SDL preloaded:\n"
" LD_PRELOAD=$(ldconfig -p | awk '/libSDL2-2.0.so.0/{print $NF; exit}') <your command>"
)
motion = {**DEFAULT_MOTION, **profile.get("motion", {})}
used: set = set()
pads: list[Gamepad] = []
for role in roles:
spec = profile["controllers"].get(role)
if not spec:
print(f" (no mapping for role '{role}' in the profile — skipping)")
continue
js = _match_joystick(sticks, spec, used)
if js is None:
print(f" (no connected controller available for role '{role}' — skipping)")
continue
pads.append(
Gamepad(
role=role, joystick=js, bindings=spec["bindings"], motion=motion, name=js.get_name()
)
)
print(f" role '{role}' <- {js.get_name()}")
if not pads:
raise SystemExit("No usable controller/role pairings. Re-run --map.")
return pads
def pump(pygame=None) -> None:
"""Process the SDL event queue so joystick reads return fresh values. Must be called from the
main thread each control tick (macOS only delivers joystick events when pumped on main)."""
if pygame is None:
pygame = _require_pygame()
pygame.event.pump()
# ----------------------------------------------------------------------------------------
# CLI: --list, --probe, --map.
# ----------------------------------------------------------------------------------------
def cmd_list() -> None:
_, sticks = init_joysticks()
if not sticks:
print("No controllers detected. Pair the Joy-Con(s) over Bluetooth and retry.")
return
print(f"{len(sticks)} controller(s) detected:\n")
for i, js in enumerate(sticks):
print(
f" [{i}] {js.get_name()}\n"
f" guid={js.get_guid()} axes={js.get_numaxes()} "
f"buttons={js.get_numbuttons()} hats={js.get_numhats()}"
)
def cmd_probe() -> None:
pygame, sticks = init_joysticks()
if not sticks:
print("No controllers detected.")
return
print("Live raw readout — move sticks / press buttons. Ctrl-C to stop.\n")
try:
while True:
pygame.event.pump()
lines = []
for i, js in enumerate(sticks):
axes = " ".join(f"{js.get_axis(a):+.2f}" for a in range(js.get_numaxes()))
btns = "".join(str(b) if js.get_button(b) else "." for b in range(js.get_numbuttons()))
hats = " ".join(str(js.get_hat(h)) for h in range(js.get_numhats()))
lines.append(f"[{i}] axes[{axes}] btn[{btns}] hat[{hats}]")
print("\r" + " | ".join(lines) + " ", end="", flush=True)
time.sleep(0.05)
except KeyboardInterrupt:
print("\nStopped.")
def _capture_stick(pygame, js, settle: float = 0.4):
"""Wait for the user to deflect one stick axis, return (index, invert) so that the intended
direction reads POSITIVE. invert is chosen from the sign of the deflection."""
pygame.event.pump()
base = [js.get_axis(a) for a in range(js.get_numaxes())]
while True:
pygame.event.pump()
best_i, best_d = -1, 0.0
for a in range(js.get_numaxes()):
d = js.get_axis(a) - base[a]
if abs(d) > abs(best_d):
best_i, best_d = a, d
if abs(best_d) > 0.6:
time.sleep(settle) # let it settle so we read the steady direction
pygame.event.pump()
d = js.get_axis(best_i) - base[best_i]
invert = d < 0 # invert so pushing the intended way yields +1
print(f" -> axis {best_i} (invert={invert})")
_wait_release_axis(pygame, js, best_i, base[best_i])
return {"type": "axis", "index": best_i, "invert": invert}
time.sleep(0.02)
def _wait_release_axis(pygame, js, idx, base, tol: float = 0.3) -> None:
while True:
pygame.event.pump()
if abs(js.get_axis(idx) - base) < tol:
return
time.sleep(0.02)
def _capture_digital(pygame, js, allow_skip: bool):
"""Wait for a button / hat / trigger press; return its binding, or None if the user skips.
Skipping is keyboard Enter, detected by a short non-blocking poll between SDL pumps."""
import select # noqa: PLC0415
import sys # noqa: PLC0415
pygame.event.pump()
base_axes = [js.get_axis(a) for a in range(js.get_numaxes())]
while True:
pygame.event.pump()
for bnum in range(js.get_numbuttons()):
if js.get_button(bnum):
print(f" -> button {bnum}")
_wait_release_button(pygame, js, bnum)
return {"type": "button", "index": bnum}
for h in range(js.get_numhats()):
hx, hy = js.get_hat(h)
if hx or hy:
print(f" -> hat {h} {(hx, hy)}")
_wait_release_hat(pygame, js, h)
return {"type": "hat", "index": h, "value": [hx, hy]}
for a in range(js.get_numaxes()): # a trigger or stick pushed as a button
d = js.get_axis(a) - base_axes[a]
if abs(d) > 0.8:
sign = 1 if d > 0 else -1
print(f" -> axis {a} as button (sign={sign})")
_wait_release_axis(pygame, js, a, base_axes[a])
return {"type": "axis", "index": a, "sign": sign, "threshold": 0.5}
if allow_skip and select.select([sys.stdin], [], [], 0)[0]:
sys.stdin.readline()
print(" -> skipped")
return None
time.sleep(0.02)
def _wait_release_button(pygame, js, bnum) -> None:
while True:
pygame.event.pump()
if not js.get_button(bnum):
return
time.sleep(0.02)
def _wait_release_hat(pygame, js, h) -> None:
while True:
pygame.event.pump()
if js.get_hat(h) == (0, 0):
return
time.sleep(0.02)
def _map_one(pygame, js, role: str) -> dict:
print(f"\n=== Mapping role '{role}' -> {js.get_name()} ===")
print("Follow each prompt. For sticks, push fully and hold briefly; for buttons, press once.\n")
bindings: dict = {}
for func in STICK_FUNCS:
print(f" {func}: {FUNC_PROMPTS[func]}")
bindings[func] = _capture_stick(pygame, js)
for func in DIGITAL_FUNCS:
print(f" {func}: {FUNC_PROMPTS[func]}")
b = _capture_digital(pygame, js, allow_skip=func in OPTIONAL_FUNCS)
if b is not None:
bindings[func] = b
return {"name": js.get_name(), "guid": js.get_guid(), "bindings": bindings}
def cmd_map(roles: list[str], profile_path: str | Path) -> None:
pygame, sticks = init_joysticks()
if not sticks:
raise SystemExit("No controllers detected. Pair the Joy-Con(s) over Bluetooth and retry.")
print(f"{len(sticks)} controller(s) detected.")
profile = load_profile(profile_path) or {}
profile.setdefault("controllers", {})
profile.setdefault("motion", dict(DEFAULT_MOTION))
if len(sticks) < len(roles):
print(
f"Note: only {len(sticks)} controller(s) connected but {len(roles)} role(s) requested "
f"({', '.join(roles)}). Mapping what's connected; pair the other and re-run for the rest."
)
used: list = []
for role in roles:
# If more than one device, let the user pick which physical controller is this role.
remaining = [(i, js) for i, js in enumerate(sticks) if i not in used]
if not remaining:
break
if len(remaining) == 1:
idx, js = remaining[0]
else:
print(f"\nWhich controller is role '{role}'?")
for i, js in remaining:
print(f" [{i}] {js.get_name()}")
raw = input(" index: ").strip()
idx = int(raw) if raw.isdigit() and int(raw) in dict(remaining) else remaining[0][0]
js = dict(remaining)[idx]
used.append(idx)
profile["controllers"][role] = _map_one(pygame, js, role)
save_profile(profile, profile_path)
print("\nDone. Test it live with --probe, or drive the sim:")
print(" .venv/bin/python -m tomctl.control --web --gamepad")
def main() -> None:
import argparse # noqa: PLC0415
ensure_udev_sdl() # Linux: relaunch with a udev-enabled SDL if the bundled one can't see joysticks
p = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("--list", action="store_true", help="List connected controllers and exit.")
g.add_argument("--probe", action="store_true", help="Live raw axis/button/hat readout (debug).")
g.add_argument("--map", action="store_true", help="Interactive mapping wizard (writes the profile).")
p.add_argument(
"--roles",
default="arm1,arm2",
help="Comma-separated roles to map, in order (default: arm1,arm2). Real arm uses arm1.",
)
p.add_argument(
"--profile", default=str(DEFAULT_PROFILE_PATH), help="Profile JSON path (load/save)."
)
args = p.parse_args()
if args.list:
cmd_list()
elif args.probe:
cmd_probe()
elif args.map:
cmd_map([r.strip() for r in args.roles.split(",") if r.strip()], args.profile)
if __name__ == "__main__":
main()