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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { JointCalibration, CalibrationState } from '../models.js';
import { scsServoSDK } from "feetech.js";
import { ROBOT_CONFIG } from '../config.js';

export class USBCalibrationManager {
  // Joint configuration
  private readonly jointIds = [1, 2, 3, 4, 5, 6];
  private readonly jointNames = ["Rotation", "Pitch", "Elbow", "Wrist_Pitch", "Wrist_Roll", "Jaw"];
  
  // Calibration state
  private jointCalibrations: Record<string, JointCalibration> = {};
  private _calibrationState: CalibrationState = {
    isCalibrating: false,
    progress: 0
  };
  
  // Connection state for calibration
  private isConnectedForCalibration = false;
  private baudRate: number = 1000000;
  
  // Calibration polling
  private calibrationPollingAbortController: AbortController | null = null;
  private lastPositions: Record<string, number> = {};
  private calibrationCallbacks: (() => void)[] = [];
  
  // Calibration completion callback with final positions
  private calibrationCompleteCallback: ((finalPositions: Record<string, number>) => void) | null = null;
  
  // Servo reading queue for calibration
  private isReadingServos = false;
  private readingQueue: Array<{
    servoId: number;
    resolve: (value: number) => void;
    reject: (error: Error) => void;
  }> = [];

  constructor(baudRate: number = ROBOT_CONFIG.usb.baudRate) {
    this.baudRate = baudRate;
    
    // Initialize joint calibrations
    this.jointNames.forEach(name => {
      this.jointCalibrations[name] = { isCalibrated: false };
    });
  }

  // Getters
  get isCalibrated(): boolean {
    return Object.values(this.jointCalibrations).every(cal => cal.isCalibrated);
  }

  get needsCalibration(): boolean {
    return !this.isCalibrated;
  }

  get calibrationState(): CalibrationState {
    return this._calibrationState;
  }

  get jointNames_(): string[] {
    return [...this.jointNames];
  }

  // Connection management for calibration
  async ensureConnectedForCalibration(): Promise<void> {
    if (this.isConnectedForCalibration) {
      console.log('[USBCalibrationManager] Already connected for calibration');
      return;
    }
    
    try {
      console.log('[USBCalibrationManager] Connecting SDK for calibration...');
      await scsServoSDK.connect({ baudRate: this.baudRate });
      this.isConnectedForCalibration = true;
      console.log('[USBCalibrationManager] Connected successfully for calibration');
    } catch (error) {
      console.error('[USBCalibrationManager] Failed to connect SDK for calibration:', error);
      throw error;
    }
  }

  async disconnectFromCalibration(): Promise<void> {
    if (!this.isConnectedForCalibration) return;
    
    try {
      await scsServoSDK.disconnect();
      this.isConnectedForCalibration = false;
      console.log('[USBCalibrationManager] Disconnected from calibration');
    } catch (error) {
      console.warn('[USBCalibrationManager] Failed to disconnect from calibration:', error);
    }
  }

  // Check if the SDK is currently connected (for external use)
  get isSDKConnected(): boolean {
    return this.isConnectedForCalibration && scsServoSDK.isConnected();
  }

  // Calibration methods
  async startCalibration(): Promise<void> {
    if (this._calibrationState.isCalibrating) {
      console.warn('[USBCalibrationManager] Calibration already in progress');
      return;
    }

    console.log('[USBCalibrationManager] Starting calibration process');
    
    // Ensure connection for calibration
    await this.ensureConnectedForCalibration();

    // Unlock all servos for calibration (allow manual movement)
    console.log('[USBCalibrationManager] πŸ”“ Unlocking all servos for calibration...');
    try {
      await scsServoSDK.unlockServos(this.jointIds);
      console.log('[USBCalibrationManager] βœ… All servos unlocked for manual movement during calibration');
    } catch (error) {
      console.warn('[USBCalibrationManager] Warning: Failed to unlock some servos for calibration:', error);
    }

    this._calibrationState = {
      isCalibrating: true,
      progress: 0
    };

    // Initialize calibrations with current values
    this.jointCalibrations = {};
    this.jointNames.forEach(name => {
      const currentValue = this.lastPositions[name] || 2048;
      this.jointCalibrations[name] = {
        isCalibrated: false,
        minServoValue: currentValue,
        maxServoValue: currentValue
      };
    });

    this.startCalibrationPolling();
    this.notifyCalibrationChange();
  }

