Windows列舉搜尋遠端藍芽裝置
阿新 • • 發佈:2019-02-09
主要使用微軟自帶的藍芽API,注意使用的藍芽介面卡應當使用的是微軟自帶的藍芽驅動(可以通過裝置和印表機介面新增遠端藍芽裝置即表示可以使用windows藍芽api,此時安裝的藍芽裝置會在裝置管理器中顯示為Bluetooth連結上的標準序列 ),否則這些api會不起作用。主要程式碼如下:
//本程式碼展示了在windows上搜索所有藍芽收發器可以搜尋到的遠端藍芽裝置 #include <windows.h> #include <BluetoothAPIs.h> #include <conio.h> #include <iostream> #include <string> #include <locale> #pragma comment(lib,"Bthprops.lib") using namespace std; int main(void) { wcout.imbue(locale("")); HBLUETOOTH_RADIO_FIND hbf = NULL; HANDLE hbr = NULL; HBLUETOOTH_DEVICE_FIND hbdf = NULL; BLUETOOTH_FIND_RADIO_PARAMS btfrp = { sizeof(BLUETOOTH_FIND_RADIO_PARAMS) }; //呼叫BluetoothFindFirstDevice搜尋本機藍芽收發器所需要的搜尋引數物件 BLUETOOTH_RADIO_INFO bri = { sizeof(BLUETOOTH_RADIO_INFO)}; //初始化一個儲存藍芽收發器資訊(BLUETOOTH_RADIO_INFO)的物件bri BLUETOOTH_DEVICE_SEARCH_PARAMS btsp = { sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS) };//呼叫BluetoothFindFirstDevice搜尋本所需要的搜尋引數物件 BLUETOOTH_DEVICE_INFO btdi = { sizeof(BLUETOOTH_DEVICE_INFO) }; //初始化一個遠端藍芽裝置資訊(BLUETOOTH_DEVICE_INFO)物件btdi,以儲存搜尋到的藍芽裝置資訊 hbf=BluetoothFindFirstRadio(&btfrp, &hbr); //得到第一個被列舉的藍芽收發器的控制代碼hbf可用於BluetoothFindNextRadio,hbr可用於BluetoothFindFirstDevice。若沒有找到本機的藍芽收發器,則得到的控制代碼hbf=NULL,具體可參考https://msdn.microsoft.com/en-us/library/aa362786(v=vs.85).aspx bool brfind = hbf != NULL; while (brfind) { if (BluetoothGetRadioInfo(hbr, &bri) == ERROR_SUCCESS)//獲取藍芽收發器的資訊,儲存在bri中 { cout << "Class of device: 0x" << uppercase << hex << bri.ulClassofDevice << endl; wcout <<"Name:"<< bri.szName << endl; //藍芽收發器的名字 cout <<"Manufacture:0x"<< uppercase << hex << bri.manufacturer << endl; cout << "Subversion:0x" << uppercase << hex << bri.lmpSubversion << endl; // btsp.hRadio = hbr; //設定執行搜尋裝置所在的控制代碼,應設為執行BluetoothFindFirstRadio函式所得到的控制代碼 btsp.fReturnAuthenticated = TRUE;//是否搜尋已配對的裝置 btsp.fReturnConnected = FALSE;//是否搜尋已連線的裝置 btsp.fReturnRemembered = TRUE;//是否搜尋已記憶的裝置 btsp.fReturnUnknown = TRUE;//是否搜尋未知裝置 btsp.fIssueInquiry=TRUE;//是否重新搜尋,True的時候會執行新的搜尋,時間較長,FALSE的時候會直接返回上次的搜尋結果。 btsp.cTimeoutMultiplier = 30;//指示查詢超時的值,以1.28秒為增量。 例如,12.8秒的查詢的cTimeoutMultiplier值為10.此成員的最大值為48.當使用大於48的值時,呼叫函式立即失敗並返回 hbdf=BluetoothFindFirstDevice(&btsp, &btdi);//通過找到第一個裝置得到的HBLUETOOTH_DEVICE_FIND控制代碼hbdf來列舉遠端藍芽裝置,搜到的第一個遠端藍芽裝置的資訊儲存在btdi物件中。若沒有遠端藍芽裝置,hdbf=NULL。 bool bfind = hbdf != NULL; while (bfind) { wcout << "[Name]:" << btdi.szName; //遠端藍芽裝置的名字 cout << ",[Address]:0x" << uppercase << hex << btdi.Address.ullLong << endl; bfind=BluetoothFindNextDevice(hbdf, &btdi);//通過BluetoothFindFirstDevice得到的HBLUETOOTH_DEVICE_FIND控制代碼來列舉搜尋下一個遠端藍芽裝置,並將遠端藍芽裝置的資訊儲存在btdi中 } BluetoothFindDeviceClose(hbdf);//使用完後記得關閉HBLUETOOTH_DEVICE_FIND控制代碼hbdf。 } CloseHandle(hbr); brfind=BluetoothFindNextRadio(hbf, &hbr);//通過BluetoothFindFirstRadio得到的HBLUETOOTH_RADIO_FIND控制代碼hbf來列舉搜尋下一個本地藍芽收發器,得到可用於BluetoothFindFirstDevice的控制代碼hbr。 } BluetoothFindRadioClose(hbf);//使用完後記得關閉HBLUETOOTH_RADIO_FIND控制代碼hbf。 cout<<"All listed"; _getch(); return 0; }