Windows 蓝牙设备管理源码

一、系统架构设计

┌─────────────────────────────────────────────────────────────┐
│                    Windows 蓝牙管理系统                    │
├─────────────────────────────────────────────────────────────┤
│  本地蓝牙管理  │  远程设备扫描  │  设备连接管理  │  服务管理  │
│                │                │                │          │
│  • 枚举本地    │  • 发现设备     │  • 配对连接    │  • 服务枚举 │
│    蓝牙适配器 │  • 获取设备信息  │  • 断开连接    │  • 服务绑定 │
│  • 获取适配器  │  • 过滤设备     │  • 连接状态    │  • 数据传输 │
│    信息       │  • 实时扫描     │    监控        │             │
└─────────────────────────────────────────────────────────────┘

二、源代码实现

2.1 头文件与库依赖 (BluetoothManager.h)

#pragma once

#include <windows.h>
#include <winsock2.h>
#include <ws2bth.h>
#include <bluetoothapis.h>
#include <vector>
#include <string>
#include <memory>
#include <functional>
#include <atomic>

#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Bthprops.lib")

// 蓝牙设备信息结构体
struct BluetoothDeviceInfo {
    BLUETOOTH_ADDRESS address;
    std::wstring name;
    std::wstring deviceClass;
    DWORD classOfDevice;
    BOOL authenticated;
    BOOL connected;
    BOOL remembered;
    SYSTEMTIME lastSeen;
    std::vector<GUID> services;
};

// 蓝牙适配器信息结构体
struct BluetoothAdapterInfo {
    HANDLE hRadio;
    BLUETOOTH_RADIO_INFO radioInfo;
    BLUETOOTH_DEVICE_INFO deviceInfo;
    BOOL isDefault;
};

// 连接状态枚举
enum class ConnectionState {
    Disconnected,
    Connecting,
    Connected,
    Pairing,
    Failed
};

// 蓝牙管理器类
class BluetoothManager {
public:
    BluetoothManager();
    ~BluetoothManager();

    // 本地蓝牙管理
    BOOL EnumerateLocalAdapters(std::vector<BluetoothAdapterInfo>& adapters);
    BOOL GetAdapterInfo(HANDLE hRadio, BLUETOOTH_RADIO_INFO& info);
    BOOL IsBluetoothEnabled();
    BOOL EnableBluetooth(BOOL enable);

    // 远程设备扫描
    BOOL StartDeviceDiscovery(std::function<void(const BluetoothDeviceInfo&)> callback);
    BOOL StopDeviceDiscovery();
    BOOL EnumerateRemoteDevices(std::vector<BluetoothDeviceInfo>& devices);
    BOOL RefreshDeviceList();

    // 设备连接管理
    BOOL ConnectToDevice(const BLUETOOTH_ADDRESS& address, const GUID& serviceGuid);
    BOOL DisconnectFromDevice(const BLUETOOTH_ADDRESS& address);
    BOOL PairDevice(const BLUETOOTH_ADDRESS& address);
    BOOL UnpairDevice(const BLUETOOTH_ADDRESS& address);
    ConnectionState GetConnectionState(const BLUETOOTH_ADDRESS& address);

    // 服务管理
    BOOL EnumerateServices(const BLUETOOTH_ADDRESS& address, std::vector<GUID>& services);
    BOOL RegisterService(const GUID& serviceGuid, LPCWSTR serviceName);
    BOOL UnregisterService(const GUID& serviceGuid);

    // 设备信息查询
    BOOL GetDeviceInfo(const BLUETOOTH_ADDRESS& address, BLUETOOTH_DEVICE_INFO& info);
    std::wstring GetDeviceName(const BLUETOOTH_ADDRESS& address);
    BOOL IsDeviceConnected(const BLUETOOTH_ADDRESS& address);
    BOOL IsDeviceAuthenticated(const BLUETOOTH_ADDRESS& address);

private:
    // Winsock 初始化
    BOOL InitializeWinsock();
    void CleanupWinsock();

    // 蓝牙API辅助函数
    static std::wstring ClassOfDeviceToString(DWORD cod);
    static std::wstring AddressToString(const BLUETOOTH_ADDRESS& address);
    static BOOL StringToAddress(const std::wstring& str, BLUETOOTH_ADDRESS& address);

private:
    WSADATA m_wsaData;
    BOOL m_wsaInitialized;
    std::vector<BluetoothAdapterInfo> m_adapters;
    std::vector<BluetoothDeviceInfo> m_devices;
    std::atomic<BOOL> m_discoveryActive;
    HBLUETOOTH_DEVICE_FIND m_deviceFindHandle;
};

2.2 核心实现代码 (BluetoothManager.cpp)

#include "BluetoothManager.h"
#include <sstream>
#include <iomanip>

// 常见蓝牙服务UUID
namespace BluetoothServices {
    const GUID SerialPort = {0x00001101, 0x0000, 0x1000, {0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}};
    const GUID GenericAccess = {0x00001800, 0x0000, 0x1000, {0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}};
    const GUID DeviceInformation = {0x0000180A, 0x0000, 0x1000, {0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}};
    const GUID BatteryService = {0x0000180F, 0x0000, 0x1000, {0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}};
}

// 构造函数
BluetoothManager::BluetoothManager() 
    : m_wsaInitialized(FALSE), m_discoveryActive(FALSE), m_deviceFindHandle(nullptr) {
    InitializeWinsock();
}

// 析构函数
BluetoothManager::~BluetoothManager() {
    if (m_discoveryActive) {
        StopDeviceDiscovery();
    }
    CleanupWinsock();
}

// 初始化Winsock
BOOL BluetoothManager::InitializeWinsock() {
    if (m_wsaInitialized) return TRUE;
    
    int result = WSAStartup(MAKEWORD(2, 2), &m_wsaData);
    if (result != 0) {
        return FALSE;
    }
    
    m_wsaInitialized = TRUE;
    return TRUE;
}

// 清理Winsock
void BluetoothManager::CleanupWinsock() {
    if (m_wsaInitialized) {
        WSACleanup();
        m_wsaInitialized = FALSE;
    }
}

// 枚举本地蓝牙适配器
BOOL BluetoothManager::EnumerateLocalAdapters(std::vector<BluetoothAdapterInfo>& adapters) {
    adapters.clear();
    
    BLUETOOTH_FIND_RADIO_PARAMS params = { sizeof(BLUETOOTH_FIND_RADIO_PARAMS) };
    HBLUETOOTH_RADIO_FIND hFind = BluetoothFindFirstRadio(&params, &adapters);
    
    if (hFind == nullptr) {
        return FALSE;
    }
    
    do {
        BluetoothAdapterInfo adapter;
        adapter.hRadio = hFind->hRadio;
        
        // 获取无线电信息
        if (GetAdapterInfo(adapter.hRadio, adapter.radioInfo)) {
            // 获取设备信息
            adapter.deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
            if (BluetoothGetDeviceInfo(adapter.hRadio, &adapter.deviceInfo) == ERROR_SUCCESS) {
                adapter.isDefault = (adapters.size() == 0);
                adapters.push_back(adapter);
            }
        }
        
        // 关闭无线电句柄
        CloseHandle(hFind->hRadio);
        
    } while (BluetoothFindNextRadio(hFind, &adapters));
    
    BluetoothFindRadioClose(hFind);
    m_adapters = adapters;
    
    return adapters.size() > 0;
}

// 获取适配器信息
BOOL BluetoothManager::GetAdapterInfo(HANDLE hRadio, BLUETOOTH_RADIO_INFO& info) {
    info.dwSize = sizeof(BLUETOOTH_RADIO_INFO);
    DWORD result = BluetoothGetRadioInfo(hRadio, &info);
    return (result == ERROR_SUCCESS);
}

