File size: 22,169 Bytes
6ce4ca6
f62f94b
 
 
 
 
 
 
 
 
 
 
 
 
6ce4ca6
 
 
 
f62f94b
 
 
 
 
6ce4ca6
 
 
 
 
 
 
 
f62f94b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ce4ca6
 
f62f94b
 
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
import {
  PortHandler,
  PacketHandler,
  COMM_SUCCESS,
  COMM_RX_TIMEOUT,
  COMM_RX_CORRUPT,
  COMM_RX_FAIL,
  COMM_TX_FAIL,
  COMM_NOT_AVAILABLE,
  SCS_LOBYTE,
  SCS_HIBYTE,
  SCS_MAKEWORD,
  GroupSyncRead, // Import GroupSyncRead
  GroupSyncWrite, // Import GroupSyncWrite
} from "./lowLevelSDK.mjs";

// Import address constants from the correct file
import {
  ADDR_SCS_PRESENT_POSITION,
  ADDR_SCS_GOAL_POSITION,
  ADDR_SCS_TORQUE_ENABLE,
  ADDR_SCS_GOAL_ACC,
  ADDR_SCS_GOAL_SPEED,
} from "./scsservo_constants.mjs";

// Define constants not present in scsservo_constants.mjs
const ADDR_SCS_MODE = 33;
const ADDR_SCS_LOCK = 55;
const ADDR_SCS_ID = 5; // Address for Servo ID
const ADDR_SCS_BAUD_RATE = 6; // Address for Baud Rate

// --- Class-based multi-instance implementation ---
export class ScsServoSDK {
  constructor() {
    this.portHandler = null;
    this.packetHandler = null;
  }

  async connect(options = {}) {
    if (this.portHandler && this.portHandler.isOpen) {
      console.log("Already connected.");
      return true;
    }
    const { baudRate = 1000000, protocolEnd = 0 } = options;
    try {
      this.portHandler = new PortHandler();
      const portRequested = await this.portHandler.requestPort();
      if (!portRequested) {
        this.portHandler = null;
        throw new Error("Failed to select a serial port.");
      }
      this.portHandler.setBaudRate(baudRate);
      const portOpened = await this.portHandler.openPort();
      if (!portOpened) {
        await this.portHandler.closePort().catch(console.error);
        this.portHandler = null;
        throw new Error(`Failed to open port at baudrate ${baudRate}.`);
      }
      this.packetHandler = new PacketHandler(protocolEnd);
      console.log(
        `Connected to serial port at ${baudRate} baud, protocol end: ${protocolEnd}.`
      );
      return true;
    } catch (err) {
      console.error("Error during connection:", err);
      if (this.portHandler) {
        try {
          await this.portHandler.closePort();
        } catch (closeErr) {
          console.error(
            "Error closing port after connection failure:",
            closeErr
          );
        }
      }
      this.portHandler = null;
      this.packetHandler = null;
      throw new Error(`Connection failed: ${err.message}`);
    }
  }

  async disconnect() {
    if (!this.portHandler || !this.portHandler.isOpen) {
      console.log("Already disconnected.");
      return true;
    }
    try {
      await this.portHandler.closePort();
      this.portHandler = null;
      this.packetHandler = null;
      console.log("Disconnected from serial port.");
      return true;
    } catch (err) {
      console.error("Error during disconnection:", err);
      this.portHandler = null;
      this.packetHandler = null;
      throw new Error(`Disconnection failed: ${err.message}`);
    }
  }

  checkConnection() {
    if (!this.portHandler || !this.packetHandler) {
      throw new Error("Not connected. Call connect() first.");
    }
  }

  async readPosition(servoId) {
    this.checkConnection();
    try {
      const [position, result, error] = await this.packetHandler.read2ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_PRESENT_POSITION
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error reading position from servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return position & 0xffff;
    } catch (err) {
      console.error(`Exception reading position from servo ${servoId}:`, err);
      throw new Error(
        `Exception reading position from servo ${servoId}: ${err.message}`
      );
    }
  }

  async readBaudRate(servoId) {
    this.checkConnection();
    try {
      const [baudIndex, result, error] = await this.packetHandler.read1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_BAUD_RATE
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error reading baud rate from servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return baudIndex;
    } catch (err) {
      console.error(`Exception reading baud rate from servo ${servoId}:`, err);
      throw new Error(
        `Exception reading baud rate from servo ${servoId}: ${err.message}`
      );
    }
  }

  async readMode(servoId) {
    this.checkConnection();
    try {
      const [modeValue, result, error] = await this.packetHandler.read1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_MODE
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error reading mode from servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return modeValue;
    } catch (err) {
      console.error(`Exception reading mode from servo ${servoId}:`, err);
      throw new Error(
        `Exception reading mode from servo ${servoId}: ${err.message}`
      );
    }
  }

