All files / contexts BLEContext.tsx

0% Statements 0/171
0% Branches 0/32
0% Functions 0/37
0% Lines 0/158

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
// BLE Context - Global state for Bluetooth management
 
import React, { createContext, useContext, useState, useCallback, useEffect, ReactNode } from 'react';
import { bleManager, WPDevice, WiFiNetwork, WiFiStatus, isBLEAvailable, checkBLEReadiness, BulkOperationResult, BulkWiFiResult } from '@/services/ble';
import { setOnLogoutBLECleanupCallback } from '@/services/api';
import { BleManager } from 'react-native-ble-plx';
 
interface BLEContextType {
  // State
  foundDevices: WPDevice[];
  isScanning: boolean;
  connectedDevices: Set<string>;
  isBLEAvailable: boolean;
  error: string | null;
  permissionError: boolean; // true if error is related to permissions
 
  // Actions
  scanDevices: () => Promise<void>;
  stopScan: () => void;
  connectDevice: (deviceId: string) => Promise<boolean>;
  disconnectDevice: (deviceId: string) => Promise<void>;
  getWiFiList: (deviceId: string) => Promise<WiFiNetwork[]>;
  setWiFi: (deviceId: string, ssid: string, password: string) => Promise<boolean>;
  getCurrentWiFi: (deviceId: string) => Promise<WiFiStatus | null>;
  rebootDevice: (deviceId: string) => Promise<void>;
  cleanupBLE: () => Promise<void>;
  clearError: () => void;
  checkPermissions: () => Promise<boolean>; // Manual permission check with UI prompts
 
