File size: 5,963 Bytes
efe2c71
 
 
 
 
 
 
 
 
 
 
 
5eb1bc0
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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/**
 * Core Robot Connection Manager
 * Single source of truth for robot connections in the web library
 * Provides singleton access to robot ports and connection state
 */

import {
  readMotorPosition as readMotorPositionUtil,
  writeMotorPosition as writeMotorPositionUtil,
  readAllMotorPositions as readAllMotorPositionsUtil,
  writeMotorRegister,
  type MotorCommunicationPort,
} from "./utils/motor-communication.js";

export interface RobotConnectionState {
  isConnected: boolean;
  robotType?: "so100_follower" | "so100_leader";
  robotId?: string;
  serialNumber?: string;
  lastError?: string;
}

export interface RobotConnectionManager {
  // State
  getState(): RobotConnectionState;

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

  // Port access
  getPort(): SerialPort | null;

  // Serial operations (shared by calibration, teleoperation, etc.)
  writeData(data: Uint8Array): Promise<void>;
  readData(timeout?: number): Promise<Uint8Array>;

  // Event system
  onStateChange(callback: (state: RobotConnectionState) => void): () => void;
}

/**
 * Singleton Robot Connection Manager Implementation
 */
class RobotConnectionManagerImpl implements RobotConnectionManager {
  private port: SerialPort | null = null;
  private state: RobotConnectionState = { isConnected: false };
  private stateChangeCallbacks: Set<(state: RobotConnectionState) => void> =
    new Set();

  getState(): RobotConnectionState {
    return { ...this.state };
  }

  async connect(
    port: SerialPort,
    robotType: string,
    robotId: string,
    serialNumber: string
  ): Promise<void> {
    try {
      // Validate port is open
      if (!port.readable || !port.writable) {
        throw new Error("Port is not open");
      }

      // Update connection state
      this.port = port;
      this.state = {
        isConnected: true,
        robotType: robotType as "so100_follower" | "so100_leader",
        robotId,
        serialNumber,
        lastError: undefined,
      };

      this.notifyStateChange();
      console.log(
        `🤖 Robot connected: ${robotType} (${robotId}) - ${serialNumber}`
      );
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Connection failed";
      this.state = {
        isConnected: false,
        lastError: errorMessage,
      };
      this.notifyStateChange();
      throw error;
    }
  }

  async disconnect(): Promise<void> {
    this.port = null;
    this.state = { isConnected: false };
    this.notifyStateChange();
    console.log("🤖 Robot disconnected");
  }

  getPort(): SerialPort | null {
    return this.port;
  }

  async writeData(data: Uint8Array): Promise<void> {
    if (!this.port?.writable) {
      throw new Error("Robot not connected or port not writable");
    }

    const writer = this.port.writable.getWriter();
    try {
      await writer.write(data);
    } finally {
      writer.releaseLock();
    }
  }

  async readData(timeout: number = 1000): Promise<Uint8Array> {
    if (!this.port?.readable) {
      throw new Error("Robot not connected or port not readable");
    }

    const reader = this.port.readable.getReader();

    try {
      const timeoutPromise = new Promise<never>((_, reject) => {
        setTimeout(() => reject(new Error("Read timeout")), timeout);
      });

      const readPromise = reader.read().then((result) => {
        if (result.done || !result.value) {
          throw new Error("Read failed - port closed or no data");
        }
        return result.value;
      });

      return await Promise.race([readPromise, timeoutPromise]);
    } finally {
      reader.releaseLock();
    }
  }

  onStateChange(callback: (state: RobotConnectionState) => void): () => void {
    this.stateChangeCallbacks.add(callback);

    // Return unsubscribe function
    return () => {
      this.stateChangeCallbacks.delete(callback);
    };
  }

  private notifyStateChange(): void {
    this.stateChangeCallbacks.forEach((callback) => {
      try {
        callback(this.getState());
      } catch (error) {
        console.warn("Error in state change callback:", error);
      }
    });
  }
}

// Singleton instance
const robotConnectionManager = new RobotConnectionManagerImpl();

/**
 * Get the singleton robot connection manager
 * This is the single source of truth for robot connections
 */
export function getRobotConnectionManager(): RobotConnectionManager {
  return robotConnectionManager;
}

/**
 * Utility functions for common robot operations
 * Uses shared motor communication utilities for consistency
 */

/**
 * Adapter to make robot connection manager compatible with motor utils
 */
class RobotConnectionManagerAdapter implements MotorCommunicationPort {
  private manager: RobotConnectionManager;

  constructor(manager: RobotConnectionManager) {
    this.manager = manager;
  }

  async write(data: Uint8Array): Promise<void> {
    return this.manager.writeData(data);
  }

  async read(timeout?: number): Promise<Uint8Array> {
    return this.manager.readData(timeout);
  }
}

export async function writeMotorPosition(
  motorId: number,
  position: number
): Promise<void> {
  const manager = getRobotConnectionManager();
  const adapter = new RobotConnectionManagerAdapter(manager);

  return writeMotorPositionUtil(adapter, motorId, position);
}

export async function readMotorPosition(
  motorId: number
): Promise<number | null> {
  const manager = getRobotConnectionManager();
  const adapter = new RobotConnectionManagerAdapter(manager);

  return readMotorPositionUtil(adapter, motorId);
}

export async function readAllMotorPositions(
  motorIds: number[]
): Promise<number[]> {
  const manager = getRobotConnectionManager();
  const adapter = new RobotConnectionManagerAdapter(manager);

  return readAllMotorPositionsUtil(adapter, motorIds);
}