  async stopCalibration(): Promise<void> {
    console.log('[USBCalibrationManager] Stopping calibration');

    this._calibrationState = {
      isCalibrating: false,
      progress: 100
    };

    // Mark all joints as calibrated
    this.jointNames.forEach(name => {
      if (this.jointCalibrations[name]) {
        this.jointCalibrations[name].isCalibrated = true;
      }
    });

    this.stopCalibrationPolling();

    // NEW: Read final positions and sync to virtual robot before locking
    console.log('[USBCalibrationManager] πŸ“ Reading final servo positions for virtual robot sync...');
    try {
      const finalPositions = await this.readFinalPositionsAndSync();
      console.log('[USBCalibrationManager] βœ… Final positions read and synced to virtual robot');
      
      // Notify robot of calibration completion with final positions
      if (this.calibrationCompleteCallback) {
        this.calibrationCompleteCallback(finalPositions);
      }
    } catch (error) {
      console.error('[USBCalibrationManager] Failed to read final positions:', error);
    }

    this.notifyCalibrationChange();

    // Keep connection open - don't disconnect automatically
    // The connection will be reused by USB drivers
    console.log('[USBCalibrationManager] Calibration complete, keeping connection for drivers');
  }

  skipCalibration(): void {
    console.log('[USBCalibrationManager] Skipping calibration, using full range');

    // Set full range for all joints
    this.jointNames.forEach(name => {
      this.jointCalibrations[name] = {
        isCalibrated: true,
        minServoValue: 0,
        maxServoValue: 4095
      };
    });

    this._calibrationState = {
      isCalibrating: false,
      progress: 100
    };

    this.notifyCalibrationChange();
  }

  // NEW: Set predefined calibration values
  async setPredefinedCalibration(): Promise<void> {
    console.log('[USBCalibrationManager] Setting predefined calibration values');

    // Ensure SDK connection for hardware access
    await this.ensureConnectedForCalibration();

    // Predefined calibration values based on known good robot configuration
    const predefinedValues: Record<string, { min: number; max: number; current: number }> = {
      "Rotation": { current: 2180, min: 764, max: 3388 },
      "Pitch": { current: 1159, min: 1138, max: 3501 },
      "Elbow": { current: 2874, min: 660, max: 2876 },
      "Wrist_Pitch": { current: 2138, min: 762, max: 3075 },
      "Wrist_Roll": { current: 2081, min: 154, max: 3995 },
      "Jaw": { current: 2061, min: 2013, max: 3555 }
    };

    // Set calibration values for all joints
    this.jointNames.forEach(name => {
      const values = predefinedValues[name];
      if (values) {
        this.jointCalibrations[name] = {
          isCalibrated: true,
          minServoValue: values.min,
          maxServoValue: values.max
        };
        // Set current position for reference
        this.lastPositions[name] = values.current;
      }
    });

    this._calibrationState = {
      isCalibrating: false,
      progress: 100
    };

    this.notifyCalibrationChange();
    console.log('[USBCalibrationManager] Predefined calibration values applied successfully');
  }

  // NEW: Read final positions and prepare for sync
  private async readFinalPositionsAndSync(): Promise<Record<string, number>> {
    const finalPositions: Record<string, number> = {};
    
    console.log('[USBCalibrationManager] Reading final positions from all servos...');
    
    // Read all servo positions sequentially
    for (let i = 0; i < this.jointIds.length; i++) {
      const servoId = this.jointIds[i];
      const jointName = this.jointNames[i];
      
      try {
        const position = await this.readServoPosition(servoId);
        finalPositions[jointName] = position;
        this.lastPositions[jointName] = position;
        
        console.log(`[USBCalibrationManager] ${jointName} (servo ${servoId}): ${position} (raw) -> ${this.normalizeValue(position, jointName).toFixed(1)}% (normalized)`);
      } catch (error) {
        console.warn(`[USBCalibrationManager] Failed to read final position for ${jointName} (servo ${servoId}):`, error);
        // Use last known position as fallback
        finalPositions[jointName] = this.lastPositions[jointName] || 2048;
      }
    }
    
    return finalPositions;
  }

  // NEW: Set callback for calibration completion with final positions
  onCalibrationCompleteWithPositions(callback: (finalPositions: Record<string, number>) => void): () => void {
    this.calibrationCompleteCallback = callback;
    return () => {
      this.calibrationCompleteCallback = null;
    };
  }

  // Post-calibration servo locking methods
  async lockServosForProduction(): Promise<void> {
    if (!this.isSDKConnected) {
      throw new Error('SDK not connected - cannot lock servos');
    }

    console.log('[USBCalibrationManager] πŸ”’ Locking all servos for production use (robot control)...');
    try {
      // Use the new lockServosForProduction function that both locks and enables torque
      await scsServoSDK.lockServosForProduction(this.jointIds);
      console.log('[USBCalibrationManager] βœ… All servos locked for production - robot is now controlled and cannot be moved manually');
    } catch (error) {
      console.error('[USBCalibrationManager] Failed to lock servos for production:', error);
      throw error;
    }
  }

  async keepServosUnlockedForConsumer(): Promise<void> {
    if (!this.isSDKConnected) {
      console.log('[USBCalibrationManager] SDK not connected - servos remain in current state');
      return;
    }

    console.log('[USBCalibrationManager] πŸ”“ Keeping servos unlocked for consumer use (reading positions)...');
    try {
      // Ensure servos are unlocked for reading
      await scsServoSDK.unlockServos(this.jointIds);
      console.log('[USBCalibrationManager] βœ… All servos remain unlocked for consumer - can be moved manually and positions read');
    } catch (error) {
      console.warn('[USBCalibrationManager] Warning: Failed to ensure servos are unlocked for consumer:', error);
    }
  }

  // Data access methods
  getCurrentRawValue(jointName: string): number | undefined {
    return this.lastPositions[jointName];
  }

  getJointCalibration(jointName: string): JointCalibration | undefined {
    return this.jointCalibrations[jointName];
  }

  getJointRange(jointName: string): number {
    const calibration = this.jointCalibrations[jointName];
    if (!calibration?.minServoValue || !calibration?.maxServoValue) return 0;
    return Math.abs(calibration.maxServoValue - calibration.minServoValue);
  }

  getAllCalibrations(): Record<string, JointCalibration> {
    return { ...this.jointCalibrations };
  }

  // Value conversion methods
  normalizeValue(servoValue: number, jointName: string): number {
    const calibration = this.jointCalibrations[jointName];
    const isGripper = jointName.toLowerCase() === 'jaw' || jointName.toLowerCase() === 'gripper';

    if (!calibration?.isCalibrated || !calibration.minServoValue || !calibration.maxServoValue) {
      if (isGripper) {
        return (servoValue / 4095) * 100;
      } else {
        return ((servoValue - 2048) / 2048) * 100;
      }
    }

    const { minServoValue, maxServoValue } = calibration;
    if (maxServoValue === minServoValue) return 0;

    const bounded = Math.max(minServoValue, Math.min(maxServoValue, servoValue));

    if (isGripper) {
      return ((bounded - minServoValue) / (maxServoValue - minServoValue)) * 100;
    } else {
      return (((bounded - minServoValue) / (maxServoValue - minServoValue)) * 200) - 100;
    }
  }

  denormalizeValue(normalizedValue: number, jointName: string): number {
    const calibration = this.jointCalibrations[jointName];
    const isGripper = jointName.toLowerCase() === 'jaw' || jointName.toLowerCase() === 'gripper';

    if (!calibration?.isCalibrated || !calibration.minServoValue || !calibration.maxServoValue) {
      // No calibration, use appropriate default conversion
      if (isGripper) {
        return Math.round((normalizedValue / 100) * 4095);
      } else {
        return Math.round(2048 + (normalizedValue / 100) * 2048);
      }
    }

    const { minServoValue, maxServoValue } = calibration;
    let ratio: number;

    if (isGripper) {
      ratio = normalizedValue / 100;
    } else {
      ratio = (normalizedValue + 100) / 200;
    }

    const servoValue = minServoValue + ratio * (maxServoValue - minServoValue);
    return Math.round(Math.max(minServoValue, Math.min(maxServoValue, servoValue)));
  }

  // Event handling
  onCalibrationChange(callback: () => void): () => void {
    this.calibrationCallbacks.push(callback);
    return () => {
      const index = this.calibrationCallbacks.indexOf(callback);
      if (index >= 0) {
        this.calibrationCallbacks.splice(index, 1);
      }
    };
  }

  // Format servo value for display
  formatServoValue(value: number | undefined): string {
    return value !== undefined ? value.toString() : '---';
  }

