簡體   English   中英

將Windows中的藍牙設備與c ++配對

[英]Pairing a bluetooth device in windows with c++

我需要能夠使用C ++ for Windows中的代碼配對設備(特別是win7或更新版本)。 我編寫了應該可以工作的代碼,但事實並非如此。 我可以配對很多設備,Roku,耳機,揚聲器等,但由於某種原因,我需要配對的設備無法正常工作。

它總是返回錯誤代碼0x05,根據bthdefs.h定義為BTH_ERROR_AUTHENTICATION_FAILURE。

所以這里奇怪的部分。 它永遠不會嘗試進行身份驗證。 在調用期間應調用以提供密鑰的回調函數不會被調用。 我已經確認它會被其他設備(如耳機)調用。

我已經嘗試使用BluetoothAuthenticateDeviceEx()而沒有回調函數,它應該在Windows中彈出GUI來完成配對。 它彈出我的耳機和其他設備,它不會彈出我的設備。

作為旁注,我可以使用Window的藍牙向導配對設備就好了。 它只是拒絕以編程方式工作。

我無法弄清楚我正在使用的winapi代碼和windows'向導在配對期間正在做什么之間的區別。

這是我能得到的最簡單的測試應用程序。 我真正的應用程序是使用Qt和mingw來構建。 此應用程序使用MSVC 2012和純Windows代碼來從問題中刪除任何混淆。 我的所有代碼都有與錯誤代碼5相同的問題。

#include <windows.h>
#include "bthdef.h"
#include "BluetoothAPIs.h"
#include <tchar.h>
#include <string>
#include <iostream>
#include <vector>

#pragma comment(lib, "bthprops.lib")

using namespace std;

vector<BLUETOOTH_DEVICE_INFO> scanDevices()
{
    vector<BLUETOOTH_DEVICE_INFO> res;

    BLUETOOTH_DEVICE_SEARCH_PARAMS bdsp;
    BLUETOOTH_DEVICE_INFO bdi;
    HBLUETOOTH_DEVICE_FIND hbf;

    ZeroMemory(&bdsp, sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS));

    // set options for how we want to load our list of BT devices
    bdsp.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    bdsp.fReturnAuthenticated = TRUE;
    bdsp.fReturnRemembered = TRUE;
    bdsp.fReturnUnknown = TRUE;
    bdsp.fReturnConnected = TRUE;
    bdsp.fIssueInquiry = TRUE;
    bdsp.cTimeoutMultiplier = 4;
    bdsp.hRadio = NULL;

    bdi.dwSize = sizeof(bdi);

    // enumerate our bluetooth devices
    hbf = BluetoothFindFirstDevice(&bdsp, &bdi);
    if (hbf)
    {
        do
        {
            res.push_back(bdi);
        } while (BluetoothFindNextDevice(hbf, &bdi));

        // close our device enumerator
        BluetoothFindDeviceClose(hbf);
    }

    return res;
}

BOOL CALLBACK bluetoothAuthCallback(LPVOID param, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS params)
{
    cout << "callback happened" << endl;
    return TRUE;
}

void pairDevice(BLUETOOTH_DEVICE_INFO device)
{
    wstring ws = device.szName;
    cout << "Pairing device " << string(ws.begin(), ws.end()) << endl;

    // register callback
    cout << "Registering callback" << endl;
    HBLUETOOTH_AUTHENTICATION_REGISTRATION hCallbackHandle = 0;
    DWORD result = BluetoothRegisterForAuthenticationEx(&device, &hCallbackHandle, (PFN_AUTHENTICATION_CALLBACK_EX)&bluetoothAuthCallback, NULL);
    if (result != ERROR_SUCCESS)
    {
        cout << "Failed to register callback" << endl;
        return;
    }

    // authenticate
    result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionNotRequired);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionRequired);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionNotRequiredBonding);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionRequiredBonding);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionNotRequiredGeneralBonding);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionRequiredGeneralBonding);
    //DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &device, NULL, MITMProtectionNotDefined);
    switch (result)
    {
    case ERROR_SUCCESS:
        cout << "pair device success" << endl;
        break;

    case ERROR_CANCELLED:
        cout << "pair device failed, user cancelled" << endl;
        break;

    case ERROR_INVALID_PARAMETER:
        cout << "pair device failed, invalid parameter" << endl;
        break;

    case ERROR_NO_MORE_ITEMS:
        cout << "pair device failed, device appears paired already" << endl;
        break;

    default:
        cout << "pair device failed, unknown error, code " << (unsigned int)result << endl;
        break;
    }
}

int _tmain(int argc, _TCHAR *argv[])
{
    cout << "Scanning bluetooth devices..." << endl;
    cout.flush();

    // scan devices
    vector<BLUETOOTH_DEVICE_INFO> devices = scanDevices();

    cout << "Got " << devices.size() << " devices" << endl;

    // list all devices
    int pdIndex = -1;
    int foundDev = -1;
    vector<BLUETOOTH_DEVICE_INFO>::const_iterator devci;
    for (devci=devices.begin();devci!=devices.end();devci++)
    {
        pdIndex++;
        wstring ws = (*devci).szName;
        cout << "Device: " << string(ws.begin(), ws.end()) << endl;

        // see if we find our device (case sensitive)
        if (ws.find(L"smp") != string::npos)
            foundDev = pdIndex;
    }

    // pick our ismp device
    if (foundDev == -1)
    {
        cout << "Could not find a device to pair" << endl;
        return 1;
    }

    BLUETOOTH_DEVICE_INFO pd = devices[foundDev];
    wstring ws = pd.szName;
    cout << "Found device to pair, " << string(ws.begin(), ws.end()) << endl;

    // attempt to pair device
    pairDevice(pd);

    return 0;
}

據我所知,我可以在你的代碼中看到很多問題:

1)你在調用'pairDevice'時調用了BluetoothRegisterForAuthenticationEx: hCallbackHandle變量只會在調用期間存在,所以你必須 'pairDevice' 之前注冊

2)之后您沒有調用BluetoothUnregister

3)您沒有刪除hCallbackHandle句柄

4)你的'bluetoothAuthCallback'是空的:你必須做類似的事情

BLUETOOTH_AUTHENTICATE_RESPONSE response;
::ZeroMemory(&response,sizeof(BLUETOOTH_AUTHENTICATE_RESPONSE));
response.authMethod = cbparams->authenticationMethod;
response.bthAddressRemote = cbparams->deviceInfo.Address;
response.negativeResponse = FALSE;
DWORD error=::BluetoothSendAuthenticationResponseEx(nullptr, &response);

(見上述評論;-)

5)你對'BluetoothAuthenticateDeviceEx'的調用將異步觸發回調例程...,所以你必須'等待'...之后離開main()函數...

也許你應該在你的身份驗證回調中添加響應。 像這樣的Smth:

BLUETOOTH_DEVICE_INFO aw = params->deviceInfo;
HANDLE lRadio = NULL;

BLUETOOTH_AUTHENTICATE_RESPONSE bar2Send;
::ZeroMemory(&bar2Send, sizeof(BLUETOOTH_AUTHENTICATE_RESPONSE));
bar2Send.bthAddressRemote = params->deviceInfo.Address;
bar2Send.authMethod = params->authenticationMethod;

DWORD result = BluetoothSendAuthenticationResponseEx(lRadio, &bar2Send);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM