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
 
 
 
b407e44
 
 
fe6e2a2
b407e44
 
 
 
 
bdc1ac8
 
 
 
 
 
 
 
 
 
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/usr/bin/env node

/**
 * lerobot CLI - Python lerobot compatible command-line interface
 * Uses @lerobot/node library for core functionality with CLI-specific interactive features
 */

import { program } from "commander";
import chalk from "chalk";
import {
  findPort,
  calibrate,
  teleoperate,
  releaseMotors,
  connectPort,
} from "@lerobot/node";
import type { RobotConnection } from "@lerobot/node";
import { SerialPort } from "serialport";
import { createInterface } from "readline";
import { platform } from "os";
import { readdir } from "fs/promises";
import { join } from "path";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { dirname } from "path";

// Get package version dynamically
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const packageJson = JSON.parse(
  readFileSync(join(__dirname, "../package.json"), "utf8")
);
const version = packageJson.version;

/**
 * CLI-specific function to list available serial ports
 * Only used by the CLI, not part of the library API
 */
async function findAvailablePorts(): Promise<string[]> {
  if (platform() === "win32") {
    // List COM ports using serialport library (equivalent to pyserial)
    const ports = await SerialPort.list();
    return ports.map((port) => port.path);
  } else {
    // List /dev/tty* ports for Unix-based systems (Linux/macOS)
    try {
      const devFiles = await readdir("/dev");
      const ttyPorts = devFiles
        .filter((file) => file.startsWith("tty"))
        .map((file) => join("/dev", file));
      return ttyPorts;
    } catch (error) {
      // Fallback to serialport library if /dev reading fails
      const ports = await SerialPort.list();
      return ports.map((port) => port.path);
    }
  }
}

/**
 * CLI-specific interactive port detection for Python lerobot compatibility
 * Matches Python lerobot's unplug/replug cable detection exactly
 */
async function detectPortInteractive(
  onMessage?: (message: string) => void
): Promise<string> {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  function waitForInput(prompt: string): Promise<string> {
    return new Promise((resolve) => {
      rl.question(prompt, (answer: string) => {
        resolve(answer);
      });
    });
  }

  try {
    const message = "Finding all available ports for the MotorsBus.";
    if (onMessage) onMessage(message);
    else console.log(message);

    // Get initial port list
    const portsBefore = await findAvailablePorts();

    // Show initial ports (Python lerobot style)
    const portsMessage = `Ports before disconnecting: [${portsBefore
      .map((p) => `'${p}'`)
      .join(", ")}]`;
    if (onMessage) onMessage(portsMessage);
    else console.log(portsMessage);

    const disconnectPrompt =
      "Remove the USB cable from your MotorsBus and press Enter when done.";
    await waitForInput(disconnectPrompt);

    // Get port list after disconnect
    const portsAfter = await findAvailablePorts();

    // Find the difference
    const portsDiff = portsBefore.filter((port) => !portsAfter.includes(port));

    if (portsDiff.length === 1) {
      const detectedPort = portsDiff[0];

      // Show empty line then the result (Python lerobot style)
      if (onMessage) {
        onMessage("");
        onMessage(`The port of this MotorsBus is '${detectedPort}'`);
        onMessage("Reconnect the USB cable.");
      } else {
        console.log("");
        console.log(`The port of this MotorsBus is '${detectedPort}'`);
        console.log("Reconnect the USB cable.");
      }

      return detectedPort;
    } else if (portsDiff.length === 0) {
      throw new Error(
        "No port difference detected. Please check cable connection."
      );
    } else {
      throw new Error(
        `Multiple ports detected: ${portsDiff.join(
          ", "
        )}. Please disconnect other devices.`
      );
    }
  } finally {
    rl.close();
  }
}

/**
 * Create robot connection directly from specified port (Python lerobot style)
 */
async function connectToSpecificPort(
  portPath: string,
  robotType: string,
  robotId: string
): Promise<RobotConnection> {
  console.log(chalk.gray(`๐Ÿ“ก Connecting to ${portPath}...`));

  const connection = await connectPort(portPath);

  if (!connection.isConnected) {
    throw new Error(
      `Failed to connect to port ${portPath}: ${connection.error}`
    );
  }

  // Configure the robot with CLI parameters
  connection.robotType = robotType;
  connection.robotId = robotId;
  connection.name = `${robotType} on ${portPath}`;

  console.log(chalk.green(`โœ… Connected to ${robotType} on ${portPath}`));
  return connection;
}

/**
 * Find port command - matches Python lerobot CLI exactly
 * Always interactive by default (like Python lerobot)
 */
