All files / services/ble MockBLEManager.ts

0% Statements 0/132
0% Branches 0/35
0% Functions 0/27
0% Lines 0/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
// Mock BLE Manager для iOS Simulator (Bluetooth недоступен)
 
import {
  IBLEManager,
  WPDevice,
  WiFiNetwork,
  WiFiStatus,
  BLEConnectionState,
  BLEDeviceConnection,
  BLEEventListener,
  BLEConnectionEvent,
  SensorHealthMetrics,
  SensorHealthStatus,
  WiFiSignalQuality,
  CommunicationHealth,
  BulkOperationResult,
  BulkWiFiResult,
} from './types';
 
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
 
export class MockBLEManager implements IBLEManager {
  private connectedDevices = new Set<string>();
  private connectionStates = new Map<string, BLEDeviceConnection>();
  private eventListeners: BLEEventListener[] = [];
  private connectingDevices = new Set<string>(); // Track devices currently being connected
 
  // Health monitoring state (mock)
  private sensorHealthMetrics = new Map<string, SensorHealthMetrics>();
  private communicationStats = new Map<string, CommunicationHealth>();
  private mockDevices: WPDevice[] = [
    {
      id: 'mock-743',
      name: 'WP_497_81a14c',
      mac: '142B2F81A14C',
      rssi: -55,
      wellId: 497,
    },
    {
      id: 'mock-769',
      name: 'WP_523_81aad4',
      mac: '142B2F81AAD4',
      rssi: -67,
      wellId: 523,
    },
  ];
 
  /**
   * Update connection state and notify listeners
   */
  private updateConnectionState(
    deviceId: string,
    state: BLEConnectionState,
    deviceName?: string,
    error?: string
  ): void {
    const existing = this.connectionStates.get(deviceId);
    const now = Date.now();
 
    const connection: BLEDeviceConnection = {
      deviceId,
      deviceName: deviceName || existing?.deviceName || deviceId,
      state,
      error,
      connectedAt: state === BLEConnectionState.CONNECTED ? now : existing?.connectedAt,
      lastActivity: now,
    };
 
    this.connectionStates.set(deviceId, connection);
    this.emitEvent(deviceId, 'state_changed', { state, error });
  }
 
  /**
   * Emit event to all registered listeners
   */
  private emitEvent(deviceId: string, event: BLEConnectionEvent, data?: any): void {
    this.eventListeners.forEach((listener) => {
      try {
        listener(deviceId, event, data);
      } catch {
        // Listener error should not crash the app
      }
    });
  }
 
  /**
   * Get current connection state for a device
   */
  getConnectionState(deviceId: string): BLEConnectionState {
    const connection = this.connectionStates.get(deviceId);
    return connection?.state || BLEConnectionState.DISCONNECTED;
  }
 
  /**
   * Get all active connections
   */
  getAllConnections(): Map<string, BLEDeviceConnection> {
    return new Map(this.connectionStates);
  }
 
  /**
   * Add event listener
   */
  addEventListener(listener: BLEEventListener): void {
    if (!this.eventListeners.includes(listener)) {
      this.eventListeners.push(listener);
    }
  }
 
  /**
   * Remove event listener
   */
  removeEventListener(listener: BLEEventListener): void {
    const index = this.eventListeners.indexOf(listener);
    if (index > -1) {
      this.eventListeners.splice(index, 1);
    }
  }
 
  async scanDevices(): Promise<WPDevice[]> {
    await delay(2000); // Simulate scan delay
    return this.mockDevices;
  }
 
  stopScan(): void {
  }
 
  async connectDevice(deviceId: string): Promise<boolean> {
    try {
      // Check if connection is already in progress
      if (this.connectingDevices.has(deviceId)) {
        throw new Error('Connection already in progress for this device');
      }
 
      // Check if already connected
      if (this.connectedDevices.has(deviceId)) {
        this.updateConnectionState(deviceId, BLEConnectionState.READY);
        this.emitEvent(deviceId, 'ready');
        return true;
      }
 
      // Mark device as connecting
      this.connectingDevices.add(deviceId);
 
      this.updateConnectionState(deviceId, BLEConnectionState.CONNECTING);
      await delay(500);
 
      this.updateConnectionState(deviceId, BLEConnectionState.CONNECTED);
      await delay(300);
 
      this.updateConnectionState(deviceId, BLEConnectionState.DISCOVERING);
      await delay(200);
 
      this.connectedDevices.add(deviceId);
      this.updateConnectionState(deviceId, BLEConnectionState.READY);
      this.emitEvent(deviceId, 'ready');
 
      return true;
    } catch (error: any) {
      const errorMessage = error?.message || 'Connection failed';
      this.updateConnectionState(deviceId, BLEConnectionState.ERROR, undefined, errorMessage);
      this.emitEvent(deviceId, 'connection_failed', { error: errorMessage });
      return false;
    } finally {
      // Always remove from connecting set when done (success or failure)
      this.connectingDevices.delete(deviceId);
    }
  }
 
  async disconnectDevice(deviceId: string): Promise<void> {
    this.updateConnectionState(deviceId, BLEConnectionState.DISCONNECTING);
    await delay(500);
    this.connectedDevices.delete(deviceId);
    this.updateConnectionState(deviceId, BLEConnectionState.DISCONNECTED);
    this.emitEvent(deviceId, 'disconnected');
  }
 
  isDeviceConnected(deviceId: string): boolean {
    return this.connectedDevices.has(deviceId);
  }
 
  async sendCommand(deviceId: string, command: string): Promise<string> {
    await delay(500);
 
    // Simulate responses
    if (command === 'pin|7856') {
      return 'pin|ok';
    }
    if (command === 'w') {
      return 'mac,142b2f81a14c|w|3|FrontierTower,-55|HomeNetwork,-67|TP-Link_5G,-75';
    }
    if (command === 'a') {
      return 'mac,142b2f81a14c|a|FrontierTower,-67';
    }
    if (command.startsWith('W|')) {
      return 'mac,142b2f81a14c|W|ok';
    }
 
    return 'ok';
  }
 
  async getWiFiList(deviceId: string): Promise<WiFiNetwork[]> {
    await delay(1500);
 
    return [
      { ssid: 'FrontierTower', rssi: -55 },
      { ssid: 'HomeNetwork', rssi: -67 },
      { ssid: 'TP-Link_5G', rssi: -75 },
      { ssid: 'Office-WiFi', rssi: -80 },
    ];
  }
 
  async setWiFi(
    deviceId: string,
    ssid: string,
    password: string
  ): Promise<boolean> {
    await delay(2000);
    return true;
  }
 
  async getCurrentWiFi(deviceId: string): Promise<WiFiStatus | null> {
    await delay(1000);
 
    return {
      ssid: 'FrontierTower',
      rssi: -67,
      connected: true,
    };
  }
 
  async rebootDevice(deviceId: string): Promise<void> {
    await delay(500);
    this.connectedDevices.delete(deviceId);
  }
 
  /**
   * Get sensor health metrics (mock implementation)
   */
  async getSensorHealth(wellId: number, mac: string): Promise<SensorHealthMetrics | null> {
    await delay(1000);
 
    const deviceKey = `WP_${wellId}_${mac.slice(-6).toLowerCase()}`;
 
    // Generate mock health metrics
    const now = Date.now();
    const mockMetrics: SensorHealthMetrics = {
      deviceId: `mock-${wellId}`,
      deviceName: deviceKey,
      overallHealth: SensorHealthStatus.GOOD,
      connectionStatus: 'online',
      lastSeen: new Date(),
      lastSeenMinutesAgo: 2,
      wifiSignalQuality: WiFiSignalQuality.GOOD,
      wifiRssi: -60,
      wifiSsid: 'FrontierTower',
      wifiConnected: true,
      communication: {
        successfulCommands: 45,
        failedCommands: 2,
        averageResponseTime: 350,
        lastSuccessfulCommand: now - 120000, // 2 minutes ago
        lastFailedCommand: now - 3600000, // 1 hour ago
      },
      bleRssi: -55,
      bleConnectionAttempts: 10,
      bleConnectionFailures: 1,
      lastHealthCheck: now,
      lastBleConnection: now - 120000,
    };
 
    this.sensorHealthMetrics.set(deviceKey, mockMetrics);
    return mockMetrics;
  }
 