// 检查蓝牙是否启用
BOOL BluetoothManager::IsBluetoothEnabled() {
    std::vector<BluetoothAdapterInfo> adapters;
    if (EnumerateLocalAdapters(adapters)) {
        for (const auto& adapter : adapters) {
            if (adapter.radioInfo.dwFlags & BLUETOOTH_RADIO_INFO_FLAGS_ENABLED) {
                return TRUE;
            }
        }
    }
    return FALSE;
}

// 启用/禁用蓝牙
BOOL BluetoothManager::EnableBluetooth(BOOL enable) {
    // 注意:这需要管理员权限
    std::vector<BluetoothAdapterInfo> adapters;
    if (EnumerateLocalAdapters(adapters)) {
        for (const auto& adapter : adapters) {
            DWORD flags = enable ? 
                (adapter.radioInfo.dwFlags | BLUETOOTH_RADIO_INFO_FLAGS_ENABLED) :
                (adapter.radioInfo.dwFlags & ~BLUETOOTH_RADIO_INFO_FLAGS_ENABLED);
            
            // 使用BluetoothSetRadioMode设置模式
            DWORD mode = enable ? BLUETOOTH_RADIO_MODE_DISCOVERABLE : BLUETOOTH_RADIO_MODE_POWER_OFF;
            if (BluetoothSetRadioMode(adapter.hRadio, mode) != ERROR_SUCCESS) {
                return FALSE;
            }
        }
        return TRUE;
    }
    return FALSE;
}

// 开始设备扫描
BOOL BluetoothManager::StartDeviceDiscovery(std::function<void(const BluetoothDeviceInfo&)> callback) {
    if (m_discoveryActive) {
        return FALSE;
    }
    
    m_discoveryActive = TRUE;
    
    // 在新线程中执行扫描
    std::thread( {
        BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = {0};
        BLUETOOTH_DEVICE_INFO deviceInfo = {0};
        
        searchParams.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
        searchParams.fReturnAuthenticated = TRUE;
        searchParams.fReturnRemembered = TRUE;
        searchParams.fReturnUnknown = TRUE;
        searchParams.fReturnConnected = TRUE;
        searchParams.fIssueInquiry = TRUE;
        searchParams.cTimeoutMultiplier = 10;  // 10秒超时
        
        deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
        
        m_deviceFindHandle = BluetoothFindFirstDevice(&searchParams, &deviceInfo);
        if (m_deviceFindHandle == nullptr) {
            m_discoveryActive = FALSE;
            return;
        }
        
        do {
            if (!m_discoveryActive) break;
            
            BluetoothDeviceInfo devInfo;
            devInfo.address = deviceInfo.Address;
            devInfo.name = deviceInfo.szName;
            devInfo.classOfDevice = deviceInfo.ulClassofDevice;
            devInfo.deviceClass = ClassOfDeviceToString(deviceInfo.ulClassofDevice);
            devInfo.authenticated = deviceInfo.fAuthenticated;
            devInfo.connected = deviceInfo.fConnected;
            devInfo.remembered = deviceInfo.fRemembered;
            devInfo.lastSeen = deviceInfo.stLastSeen;
            
            // 获取设备服务
            EnumerateServices(devInfo.address, devInfo.services);
            
            callback(devInfo);
            
        } while (m_discoveryActive && BluetoothFindNextDevice(m_deviceFindHandle, &deviceInfo));
        
        BluetoothFindDeviceClose(m_deviceFindHandle);
        m_deviceFindHandle = nullptr;
        m_discoveryActive = FALSE;
    }).detach();
    
    return TRUE;
}

// 停止设备扫描
BOOL BluetoothManager::StopDeviceDiscovery() {
    if (m_discoveryActive) {
        m_discoveryActive = FALSE;
        if (m_deviceFindHandle) {
            BluetoothFindDeviceClose(m_deviceFindHandle);
            m_deviceFindHandle = nullptr;
        }
        return TRUE;
    }
    return FALSE;
}