  // Bulk operations
  bulkDisconnect: (deviceIds: string[]) => Promise<BulkOperationResult[]>;
  bulkReboot: (deviceIds: string[]) => Promise<BulkOperationResult[]>;
  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 BLEContext = createContext<BLEContextType | undefined>(undefined);
 
export function BLEProvider({ children }: { children: ReactNode }) {
  const [foundDevices, setFoundDevices] = useState<WPDevice[]>([]);
  const [isScanning, setIsScanning] = useState(false);
  const [connectedDevices, setConnectedDevices] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [permissionError, setPermissionError] = useState(false);
 
  // Lazy BleManager instance for permission checks
  const [bleManagerInstance] = useState(() => new BleManager());
 
  const isPermissionError = (errorMessage: string): boolean => {
    const permissionKeywords = [
      'permission',
      'unauthorized',
      'not granted',
      'denied',
      'bluetooth is disabled',
      'enable it in settings',
    ];
    const lowerMessage = errorMessage.toLowerCase();
    return permissionKeywords.some(keyword => lowerMessage.includes(keyword));
  };
 
  const checkPermissions = useCallback(async (): Promise<boolean> => {
    try {
      setError(null);
      setPermissionError(false);
      const ready = await checkBLEReadiness(bleManagerInstance);
      return ready;
    } catch {
      const errorMsg = 'Failed to check Bluetooth permissions';
      setError(errorMsg);
      setPermissionError(true);
      return false;
    }
  }, [bleManagerInstance]);
 
  const scanDevices = useCallback(async () => {
    try {
      setError(null);
      setPermissionError(false);
      setIsScanning(true);
      const devices = await bleManager.scanDevices();
      // Sort by RSSI (strongest first)
      const sorted = devices.sort((a, b) => b.rssi - a.rssi);
      setFoundDevices(sorted);
    } catch (err: any) {
      const errorMsg = err.message || 'Failed to scan for devices';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    } finally {
      setIsScanning(false);
    }
  }, []);
 
  const stopScan = useCallback(() => {
    bleManager.stopScan();
    setIsScanning(false);
  }, []);
 
  const connectDevice = useCallback(async (deviceId: string): Promise<boolean> => {
    try {
      setError(null);
      setPermissionError(false);
      const success = await bleManager.connectDevice(deviceId);
      if (success) {
        setConnectedDevices(prev => new Set(prev).add(deviceId));
      } else {
        // Connection failed but no exception - set user-friendly error
        const errorMsg = 'Could not connect to sensor. Please move closer and try again.';
        setError(errorMsg);
        setPermissionError(false);
      }
      return success;
    } catch (err: any) {
      const errorMsg = err.message || 'Failed to connect to device';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      return false;
    }
  }, []);
 
  const disconnectDevice = useCallback(async (deviceId: string): Promise<void> => {
    try {
      await bleManager.disconnectDevice(deviceId);
      setConnectedDevices(prev => {
        const next = new Set(prev);
        next.delete(deviceId);
        return next;
      });
    } catch (err: any) {
      setError(err.message || 'Failed to disconnect device');
    }
  }, []);
 
  const getWiFiList = useCallback(async (deviceId: string): Promise<WiFiNetwork[]> => {
    try {
      setError(null);
      const networks = await bleManager.getWiFiList(deviceId);
      return networks;
    } catch (err: any) {
      setError(err.message || 'Failed to get WiFi networks');
      throw err;
    }
  }, []);
 
  const setWiFi = useCallback(
    async (deviceId: string, ssid: string, password: string): Promise<boolean> => {
      try {
        setError(null);
        return await bleManager.setWiFi(deviceId, ssid, password);
      } catch (err: any) {
        setError(err.message || 'Failed to configure WiFi');
        throw err;
      }
    },
    []
  );
 
  const getCurrentWiFi = useCallback(
    async (deviceId: string): Promise<WiFiStatus | null> => {
      try {
        setError(null);
        return await bleManager.getCurrentWiFi(deviceId);
      } catch (err: any) {
        setError(err.message || 'Failed to get current WiFi');
        throw err;
      }
    },
    []
  );
 
  const rebootDevice = useCallback(async (deviceId: string): Promise<void> => {
    try {
      setError(null);
      await bleManager.rebootDevice(deviceId);
      // Remove from connected devices
      setConnectedDevices(prev => {
        const next = new Set(prev);
        next.delete(deviceId);
        return next;
      });
    } catch (err: any) {
      setError(err.message || 'Failed to reboot device');
      throw err;
    }
  }, []);
 
  const clearError = useCallback(() => {
    setError(null);
    setPermissionError(false);
  }, []);
 
  const cleanupBLE = useCallback(async () => {
    try {
 
      // Stop any ongoing scan
      if (isScanning) {
        stopScan();
      }
 
      // Cleanup via bleManager (disconnects all devices)
      await bleManager.cleanup();
 
      // Clear context state
      setFoundDevices([]);
      setConnectedDevices(new Set());
      setError(null);
 
    } catch {
      // Don't throw - we want to allow logout to proceed even if BLE cleanup fails
    }
  }, [isScanning, stopScan]);
 
  // Bulk operations
  const bulkDisconnect = useCallback(async (deviceIds: string[]): Promise<BulkOperationResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkDisconnect(deviceIds);
      // Update connected devices set
      const successfulDisconnects = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulDisconnects.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulDisconnects.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk disconnect failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);
 
  const bulkReboot = useCallback(async (deviceIds: string[]): Promise<BulkOperationResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkReboot(deviceIds);
      // Devices that were rebooted are no longer connected
      const successfulReboots = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulReboots.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulReboots.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk reboot failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);
 
  const bulkSetWiFi = useCallback(async (
    devices: Array<{ id: string; name: string }>,
    ssid: string,
    password: string,
    onProgress?: (deviceId: string, status: 'connecting' | 'configuring' | 'rebooting' | 'success' | 'error', error?: string) => void
  ): Promise<BulkWiFiResult[]> => {
    try {
      setError(null);
      setPermissionError(false);
      const results = await bleManager.bulkSetWiFi(devices, ssid, password, onProgress);
      // Update connected devices - successful setups result in reboots (disconnected)
      const successfulSetups = results.filter(r => r.success).map(r => r.deviceId);
      if (successfulSetups.length > 0) {
        setConnectedDevices(prev => {
          const next = new Set(prev);
          successfulSetups.forEach(id => next.delete(id));
          return next;
        });
      }
      return results;
    } catch (err: any) {
      const errorMsg = err.message || 'Bulk WiFi configuration failed';
      setError(errorMsg);
      setPermissionError(isPermissionError(errorMsg));
      throw err;
    }
  }, []);
 
  // Register BLE cleanup callback for logout
  useEffect(() => {
    setOnLogoutBLECleanupCallback(cleanupBLE);
 
    return () => {
      setOnLogoutBLECleanupCallback(null);
    };
  }, [cleanupBLE]);
 
  const value: BLEContextType = {
    foundDevices,
    isScanning,
    connectedDevices,
    isBLEAvailable,
    error,
    permissionError,
    scanDevices,
    stopScan,
    connectDevice,
    disconnectDevice,
    getWiFiList,
    setWiFi,
    getCurrentWiFi,
    rebootDevice,
    cleanupBLE,
    clearError,
    checkPermissions,
    bulkDisconnect,
    bulkReboot,
    bulkSetWiFi,
  };
 
  return <BLEContext.Provider value={value}>{children}</BLEContext.Provider>;
}
 
export function useBLE() {
  const context = useContext(BLEContext);
  if (context === undefined) {
    throw new Error('useBLE must be used within a BLEProvider');
  }
  return context;
}