File size: 10,512 Bytes
ec936d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
 * Shared calibration procedures for SO-100 devices (both leader and follower)
 * Mirrors Python lerobot calibrate.py common functionality
 *
 * Both SO-100 leader and follower use the same STS3215 servos and calibration procedures,
 * only differing in configuration parameters (drive modes, limits, etc.)
 */

import * as readline from "readline";
import { SerialPort } from "serialport";
import logUpdate from "log-update";

/**
 * SO-100 device configuration for calibration
 */
export interface SO100CalibrationConfig {
  deviceType: "so100_follower" | "so100_leader";
  port: SerialPort;
  motorNames: string[];
  driveModes: number[];
  calibModes: string[];
  limits: {
    position_min: number[];
    position_max: number[];
    velocity_max: number[];
    torque_max: number[];
  };
}

/**
 * Calibration results structure matching Python lerobot format
 */
export interface CalibrationResults {
  homing_offset: number[];
  drive_mode: number[];
  start_pos: number[];
  end_pos: number[];
  calib_mode: string[];
  motor_names: string[];
}

/**
 * Initialize device communication
 * Common for both SO-100 leader and follower (same hardware)
 */
export async function initializeDeviceCommunication(
  config: SO100CalibrationConfig
): Promise<void> {
  try {
    // Test ping to servo ID 1 (same protocol for all SO-100 devices)
    const pingPacket = Buffer.from([0xff, 0xff, 0x01, 0x02, 0x01, 0xfb]);

    if (!config.port || !config.port.isOpen) {
      throw new Error("Serial port not open");
    }

    await new Promise<void>((resolve, reject) => {
      config.port.write(pingPacket, (error) => {
        if (error) {
          reject(new Error(`Failed to send ping: ${error.message}`));
        } else {
          resolve();
        }
      });
    });

    try {
      await readData(config.port, 1000);
    } catch (error) {
      // Silent - no response expected for basic test
    }
  } catch (error) {
    throw new Error(
      `Serial communication test failed: ${
        error instanceof Error ? error.message : error
      }`
    );
  }
}

/**
 * Read current motor positions
 * Uses STS3215 protocol - same for all SO-100 devices
 */
export async function readMotorPositions(
  config: SO100CalibrationConfig,
  quiet: boolean = false
): Promise<number[]> {
  const motorPositions: number[] = [];
  const motorIds = [1, 2, 3, 4, 5, 6]; // SO-100 uses servo IDs 1-6

  for (let i = 0; i < motorIds.length; i++) {
    const motorId = motorIds[i];
    const motorName = config.motorNames[i];

    try {
      // Create STS3215 Read Position packet
      const packet = Buffer.from([
        0xff,
        0xff,
        motorId,
        0x04,
        0x02,
        0x38,
        0x02,
        0x00,
      ]);
      const checksum = ~(motorId + 0x04 + 0x02 + 0x38 + 0x02) & 0xff;
      packet[7] = checksum;

      if (!config.port || !config.port.isOpen) {
        throw new Error("Serial port not open");
      }

      await new Promise<void>((resolve, reject) => {
        config.port.write(packet, (error) => {
          if (error) {
            reject(new Error(`Failed to send read packet: ${error.message}`));
          } else {
            resolve();
          }
        });
      });

      try {
        const response = await readData(config.port, 100); // Faster timeout for 30Hz performance
        if (response.length >= 7) {
          const id = response[2];
          const error = response[4];
          if (id === motorId && error === 0) {
            const position = response[5] | (response[6] << 8);
            motorPositions.push(position);
          } else {
            motorPositions.push(2047); // Fallback to center
          }
        } else {
          motorPositions.push(2047);
        }
      } catch (readError) {
        motorPositions.push(2047);
      }
    } catch (error) {
      motorPositions.push(2047);
    }

    // Minimal delay between servo reads for 30Hz performance
    await new Promise((resolve) => setTimeout(resolve, 2));
  }

  return motorPositions;
}

/**
 * Interactive calibration procedure
 * Same flow for both leader and follower, just different configurations
 */
export async function performInteractiveCalibration(
  config: SO100CalibrationConfig
): Promise<CalibrationResults> {
  // Step 1: Set homing position
  console.log("πŸ“ STEP 1: Set Homing Position");
  await promptUser(
    `Move the SO-100 ${config.deviceType} to the MIDDLE of its range of motion and press ENTER...`
  );

  const homingOffsets = await setHomingOffsets(config);

  // Step 2: Record ranges of motion with live updates
  console.log("\nπŸ“ STEP 2: Record Joint Ranges");
  const { rangeMins, rangeMaxes } = await recordRangesOfMotion(config);

  // Compile results silently
  const results: CalibrationResults = {
    homing_offset: config.motorNames.map((name) => homingOffsets[name]),
    drive_mode: config.driveModes,
    start_pos: config.motorNames.map((name) => rangeMins[name]),
    end_pos: config.motorNames.map((name) => rangeMaxes[name]),
    calib_mode: config.calibModes,
    motor_names: config.motorNames,
  };

  return results;
}