// 枚举远程设备
BOOL BluetoothManager::EnumerateRemoteDevices(std::vector<BluetoothDeviceInfo>& devices) {
    devices.clear();
    
    BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = {0};
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    
    searchParams.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    searchParams.fReturnAuthenticated = TRUE;
    searchParams.fReturnRemembered = TRUE;
    searchParams.fReturnUnknown = TRUE;
    searchParams.fReturnConnected = TRUE;
    searchParams.fIssueInquiry = TRUE;
    searchParams.cTimeoutMultiplier = 10;
    
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    
    HBLUETOOTH_DEVICE_FIND hFind = BluetoothFindFirstDevice(&searchParams, &deviceInfo);
    if (hFind == nullptr) {
        return FALSE;
    }
    
    do {
        BluetoothDeviceInfo devInfo;
        devInfo.address = deviceInfo.Address;
        devInfo.name = deviceInfo.szName;
        devInfo.classOfDevice = deviceInfo.ulClassofDevice;
        devInfo.deviceClass = ClassOfDeviceToString(deviceInfo.ulClassofDevice);
        devInfo.authenticated = deviceInfo.fAuthenticated;
        devInfo.connected = deviceInfo.fConnected;
        devInfo.remembered = deviceInfo.fRemembered;
        devInfo.lastSeen = deviceInfo.stLastSeen;
        
        // 获取设备服务
        EnumerateServices(devInfo.address, devInfo.services);
        
        devices.push_back(devInfo);
        
    } while (BluetoothFindNextDevice(hFind, &deviceInfo));
    
    BluetoothFindDeviceClose(hFind);
    m_devices = devices;
    
    return devices.size() > 0;
}

// 刷新设备列表
BOOL BluetoothManager::RefreshDeviceList() {
    return EnumerateRemoteDevices(m_devices);
}

// 连接到设备
BOOL BluetoothManager::ConnectToDevice(const BLUETOOTH_ADDRESS& address, const GUID& serviceGuid) {
    // 首先检查是否已配对
    if (!IsDeviceAuthenticated(address)) {
        if (!PairDevice(address)) {
            return FALSE;
        }
    }
    
    // 获取设备信息
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    deviceInfo.Address = address;
    
    // 设置服务状态为启用
    DWORD result = BluetoothSetServiceState(nullptr, &deviceInfo, 
                                           (LPGUID)&serviceGuid, BLUETOOTH_SERVICE_ENABLE);
    
    return (result == ERROR_SUCCESS);
}

// 断开设备连接
BOOL BluetoothManager::DisconnectFromDevice(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    deviceInfo.Address = address;
    
    // 禁用所有服务
    std::vector<GUID> services;
    if (EnumerateServices(address, services)) {
        for (const auto& service : services) {
            BluetoothSetServiceState(nullptr, &deviceInfo, 
                                    (LPGUID)&service, BLUETOOTH_SERVICE_DISABLE);
        }
    }
    
    return TRUE;
}

// 配对设备
BOOL BluetoothManager::PairDevice(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    deviceInfo.Address = address;
    
    DWORD result = BluetoothAuthenticateDevice(nullptr, nullptr, &deviceInfo, nullptr);
    return (result == ERROR_SUCCESS);
}

// 取消配对
BOOL BluetoothManager::UnpairDevice(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    deviceInfo.Address = address;
    
    DWORD result = BluetoothRemoveDevice(&address);
    return (result == ERROR_SUCCESS);
}

// 获取连接状态
ConnectionState BluetoothManager::GetConnectionState(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO deviceInfo;
    if (GetDeviceInfo(address, deviceInfo)) {
        if (deviceInfo.fConnected) {
            return ConnectionState::Connected;
        } else if (deviceInfo.fAuthenticated) {
            return ConnectionState::Disconnected;
        } else {
            return ConnectionState::Failed;
        }
    }
    return ConnectionState::Failed;
}

