Spaces:
Build error
Build error
File size: 8,687 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 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 |
import type { Consumer, 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 USBConsumer implements Consumer {
readonly id: string;
readonly name = 'USB Consumer';
readonly config: USBDriverConfig;
private _status: ConnectionStatus = { isConnected: false };
private statusCallbacks: ((status: ConnectionStatus) => void)[] = [];
private commandCallbacks: ((command: RobotCommand) => void)[] = [];
// Listening state
private isListening = false;
private pollingAbortController: AbortController | null = null;
// Joint configuration
private readonly jointIds = [1, 2, 3, 4, 5, 6];
private readonly jointNames = ["Rotation", "Pitch", "Elbow", "Wrist_Pitch", "Wrist_Roll", "Jaw"];
private lastPositions: Record<string, number> = {};
// Shared calibration manager
private calibrationManager: USBCalibrationManager;
// Servo reading queue
private isReadingServos = false;
private readingQueue: Array<{
servoId: number;
resolve: (value: number) => void;
reject: (error: Error) => void;
}> = [];
// Error tracking for better backoff
private consecutiveErrors = 0;
private lastErrorTime = 0;
constructor(config: USBDriverConfig, calibrationManager: USBCalibrationManager) {
this.config = config;
this.calibrationManager = calibrationManager;
this.id = `usb-consumer-${Date.now()}`;
}
get status(): ConnectionStatus {
return this._status;
}
async connect(): Promise<void> {
if (this._status.isConnected) {
console.debug('[USBConsumer] Already connected');
return;
}
try {
console.debug('[USBConsumer] Connecting...');
// Check if calibration is needed
if (this.calibrationManager.needsCalibration) {
throw new Error('USB Consumer requires calibration. Please complete calibration first.');
}
// Ensure the SDK is connected (reuse calibration connection if available)
if (!this.calibrationManager.isSDKConnected) {
console.debug('[USBConsumer] Establishing new SDK connection');
await scsServoSDK.connect({
baudRate: this.config.baudRate || ROBOT_CONFIG.usb.baudRate
});
} else {
console.debug('[USBConsumer] Reusing existing SDK connection from calibration');
}
// Ensure servos remain unlocked for consumer (reading positions)
console.debug('[USBConsumer] 🔓 Ensuring servos remain unlocked for position reading...');
await this.calibrationManager.keepServosUnlockedForConsumer();
this._status = {
isConnected: true,
lastConnected: new Date()
};
this.notifyStatusChange();
console.debug('[USBConsumer] ✅ Connected successfully - servos unlocked for reading');
} catch (error) {
console.error('[USBConsumer] 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) {
await this.stopListening();
console.debug('[USBConsumer] Disconnecting (keeping shared SDK connection)');
// 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();
}
async startListening(): Promise<void> {
if (this.isListening) {
console.warn('[USBConsumer] Already listening');
return;
}
this.isListening = true;
this.pollingAbortController = new AbortController();
console.debug('[USBConsumer] Starting continuous polling');
this.pollContinuously();
}
async stopListening(): Promise<void> {
if (!this.isListening) return;
this.isListening = false;
if (this.pollingAbortController) {
this.pollingAbortController.abort();
this.pollingAbortController = null;
}
console.debug('[USBConsumer] Stopped listening');
}
// 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);
}
};
}
onCommand(callback: (command: RobotCommand) => void): () => void {
this.commandCallbacks.push(callback);
return () => {
const index = this.commandCallbacks.indexOf(callback);
if (index >= 0) {
this.commandCallbacks.splice(index, 1);
}
};
}
// 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 pollContinuously(): Promise<void> {
while (this.isListening && this._status.isConnected && !this.pollingAbortController?.signal.aborted) {
try {
const changes: { name: string; value: number }[] = [];
const readPromises = this.jointIds.map(async (servoId, i) => {
const jointName = this.jointNames[i];
try {
const position = await this.readServoPosition(servoId);
const lastPosition = this.lastPositions[jointName];
if (position !== lastPosition) {
// Use calibration manager for normalization
const normalizedValue = this.calibrationManager.normalizeValue(position, jointName);
this.lastPositions[jointName] = position;
return { name: jointName, value: normalizedValue };
}
} catch (error) {
// Silent continue on read errors
}
return null;
});
const results = await Promise.all(readPromises);
results.forEach(result => {
if (result) {
changes.push(result);
}
});
if (changes.length > 0) {
const command: RobotCommand = {
joints: changes,
timestamp: Date.now()
};
this.notifyCommand(command);
// Reset error counter on successful read
this.consecutiveErrors = 0;
}
await new Promise(resolve => setTimeout(resolve, ROBOT_CONFIG.polling.consumerPollingRate));
} catch (error) {
if (!this.pollingAbortController?.signal.aborted) {
console.error('[USBConsumer] Polling error:', error);
// Smart error backoff
this.consecutiveErrors++;
this.lastErrorTime = Date.now();
const backoffTime = this.consecutiveErrors > ROBOT_CONFIG.polling.maxPollingErrors
? ROBOT_CONFIG.polling.errorBackoffRate * 3 // Longer backoff after many errors
: ROBOT_CONFIG.polling.errorBackoffRate;
await new Promise(resolve => setTimeout(resolve, backoffTime));
}
}
}
}
private notifyStatusChange(): void {
this.statusCallbacks.forEach(callback => {
try {
callback(this._status);
} catch (error) {
console.error('[USBConsumer] Error in status callback:', error);
}
});
}
private notifyCommand(command: RobotCommand): void {
this.commandCallbacks.forEach(callback => {
try {
callback(command);
} catch (error) {
console.error('[USBConsumer] Error in command callback:', error);
}
});
}
} |