Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //This program discovers and list all bluetooth devices in range and attempts to establish connections
- //The program starts with looking at the status of bluetooth on computer(i.e. Local Radio) by calling IsBluetoothOn()
- //if it is Off then it attempts to open local radio of computer by calling func TurnOnBluetooth()
- //if the function fails to open bluetooth, it prints to request user to enable bluetooth manually and restart program
- //then when bluetooth radio of computer is enabled, the program attempts to find all the device within range and
- //finds the device named hc-05 by using the function FindBtDev(). This function if successful will return the data
- //about bluetooth module to main function, if function fails then the program notify user that unable to find device and
- //after some delay again looks for the device.
- //finally when the device is found and data is return by FindBtDev() then status of connection and authentication of device
- //is checked, if device is not authenticated (i.e false) then the pairDevice() function is called to attempt to pair with device.
- //finally the BluetoothSetService function is used to set seiral serivce class and enable service of the device. this creates a
- //virtual com.
- //BUGS and ISSUES:
- // the trunning on bluetooth radio function is not working at all. need to debug it.
- //==========Header============================
- #include <winsock2.h>
- #include <windows.h>
- #include <ws2bth.h>
- #include <BluetoothAPIs.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string>
- #include <iostream>
- #include <conio.h>
- #include <initguid.h>
- #include <windef.h>
- //#include <tchar.h>
- #pragma comment(lib, "ws2_32.lib")
- #pragma comment(lib, "irprops.lib")
- #pragma comment(lib, "Bthprops.lib")
- using namespace std;
- #define MAX_NAME 248
- typedef DWORD (WINAPI *f_BluetoothEnableRadio)(BOOL);
- typedef int (WINAPI* f_BthSetMode)(enum RadioMode);
- //================================function prototypes===================================================================================
- bool TurnOnBluetooth(void);//attempts to turn on bluetooth radio of computer and returns true if successful and false if error occurs.
- int IsBluetoothOn(void);//returns 0 if bluetooth radio off, returns 1 if On and returns -1 if the function failed to complete.
- bool pairDevice(BLUETOOTH_DEVICE_INFO); //returns true if successful and false if not takes bluetooth deivce info struct.
- bool FindBtDev(BLUETOOTH_DEVICE_INFO*); //returns true if successful and false if not takes bluetooth deivce info struct's pointer.
- void CloseAllHandle(void);//a function to close all windows handles. wil be called at last as a clean up function.
- //======================================================================================================================================
- HANDLE m_radio ; //Windows handle to local radio, declared here as a global variable
- HBLUETOOTH_AUTHENTICATION_REGISTRATION hRegHandle = 0;
- /// Bluetooth states.
- enum RadioMode //enumeration created for bluetooth radio state.
- {
- /// Bluetooth off.
- Off,
- /// Bluetooth is on but not discoverable.
- On,
- /// Bluetooth is on and discoverable.
- Discoverable,
- };
- BOOL CALLBACK bluetoothAuthCallback(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS pAuthCallbackParams)
- {
- DWORD dwRet;
- BLUETOOTH_AUTHENTICATE_RESPONSE response;
- BLUETOOTH_PIN_INFO HcPin;
- HcPin.pin[0]='1';
- HcPin.pin[1]='2';
- HcPin.pin[2]='3';
- HcPin.pin[3]='4';
- HcPin.pinLength=4;
- BLUETOOTH_PASSKEY_INFO pass={1234};
- ::ZeroMemory(&response,sizeof(BLUETOOTH_AUTHENTICATE_RESPONSE));
- response.authMethod = pAuthCallbackParams->authenticationMethod;
- response.bthAddressRemote = pAuthCallbackParams->deviceInfo.Address;
- response.pinInfo= HcPin;
- response.negativeResponse = FALSE;
- response.passkeyInfo=pass;
- fprintf(stderr, "BluetoothAuthCallback 0x%x\n", pAuthCallbackParams->deviceInfo.Address.ullLong);
- //dwRet = BluetoothSendAuthenticationResponse(NULL, &(pAuthCallbackParams->deviceInfo), L"1234");
- dwRet = BluetoothSendAuthenticationResponseEx(m_radio, &response);
- if(dwRet != ERROR_SUCCESS)
- {
- fprintf(stderr, "BluetoothSendAuthenticationResponse ret %d\n", dwRet);
- //ExitProcess(2);
- return TRUE;
- }
- fprintf(stderr, "BluetoothAuthCallback finish\n");
- // ExitProcess(0);
- return FALSE;
- }
- int main(int argc, char ** argv) //main code here.
- {
- //======================variables===============================================
- char x;
- DWORD ret;
- const GUID serial=SerialPortServiceClass_UUID;
- bool retVal;
- int IsOn; //variable that tells whether function is working or not
- BLUETOOTH_DEVICE_INFO desired_device_info={sizeof(BLUETOOTH_DEVICE_INFO),0,}; //a struct variable that will store info of desired device
- // DWORD numServices;
- // GUID guidServices[10];
- //==========================================================================================
- IsOn=IsBluetoothOn(); //start by checking wether bluetooth module is on or off
- if(IsOn==0){ //i.e the device is not ON then//then ask user to turn on the bluetooth
- //attempt to turn on the device
- //if(!TurnOnBluetooth()){
- //if result of our above attempt is zero then failed to open bluetooth module
- // then ask user to enable bluetooth manually,
- cout<<"Enable bluetooth Manually and restart program"<<endl;
- cout<<"Press any key to exit"<<endl;
- x=_getch();
- return 0;
- //}
- }else if(IsOn==-1){
- cout<<"Error Occured Closing Program"<<endl;
- cout<<"Press any key to exit"<<endl;
- x=_getch();
- return 0;
- }
- //if IsOn==1 then local bluetooth is on
- retVal= FindBtDev(&desired_device_info);
- if(retVal==false)
- {//device not found
- cout<<"Error cannot find device"<<endl;
- cout<<"Searching again, Press any key to exit program"<<endl;
- while(FindBtDev(&desired_device_info)==false){ //contiune looking until you find the device
- Sleep(1000);
- if(_getch()){ //if user press any key exit from the search
- CloseAllHandle();
- return 0;}
- }
- }
- if(!BluetoothIsConnectable(m_radio)) //check if local bluetooth radios accept incomming connections
- { //if not then attempt to turn this true
- cout<<"Incomming connection was not ON, turning it On"<<endl;
- if(BluetoothEnableIncomingConnections(m_radio,TRUE))
- cout<<"Incomming connections enabled"<<endl;
- else
- cout<<"Error Unable to enable incoming connections"<<endl;
- }else
- cout<<"Incomming connection was ON!"<<endl;
- if(desired_device_info.fConnected==FALSE && desired_device_info.fRemembered==TRUE){ //iff device is connected, then will we attempt to establish comport communication
- cout<<"Device is out of range or switched Off."<<endl;
- }
- if(desired_device_info.fRemembered==FALSE && desired_device_info.fConnected==FALSE){ //if the device is not remembered then attempt to create authentication and comport.
- cout<<"Device Found Attempting to connect"<<endl;
- 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); //this will make the device as bluetooth com port hopefully
- if(ret !=ERROR_SUCCESS && ret!=E_INVALIDARG){// if the operation is not successful and does not contain invalid argument
- 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;
- }
- /*ret = BluetoothEnumerateInstalledServices(m_radio, &desired_device_info, &numServices, guidServices);
- if(ret !=ERROR_SUCCESS)
- cout<<"Error getting device service. error ID: "<<ret<<endl;*/
- BluetoothGetDeviceInfo(m_radio,&desired_device_info); //get updated device infor
- BluetoothUpdateDeviceRecord(&desired_device_info);
- cout<<"Name: "<<desired_device_info.szName <<endl;
- wprintf(L" \tAddress: %02X:%02X:%02X:%02X:%02X:%02X\r\n", desired_device_info.Address.rgBytes[5],
- desired_device_info.Address.rgBytes[4], desired_device_info.Address.rgBytes[3], desired_device_info.Address.rgBytes[2],
- desired_device_info.Address.rgBytes[1], desired_device_info.Address.rgBytes[0]);
- wprintf(L" \tConnected: %s\r\n", desired_device_info.fConnected ? L"true" : L"false");
- wprintf(L" \tAuthenticated: %s\r\n", desired_device_info.fAuthenticated ? L"true" : L"false");
- wprintf(L" \tRemembered: %s\r\n", desired_device_info.fRemembered ? L"true" : L"false");
- cout<<"Operation Successful check if comport created"<<endl;
- }//end of if device is not remembered.
- cout<<"Press any key to exit"<<endl;
- CloseAllHandle();
- x=_getch();
- return 0;
- } //end of main
- //bool TurnOnBluetooth(void){
- // OSVERSIONINFO osvi; //this struct will store the version of windows
- // DWORD dwType = REG_SZ;
- // HKEY hKey;
- // BOOL fEnable=TRUE; //because its the turn on function
- // HINSTANCE hGetProcIDDLL;
- // TCHAR value[1024]; //will store the address to the dll file we need to load
- // DWORD value_length = 1024*sizeof(TCHAR);
- // const std::string& location = "SYSTEM\\CurrentControlSet\\Services\\BTHPORT\\Parameters\\Radio Support";
- // const std::string& ValueName = "SupportDLL";
- //
- //
- // ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); //allocating memory by filing with zeros
- // osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- //
- // GetVersionEx(&osvi);
- //
- // if((osvi.dwMajorVersion <= 6) && osvi.dwMinorVersion <= 1){ // windows 7 or less then
- //
- // if(ERROR_SUCCESS != RegOpenKeyExA(HKEY_LOCAL_MACHINE,location.c_str(),0, KEY_QUERY_VALUE,&hKey)) //go to the above registry location
- // {
- // cout<<"Error Locating Bluetooth Module,Check Bluetooth Driver"<<endl;
- // RegCloseKey(hKey); //close this handle
- // return 0;
- //
- //
- // }else if(ERROR_SUCCESS !=RegQueryValueExA(hKey, ValueName.c_str(), 0, 0, (LPBYTE) value, &value_length))
- // { //if registry location is found then look for the valueName and get its string Value
- // cout<<"Bluetooth Driver might be corrupt,reinstall driver or Enable Manually"<<endl;
- // RegCloseKey(hKey); //close this handle
- // return 0;
- // }
- //
- // RegCloseKey(hKey); //close this handle
- //
- // std::wstring stringValue =std::wstring(value, (size_t)value_length - 1);
- // size_t i = stringValue.length();
- // while( i > 0 && stringValue[i-1] == '\0' ){
- // --i;
- // }
- // stringValue=stringValue.substr(0,i);
- //
- // size_t count = stringValue.find('/');
- // while (count != string::npos){
- //
- // stringValue[count]='\\'+'\\';
- // count= stringValue.find('\\', i + 1);
- // }
- //
- // cout<<"The bluetooth SUpport DLL is located in:"<<endl;
- // cout<<stringValue.c_str()<<endl;
- // hGetProcIDDLL = LoadLibrary(stringValue.c_str()); //load the dll
- // if (hGetProcIDDLL == NULL) {
- // cout << "cannot locate the bluetooth driver file, Enable Manually" << endl;
- // FreeLibrary(hGetProcIDDLL); //unload the library and free the handle
- // return 0;
- // }
- // //now get the function and run it.
- // f_BluetoothEnableRadio BluetoothEnableRadio= (f_BluetoothEnableRadio)GetProcAddress(hGetProcIDDLL,"BluetoothEnableRadio");
- // //return error if function was not found
- // if(!BluetoothEnableRadio)
- // {
- // cout << "Driver does not provide Software switch of bluetooth, Enable Manually" << endl;
- // FreeLibrary(hGetProcIDDLL); //unload the library and free the handle
- // return 0;
- // }
- //
- // if(ERROR_SUCCESS !=BluetoothEnableRadio(fEnable)){
- //
- // cout << "Unable to switch ON bluetooth module, Enable Manually" << endl;
- // FreeLibrary(hGetProcIDDLL); //unload the library and free the handle
- // return 0;
- // }
- // cout<<"Bluetooth Module Enabled"<<endl;
- // FreeLibrary(hGetProcIDDLL); //unload the library and free the handle
- //
- // }else{
- // cout<<"Software not fully compatibile with current version of Windows"<< endl;
- // cout<<"Cannot Enable Bluetooth Automatically"<<endl;
- // return 0;
- // }
- //return 1; //the operation was successfull
- //}
- //return false if error occured and true if operation is successful
- int IsBluetoothOn(void){
- int ErrorCode;
- HANDLE r_radio;
- HBLUETOOTH_RADIO_FIND m_bt;
- BLUETOOTH_FIND_RADIO_PARAMS m_bt_find_radio = {sizeof(BLUETOOTH_FIND_RADIO_PARAMS)}; //a struct that needs to be passed
- int result;
- //do a search now to check
- m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &r_radio);
- if(m_bt != NULL){
- cout<<"Bluetooth Radio Found !"<<endl;
- result=1;
- if(CloseHandle(r_radio) == FALSE){
- cout<<"CloseHandle() failed with error code "<< GetLastError()<<endl;
- result= -1;
- } //close the handle
- }else{
- ErrorCode=GetLastError();
- result= -1;
- if(ErrorCode == ERROR_NO_MORE_ITEMS){
- cout<<"Bluetooth Module not enabled !"<<endl;
- result= 0;
- }else
- cout<<"Bluetooth Radio search failed with error code"<< ErrorCode<<endl;
- }
- return result;
- }
- bool FindBtDev(BLUETOOTH_DEVICE_INFO *desired_device_info){
- //======================Handles============================================================
- HBLUETOOTH_RADIO_FIND m_bt;
- HBLUETOOTH_DEVICE_FIND m_bt_dev ;
- //==========================================================================================
- //================VAriables=================================================================
- int m_radio_id;
- int m_device_id;
- DWORD mbtinfo_ret;
- bool FuncResult=false;
- //=================================================================================================
- //=======================Struct=====================================================================
- BLUETOOTH_FIND_RADIO_PARAMS m_bt_find_radio = {sizeof(BLUETOOTH_FIND_RADIO_PARAMS)};
- BLUETOOTH_RADIO_INFO m_bt_info = {sizeof(BLUETOOTH_RADIO_INFO),0,};
- BLUETOOTH_DEVICE_SEARCH_PARAMS m_search_params = {
- sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS),
- 1,
- 0,
- 1,
- 1,
- 1,
- 15,
- NULL};
- BLUETOOTH_DEVICE_INFO m_device_info = {sizeof(BLUETOOTH_DEVICE_INFO),0,};
- //================================================================================================
- // Iterate for available bluetooth radio devices in range
- // Starting from the local
- m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &m_radio);
- if(m_bt == NULL){
- //cout<<"Bluetooth Radio Found !"<<endl;
- cout<<"Bluetooth Radio failed with error code"<< GetLastError()<<endl;
- FuncResult= false;
- }
- m_radio_id = 0;
- do {
- // Then get the radio device info....
- mbtinfo_ret = BluetoothGetRadioInfo(m_radio, &m_bt_info);
- if(mbtinfo_ret == ERROR_SUCCESS)
- cout<<"Bluetooth Radio looks fine!"<<endl;
- else{
- cout<<"BluetoothGetRadioInfo() failed wit error code "<< mbtinfo_ret<<endl;
- FuncResult= false;
- }
- //commented out radio information i dont need.
- /*wprintf(L"Radio %d:\r\n", m_radio_id);
- wprintf(L"\tInstance Name: %s\r\n", m_bt_info.szName);
- wprintf(L"\tAddress: %02X:%02X:%02X:%02X:%02X:%02X\r\n", m_bt_info.address.rgBytes[5],
- m_bt_info.address.rgBytes[4], m_bt_info.address.rgBytes[3], m_bt_info.address.rgBytes[2],
- m_bt_info.address.rgBytes[1], m_bt_info.address.rgBytes[0]);
- wprintf(L"\tClass: 0x%08x\r\n", m_bt_info.ulClassofDevice);
- wprintf(L"\tManufacturer: 0x%04x\r\n", m_bt_info.manufacturer);*/
- m_search_params.hRadio = m_radio;
- ZeroMemory(&m_device_info, sizeof(BLUETOOTH_DEVICE_INFO));
- m_device_info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
- // Next for every radio, get the device
- m_bt_dev = BluetoothFindFirstDevice(&m_search_params, &m_device_info);
- if(m_bt_dev != NULL)
- cout<<"BluetoothFindFirstDevice() is working!"<<endl;
- else{
- cout<<"Failed to find Devices with error code: "<<GetLastError()<<endl;
- FuncResult= false;
- }
- m_radio_id++;
- m_device_id = 0;
- //Get the device info
- do
- {
- //-----this list all the bluetooth devices nearby, this can be commented out.
- wprintf(L"\n\tDevice %d:\r\n", m_device_id);
- wprintf(L" \tInstance Name: %s\r\n", m_device_info.szName);
- wprintf(L" \tAddress: %02X:%02X:%02X:%02X:%02X:%02X\r\n", m_device_info.Address.rgBytes[5],
- m_device_info.Address.rgBytes[4], m_device_info.Address.rgBytes[3], m_device_info.Address.rgBytes[2],
- m_device_info.Address.rgBytes[1], m_device_info.Address.rgBytes[0]);
- wprintf(L" \tClass: 0x%08x\r\n", m_device_info.ulClassofDevice);
- wprintf(L" \tConnected: %s\r\n", m_device_info.fConnected ? L"true" : L"false");
- wprintf(L" \tAuthenticated: %s\r\n", m_device_info.fAuthenticated ? L"true" : L"false");
- wprintf(L" \tRemembered: %s\r\n", m_device_info.fRemembered ? L"true" : L"false");
- m_device_id++;
- //------------------------------------------------------------------------
- if(wcscmp(m_device_info.szName,L"HC-05")==0) //this search specifically for hc-05 bluetooth module.
- {
- *desired_device_info=m_device_info;
- FuncResult= true;
- break;
- }else{
- FuncResult= false;
- }
- } while(BluetoothFindNextDevice(m_bt_dev, &m_device_info));
- // NO more device, close the device handle
- if(BluetoothFindDeviceClose(m_bt_dev) == TRUE)
- cout<<"BluetoothFindDeviceClose(m_bt_dev) is OK!"<<endl;
- else{
- cout<<"BluetoothFindDeviceClose(m_bt_dev) failed with error code "<< GetLastError()<<endl;
- FuncResult= false;
- }
- } while(BluetoothFindNextRadio(&m_bt_find_radio, &m_radio));
- // No more radio, close the radio handle
- if(BluetoothFindRadioClose(m_bt) == TRUE)
- cout<<"BluetoothFindRadioClose(m_bt) is OK!"<<endl;
- else{
- cout<<"BluetoothFindRadioClose(m_bt) failed with error code "<< GetLastError()<<endl;
- FuncResult= false;
- }
- return FuncResult;
- }
- 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);
- }
Add Comment
Please, Sign In to add comment