File size: 2,288 Bytes
efe2c71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useCallback } from "react";
import {
  getRobotConnectionManager,
  type RobotConnectionState,
  writeMotorPosition,
  readMotorPosition,
  readAllMotorPositions,
} from "../../lerobot/web/robot-connection";

export interface UseRobotConnectionResult {
  // Connection state
  isConnected: boolean;
  robotType?: "so100_follower" | "so100_leader";
  robotId?: string;
  serialNumber?: string;
  lastError?: string;

  // Connection management
  connect: (
    port: SerialPort,
    robotType: string,
    robotId: string,
    serialNumber: string
  ) => Promise<void>;
  disconnect: () => Promise<void>;

  // Robot operations
  writeMotorPosition: (motorId: number, position: number) => Promise<void>;
  readMotorPosition: (motorId: number) => Promise<number | null>;
  readAllMotorPositions: (motorIds: number[]) => Promise<number[]>;

  // Raw port access (for advanced use cases)
  getPort: () => SerialPort | null;
}

/**
 * React hook for robot connection management
 * Uses the singleton connection manager as single source of truth
 */
export function useRobotConnection(): UseRobotConnectionResult {
  const manager = getRobotConnectionManager();
  const [state, setState] = useState<RobotConnectionState>(manager.getState());

  // Subscribe to connection state changes
  useEffect(() => {
    const unsubscribe = manager.onStateChange(setState);

    // Set initial state
    setState(manager.getState());

    return unsubscribe;
  }, [manager]);

  // Connection management functions
  const connect = useCallback(
    async (
      port: SerialPort,
      robotType: string,
      robotId: string,
      serialNumber: string
    ) => {
      await manager.connect(port, robotType, robotId, serialNumber);
    },
    [manager]
  );

  const disconnect = useCallback(async () => {
    await manager.disconnect();
  }, [manager]);

  const getPort = useCallback(() => {
    return manager.getPort();
  }, [manager]);

  return {
    // State
    isConnected: state.isConnected,
    robotType: state.robotType,
    robotId: state.robotId,
    serialNumber: state.serialNumber,
    lastError: state.lastError,

    // Methods
    connect,
    disconnect,
    writeMotorPosition,
    readMotorPosition,
    readAllMotorPositions,
    getPort,
  };
}