我已經創建了一個程序,只使用Window的藍牙API列出範圍內的藍牙設備,然後搜索特定的藍牙設備(HC-05藍牙模塊)。如果搜索成功,則程序使用串行端口GUID(1101)來認證並設置設備的服務狀態以創建虛擬化合物。我的目標是以編程方式與BT設備進行配對和通信,而不會打擾用戶。無法使用C++的窗口藍牙API連接到藍牙設備
下面是main()的一部分,其中試圖驗證和創建虛擬端口。
if(desired_device_info.fAuthenticated==FALSE){ //if device is not authenticated then,
BluetoothGetDeviceInfo(m_radio,&desired_device_info); //get updated device information
if(!pairDevice(desired_device_info)){//attempt to pair with the device.
cout<<"Authentication failed, Try manually"<<endl;
CloseAllHandle();
return 0;}
}
ret=BluetoothSetServiceState(m_radio,&desired_device_info,&serial,BLUETOOTH_SERVICE_ENABLE);
if(ret !=ERROR_SUCCESS && ret!=E_INVALIDARG){
if(ret == ERROR_INVALID_PARAMETER)
cout<< "Invalid Parameter" << endl;
if(ret == ERROR_SERVICE_DOES_NOT_EXIST)
cout<< "Service not found" << endl;
cout<<"Press any key to exit"<<endl;
CloseAllHandle();
x=_getch();
return 0;
}
BluetoothGetDeviceInfo(m_radio,&desired_device_info); //get updated device infor
BluetoothUpdateDeviceRecord(&desired_device_info);
以上段使用的pairDevice()函數是:
bool pairDevice(BLUETOOTH_DEVICE_INFO device){
DWORD errorCode;
bool result=false;
//wchar_t passKey=L'1234\n';
PWSTR * passKey = new PWSTR[1];
passKey[0]=L"1234";// this is the default pass key/pin code for HC-05, can be changed to a custom value.
errorCode=BluetoothAuthenticateDevice(NULL,m_radio,&device,*passKey,4); //here 4 is the size of device passkey
//errorCode=BluetoothRegisterForAuthenticationEx(&device, &hRegHandle, (PFN_AUTHENTICATION_CALLBACK_EX)&bluetoothAuthCallback, NULL);
// if(errorCode != ERROR_SUCCESS)
// {
// fprintf(stderr, "BluetoothRegisterForAuthenticationEx ret %d\n", errorCode);
// CloseAllHandle();
// _getch();
// return false;
// //ExitProcess(2);
//
// }
//errorCode = BluetoothAuthenticateDeviceEx(NULL,m_radio, &device, NULL, MITMProtectionNotRequired);
switch(errorCode)
{case(ERROR_SUCCESS):
cout<<"Device authenticated successfully"<<endl;
result=true;
break;
case(ERROR_CANCELLED):
cout<<"Device authenticated failed"<<endl;
result=false;
break;
case(ERROR_INVALID_PARAMETER):
cout<<"Invalid parameters"<<endl;
result=false;
break;
case(ERROR_NO_MORE_ITEMS):
cout<<"Device not available"<<endl;
result=false;
break;
}
if(errorCode != ERROR_SUCCESS)
cout<<"Failure due to: "<<GetLastError() <<endl;
return result;
}
void CloseAllHandle(void){
if(CloseHandle(m_radio) == FALSE){
cout<<"CloseHandle() failed with error code "<< GetLastError()<<endl;
}
BluetoothUnregisterAuthentication(hRegHandle);
}
所有這一切工作正常,但問題是,即使是虛擬COMPORT的認證和創建後的設備連接狀態保持假。
當串行終端嘗試與上面創建COMPORT它返回下列錯誤進行通信:
Element not found. (1168)
我有累使用回調方法對設備進行認證,但它不能正常工作,返回錯誤,如:
The device is not connected. (1167) The device does not recognize the command. (22)
我真的很感激,如果有人可以調試此代碼,因爲我無法找到resour ces或使用窗口的藍牙API教程。
Here是完整的代碼。
英語不是我的母語,但我盡我所能,儘可能在語法上儘可能準確。 –