File size: 20,618 Bytes
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
130ae50
ba80dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130ae50
 
 
ba80dbe
 
130ae50
ba80dbe
 
 
 
 
 
 
 
130ae50
 
ba80dbe
 
 
 
 
 
 
 
 
 
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
130ae50
 
 
 
 
 
 
ba80dbe
 
130ae50
 
 
ba80dbe
130ae50
 
 
 
 
 
ba80dbe
130ae50
 
 
ba80dbe
 
 
 
 
 
 
 
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
 
 
130ae50
 
ba80dbe
130ae50
 
ba80dbe
130ae50
 
ba80dbe
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130ae50
 
 
ba80dbe
 
 
130ae50
 
 
 
ba80dbe
 
 
 
 
 
 
130ae50
 
 
 
 
 
ba80dbe
 
 
 
130ae50
 
ba80dbe
 
 
 
130ae50
 
 
ba80dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
 
 
 
130ae50
 
ba80dbe
 
 
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
130ae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba80dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/**
 * 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";

/**
 * Sign-magnitude encoding functions for Feetech STS3215 motors
 * Mirrors Python lerobot/common/utils/encoding_utils.py
 */

/**
 * Encode a signed integer using sign-magnitude format
 * Bit at sign_bit_index represents sign (0=positive, 1=negative)
 * Lower bits represent magnitude
 */
function encodeSignMagnitude(value: number, signBitIndex: number): number {
  const maxMagnitude = (1 << signBitIndex) - 1;
  const magnitude = Math.abs(value);

  if (magnitude > maxMagnitude) {
    throw new Error(
      `Magnitude ${magnitude} exceeds ${maxMagnitude} (max for signBitIndex=${signBitIndex})`
    );
  }

  const directionBit = value < 0 ? 1 : 0;
  return (directionBit << signBitIndex) | magnitude;
}

/**
 * Decode a sign-magnitude encoded value back to signed integer
 * Extracts sign bit and magnitude, then applies sign
 */
function decodeSignMagnitude(
  encodedValue: number,
  signBitIndex: number
): number {
  const directionBit = (encodedValue >> signBitIndex) & 1;
  const magnitudeMask = (1 << signBitIndex) - 1;
  const magnitude = encodedValue & magnitudeMask;
  return directionBit ? -magnitude : magnitude;
}

/**
 * Device configuration for calibration
 * Despite the "SO100" name, this interface is now device-agnostic and configurable
 * for any robot using similar serial protocols (Feetech STS3215, etc.)
 */
import type {
  SO100CalibrationConfig,
  CalibrationResults,
} from "../types/calibration.js";

/**
 * 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 device-specific protocol - configurable for different robot types
 */
export async function readMotorPositions(
  config: SO100CalibrationConfig,
  quiet: boolean = false
): Promise<number[]> {
  const motorPositions: number[] = [];

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

    try {
      // Create Read Position packet using configurable address
      const packet = Buffer.from([
        0xff,
        0xff,
        motorId,
        0x04,
        0x02,
        config.protocol.presentPositionAddress, // Configurable address instead of hardcoded 0x38
        0x02,
        0x00,
      ]);
      const checksum =
        ~(
          motorId +
          0x04 +
          0x02 +
          config.protocol.presentPositionAddress +
          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 {
            // Use half of max resolution as fallback instead of hardcoded 2047
            motorPositions.push(
              Math.floor((config.protocol.resolution - 1) / 2)
            );
          }
        } else {
          motorPositions.push(Math.floor((config.protocol.resolution - 1) / 2));
        }
      } catch (readError) {
        motorPositions.push(Math.floor((config.protocol.resolution - 1) / 2));
      }
    } catch (error) {
      motorPositions.push(Math.floor((config.protocol.resolution - 1) / 2));
    }

    // 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
  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
  const { rangeMins, rangeMaxes } = await recordRangesOfMotion(config);

  // Step 3: Set special range for wrist_roll (full turn motor)
  rangeMins["wrist_roll"] = 0;
  rangeMaxes["wrist_roll"] = 4095;

  // Step 4: Write hardware position limits to motors (matching Python behavior)
  await writeHardwarePositionLimits(config, rangeMins, rangeMaxes);

  // Compile results in Python-compatible format
  const results: CalibrationResults = {};

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

    results[motorName] = {
      id: motorId,
      drive_mode: config.driveModes[i],
      homing_offset: homingOffsets[motorName],
      range_min: rangeMins[motorName],
      range_max: rangeMaxes[motorName],
    };
  }

  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
}

