File size: 3,647 Bytes
fc9bd9f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | import { useEffect, useRef, useState, useCallback } from "react";
import { URDFViewerElement } from "@/lib/urdfViewerHelpers";
import { useApi } from "@/contexts/ApiContext";
interface JointData {
type: "joint_update";
joints: Record<string, number>;
timestamp: number;
}
interface UseRealTimeJointsProps {
viewerRef: React.RefObject<URDFViewerElement>;
enabled?: boolean;
websocketUrl?: string;
}
const INITIAL_RECONNECT_DELAY_MS = 1000;
const MAX_RECONNECT_DELAY_MS = 30000;
export const useRealTimeJoints = ({
viewerRef,
enabled = true,
websocketUrl,
}: UseRealTimeJointsProps) => {
const { wsBaseUrl } = useApi();
const finalWebSocketUrl = websocketUrl || `${wsBaseUrl}/ws/joint-data`;
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const reconnectDelayRef = useRef(INITIAL_RECONNECT_DELAY_MS);
const intentionallyClosedRef = useRef(false);
const [isConnected, setIsConnected] = useState(false);
const updateJointValues = useCallback(
(joints: Record<string, number>) => {
const viewer = viewerRef.current;
if (!viewer || typeof viewer.setJointValue !== "function") return;
Object.entries(joints).forEach(([jointName, value]) => {
try {
viewer.setJointValue(jointName, value);
} catch (error) {
console.warn(`Failed to set joint ${jointName}:`, error);
}
});
},
[viewerRef]
);
useEffect(() => {
if (!enabled) return;
intentionallyClosedRef.current = false;
const connect = () => {
if (intentionallyClosedRef.current) return;
let ws: WebSocket;
try {
ws = new WebSocket(finalWebSocketUrl);
} catch (error) {
console.error("Failed to create WebSocket:", error);
scheduleReconnect();
return;
}
wsRef.current = ws;
ws.onopen = () => {
setIsConnected(true);
reconnectDelayRef.current = INITIAL_RECONNECT_DELAY_MS;
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as JointData;
if (data.type === "joint_update" && data.joints) {
updateJointValues(data.joints);
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
};
ws.onclose = (event) => {
setIsConnected(false);
wsRef.current = null;
if (intentionallyClosedRef.current) return;
if (event.code === 1000) return; // clean close
scheduleReconnect();
};
ws.onerror = () => {
setIsConnected(false);
};
};
const scheduleReconnect = () => {
if (reconnectTimeoutRef.current) return;
const delay = reconnectDelayRef.current;
reconnectDelayRef.current = Math.min(
delay * 2,
MAX_RECONNECT_DELAY_MS
);
reconnectTimeoutRef.current = setTimeout(() => {
reconnectTimeoutRef.current = null;
connect();
}, delay);
};
connect();
return () => {
intentionallyClosedRef.current = true;
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
if (wsRef.current) {
wsRef.current.close(1000);
wsRef.current = null;
}
setIsConnected(false);
};
}, [enabled, finalWebSocketUrl, updateJointValues]);
return { isConnected };
};
|