// 枚举设备服务
BOOL BluetoothManager::EnumerateServices(const BLUETOOTH_ADDRESS& address, std::vector<GUID>& services) {
    services.clear();
    
    BLUETOOTH_DEVICE_INFO deviceInfo = {0};
    deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    deviceInfo.Address = address;
    
    DWORD serviceCount = 0;
    DWORD result = BluetoothEnumerateInstalledServices(nullptr, &deviceInfo, &serviceCount, nullptr);
    if (result == ERROR_SUCCESS && serviceCount > 0) {
        services.resize(serviceCount);
        result = BluetoothEnumerateInstalledServices(nullptr, &deviceInfo, &serviceCount, services.data());
        return (result == ERROR_SUCCESS);
    }
    
    return FALSE;
}

// 获取设备信息
BOOL BluetoothManager::GetDeviceInfo(const BLUETOOTH_ADDRESS& address, BLUETOOTH_DEVICE_INFO& info) {
    info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    info.Address = address;
    DWORD result = BluetoothGetDeviceInfo(nullptr, &info);
    return (result == ERROR_SUCCESS);
}

// 获取设备名称
std::wstring BluetoothManager::GetDeviceName(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO info;
    if (GetDeviceInfo(address, info)) {
        return info.szName;
    }
    return L"Unknown Device";
}

// 检查设备是否已连接
BOOL BluetoothManager::IsDeviceConnected(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO info;
    if (GetDeviceInfo(address, info)) {
        return info.fConnected;
    }
    return FALSE;
}

// 检查设备是否已认证
BOOL BluetoothManager::IsDeviceAuthenticated(const BLUETOOTH_ADDRESS& address) {
    BLUETOOTH_DEVICE_INFO info;
    if (GetDeviceInfo(address, info)) {
        return info.fAuthenticated;
    }
    return FALSE;
}

// 设备类别转换为字符串
std::wstring BluetoothManager::ClassOfDeviceToString(DWORD cod) {
    std::wstringstream ss;
    
    // 主要设备类别
    DWORD majorClass = (cod & 0x1F00) >> 8;
    switch (majorClass) {
        case 0x01: ss << L"Computer"; break;
        case 0x02: ss << L"Phone"; break;
        case 0x03: ss << L"LAN/Network Access Point"; break;
        case 0x04: ss << L"Audio/Video"; break;
        case 0x05: ss << L"Peripheral"; break;
        case 0x06: ss << L"Imaging"; break;
        case 0x07: ss << L"Wearable"; break;
        case 0x08: ss << L"Toy"; break;
        case 0x09: ss << L"Health"; break;
        default: ss << L"Unknown"; break;
    }
    
    // 次要设备类别
    DWORD minorClass = (cod & 0xFC) >> 2;
    if (majorClass == 0x02) { // Phone
        switch (minorClass) {
            case 0x01: ss << L" Cellular"; break;
            case 0x02: ss << L" Cordless"; break;
            case 0x03: ss << L" Smartphone"; break;
            case 0x04: ss << L" Modem"; break;
            case 0x05: ss << L" ISDN"; break;
        }
    }
    
    return ss.str();
}

// 地址转换为字符串
std::wstring BluetoothManager::AddressToString(const BLUETOOTH_ADDRESS& address) {
    std::wstringstream ss;
    ss << std::hex << std::uppercase << std::setfill(L'0')
       << std::setw(2) << (int)address.rgBytes[5] << L":"
       << std::setw(2) << (int)address.rgBytes[4] << L":"
       << std::setw(2) << (int)address.rgBytes[3] << L":"
       << std::setw(2) << (int)address.rgBytes[2] << L":"
       << std::setw(2) << (int)address.rgBytes[1] << L":"
       << std::setw(2) << (int)address.rgBytes[0];
    return ss.str();
}

// 字符串转换为地址
BOOL BluetoothManager::StringToAddress(const std::wstring& str, BLUETOOTH_ADDRESS& address) {
    if (str.length() != 17) return FALSE;
    
    int values[6];
    swscanf_s(str.c_str(), L"%02x:%02x:%02x:%02x:%02x:%02x",
              &values[0], &values[1], &values[2], &values[3], &values[4], &values[5]);
    
    for (int i = 0; i < 6; i++) {
        address.rgBytes[i] = (BYTE)values[5-i];
    }
    
    return TRUE;
}

2.3 主程序示例 (Main.cpp)

