File size: 7,192 Bytes
ebcc4b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { Producer, ConnectionStatus, RobotCommand, USBDriverConfig } from '../models.js';
import { USBCalibrationManager } from '../calibration/USBCalibrationManager.js';
import { scsServoSDK } from "feetech.js";
import { ROBOT_CONFIG } from '../config.js';

export class USBProducer implements Producer {
  readonly id: string;
  readonly name = 'USB Producer';
  readonly config: USBDriverConfig;
  
  private _status: ConnectionStatus = { isConnected: false };
  private statusCallbacks: ((status: ConnectionStatus) => void)[] = [];
  
  // Joint configuration
  private readonly jointIds = [1, 2, 3, 4, 5, 6];
  private readonly jointNames = ["Rotation", "Pitch", "Elbow", "Wrist_Pitch", "Wrist_Roll", "Jaw"];
  
  // Shared calibration manager
  private calibrationManager: USBCalibrationManager;
  
  // Serial command processing to prevent "Port is busy" errors
  private commandQueue: Array<{ joints: Array<{ name: string; value: number }>, resolve: () => void, reject: (error: Error) => void }> = [];
  private isProcessingCommands = false;

  constructor(config: USBDriverConfig, calibrationManager: USBCalibrationManager) {
    this.config = config;
    this.calibrationManager = calibrationManager;
    this.id = `usb-producer-${Date.now()}`;
  }

  get status(): ConnectionStatus { 
    return this._status; 
  }

  async connect(): Promise<void> {
    if (this._status.isConnected) {
      console.debug('[USBProducer] Already connected');
      return;
    }

    try {
      console.debug('[USBProducer] Connecting...');
      
      // Check if calibration is needed
      if (this.calibrationManager.needsCalibration) {
        throw new Error('USB Producer requires calibration. Please complete calibration first.');
      }

      // Ensure the SDK is connected (reuse calibration connection if available)
      if (!this.calibrationManager.isSDKConnected) {
        console.debug('[USBProducer] Establishing new SDK connection');
        await scsServoSDK.connect({
          baudRate: this.config.baudRate || ROBOT_CONFIG.usb.baudRate
        });
      } else {
        console.debug('[USBProducer] Reusing existing SDK connection from calibration');
      }

      // Lock servos for production use (robot control)
      console.debug('[USBProducer] πŸ”’ Locking servos for production use...');
      await this.calibrationManager.lockServosForProduction();

      this._status = { 
        isConnected: true, 
        lastConnected: new Date()
      };
      this.notifyStatusChange();
      
      console.debug('[USBProducer] βœ… Connected successfully - servos locked for robot control');
    } catch (error) {
      console.error('[USBProducer] Connection failed:', error);
      this._status = { 
        isConnected: false, 
        error: error instanceof Error ? error.message : 'Connection failed'
      };
      this.notifyStatusChange();
      throw error;
    }
  }

  async disconnect(): Promise<void> {
    if (this._status.isConnected) {
      console.debug('[USBProducer] πŸ”“ Disconnecting and unlocking servos...');
      
      try {
        // Safely unlock servos when disconnecting (best practice)
        if (this.calibrationManager.isSDKConnected) {
          console.debug('[USBProducer] πŸ”“ Safely unlocking servos for manual movement...');
          await scsServoSDK.unlockServosForManualMovement(this.jointIds);
          console.debug('[USBProducer] βœ… Servos safely unlocked - can now be moved manually');
        }
      } catch (error) {
        console.warn('[USBProducer] Warning: Failed to unlock servos during disconnect:', error);
      }
      
      // Don't disconnect the SDK here - let calibration manager handle it
      // This allows multiple USB drivers to share the same connection
    }

    this._status = { isConnected: false };
    this.notifyStatusChange();
    console.debug('[USBProducer] βœ… Disconnected');
  }

  async sendCommand(command: RobotCommand): Promise<void> {
    if (!this._status.isConnected) {
      throw new Error('Cannot send command: USB Producer not connected');
    }

    console.debug(`[USBProducer] Queuing command:`, command);
    
    // Queue command for serial processing
    return new Promise((resolve, reject) => {
      this.commandQueue.push({
        joints: command.joints,
        resolve,
        reject
      });
      
      // Start processing if not already running
      this.processCommandQueue();
    });
  }

  // Event handlers
  onStatusChange(callback: (status: ConnectionStatus) => void): () => void {
    this.statusCallbacks.push(callback);
    return () => {
      const index = this.statusCallbacks.indexOf(callback);
      if (index >= 0) {
        this.statusCallbacks.splice(index, 1);
      }
    };
  }

  // Private methods
  private async processCommandQueue(): Promise<void> {
    if (this.isProcessingCommands || this.commandQueue.length === 0) {
      return;
    }

    this.isProcessingCommands = true;

    try {
      while (this.commandQueue.length > 0) {
        const { joints, resolve, reject } = this.commandQueue.shift()!;
        
        try {
          // Process servos sequentially to prevent "Port is busy" errors
          for (const jointCmd of joints) {
            const jointIndex = this.jointNames.indexOf(jointCmd.name);
            if (jointIndex >= 0) {
              const servoId = this.jointIds[jointIndex];
              const servoPosition = this.calibrationManager.denormalizeValue(jointCmd.value, jointCmd.name);
              
              await this.writeServoWithRetry(servoId, servoPosition, jointCmd.name);
              
              // Small delay between servo writes to prevent port conflicts
              await new Promise(resolve => setTimeout(resolve, ROBOT_CONFIG.usb.servoWriteDelay));
            }
          }
          
          resolve();
        } catch (error) {
          reject(error as Error);
        }
      }
    } finally {
      this.isProcessingCommands = false;
    }
  }

  private async writeServoWithRetry(servoId: number, position: number, jointName: string): Promise<void> {
    let lastError: Error | null = null;
    
    for (let attempt = 1; attempt <= ROBOT_CONFIG.usb.maxRetries; attempt++) {
      try {
        await scsServoSDK.writePositionUnlocked(servoId, position);
        console.debug(`[USBProducer] βœ… ${jointName} (servo ${servoId}) -> ${position}`);
        return; // Success!
      } catch (error) {
        lastError = error as Error;
        console.warn(`[USBProducer] Attempt ${attempt}/${ROBOT_CONFIG.usb.maxRetries} failed for servo ${servoId}:`, error);
        
        if (attempt < ROBOT_CONFIG.usb.maxRetries) {
          await new Promise(resolve => setTimeout(resolve, ROBOT_CONFIG.usb.retryDelay));
        }
      }
    }
    
    // All retries failed
    throw new Error(`Failed to write servo ${servoId} after ${ROBOT_CONFIG.usb.maxRetries} attempts: ${lastError?.message}`);
  }

  private notifyStatusChange(): void {
    this.statusCallbacks.forEach(callback => {
      try {
        callback(this._status);
      } catch (error) {
        console.error('[USBProducer] Error in status callback:', error);
      }
    });
  }
}