  async writePosition(servoId, position) {
    this.checkConnection();
    try {
      if (position < 0 || position > 4095) {
        throw new Error(
          `Invalid position value ${position} for servo ${servoId}. Must be between 0 and 4095.`
        );
      }
      const targetPosition = Math.round(position);
      const [result, error] = await this.packetHandler.write2ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_GOAL_POSITION,
        targetPosition
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error writing position to servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return "success";
    } catch (err) {
      console.error(`Exception writing position to servo ${servoId}:`, err);
      throw new Error(
        `Failed to write position to servo ${servoId}: ${err.message}`
      );
    }
  }

  async writeTorqueEnable(servoId, enable) {
    this.checkConnection();
    try {
      const enableValue = enable ? 1 : 0;
      const [result, error] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_TORQUE_ENABLE,
        enableValue
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error setting torque for servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return "success";
    } catch (err) {
      console.error(`Exception setting torque for servo ${servoId}:`, err);
      throw new Error(
        `Exception setting torque for servo ${servoId}: ${err.message}`
      );
    }
  }

  async writeAcceleration(servoId, acceleration) {
    this.checkConnection();
    try {
      const clampedAcceleration = Math.max(
        0,
        Math.min(254, Math.round(acceleration))
      );
      const [result, error] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_GOAL_ACC,
        clampedAcceleration
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error writing acceleration to servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error code: ${error}`
        );
      }
      return "success";
    } catch (err) {
      console.error(`Exception writing acceleration to servo ${servoId}:`, err);
      throw new Error(
        `Exception writing acceleration to servo ${servoId}: ${err.message}`
      );
    }
  }

  async setWheelMode(servoId) {
    this.checkConnection();
    let unlocked = false;
    try {
      console.log(`Setting servo ${servoId} to wheel mode...`);
      const [resUnlock, errUnlock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        0
      );
      if (resUnlock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to unlock servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resUnlock
          )}, Error: ${errUnlock}`
        );
      }
      unlocked = true;
      const [resMode, errMode] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_MODE,
        1
      );
      if (resMode !== COMM_SUCCESS) {
        throw new Error(
          `Failed to set wheel mode for servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resMode
          )}, Error: ${errMode}`
        );
      }
      const [resLock, errLock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        1
      );
      if (resLock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to lock servo ${servoId} after setting mode: ${this.packetHandler.getTxRxResult(
            resLock
          )}, Error: ${errLock}`
        );
      }
      unlocked = false;
      console.log(`Successfully set servo ${servoId} to wheel mode.`);
      return "success";
    } catch (err) {
      console.error(`Exception setting wheel mode for servo ${servoId}:`, err);
      if (unlocked) {
        await this.tryLockServo(servoId);
      }
      throw new Error(
        `Failed to set wheel mode for servo ${servoId}: ${err.message}`
      );
    }
  }

  async setPositionMode(servoId) {
    this.checkConnection();
    let unlocked = false;
    try {
      console.log(`Setting servo ${servoId} back to position mode...`);
      const [resUnlock, errUnlock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        0
      );
      if (resUnlock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to unlock servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resUnlock
          )}, Error: ${errUnlock}`
        );
      }
      unlocked = true;
      const [resMode, errMode] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_MODE,
        0
      );
      if (resMode !== COMM_SUCCESS) {
        throw new Error(
          `Failed to set position mode for servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resMode
          )}, Error: ${errMode}`
        );
      }
      const [resLock, errLock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        1
      );
      if (resLock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to lock servo ${servoId} after setting mode: ${this.packetHandler.getTxRxResult(
            resLock
          )}, Error: ${errLock}`
        );
      }
      unlocked = false;
      console.log(`Successfully set servo ${servoId} back to position mode.`);
      return "success";
    } catch (err) {
      console.error(
        `Exception setting position mode for servo ${servoId}:`,
        err
      );
      if (unlocked) {
        await this.tryLockServo(servoId);
      }
      throw new Error(
        `Failed to set position mode for servo ${servoId}: ${err.message}`
      );
    }
  }

  async tryLockServo(servoId) {
    try {
      await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        1
      );
    } catch (lockErr) {
      console.error(`Failed to re-lock servo ${servoId}:`, lockErr);
    }
  }

  async writeWheelSpeed(servoId, speed) {
    this.checkConnection();
    try {
      const clampedSpeed = Math.max(-10000, Math.min(10000, Math.round(speed)));
      let speedValue = Math.abs(clampedSpeed) & 0x7fff;
      if (clampedSpeed < 0) {
        speedValue |= 0x8000;
      }
      const [result, error] = await this.packetHandler.write2ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_GOAL_SPEED,
        speedValue
      );
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Error writing wheel speed to servo ${servoId}: ${this.packetHandler.getTxRxResult(
            result
          )}, Error: ${error}`
        );
      }
      return "success";
    } catch (err) {
      console.error(`Exception writing wheel speed to servo ${servoId}:`, err);
      throw new Error(
        `Exception writing wheel speed to servo ${servoId}: ${err.message}`
      );
    }
  }

  async syncWriteWheelSpeed(servoSpeeds) {
    this.checkConnection();
    const groupSyncWrite = new GroupSyncWrite(
      this.portHandler,
      this.packetHandler,
      ADDR_SCS_GOAL_SPEED,
      2
    );
    let paramAdded = false;
    const entries =
      servoSpeeds instanceof Map
        ? servoSpeeds.entries()
        : Object.entries(servoSpeeds);
    for (const [idStr, speed] of entries) {
      const servoId = parseInt(idStr, 10);
      if (isNaN(servoId) || servoId < 1 || servoId > 252) {
        throw new Error(`Invalid servo ID "${idStr}" in syncWriteWheelSpeed.`);
      }
      if (speed < -10000 || speed > 10000) {
        throw new Error(
          `Invalid speed value ${speed} for servo ${servoId} in syncWriteWheelSpeed. Must be between -10000 and 10000.`
        );
      }
      const clampedSpeed = Math.max(-10000, Math.min(10000, Math.round(speed)));
      let speedValue = Math.abs(clampedSpeed) & 0x7fff;
      if (clampedSpeed < 0) {
        speedValue |= 0x8000;
      }
      const data = [SCS_LOBYTE(speedValue), SCS_HIBYTE(speedValue)];
      if (groupSyncWrite.addParam(servoId, data)) {
        paramAdded = true;
      } else {
        console.warn(
          `Failed to add servo ${servoId} to sync write speed group (possibly duplicate).`
        );
      }
    }
    if (!paramAdded) {
      console.log("Sync Write Speed: No valid servo speeds provided or added.");
      return "success";
    }
    try {
      const result = await groupSyncWrite.txPacket();
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Sync Write Speed txPacket failed: ${this.packetHandler.getTxRxResult(
            result
          )}`
        );
      }
      return "success";
    } catch (err) {
      console.error("Exception during syncWriteWheelSpeed:", err);
      throw new Error(`Sync Write Speed failed: ${err.message}`);
    }
  }

  async syncReadPositions(servoIds) {
    this.checkConnection();
    if (!Array.isArray(servoIds) || servoIds.length === 0) {
      console.log("Sync Read: No servo IDs provided.");
      return new Map();
    }
    const startAddress = ADDR_SCS_PRESENT_POSITION;
    const positions = new Map();
    for (const id of servoIds) {
      if (id < 1 || id > 252) {
        console.warn(`Sync Read: Invalid servo ID ${id} skipped.`);
        continue;
      }
      try {
        const [pos, result, error] = await this.packetHandler.read2ByteTxRx(
          this.portHandler,
          id,
          startAddress
        );
        if (result === COMM_SUCCESS) {
          positions.set(id, pos & 0xffff);
        } else {
          console.warn(
            `Sync Read: Failed to read position for servo ID ${id}: ${this.packetHandler.getTxRxResult(
              result
            )}, Error: ${error}`
          );
        }
      } catch (e) {
        console.warn(`Sync Read: Exception reading servo ID ${id}:`, e);
      }
    }
    return positions;
  }

  async syncWritePositions(servoPositions) {
    this.checkConnection();
    const groupSyncWrite = new GroupSyncWrite(
      this.portHandler,
      this.packetHandler,
      ADDR_SCS_GOAL_POSITION,
      2
    );
    let paramAdded = false;
    const entries =
      servoPositions instanceof Map
        ? servoPositions.entries()
        : Object.entries(servoPositions);
    for (const [idStr, position] of entries) {
      const servoId = parseInt(idStr, 10);
      if (isNaN(servoId) || servoId < 1 || servoId > 252) {
        throw new Error(`Invalid servo ID "${idStr}" in syncWritePositions.`);
      }
      if (position < 0 || position > 4095) {
        throw new Error(
          `Invalid position value ${position} for servo ${servoId} in syncWritePositions. Must be between 0 and 4095.`
        );
      }
      const targetPosition = Math.round(position);
      const data = [SCS_LOBYTE(targetPosition), SCS_HIBYTE(targetPosition)];
      if (groupSyncWrite.addParam(servoId, data)) {
        paramAdded = true;
      } else {
        console.warn(
          `Failed to add servo ${servoId} to sync write group (possibly duplicate).`
        );
      }
    }
    if (!paramAdded) {
      console.log("Sync Write: No valid servo positions provided or added.");
      return "success";
    }
    try {
      const result = await groupSyncWrite.txPacket();
      if (result !== COMM_SUCCESS) {
        throw new Error(
          `Sync Write txPacket failed: ${this.packetHandler.getTxRxResult(
            result
          )}`
        );
      }
      return "success";
    } catch (err) {
      console.error("Exception during syncWritePositions:", err);
      throw new Error(`Sync Write failed: ${err.message}`);
    }
  }

  async setBaudRate(servoId, baudRateIndex) {
    this.checkConnection();
    if (servoId < 1 || servoId > 252) {
      throw new Error(
        `Invalid servo ID provided: ${servoId}. Must be between 1 and 252.`
      );
    }
    if (baudRateIndex < 0 || baudRateIndex > 7) {
      throw new Error(
        `Invalid baudRateIndex: ${baudRateIndex}. Must be between 0 and 7.`
      );
    }
    let unlocked = false;
    try {
      console.log(
        `Setting baud rate for servo ${servoId}: Index=${baudRateIndex}`
      );
      const [resUnlock, errUnlock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        0
      );
      if (resUnlock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to unlock servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resUnlock
          )}, Error: ${errUnlock}`
        );
      }
      unlocked = true;
      const [resBaud, errBaud] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_BAUD_RATE,
        baudRateIndex
      );
      if (resBaud !== COMM_SUCCESS) {
        throw new Error(
          `Failed to write baud rate index ${baudRateIndex} to servo ${servoId}: ${this.packetHandler.getTxRxResult(
            resBaud
          )}, Error: ${errBaud}`
        );
      }
      const [resLock, errLock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        servoId,
        ADDR_SCS_LOCK,
        1
      );
      if (resLock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to lock servo ${servoId} after setting baud rate: ${this.packetHandler.getTxRxResult(
            resLock
          )}, Error: ${errLock}.`
        );
      }
      unlocked = false;
      console.log(
        `Successfully set baud rate for servo ${servoId}. Index: ${baudRateIndex}. Remember to potentially reconnect with the new baud rate.`
      );
      return "success";
    } catch (err) {
      console.error(
        `Exception during setBaudRate for servo ID ${servoId}:`,
        err
      );
      if (unlocked) {
        await this.tryLockServo(servoId);
      }
      throw new Error(
        `Failed to set baud rate for servo ${servoId}: ${err.message}`
      );
    }
  }

  async setServoId(currentServoId, newServoId) {
    this.checkConnection();
    if (
      currentServoId < 1 ||
      currentServoId > 252 ||
      newServoId < 1 ||
      newServoId > 252
    ) {
      throw new Error(
        `Invalid servo ID provided. Current: ${currentServoId}, New: ${newServoId}. Must be between 1 and 252.`
      );
    }
    if (currentServoId === newServoId) {
      console.log(`Servo ID is already ${newServoId}. No change needed.`);
      return "success";
    }
    let unlocked = false;
    let idWritten = false;
    try {
      console.log(`Setting servo ID: From ${currentServoId} to ${newServoId}`);
      const [resUnlock, errUnlock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        currentServoId,
        ADDR_SCS_LOCK,
        0
      );
      if (resUnlock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to unlock servo ${currentServoId}: ${this.packetHandler.getTxRxResult(
            resUnlock
          )}, Error: ${errUnlock}`
        );
      }
      unlocked = true;
      const [resId, errId] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        currentServoId,
        ADDR_SCS_ID,
        newServoId
      );
      if (resId !== COMM_SUCCESS) {
        throw new Error(
          `Failed to write new ID ${newServoId} to servo ${currentServoId}: ${this.packetHandler.getTxRxResult(
            resId
          )}, Error: ${errId}`
        );
      }
      idWritten = true;
      const [resLock, errLock] = await this.packetHandler.write1ByteTxRx(
        this.portHandler,
        newServoId,
        ADDR_SCS_LOCK,
        1
      );
      if (resLock !== COMM_SUCCESS) {
        throw new Error(
          `Failed to lock servo with new ID ${newServoId}: ${this.packetHandler.getTxRxResult(
            resLock
          )}, Error: ${errLock}. Configuration might be incomplete.`
        );
      }
      unlocked = false;
      console.log(
        `Successfully set servo ID from ${currentServoId} to ${newServoId}. Remember to use the new ID for future commands.`
      );
      return "success";
    } catch (err) {
      console.error(
        `Exception during setServoId for current ID ${currentServoId}:`,
        err
      );
      if (unlocked) {
        const idToLock = idWritten ? newServoId : currentServoId;
        console.warn(`Attempting to re-lock servo using ID ${idToLock}...`);
        await this.tryLockServo(idToLock);
      }
      throw new Error(
        `Failed to set servo ID from ${currentServoId} to ${newServoId}: ${err.message}`
      );
    }
  }
}

// For backward compatibility: keep a singleton instance
export const scsServoSDK = new ScsServoSDK();