/**
 * Reset homing offsets to 0 for all motors
 * Mirrors Python reset_calibration() - critical step before calculating new offsets
 * This ensures Present_Position reflects true physical position without existing offsets
 */
async function resetHomingOffsets(
  config: SO100CalibrationConfig
): Promise<void> {
  for (let i = 0; i < config.motorIds.length; i++) {
    const motorId = config.motorIds[i];
    const motorName = config.motorNames[i];

    try {
      // Write 0 to Homing_Offset register using configurable address
      const homingOffsetValue = 0;

      // Create Write Homing_Offset packet using configurable address
      const packet = Buffer.from([
        0xff,
        0xff, // Header
        motorId, // Servo ID
        0x05, // Length (Instruction + Address + Data + Checksum)
        0x03, // Instruction: WRITE_DATA
        config.protocol.homingOffsetAddress, // Configurable address instead of hardcoded 0x1f
        homingOffsetValue & 0xff, // Data_L (low byte)
        (homingOffsetValue >> 8) & 0xff, // Data_H (high byte)
        0x00, // Checksum (will calculate)
      ]);

      // Calculate checksum using configurable address
      const checksum =
        ~(
          motorId +
          0x05 +
          0x03 +
          config.protocol.homingOffsetAddress +
          (homingOffsetValue & 0xff) +
          ((homingOffsetValue >> 8) & 0xff)
        ) & 0xff;
      packet[8] = checksum;

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

      // Send reset packet
      await new Promise<void>((resolve, reject) => {
        config.port.write(packet, (error) => {
          if (error) {
            reject(
              new Error(
                `Failed to reset homing offset for ${motorName}: ${error.message}`
              )
            );
          } else {
            resolve();
          }
        });
      });

      // Wait for response (silent unless error)
      try {
        await readData(config.port, 200);
      } catch (error) {
        // Silent - response not required for successful operation
      }
    } catch (error) {
      throw new Error(
        `Failed to reset homing offset for ${motorName}: ${
          error instanceof Error ? error.message : error
        }`
      );
    }

    // Small delay between motor writes
    await new Promise((resolve) => setTimeout(resolve, 20));
  }
}

/**
 * Record homing offsets (current positions as center)
 * Mirrors Python bus.set_half_turn_homings()
 *
 * CRITICAL: Must reset existing homing offsets to 0 first (like Python does)
 * CRITICAL: Must WRITE the new homing offsets to motors immediately (like Python does)
 */
async function setHomingOffsets(
  config: SO100CalibrationConfig
): Promise<{ [motor: string]: number }> {
  // CRITICAL: Reset existing homing offsets to 0 first (matching Python)
  await resetHomingOffsets(config);

  // Wait a moment for reset to take effect
  await new Promise((resolve) => setTimeout(resolve, 100));

  // Now read positions (which will be true physical positions)
  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];

    // Generic formula: pos - int((max_res - 1) / 2) using configurable resolution
    const halfTurn = Math.floor((config.protocol.resolution - 1) / 2);
    homingOffsets[motorName] = position - halfTurn;
  }

  // CRITICAL: Write homing offsets to motors immediately (matching Python exactly)
  // Python does: for motor, offset in homing_offsets.items(): self.write("Homing_Offset", motor, offset)
  await writeHomingOffsetsToMotors(config, homingOffsets);

  return homingOffsets;
}

/**
 * Write homing offsets to motor registers immediately
 * Mirrors Python's immediate writing in set_half_turn_homings()
 */