#include "BluetoothManager.h"
#include <iostream>
#include <conio.h>

using namespace std;

// 显示设备信息
void DisplayDeviceInfo(const BluetoothDeviceInfo& device) {
    wcout << L"=========================================" << endl;
    wcout << L"设备名称: " << device.name << endl;
    wcout << L"设备地址: ";
    
    // 显示地址
    for (int i = 5; i >= 0; i--) {
        wprintf(L"%02X", device.address.rgBytes[i]);
        if (i > 0) wcout << L":";
    }
    wcout << endl;
    
    wcout << L"设备类别: " << device.deviceClass << endl;
    wcout << L"已认证: " << (device.authenticated ? L"是" : L"否") << endl;
    wcout << L"已连接: " << (device.connected ? L"是" : L"否") << endl;
    wcout << L"已记住: " << (device.remembered ? L"是" : L"否") << endl;
    
    if (device.services.size() > 0) {
        wcout << L"支持的服务 (" << device.services.size() << L"):" << endl;
        for (size_t i = 0; i < device.services.size(); i++) {
            wcout << L"  Service " << i+1 << L": ";
            // 检查是否是常见服务
            if (IsEqualGUID(device.services[i], BluetoothServices::SerialPort)) {
                wcout << L"串口服务";
            } else if (IsEqualGUID(device.services[i], BluetoothServices::GenericAccess)) {
                wcout << L"通用访问服务";
            } else if (IsEqualGUID(device.services[i], BluetoothServices::DeviceInformation)) {
                wcout << L"设备信息服务";
            } else {
                wcout << L"未知服务";
            }
            wcout << endl;
        }
    }
    wcout << endl;
}

// 显示本地适配器信息
void DisplayAdapterInfo(const BluetoothAdapterInfo& adapter) {
    wcout << L"=========================================" << endl;
    wcout << L"蓝牙适配器: " << adapter.radioInfo.szName << endl;
    wcout << L"制造商: " << adapter.radioInfo.szManufacturer << endl;
    wcout << L"版本: " << adapter.radioInfo.lmpVersion << L"." << adapter.radioInfo.lmpSubversion << endl;
    wcout << L"地址: ";
    
    for (int i = 5; i >= 0; i--) {
        wprintf(L"%02X", adapter.radioInfo.address.rgBytes[i]);
        if (i > 0) wcout << L":";
    }
    wcout << endl;
    
    wcout << L"状态: " << (adapter.radioInfo.dwFlags & BLUETOOTH_RADIO_INFO_FLAGS_ENABLED ? L"启用" : L"禁用") << endl;
    wcout << L"默认适配器: " << (adapter.isDefault ? L"是" : L"否") << endl;
    wcout << endl;
}

