gpt4 book ai didi

c++ - 如何找到具有特定设备名称的蓝牙设备的端口名称?

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:41 24 4
gpt4 key购买 nike

如何找到具有特定设备名称的蓝牙设备的端口名称?

我有这段代码,它枚举了所有蓝牙设备,但没有给我它们的端口名称:

HBLUETOOTH_DEVICE_FIND founded_device;

BLUETOOTH_DEVICE_INFO device_info;
device_info.dwSize = sizeof(device_info);

BLUETOOTH_DEVICE_SEARCH_PARAMS search_criteria;
search_criteria.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
search_criteria.fReturnAuthenticated = TRUE;
search_criteria.fReturnRemembered = FALSE;
search_criteria.fReturnConnected = FALSE;
search_criteria.fReturnUnknown = FALSE;
search_criteria.fIssueInquiry = FALSE;
search_criteria.cTimeoutMultiplier = 0;

founded_device = BluetoothFindFirstDevice(&search_criteria, &device_info);

if(founded_device == NULL)
return -1;

do {
wstring ws = device_info.szName;
cout << string(ws.begin(), ws.end()) << endl;

} while (BluetoothFindNextDevice(founded_device, &device_info));

然后我有这段代码,它枚举了所有端口名称但没有给我设备名称:

DWORD bytesNeeded = 0;
DWORD portCount = 0;

BOOL ret = EnumPorts(nullptr, 2, nullptr, 0, &bytesNeeded, &portCount);

BYTE *ports = new BYTE[bytesNeeded];

if(EnumPorts(nullptr, 2, (LPBYTE)ports, bytesNeeded, &bytesNeeded, &portCount))
{
PORT_INFO_2 *portInfo = (PORT_INFO_2*)ports;

for(DWORD i = 0; i < portCount; ++i)
cout << portInfo[i].pPortName << endl;
}

delete [] ports;

我需要在我的应用程序启动时自动连接到特定设备,因此我需要在第一段代码中获取蓝牙设备的端口名称以便连接到它,或者检查第二段代码在连接之前确保它是正确的设备。

我该怎么做?

最佳答案

我记得过去曾为此苦苦挣扎过。我找到的唯一解决方案是使用套接字使用其地址与蓝牙设备通信,然后使用 send()recv() 方法与设备通信。

// assuming you have the BT device address in blueToothDeviceAddr;
char blueToothDeviceAddr[18];

SOCKET sock;
SOCKADDR_BTH sa = { 0,0,0,0 };
int sa_len = sizeof(sa);

// initialize windows sockets
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 0 );
if( WSAStartup( wVersionRequested, &wsaData ) != 0 )
{
ExitProcess(100);
}

// parse the specified Bluetooth address

if( SOCKET_ERROR == WSAStringToAddress( blueToothDeviceAddr, AF_BTH,
NULL, (LPSOCKADDR) &sa, &sa_len ) )
{
ExitProcess(101);
}

// query it for the right port

// create the socket
sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if( SOCKET_ERROR == sock )
{
ExitProcess(102);
}

// fill in the rest of the SOCKADDR_BTH struct
GUID pService = (GUID)SerialPortServiceClass_UUID;
SOCKADDR_BTH outSA;
sa.port = SDPGetPort(blueToothDeviceAddr, (LPGUID) &pService,&outSA);
if( sa.port == 0 )
{
ExitProcess(103);
}

// in case you have a pass code you need to register for authetication callback
// look the web for this part

// connect to the device
if( SOCKET_ERROR == connect( sock, (LPSOCKADDR) &outSA, sa_len ) )
{
int lastError = GetLastError();
ExitProcess(105);
}

关于c++ - 如何找到具有特定设备名称的蓝牙设备的端口名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com