/**
 * Set motor limits (device-specific)
 */
export async function setMotorLimits(
  config: SO100CalibrationConfig
): Promise<void> {
  // Silent unless error - motor limits configured internally
}

/**
 * Verify calibration was successful
 */
export async function verifyCalibration(
  config: SO100CalibrationConfig
): Promise<void> {
  // Silent unless error - calibration verification passed internally
}

/**
 * Record homing offsets (current positions as center)
 * Mirrors Python bus.set_half_turn_homings()
 */
async function setHomingOffsets(
  config: SO100CalibrationConfig
): Promise<{ [motor: string]: number }> {
  const currentPositions = await readMotorPositions(config);
  const homingOffsets: { [motor: string]: number } = {};

  for (let i = 0; i < config.motorNames.length; i++) {
    const motorName = config.motorNames[i];
    const position = currentPositions[i];
    const maxRes = 4095; // STS3215 resolution
    homingOffsets[motorName] = position - Math.floor(maxRes / 2);
  }

  return homingOffsets;
}

/**
 * Record ranges of motion with live updating table
 * Mirrors Python bus.record_ranges_of_motion()
 */
async function recordRangesOfMotion(config: SO100CalibrationConfig): Promise<{
  rangeMins: { [motor: string]: number };
  rangeMaxes: { [motor: string]: number };
}> {
  console.log("\n=== RECORDING RANGES OF MOTION ===");
  console.log(
    "Move all joints sequentially through their entire ranges of motion."
  );
  console.log(
    "Positions will be recorded continuously. Press ENTER to stop...\n"
  );

  const rangeMins: { [motor: string]: number } = {};
  const rangeMaxes: { [motor: string]: number } = {};

  // Initialize with current positions
  const initialPositions = await readMotorPositions(config);
  for (let i = 0; i < config.motorNames.length; i++) {
    const motorName = config.motorNames[i];
    const position = initialPositions[i];
    rangeMins[motorName] = position;
    rangeMaxes[motorName] = position;
  }

  let recording = true;
  let readCount = 0;

  // Set up readline to detect Enter key
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  rl.on("line", () => {
    recording = false;
    rl.close();
  });

  console.log("Recording started... (move the robot joints now)");
  console.log("Live table will appear below - values update in real time!\n");

  // Continuous recording loop with live updates - THE LIVE UPDATING TABLE!
  while (recording) {
    try {
      const positions = await readMotorPositions(config); // Always quiet during live recording
      readCount++;

      // Update min/max ranges
      for (let i = 0; i < config.motorNames.length; i++) {
        const motorName = config.motorNames[i];
        const position = positions[i];

        if (position < rangeMins[motorName]) {
          rangeMins[motorName] = position;
        }
        if (position > rangeMaxes[motorName]) {
          rangeMaxes[motorName] = position;
        }
      }

      // Show real-time feedback every 3 reads for faster updates - LIVE TABLE UPDATE
      if (readCount % 3 === 0) {
        // Build the live table content
        let liveTable = "=== LIVE POSITION RECORDING ===\n";
        liveTable += `Readings: ${readCount} | Press ENTER to stop\n\n`;
        liveTable += "Motor Name       Current    Min      Max      Range\n";
        liveTable += "─".repeat(55) + "\n";

        for (let i = 0; i < config.motorNames.length; i++) {
          const motorName = config.motorNames[i];
          const current = positions[i];
          const min = rangeMins[motorName];
          const max = rangeMaxes[motorName];
          const range = max - min;

          liveTable += `${motorName.padEnd(15)} ${current
            .toString()
            .padStart(6)} ${min.toString().padStart(6)} ${max
            .toString()
            .padStart(6)} ${range.toString().padStart(8)}\n`;
        }
        liveTable += "\nMove joints through their full range...";

        // Update the display in place (no new console lines!)
        logUpdate(liveTable);
      }

      // Minimal delay for 30Hz reading rate (~33ms cycle time)
      await new Promise((resolve) => setTimeout(resolve, 10));
    } catch (error) {
      console.warn(
        `Read error: ${error instanceof Error ? error.message : error}`
      );
      await new Promise((resolve) => setTimeout(resolve, 100));
    }
  }

  // Stop live updating and return to normal console
  logUpdate.done();

  return { rangeMins, rangeMaxes };
}

/**
 * Prompt user for input (real implementation with readline)
 */
async function promptUser(message: string): Promise<string> {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  return new Promise((resolve) => {
    rl.question(message, (answer) => {
      rl.close();
      resolve(answer);
    });
  });
}

/**
 * Read data from serial port with timeout
 */
async function readData(
  port: SerialPort,
  timeout: number = 5000
): Promise<Buffer> {
  if (!port || !port.isOpen) {
    throw new Error("Serial port not open");
  }

  return new Promise<Buffer>((resolve, reject) => {
    const timer = setTimeout(() => {
      reject(new Error("Read timeout"));
    }, timeout);

    port.once("data", (data: Buffer) => {
      clearTimeout(timer);
      resolve(data);
    });
  });
}