  /**
   * Get all cached sensor health metrics (mock)
   */
  getAllSensorHealth(): Map<string, SensorHealthMetrics> {
    return new Map(this.sensorHealthMetrics);
  }
 
  /**
   * Cleanup all BLE connections and state
   * Should be called on app logout to properly release resources
   */
  async cleanup(): Promise<void> {
 
    // Disconnect all connected devices
    const deviceIds = Array.from(this.connectedDevices);
    for (const deviceId of deviceIds) {
      await this.disconnectDevice(deviceId);
    }
 
    this.connectedDevices.clear();
    this.connectionStates.clear();
    this.connectingDevices.clear();
 
    // Clear health monitoring data
    this.sensorHealthMetrics.clear();
    this.communicationStats.clear();
 
    this.eventListeners = [];
  }
 
  /**
   * Bulk disconnect multiple devices (mock)
   */
  async bulkDisconnect(deviceIds: string[]): Promise<BulkOperationResult[]> {
    const results: BulkOperationResult[] = [];
 
    for (const deviceId of deviceIds) {
      await delay(100); // Simulate disconnect time
 
      const mockDevice = this.mockDevices.find(d => d.id === deviceId);
      const deviceName = mockDevice?.name || deviceId;
 
      try {
        await this.disconnectDevice(deviceId);
        results.push({
          deviceId,
          deviceName,
          success: true,
        });
      } catch (error: any) {
        results.push({
          deviceId,
          deviceName,
          success: false,
          error: error?.message || 'Disconnect failed',
        });
      }
    }
 
    return results;
  }
 
  /**
   * Bulk reboot multiple devices (mock)
   */
  async bulkReboot(deviceIds: string[]): Promise<BulkOperationResult[]> {
    const results: BulkOperationResult[] = [];
 
    for (const deviceId of deviceIds) {
      await delay(500); // Simulate reboot time
 
      const mockDevice = this.mockDevices.find(d => d.id === deviceId);
      const deviceName = mockDevice?.name || deviceId;
 
      try {
        // Mock reboot success
        await this.rebootDevice(deviceId);
        results.push({
          deviceId,
          deviceName,
          success: true,
        });
      } catch (error: any) {
        results.push({
          deviceId,
          deviceName,
          success: false,
          error: error?.message || 'Reboot failed',
        });
      }
    }
 
    return results;
  }
 
  /**
   * Bulk WiFi configuration for multiple devices (mock)
   */
  async bulkSetWiFi(
    devices: Array<{ id: string; name: string }>,
    ssid: string,
    password: string,
    onProgress?: (deviceId: string, status: 'connecting' | 'configuring' | 'rebooting' | 'success' | 'error', error?: string) => void
  ): Promise<BulkWiFiResult[]> {
    const results: BulkWiFiResult[] = [];
 
    for (const device of devices) {
      const { id: deviceId, name: deviceName } = device;
 
      try {
        // Step 1: Connect (mock)
        onProgress?.(deviceId, 'connecting');
        await delay(800);
        await this.connectDevice(deviceId);
 
        // Step 2: Set WiFi (mock)
        onProgress?.(deviceId, 'configuring');
        await delay(1200);
        await this.setWiFi(deviceId, ssid, password);
 
        // Step 3: Reboot (mock)
        onProgress?.(deviceId, 'rebooting');
        await delay(600);
        await this.rebootDevice(deviceId);
 
        // Success
        onProgress?.(deviceId, 'success');
        results.push({
          deviceId,
          deviceName,
          success: true,
        });
      } catch (error: any) {
        const errorMessage = error?.message || 'WiFi configuration failed';
        onProgress?.(deviceId, 'error', errorMessage);
        results.push({
          deviceId,
          deviceName,
          success: false,
          error: errorMessage,
        });
      }
    }
 
    return results;
  }
}