async function writeHomingOffsetsToMotors(
  config: SO100CalibrationConfig,
  homingOffsets: { [motor: string]: number }
): Promise<void> {
  for (let i = 0; i < config.motorIds.length; i++) {
    const motorId = config.motorIds[i];
    const motorName = config.motorNames[i];
    const homingOffset = homingOffsets[motorName];

    try {
      // Encode using sign-magnitude format (like Python)
      const encodedOffset = encodeSignMagnitude(
        homingOffset,
        config.protocol.signMagnitudeBit
      );

      // Create Write Homing_Offset packet
      const packet = Buffer.from([
        0xff,
        0xff, // Header
        motorId, // Servo ID
        0x05, // Length
        0x03, // Instruction: WRITE_DATA
        config.protocol.homingOffsetAddress, // Homing_Offset address
        encodedOffset & 0xff, // Data_L (low byte)
        (encodedOffset >> 8) & 0xff, // Data_H (high byte)
        0x00, // Checksum (will calculate)
      ]);

      // Calculate checksum
      const checksum =
        ~(
          motorId +
          0x05 +
          0x03 +
          config.protocol.homingOffsetAddress +
          (encodedOffset & 0xff) +
          ((encodedOffset >> 8) & 0xff)
        ) & 0xff;
      packet[8] = checksum;

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

      // Send packet
      await new Promise<void>((resolve, reject) => {
        config.port.write(packet, (error) => {
          if (error) {
            reject(
              new Error(
                `Failed to write homing offset for ${motorName}: ${error.message}`
              )
            );
          } else {
            resolve();
          }
        });
      });

      // Wait for response (silent unless error)
      try {
        await readData(config.port, 200);
      } catch (error) {
        // Silent - response not required for successful operation
      }
    } catch (error) {
      throw new Error(
        `Failed to write homing offset for ${motorName}: ${
          error instanceof Error ? error.message : error
        }`
      );
    }

    // Small delay between motor writes
    await new Promise((resolve) => setTimeout(resolve, 20));
  }
}

/**
 * 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(
    "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 } = {};

  // Read actual current positions (matching Python exactly)
  // Python does: start_positions = self.sync_read("Present_Position", motors, normalize=False)
  // mins = start_positions.copy(); maxes = start_positions.copy()
  const startPositions = await readMotorPositions(config);

  for (let i = 0; i < config.motorNames.length; i++) {
    const motorName = config.motorNames[i];
    const startPosition = startPositions[i];
    rangeMins[motorName] = startPosition; // Use actual position, not hardcoded 2047
    rangeMaxes[motorName] = startPosition; // Use actual position, not hardcoded 2047
  }

  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();
  });

  // 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 = `Readings: ${readCount}\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);
    });
  });
}

/**
 * Write hardware position limits to motors
 * Mirrors Python lerobot write_calibration() behavior where it writes:
 * - Min_Position_Limit register with calibration.range_min
 * - Max_Position_Limit register with calibration.range_max
 * This physically constrains the motors to the calibrated ranges
 */
async function writeHardwarePositionLimits(
  config: SO100CalibrationConfig,
  rangeMins: { [motor: string]: number },
  rangeMaxes: { [motor: string]: number }
): Promise<void> {
  for (let i = 0; i < config.motorIds.length; i++) {
    const motorId = config.motorIds[i];
    const motorName = config.motorNames[i];
    const minLimit = rangeMins[motorName];
    const maxLimit = rangeMaxes[motorName];

    try {
      // Write Min_Position_Limit register
      await writeMotorRegister(
        config,
        motorId,
        config.protocol.minPositionLimitAddress,
        minLimit,
        `Min_Position_Limit for ${motorName}`
      );

      // Small delay between writes
      await new Promise((resolve) => setTimeout(resolve, 20));

      // Write Max_Position_Limit register
      await writeMotorRegister(
        config,
        motorId,
        config.protocol.maxPositionLimitAddress,
        maxLimit,
        `Max_Position_Limit for ${motorName}`
      );

      // Small delay between motors
      await new Promise((resolve) => setTimeout(resolve, 20));
    } catch (error) {
      throw new Error(
        `Failed to write position limits for ${motorName}: ${
          error instanceof Error ? error.message : error
        }`
      );
    }
  }
}

/**
 * Generic function to write a 2-byte value to a motor register
 * Used for both Min_Position_Limit and Max_Position_Limit
 */
async function writeMotorRegister(
  config: SO100CalibrationConfig,
  motorId: number,
  registerAddress: number,
  value: number,
  description: string
): Promise<void> {
  // Create Write Register packet
  const packet = Buffer.from([
    0xff,
    0xff, // Header
    motorId, // Servo ID
    0x05, // Length (Instruction + Address + Data + Checksum)
    0x03, // Instruction: WRITE_DATA
    registerAddress, // Register address
    value & 0xff, // Data_L (low byte)
    (value >> 8) & 0xff, // Data_H (high byte)
    0x00, // Checksum (will calculate)
  ]);

  // Calculate checksum
  const checksum =
    ~(
      motorId +
      0x05 +
      0x03 +
      registerAddress +
      (value & 0xff) +
      ((value >> 8) & 0xff)
    ) & 0xff;
  packet[8] = checksum;

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

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

  // Wait for response (silent unless error)
  try {
    await readData(config.port, 200);
  } catch (error) {
    // Silent - response not required for successful operation
  }
}