  // Cleanup
  async destroy(): Promise<void> {
    console.log('[USBCalibrationManager] 🧹 Destroying calibration manager...');
    
    this.stopCalibrationPolling();
    
    // Safely unlock all servos before disconnecting (best practice)
    if (this.isSDKConnected) {
      try {
        console.log('[USBCalibrationManager] πŸ”“ Safely unlocking all servos before cleanup...');
        await scsServoSDK.unlockServosForManualMovement(this.jointIds);
        console.log('[USBCalibrationManager] βœ… All servos safely unlocked for manual movement');
      } catch (error) {
        console.warn('[USBCalibrationManager] Warning: Failed to safely unlock servos during cleanup:', error);
      }
    }
    
    await this.disconnectFromCalibration();
    this.calibrationCallbacks = [];
    this.calibrationCompleteCallback = null;
    
    console.log('[USBCalibrationManager] βœ… Calibration manager destroyed');
  }

  // Private methods
  private async readServoPosition(servoId: number): Promise<number> {
    return new Promise((resolve, reject) => {
      this.readingQueue.push({ servoId, resolve, reject });
      this.processReadingQueue();
    });
  }

  private async processReadingQueue(): Promise<void> {
    if (this.isReadingServos || this.readingQueue.length === 0) {
      return;
    }

    this.isReadingServos = true;

    try {
      const batch = [...this.readingQueue];
      this.readingQueue = [];

      for (const { servoId, resolve, reject } of batch) {
        try {
          const position = await scsServoSDK.readPosition(servoId);
          resolve(position);
        } catch (error) {
          reject(error instanceof Error ? error : new Error(`Failed to read servo ${servoId}`));
        }

        await new Promise(resolve => setTimeout(resolve, 5));
      }
    } finally {
      this.isReadingServos = false;

      if (this.readingQueue.length > 0) {
        setTimeout(() => this.processReadingQueue(), 50);
      }
    }
  }

  private async startCalibrationPolling(): Promise<void> {
    this.stopCalibrationPolling();

    this.calibrationPollingAbortController = new AbortController();
    const signal = this.calibrationPollingAbortController.signal;

    console.log('[USBCalibrationManager] Starting calibration polling');

    try {
      while (!signal.aborted && this._calibrationState.isCalibrating) {
        const readPromises = this.jointIds.map(async (servoId, i) => {
          if (signal.aborted) return null;

          const jointName = this.jointNames[i];

          try {
            const currentValue = await this.readServoPosition(servoId);
            return { jointName, currentValue };
          } catch (error) {
            return null;
          }
        });

        const results = await Promise.all(readPromises);
        let hasUpdates = false;

        results.forEach(result => {
          if (!result) return;

          const { jointName, currentValue } = result;
          this.lastPositions[jointName] = currentValue;

          const calibration = this.jointCalibrations[jointName];
          if (calibration) {
            if (currentValue < calibration.minServoValue!) {
              calibration.minServoValue = currentValue;
              hasUpdates = true;
            }
            if (currentValue > calibration.maxServoValue!) {
              calibration.maxServoValue = currentValue;
              hasUpdates = true;
            }
          }
        });

        if (hasUpdates) {
          this.notifyCalibrationChange();
        }

        // Calculate progress
        const totalRangeNeeded = 500;
        let totalRangeDiscovered = 0;

        this.jointNames.forEach(name => {
          const calibration = this.jointCalibrations[name];
          if (calibration?.minServoValue !== undefined && calibration?.maxServoValue !== undefined) {
            totalRangeDiscovered += Math.abs(calibration.maxServoValue - calibration.minServoValue);
          }
        });

        const newProgress = Math.min(100, (totalRangeDiscovered / (totalRangeNeeded * this.jointNames.length)) * 100);
        if (Math.abs(newProgress - this._calibrationState.progress) > 1) {
          this._calibrationState.progress = newProgress;
          this.notifyCalibrationChange();
        }

        await new Promise(resolve => setTimeout(resolve, 10));
      }
    } catch (error) {
      if (!signal.aborted) {
        console.error('[USBCalibrationManager] Calibration polling error:', error);
      }
    }
  }

  private stopCalibrationPolling(): void {
    if (this.calibrationPollingAbortController) {
      this.calibrationPollingAbortController.abort();
      this.calibrationPollingAbortController = null;
    }
  }

  private notifyCalibrationChange(): void {
    this.calibrationCallbacks.forEach(callback => {
      try {
        callback();
      } catch (error) {
        console.error('[USBCalibrationManager] Error in calibration callback:', error);
      }
    });
  }
}