program
  .command("find-port")
  .description("Find robot port with interactive cable detection")
  .addHelpText(
    "after",
    `
Examples:
  $ lerobot find-port

This command will:
  1. List current ports
  2. Ask you to unplug your robot
  3. Detect which port disappeared
  4. Ask you to reconnect
`
  )
  .action(async () => {
    try {
      console.log(chalk.blue("๐Ÿ” Finding robot port..."));

      // Always use interactive cable detection (Python lerobot behavior)
      await detectPortInteractive((message) =>
        console.log(chalk.gray(message))
      );
      // No additional success message - detectPortInteractive already shows the result
    } catch (error) {
      console.error(
        chalk.red(`โŒ Error: ${error instanceof Error ? error.message : error}`)
      );
      process.exit(1);
    }
  });

/**
 * Calibrate command - matches Python lerobot exactly
 */
program
  .command("calibrate")
  .description("Calibrate robot motors")
  .requiredOption("--robot.type <type>", "Robot type (e.g., so100_follower)")
  .requiredOption(
    "--robot.port <port>",
    "Serial port (e.g., /dev/ttyUSB0, COM4)"
  )
  .option("--robot.id <id>", "Robot ID", "default")
  .option("--output <path>", "Output calibration file path")
  .addHelpText(
    "after",
    `
Examples:
  $ lerobot calibrate --robot.type=so100_follower --robot.port=/dev/ttyUSB0 --robot.id=my_arm
  $ lerobot calibrate --robot.type=so100_follower --robot.port=COM4 --robot.id=my_arm
`
  )
  .action(async (options) => {
    try {
      const robotType = options["robot.type"];
      const robotPort = options["robot.port"];
      const robotId = options["robot.id"] || "default";

      console.log(chalk.blue(`๐Ÿ”ง Starting calibration for ${robotType}...`));

      // Step 1: Connect directly to specified port (Python lerobot style)
      const robot = await connectToSpecificPort(robotPort, robotType, robotId);

      // Step 2: Release motors
      console.log(chalk.gray("๐Ÿ”“ Releasing motors for calibration setup..."));
      await releaseMotors(robot);
      console.log(
        chalk.green("โœ… Motors released - robot can now be moved by hand")
      );

      // Step 3: Wait for user to position robot
      console.log(
        chalk.yellow(
          "\n๐Ÿ“ Move robot to your preferred starting position, then press Enter..."
        )
      );
      const rl = createInterface({
        input: process.stdin,
        output: process.stdout,
      });

      await new Promise<void>((resolve) => {
        rl.question("", () => {
          rl.close();
          resolve();
        });
      });

      console.log(chalk.blue("\n๐ŸŽฏ Starting calibration process..."));
      const calibrationProcess = await calibrate({
        robot,
        outputPath: options.output,
        onProgress: (message) => console.log(chalk.gray(message)),
        onLiveUpdate: (data) => {
          // Clear previous output and display live data as table
          process.stdout.write("\x1B[2J\x1B[0f"); // Clear screen and move cursor to top

          console.log(chalk.cyan("๐Ÿ“Š Live Motor Data:"));
          console.log(
            "โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”"
          );
          console.log(
            "โ”‚ Motor           โ”‚ Current โ”‚ Min     โ”‚ Max     โ”‚ Range   โ”‚"
          );
          console.log(
            "โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค"
          );

          Object.entries(data).forEach(([name, info]) => {
            const motorName = name.padEnd(15);
            const current = info.current.toString().padStart(7);
            const min = info.min.toString().padStart(7);
            const max = info.max.toString().padStart(7);
            const range = info.range.toString().padStart(7);
            console.log(
              `โ”‚ ${motorName} โ”‚ ${current} โ”‚ ${min} โ”‚ ${max} โ”‚ ${range} โ”‚`
            );
          });

          console.log(
            "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜"
          );
          console.log(
            chalk.yellow(
              "Move motors through full range, then press Enter when done..."
            )
          );
        },
      });

      const results = await calibrationProcess.result;
      console.log(chalk.green("\nโœ… Calibration completed successfully!"));

      // CRITICAL: Close robot connection to allow process to exit
      if (robot.port && robot.port.close) {
        await robot.port.close();
      }
    } catch (error) {
      console.error(
        chalk.red(
          `โŒ Calibration failed: ${
            error instanceof Error ? error.message : error
          }`
        )
      );

      // Close robot connection even on error
      try {
        if (robot && robot.port && robot.port.close) {
          await robot.port.close();
        }
      } catch (closeError) {
        // Ignore close errors
      }

      process.exit(1);
    }
  });

/**
 * Teleoperate command - matches Python lerobot exactly
 */
program
  .command("teleoperate")
  .description("Control robot through teleoperation")
  .requiredOption("--robot.type <type>", "Robot type (e.g., so100_follower)")
  .requiredOption(
    "--robot.port <port>",
    "Serial port (e.g., /dev/ttyUSB0, COM4)"
  )
  .option("--robot.id <id>", "Robot ID", "default")
  .option("--teleop.type <type>", "Teleoperator type", "keyboard")
  .option("--duration <seconds>", "Duration in seconds (0 = unlimited)", "0")
  .addHelpText(
    "after",
    `
Examples:
  $ lerobot teleoperate --robot.type=so100_follower --robot.port=/dev/ttyUSB0 --robot.id=my_arm
  $ lerobot teleoperate --robot.type=so100_follower --robot.port=COM4 --robot.id=my_arm
`
  )
  .action(async (options) => {
    try {
      const robotType = options["robot.type"];
      const robotPort = options["robot.port"];
      const robotId = options["robot.id"] || "default";
      const teleopType = options["teleop.type"] || "keyboard";

      console.log(chalk.blue(`๐ŸŽฎ Starting teleoperation for ${robotType}...`));

      // Connect directly to specified port (Python lerobot style)
      const robot = await connectToSpecificPort(robotPort, robotType, robotId);

      const teleoperationProcess = await teleoperate({
        robot,
        teleop: {
          type: teleopType,
        },
        onStateUpdate: (state) => {
          if (state.isActive) {
            const motorInfo = state.motorConfigs
              .map(
                (motor) => `${motor.name}:${Math.round(motor.currentPosition)}`
              )
              .join(" ");
            process.stdout.write(`\r${chalk.cyan("๐Ÿค– Motors:")} ${motorInfo}`);
          }
        },
      });

      // Start teleoperation
      teleoperationProcess.start();

      // Handle duration limit
      const duration = parseInt(options.duration || "0");
      if (duration > 0) {
        setTimeout(() => {
          console.log(
            chalk.yellow(
              `\nโฐ Duration limit reached (${duration}s). Stopping...`
            )
          );
          teleoperationProcess.stop();
          process.exit(0);
        }, duration * 1000);
      }

      // Handle process termination
      process.on("SIGINT", async () => {
        console.log(chalk.yellow("\n๐Ÿ›‘ Stopping teleoperation..."));
        teleoperationProcess.stop();
        await teleoperationProcess.disconnect();
        process.exit(0);
      });

      console.log(chalk.green("โœ… Teleoperation started successfully!"));
      console.log(chalk.gray("Press Ctrl+C to stop"));
    } catch (error) {
      console.error(
        chalk.red(
          `โŒ Teleoperation failed: ${
            error instanceof Error ? error.message : error
          }`
        )
      );
      process.exit(1);
    }
  });

/**
 * Release motors command
 */
program
  .command("release-motors")
  .description("Release robot motors for manual movement")
  .requiredOption("--robot.type <type>", "Robot type (e.g., so100_follower)")
  .requiredOption(
    "--robot.port <port>",
    "Serial port (e.g., /dev/ttyUSB0, COM4)"
  )
  .option("--robot.id <id>", "Robot ID", "default")
  .option("--motors <ids>", "Specific motor IDs to release (comma-separated)")
  .addHelpText(
    "after",
    `
Examples:
  $ lerobot release-motors --robot.type=so100_follower --robot.port=/dev/ttyUSB0 --robot.id=my_arm
  $ lerobot release-motors --robot.type=so100_follower --robot.port=COM4 --robot.id=my_arm --motors=1,2,3
`
  )
  .action(async (options) => {
    try {
      const robotType = options["robot.type"];
      const robotPort = options["robot.port"];
      const robotId = options["robot.id"] || "default";

      console.log(chalk.blue(`๐Ÿ”“ Releasing motors for ${robotType}...`));

      // Connect directly to specified port (Python lerobot style)
      const robot = await connectToSpecificPort(robotPort, robotType, robotId);

      const motorIds = options.motors
        ? options.motors.split(",").map((id: string) => parseInt(id.trim()))
        : undefined;

      await releaseMotors(robot, motorIds);

      console.log(chalk.green("โœ… Motors released successfully!"));
      console.log(chalk.gray("Motors can now be moved freely by hand."));
    } catch (error) {
      console.error(
        chalk.red(
          `โŒ Failed to release motors: ${
            error instanceof Error ? error.message : error
          }`
        )
      );
      process.exit(1);
    }
  });

/**
 * Version and help setup
 */
program
  .name("lerobot")
  .description(
    "Control your robot with Node.js (inspired by LeRobot in Python)"
  )
  .version(version)
  .addHelpText(
    "after",
    `
    `
  );

/**
 * Parse CLI arguments and run
 */
program.parse();

// Show help if no command provided
if (!process.argv.slice(2).length) {
  program.outputHelp();
}