Skip to content

一个强大的 Flutter 插件,用于检测和管理 PC 平台(macOS 和 Windows)的 Bluetooth 和 WiFi 硬件状态。

License

Notifications You must be signed in to change notification settings

lizy-coding/pc_connect

Repository files navigation

PC Connect

pub package Platform License: MIT

一个强大的 Flutter 插件,用于检测和管理 PC 平台(macOS 和 Windows)的 Bluetooth 和 WiFi 硬件状态。

✨ 特性

  • 🔍 硬件检测: 准确检测 Bluetooth 和 WiFi 硬件是否可用
  • 📱 状态监控: 实时监听蓝牙和网络连接状态变化
  • 🔄 智能回退: 多层检测机制,确保检测结果的可靠性
  • 🖥️ 跨平台: 支持 macOS 和 Windows 平台
  • 原生性能: 使用平台原生 API 获得最佳性能
  • 🛡️ 稳定可靠: 完善的错误处理和异常恢复机制

🏗️ 架构设计

graph TB
    A[Flutter App] --> B[PcConnect API]
    B --> C[Platform Interface]
    C --> D[Method Channel]
    D --> E{Platform Check}
    
    E -->|macOS| F[macOS Native]
    E -->|Windows| G[Windows Native]
    
    F --> F1[IOBluetooth Framework]
    F --> F2[SystemConfiguration Framework]
    
    G --> G1[Windows Bluetooth API]
    G --> G2[Windows WiFi API]
    
    B --> H[Third-party Packages]
    H --> H1[universal_ble]
    H --> H2[connectivity_plus]
    H --> H3[network_info_plus]
    
    subgraph "错误处理机制"
        I[Third-party Failed] --> J[Fallback to Native]
        J --> K[Return Reliable Result]
    end
    
    style A fill:#e1f5fe
    style F fill:#f3e5f5
    style G fill:#e8f5e8
    style H fill:#fff3e0
Loading

🔄 运行逻辑流程

sequenceDiagram
    participant App as Flutter App
    participant API as PcConnect
    participant UBle as Universal BLE
    participant Native as Native Platform
    participant Hardware as Hardware

    App->>API: getBluetoothStatus()
    
    Note over API: 第一层检测
    API->>UBle: getBluetoothAvailabilityState()
    
    alt Universal BLE 成功
        UBle->>Hardware: 检测蓝牙硬件
        Hardware-->>UBle: 返回状态
        UBle-->>API: 返回可用性状态
    else Universal BLE 失败
        Note over API: 回退机制启动
        API->>Native: isBluetoothHardwareAvailable()
        Native->>Hardware: 原生API检测
        Hardware-->>Native: 返回硬件状态
        Native-->>API: 返回检测结果
    end
    
    API-->>App: 返回 BluetoothStatus
    
    Note over App: 状态监听
    API->>App: bluetoothStateStream
    API->>App: connectivityStream
Loading

📁 项目结构

pc_connect/
├── lib/
│   ├── pc_connect.dart                    # 主要API接口
│   ├── pc_connect_platform_interface.dart # 平台接口定义
│   └── pc_connect_method_channel.dart     # 方法通道实现
├── macos/
│   └── Classes/
│       └── PcConnectPlugin.swift          # macOS原生实现
├── windows/
│   ├── pc_connect_plugin.cpp              # Windows原生实现
│   ├── pc_connect_plugin.h                # Windows头文件
│   └── pc_connect_plugin_c_api.cpp        # C API包装
└── example/
    ├── lib/main.dart                      # 示例应用
    ├── macos/                             # macOS示例配置
    └── windows/                           # Windows示例配置

🚀 快速开始

安装

pubspec.yaml 中添加依赖:

dependencies:
  pc_connect: ^0.0.1

运行安装命令:

flutter pub get

基础使用

