Loading files
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { ConnectionState, RoomEvent } from "livekit-client";
import { useRoom } from "@/components/livekit/RoomProvider";
import { useIdentity } from "@/lib/identity";
import {
BRIDGE_IDENTITY,
CONTROL_TOPIC,
DIRECTOR_TOPIC,
HELD,
STATE_TOPIC,
type DirectorFrame,
type IntentFrame,
type SessionState,
} from "@/lib/types";
import { DEFAULT_CAMERA } from "@/lib/config";
import { teleopMockOverride, useMockKey } from "@/lib/mockStates";
export type Phase = "viewing" | "queueing" | "controlling";
export type Driver = { id: string; name: string };
export type TeleopContextValue = {
phase: Phase;
controlling: boolean;
/** 1-based position in the queue, or 0 if not queued */
queuePosition: number;
queueCount: number;
/** arm id you're driving (e.g. "arm1"), or null */
armId: string | null;
/** seconds left in your turn, if the bridge reports it */
remainingS: number | null;
/** arms currently being driven (for the HUD) */
drivers: Driver[];
/** raw latest bridge broadcast (for detailed surfaces that want the full arm board / queue) */
session: SessionState | null;
/** Date.now() when the last `session` broadcast arrived, or null if none yet — the freshness
* signal useSystemStatus ages out to detect a present-but-silent bridge. */
lastSessionAt: number | null;
/** camera the broadcast should pin — driven by whoever is controlling (defaults to DEFAULT_CAMERA = side) */
broadcastCamera: string;
/** publish your camera pick to the broadcast; a no-op unless you're the one controlling */
setBroadcastCamera: (trackName: string) => void;
/** token grants data publish? (operator yes, read-only viewer no) */
canDrive: boolean;
/** LIVEKIT_* env not set → demo mode */
unconfigured: boolean;
identity: string;
name: string;
join: () => void;
leave: () => void;
// teleop input — fed by the joystick, buttons, and keyboard into one held set
setJog: (dx: number, dy: number) => void;
setZ: (dir: -1 | 0 | 1) => void;
setGrip: (dir: -1 | 0 | 1) => void;
};
const Ctx = createContext<TeleopContextValue | null>(null);
export function useTeleop(): TeleopContextValue {
const v = useContext(Ctx);
if (!v) throw new Error("useTeleop must be used within <TeleopProvider>");
return v;
}
const TICK_MS = 40; // ~25 Hz, inside the spec's 20-30 Hz window
const JOG_THRESHOLD = 0.35; // joystick tilt past this counts as a held jog direction
export function TeleopProvider({ children }: { children: ReactNode }) {
const { room, status, holdRef } = useRoom();
const { identity, name } = useIdentity();
// the latest bridge broadcast; everything below is derived from it (no cascading setState)
const [session, setSession] = useState<SessionState | null>(null);
// wall-clock stamp of the last broadcast — the staleness watchdog in useSystemStatus reads this
const [lastSessionAt, setLastSessionAt] = useState<number | null>(null);
// the camera the broadcast pins — updated by "director" frames (and bridge-owned
// session.primary_camera, if the Pi ever sets it). The /broadcast egress page reads this.
const [broadcastCamera, setBroadcastCameraState] = useState<string>(DEFAULT_CAMERA);
const { phase, armId, queuePosition, queueCount, remainingS, drivers } = useMemo(() => {
const arms = session?.arms || {};
const driverList: Driver[] = [];
let myArm: string | null = null;
for (const aid of Object.keys(arms)) {
const info = arms[aid] || {};
if (info.driver) driverList.push({ id: aid, name: info.name || info.driver });
if (info.driver === identity) myArm = aid;
}
const queue = session?.queue || [];
const qIdx = queue.findIndex((qq) => qq.id === identity);
return {
phase: (myArm ? "controlling" : qIdx !== -1 ? "queueing" : "viewing") as Phase,
armId: myArm,
queuePosition: qIdx === -1 ? 0 : qIdx + 1,
queueCount: queue.length,
remainingS: myArm ? arms[myArm]?.remaining_s ?? null : null,
drivers: driverList,
};
}, [session, identity]);
const canDrive = useMemo(
() => !(room?.localParticipant?.permissions?.canPublishData === false),
[room],
);
const unconfigured = status === "unconfigured";
const controlling = phase === "controlling";
// veto RoomProvider's idle disconnects while queued/driving — hanging up would forfeit the
// slot after the bridge's short disconnect grace
useEffect(() => {
holdRef.current = phase !== "viewing";
return () => {
holdRef.current = false;
};
}, [phase, holdRef]);
// teleop input sources the publish loop reads (refs → no re-render on input)
const jog = useRef({ x: 0, y: 0 });
const zHold = useRef<-1 | 0 | 1>(0);
const gripHold = useRef<-1 | 0 | 1>(0);
const keyHeld = useRef<Set<string>>(new Set());
const seqRef = useRef(0);
const controllingRef = useRef(false);
useEffect(() => {
controllingRef.current = controlling;
}, [controlling]);
const prevDriverSig = useRef<string | null>(null); // active-driver signature, to reset the broadcast pin on change
const buildHeld = useCallback((): string[] => {
const s = new Set<string>(keyHeld.current);
const { x, y } = jog.current;
if (y < -JOG_THRESHOLD) s.add(HELD.up);
if (y > JOG_THRESHOLD) s.add(HELD.down);
if (x < -JOG_THRESHOLD) s.add(HELD.left);
if (x > JOG_THRESHOLD) s.add(HELD.right);
if (zHold.current === 1) s.add(HELD.zUp);
if (zHold.current === -1) s.add(HELD.zDown);
if (gripHold.current === 1) s.add(HELD.gripOpen);
if (gripHold.current === -1) s.add(HELD.gripClose);
return Array.from(s);
}, []);
const publish = useCallback(
(frame: IntentFrame) => {
if (!room || room.state !== ConnectionState.Connected) return;
room.localParticipant
.publishData(new TextEncoder().encode(JSON.stringify(frame)), {
reliable: true,
topic: CONTROL_TOPIC,
})
.catch(() => {
/* transient send failure; next frame resends full state */
});
},
[room],
);
// publish loop — runs only while you hold an arm. Empty held is a keepalive.
useEffect(() => {
if (!room || !controlling) return;
const id = setInterval(() => {
publish({
seq: ++seqRef.current,
t: Date.now() / 1000,
type: "intent",
deadman: controllingRef.current && document.hasFocus(),
held: buildHeld(),
});
}, TICK_MS);
return () => {
clearInterval(id);
jog.current = { x: 0, y: 0 };
zHold.current = 0;
gripHold.current = 0;
keyHeld.current.clear();
// final released frame so the arm holds
publish({ seq: ++seqRef.current, t: Date.now() / 1000, type: "intent", deadman: false, held: [] });
};
}, [room, controlling, publish, buildHeld]);
// session broadcasts → store the latest snapshot (phase/queue/arm derive from it above)
useEffect(() => {
if (!room) return;
const onData = (payload: Uint8Array, _p?: unknown, _k?: unknown, topic?: string) => {
if (topic === DIRECTOR_TOPIC) {
try {
const f = JSON.parse(new TextDecoder().decode(payload)) as DirectorFrame;
if (f.primary_camera) setBroadcastCameraState(f.primary_camera);
} catch {
/* ignore malformed */
}
return;
}
if (topic !== STATE_TOPIC) return;
try {
const s = JSON.parse(new TextDecoder().decode(payload)) as SessionState;
console.debug("[teleop] session broadcast:", s);
setSession(s);
setLastSessionAt(Date.now());
// When the active driver changes or leaves, reset the broadcast pin to the default (side) until
// the new driver customizes it — otherwise it keeps the previous driver's last pinned feed.
const driverSig = Object.entries(s.arms || {})
.filter(([, a]) => a.driver)
.map(([aid, a]) => `${aid}:${a.driver}`)
.sort()
.join("|");
if (driverSig !== prevDriverSig.current) {
prevDriverSig.current = driverSig;
setBroadcastCameraState(DEFAULT_CAMERA);
}
// if the bridge ever owns the pin, let it win too
if (s.primary_camera) setBroadcastCameraState(s.primary_camera);
} catch {
/* ignore malformed */
}
};
room.on(RoomEvent.DataReceived, onData);
return () => {
room.off(RoomEvent.DataReceived, onData);
setSession(null);
setLastSessionAt(null);
};
}, [room]);
// keyboard: arrow keys jog the arm while controlling — Z and gripper are on-screen only
useEffect(() => {
const MOVE: Record<string, string> = {
ArrowUp: HELD.up,
ArrowDown: HELD.down,
ArrowLeft: HELD.left,
ArrowRight: HELD.right,
};
const typing = (e: KeyboardEvent) => {
const t = e.target as HTMLElement | null;
return !!t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable);
};
const onKeydown = (e: KeyboardEvent) => {
if (typing(e) || !controllingRef.current) return;
const tok = MOVE[e.key];
if (tok) {
keyHeld.current.add(tok);
e.preventDefault();
}
};
const onKeyup = (e: KeyboardEvent) => {
const tok = MOVE[e.key];
if (tok) keyHeld.current.delete(tok);
};
const drop = () => keyHeld.current.clear();
const onVisibility = () => {
if (document.hidden) drop();
};
window.addEventListener("keydown", onKeydown);
window.addEventListener("keyup", onKeyup);
window.addEventListener("blur", drop);
document.addEventListener("visibilitychange", onVisibility);
return () => {
window.removeEventListener("keydown", onKeydown);
window.removeEventListener("keyup", onKeyup);
window.removeEventListener("blur", drop);
document.removeEventListener("visibilitychange", onVisibility);
};
}, []);
const join = useCallback(() => {
if (!room || room.state !== ConnectionState.Connected) {
console.warn("[teleop] join skipped — room not connected", room?.state);
return;
}
console.info("[teleop] join → RPC to", BRIDGE_IDENTITY, { name });
room.localParticipant
.performRpc({ destinationIdentity: BRIDGE_IDENTITY, method: "join", payload: JSON.stringify({ name }) })
.then((res) => console.info("[teleop] join RPC ok:", res))
.catch((err) => console.error("[teleop] join RPC failed:", err?.message || err));
}, [room, name]);
const leave = useCallback(() => {
if (!room || room.state !== ConnectionState.Connected) return;
console.info("[teleop] release → RPC to", BRIDGE_IDENTITY);
room.localParticipant
.performRpc({ destinationIdentity: BRIDGE_IDENTITY, method: "release", payload: "{}" })
.then((res) => console.info("[teleop] release RPC ok:", res))
.catch((err) => console.error("[teleop] release RPC failed:", err?.message || err));
}, [room]);
// Publish the pinned camera to the broadcast — but ONLY while you hold an arm, so a
// random spectator flipping cameras on the cabinet can't hijack the public stream. The
// pin therefore follows whoever is currently driving; nobody driving → it stays put.
const setBroadcastCamera = useCallback(
(trackName: string) => {
if (!controllingRef.current || !room || room.state !== ConnectionState.Connected) return;
setBroadcastCameraState(trackName);
const frame: DirectorFrame = { primary_camera: trackName };
room.localParticipant
.publishData(new TextEncoder().encode(JSON.stringify(frame)), {
reliable: true,
topic: DIRECTOR_TOPIC,
})
.catch(() => {
/* transient; the next selection resends full state */
});
},
[room],
);
const setJog = useCallback((dx: number, dy: number) => {
jog.current = { x: dx, y: dy };
}, []);
const setZ = useCallback((dir: -1 | 0 | 1) => {
zHold.current = dir;
}, []);
const setGrip = useCallback((dir: -1 | 0 | 1) => {
gripHold.current = dir;
}, []);
// `?mock=<state>` overlays a fixed UX fixture onto the live value (no-op when the param is absent)
const mockKey = useMockKey();
const value = useMemo<TeleopContextValue>(
() => {
const base: TeleopContextValue = {
phase, controlling, queuePosition, queueCount, armId, remainingS, drivers, session, lastSessionAt,
broadcastCamera, setBroadcastCamera,
canDrive, unconfigured, identity, name, join, leave, setJog, setZ, setGrip,
};
const override = teleopMockOverride(mockKey);
return override ? { ...base, ...override } : base;
},
[mockKey,
phase, controlling, queuePosition, queueCount, armId, remainingS, drivers, session, lastSessionAt,
broadcastCamera, setBroadcastCamera,
canDrive, unconfigured, identity, name, join, leave, setJog, setZ, setGrip],
);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}