import 'dart:async'; /// USB 检测服务 /// 监听 U盘插入/拔出事件 class UsbDetectionService { static final UsbDetectionService instance = UsbDetectionService._internal(); UsbDetectionService._internal(); /// USB 状态 bool _isUsbConnected = false; String? _usbPath; /// 状态流 final StreamController _stateController = StreamController.broadcast(); /// 监听 USB 状态变化 Stream get stateStream => _stateController.stream; /// 当前 USB 是否连接 bool get isConnected => _isUsbConnected; /// USB 路径 String? get usbPath => _usbPath; /// 开始监听 USB 事件 void startMonitoring() { // TODO: 实现平台特定的 USB 监听 // Android: 使用 BroadcastReceiver 监听 ACTION_MEDIA_MOUNTED // Linux: 监听 /dev/disk/by-path/ 或使用 udev // Windows: 监听 WM_DEVICECHANGE // 模拟实现:定时检测 _startPolling(); } /// 停止监听 void stopMonitoring() { // _stopPolling(); } /// 模拟轮询检测(待平台实现) void _startPolling() { // TODO: 根据平台实现真实的 USB 检测 // 定时检测 /mnt/usb 或 /media/*/ 目录 } /// 手动检测 USB Future detectUsb() async { // TODO: 实现平台特定的 USB 检测 // Android: 检查 getExternalFilesDir 或 mount points // Linux: 检查 /mnt, /media 目录 // Windows: 检查 D:, E: 等驱动器 // 返回检测结果 return _isUsbConnected; } /// 获取 USB 上的程序文件列表 Future> listProgramFiles() async { if (!_isUsbConnected || _usbPath == null) { return []; } // TODO: 扫描 USB 目录中的 .json 程序文件 // 示例路径: $_usbPath/programs/*.json return []; } /// 模拟 USB 连接(用于测试) void simulateConnection(String path) { _isUsbConnected = true; _usbPath = path; _stateController.add(UsbState.connected(path)); } /// 模拟 USB 断开(用于测试) void simulateDisconnection() { _isUsbConnected = false; _usbPath = null; _stateController.add(UsbState.disconnected()); } /// 释放资源 void dispose() { stopMonitoring(); _stateController.close(); } } /// USB 状态 class UsbState { final bool isConnected; final String? path; const UsbState.connected(String path) : isConnected = true, path = path; const UsbState.disconnected() : isConnected = false, path = null; }