import 'package:pc_connect/pc_connect.dart';

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _pcConnect = PcConnect();
  BluetoothStatus? _bluetoothStatus;
  WiFiStatus? _wifiStatus;

  @override
  void initState() {
    super.initState();
    _checkHardwareStatus();
    _listenToChanges();
  }

  // 检测硬件状态
  Future<void> _checkHardwareStatus() async {
    final bluetoothStatus = await _pcConnect.getBluetoothStatus();
    final wifiStatus = await _pcConnect.getWiFiStatus();

    setState(() {
      _bluetoothStatus = bluetoothStatus;
      _wifiStatus = wifiStatus;
    });
  }

  // 监听状态变化
  void _listenToChanges() {
    // 监听蓝牙状态变化
    _pcConnect.bluetoothStateStream.listen((state) {
      _checkHardwareStatus();
    });

    // 监听网络连接变化
    _pcConnect.connectivityStream.listen((results) {
      _checkHardwareStatus();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 蓝牙状态显示
          ListTile(
            leading: Icon(
              Icons.bluetooth,
              color: _bluetoothStatus?.isAvailable == true 
                  ? Colors.blue 
                  : Colors.grey,
            ),
            title: Text('蓝牙状态'),
            subtitle: Text(_getBluetoothStatusText()),
            trailing: _bluetoothStatus?.isSupported == true
                ? IconButton(
                    icon: Icon(Icons.power_settings_new),
                    onPressed: () async {
                      if (_bluetoothStatus?.isAvailable != true) {
                        await _pcConnect.enableBluetooth();
                        _checkHardwareStatus();
                      }
                    },
                  )
                : null,
          ),
          // WiFi状态显示
          ListTile(
            leading: Icon(
              Icons.wifi,
              color: _wifiStatus?.isConnected == true 
                  ? Colors.green 
                  : Colors.grey,
            ),
            title: Text('WiFi状态'),
            subtitle: Text(_getWiFiStatusText()),
          ),
        ],
      ),
    );
  }

  String _getBluetoothStatusText() {
    if (_bluetoothStatus == null) return '检测中...';
    if (!_bluetoothStatus!.isSupported) return '不支持蓝牙硬件';
    if (_bluetoothStatus!.isAvailable) return '蓝牙已开启';
    return '蓝牙硬件可用但未开启';
  }

  String _getWiFiStatusText() {
    if (_wifiStatus == null) return '检测中...';
    if (!_wifiStatus!.isSupported) return '不支持WiFi硬件';
    if (_wifiStatus!.isConnected) {
      return '已连接: ${_wifiStatus!.currentSSID ?? '未知网络'}';
    }
    return 'WiFi硬件可用但未连接';
  }
}

📚 API 文档

主要方法

getBluetoothStatus()

获取蓝牙硬件状态。

Future<BluetoothStatus> getBluetoothStatus()

返回值: BluetoothStatus

  • isSupported: 是否支持蓝牙硬件
  • isAvailable: 蓝牙是否已开启
  • state: 详细的蓝牙状态 (AvailabilityState)
  • error: 错误信息(如果有)

getWiFiStatus()

获取WiFi硬件状态。

Future<WiFiStatus> getWiFiStatus()

返回值: WiFiStatus

  • isSupported: 是否支持WiFi硬件
  • isConnected: 是否已连接WiFi
  • currentSSID: 当前连接的网络名称
  • currentIP: 当前IP地址
  • error: 错误信息(如果有)

enableBluetooth()

尝试启用蓝牙。

Future<bool> enableBluetooth()

返回值: bool - 是否成功启用

状态监听

bluetoothStateStream

监听蓝牙状态变化的流。

Stream<AvailabilityState> get bluetoothStateStream

connectivityStream

监听网络连接状态变化的流。

Stream<List<ConnectivityResult>> get connectivityStream

🖥️ 平台特定配置

macOS

确保在 macos/Runner/Info.plist 中添加必要的权限:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>此应用需要访问蓝牙以检测硬件状态</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>此应用需要访问蓝牙以检测硬件状态</string>

Windows

  • 最低支持 Windows 7
  • 需要 Visual Studio 2019 或更高版本进行编译
  • 确保系统已安装蓝牙驱动

🔧 技术实现

检测机制

  1. 第一层检测: 使用 universal_ble 包进行标准检测
  2. 回退机制: 当第一层检测失败时,使用平台原生API
  3. 错误处理: 完善的异常捕获和错误恢复

原生实现

macOS

  • 使用 IOBluetooth 框架检测蓝牙硬件
  • 使用 SystemConfiguration 框架检测WiFi硬件

Windows

  • 使用 Windows Bluetooth API
  • 使用 Windows WiFi API

🐛 故障排除

常见问题

  1. macOS 上蓝牙检测失败

    • 确保已添加必要的权限声明
    • 检查 universal_ble 依赖是否正确安装
  2. Windows 编译错误

    • 确保使用兼容的 Visual Studio 版本
    • 检查 Windows SDK 是否正确安装
  3. 权限被拒绝

    • 在系统设置中手动授予应用蓝牙权限
    • 重新启动应用

📈 版本历史

v0.0.1

  • 初始版本发布
  • 支持 macOS 和 Windows 平台
  • 基础的蓝牙和WiFi检测功能
  • 实现智能回退机制

🤝 贡献

欢迎提交 Issue 和 Pull Request!

  1. Fork 这个项目
  2. 创建你的特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交你的修改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 创建一个 Pull Request

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

📞 支持

如果你在使用过程中遇到问题,请:

  1. 查看 常见问题 部分
  2. 搜索现有的 Issues
  3. 创建新的 Issue 并详细描述问题

⭐ 如果这个项目对你有帮助,请给它一个星标!

About

一个强大的 Flutter 插件,用于检测和管理 PC 平台(macOS 和 Windows)的 Bluetooth 和 WiFi 硬件状态。

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published