WellNuo/contexts/BLEContext.tsx
Sergei 2b2bd88726 Add BLE cleanup on user logout
Implement comprehensive BLE cleanup functionality that properly
disconnects all devices and releases resources when user logs out.

Changes:
- Add cleanup() method to BLEManager and MockBLEManager
- Update IBLEManager interface to include cleanup
- Add cleanupBLE() to BLEContext to disconnect all devices
- Implement callback mechanism in api.ts for BLE cleanup on logout
- Wire up BLE cleanup in app layout to trigger on logout
- Add unit tests for BLE cleanup functionality

This ensures no BLE connections remain active after logout,
preventing resource leaks and potential connection issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-29 10:57:43 -08:00

201 lines
5.9 KiB
TypeScript

// BLE Context - Global state for Bluetooth management
import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';
import { bleManager, WPDevice, WiFiNetwork, WiFiStatus, isBLEAvailable } from '@/services/ble';
interface BLEContextType {
// State
foundDevices: WPDevice[];
isScanning: boolean;
connectedDevices: Set<string>;
isBLEAvailable: boolean;
error: string | null;
// 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;
}
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 scanDevices = useCallback(async () => {
try {
setError(null);
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) {
setError(err.message || 'Failed to scan for devices');
throw err;
} finally {
setIsScanning(false);
}
}, []);
const stopScan = useCallback(() => {
bleManager.stopScan();
setIsScanning(false);
}, []);
const connectDevice = useCallback(async (deviceId: string): Promise<boolean> => {
console.log('[BLEContext] connectDevice called:', deviceId);
try {
setError(null);
const success = await bleManager.connectDevice(deviceId);
console.log('[BLEContext] connectDevice result:', success);
if (success) {
setConnectedDevices(prev => new Set(prev).add(deviceId));
} else {
// Connection failed but no exception - set user-friendly error
setError('Could not connect to sensor. Please move closer and try again.');
}
return success;
} catch (err: any) {
console.error('[BLEContext] connectDevice exception:', err);
setError(err.message || 'Failed to connect to device');
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[]> => {
console.log('[BLEContext] getWiFiList called:', deviceId);
try {
setError(null);
const networks = await bleManager.getWiFiList(deviceId);
console.log('[BLEContext] getWiFiList success, found networks:', networks.length);
return networks;
} catch (err: any) {
console.error('[BLEContext] getWiFiList failed:', err);
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);
}, []);
const cleanupBLE = useCallback(async () => {
try {
console.log('[BLEContext] Cleanup called - cleaning up all BLE connections');
// 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);
console.log('[BLEContext] Cleanup complete');
} catch (err: any) {
console.error('[BLEContext] Cleanup error:', err);
// Don't throw - we want to allow logout to proceed even if BLE cleanup fails
}
}, [isScanning, stopScan]);
const value: BLEContextType = {
foundDevices,
isScanning,
connectedDevices,
isBLEAvailable,
error,
scanDevices,
stopScan,
connectDevice,
disconnectDevice,
getWiFiList,
setWiFi,
getCurrentWiFi,
rebootDevice,
cleanupBLE,
clearError,
};
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;
}