int main() {
    setlocale(LC_ALL, ""); // 设置本地化以支持中文
    
    wcout << L"Windows 蓝牙设备管理器" << endl;
    wcout << L"==============================" << endl << endl;
    
    BluetoothManager btManager;
    
    // 1. 枚举本地蓝牙适配器
    wcout << L"1. 枚举本地蓝牙适配器..." << endl;
    vector<BluetoothAdapterInfo> adapters;
    if (btManager.EnumerateLocalAdapters(adapters)) {
        wcout << L"找到 " << adapters.size() << L" 个蓝牙适配器:" << endl;
        for (const auto& adapter : adapters) {
            DisplayAdapterInfo(adapter);
        }
    } else {
        wcout << L"未找到蓝牙适配器!" << endl;
        return 1;
    }
    
    // 2. 检查蓝牙状态
    wcout << L"2. 检查蓝牙状态..." << endl;
    if (btManager.IsBluetoothEnabled()) {
        wcout << L"蓝牙已启用" << endl;
    } else {
        wcout << L"蓝牙未启用,正在尝试启用..." << endl;
        if (btManager.EnableBluetooth(TRUE)) {
            wcout << L"蓝牙已启用" << endl;
        } else {
            wcout << L"无法启用蓝牙!" << endl;
        }
    }
    
    // 3. 扫描远程设备
    wcout << L"\n3. 扫描远程蓝牙设备 (按任意键停止扫描)..." << endl;
    atomic<bool> scanCompleted(false);
    
    btManager.StartDeviceDiscovery(const BluetoothDeviceInfo& device {
        if (!scanCompleted) {
            DisplayDeviceInfo(device);
        }
    });
    
    // 等待用户按键
    _getch();
    btManager.StopDeviceDiscovery();
    scanCompleted = true;
    
    // 4. 枚举所有远程设备
    wcout << L"\n4. 已发现的设备列表:" << endl;
    vector<BluetoothDeviceInfo> devices;
    if (btManager.EnumerateRemoteDevices(devices)) {
        wcout << L"找到 " << devices.size() << L" 个远程设备:" << endl;
        for (size_t i = 0; i < devices.size(); i++) {
            wcout << i+1 << L". ";
            DisplayDeviceInfo(devices[i]);
        }
    } else {
        wcout << L"未发现远程设备!" << endl;
    }
    
    // 5. 连接设备示例
    if (devices.size() > 0) {
        wcout << L"\n5. 连接设备示例:" << endl;
        wcout << L"选择要连接的设备 (1-" << devices.size() << L"): ";
        
        int choice;
        wcin >> choice;
        
        if (choice >= 1 && choice <= (int)devices.size()) {
            const BluetoothDeviceInfo& selectedDevice = devices[choice-1];
            
            wcout << L"正在连接设备: " << selectedDevice.name << L"..." << endl;
            
            // 连接到串口服务
            if (btManager.ConnectToDevice(selectedDevice.address, BluetoothServices::SerialPort)) {
                wcout << L"连接成功!" << endl;
                
                // 检查连接状态
                ConnectionState state = btManager.GetConnectionState(selectedDevice.address);
                wcout << L"连接状态: " << (state == ConnectionState::Connected ? L"已连接" : L"未连接") << endl;
                
                // 断开连接
                wcout << L"按任意键断开连接..." << endl;
                _getch();
                
                btManager.DisconnectFromDevice(selectedDevice.address);
                wcout << L"已断开连接" << endl;
            } else {
                wcout << L"连接失败!" << endl;
            }
        }
    }
    
    wcout << L"\n程序结束。" << endl;
    return 0;
}

参考代码 Windows枚举本地蓝牙设备 www.youwenfan.com/contentcnu/60491.html

三、Visual Studio 项目配置

3.1 项目属性设置

1. 右键项目 -> 属性
2. 配置属性 -> C/C++
   - 常规 -> 附加包含目录: 添加Windows SDK头文件路径
   - 代码生成 -> 运行库: 多线程 (/MT) 或 多线程DLL (/MD)
3. 配置属性 -> 链接器
   - 输入 -> 附加依赖项: 添加 Ws2_32.lib; Bthprops.lib;
   - 系统 -> 子系统: 控制台 (/SUBSYSTEM:CONSOLE)

3.2 编译注意事项

  1. 管理员权限: 某些蓝牙操作需要管理员权限,请右键"以管理员身份运行"Visual Studio
  2. Windows SDK: 确保安装了Windows SDK
  3. Unicode设置: 项目使用Unicode字符集,确保字符串处理正确

四、功能扩展建议

4.1 可以添加的功能

  1. 设备过滤: 按设备类别过滤显示
  2. 自动重连: 检测断开后自动重连
  3. 数据传输: 实现串口数据收发
  4. GUI界面: 使用Qt或MFC创建图形界面
  5. 设备缓存: 保存已配对设备信息
  6. RSSI监测: 显示信号强度

4.2 常见问题解决

问题 解决方案
无法发现设备 确保蓝牙已启用,设备处于可发现模式
连接失败 检查设备是否已配对,服务是否支持
权限不足 以管理员身份运行程序
编译错误 检查Windows SDK版本,链接库是否正确
posted @ 2026-05-08 12:20  晃悠人生  阅读(7)  评论(0)    收藏  举报