基本信息
源码名称:c++蓝牙示例代码
源码大小:0.14M
文件格式:.rar
开发语言:C/C++
更新时间:2024-09-18
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
BlueToothTest

#include "StdAfx.h"
#include <ws2bth.h>
#include "BlueTooth.h"

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

CBlueTooth::CBlueTooth()
{    
}

CBlueTooth::~CBlueTooth()
{
    RemoveAllLocalDev();
	RemoveAllRemoteDev();
}

/******************************************************************************\
用 Socket 函数搜索附近的蓝牙设备,成功时返回设备数,否则返回-1
\******************************************************************************/
int CBlueTooth::ScanBySocket()
{
	RemoveAllRemoteDev();

	WSAQUERYSET wsaq;
	HANDLE      hLookup =   NULL;
	union
	{
		CHAR buf[5000];
		double __unused; // ensure proper alignment
	};

	LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
	DWORD dwSize = sizeof(buf);
    memset(&wsaq,0,sizeof(wsaq));
	wsaq.dwSize = sizeof(wsaq);
	wsaq.dwNameSpace = NS_BTH;
	wsaq.lpcsaBuffer = NULL;
	if (ERROR_SUCCESS != WSALookupServiceBegin (&wsaq, LUP_CONTAINERS, &hLookup))
	{
		return -1;
	}
	ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
	pwsaResults->dwSize = sizeof(WSAQUERYSET);
	pwsaResults->dwNameSpace = NS_BTH;
	pwsaResults->lpBlob = NULL;
	while (ERROR_SUCCESS == WSALookupServiceNext (hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaResults))
	{
		ASSERT (pwsaResults->dwNumberOfCsAddrs == 1);
		RemoteDev dev;		
		dev.Address =   ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;
        dev.sName   =   pwsaResults->lpszServiceInstanceName;
		m_arrRemote.Add(dev);
	}
	WSALookupServiceEnd(hLookup);
	return (int)m_arrRemote.GetSize();
}

//
// 用蓝牙 APIs 搜索附近的蓝牙设备,成功时返回设备数,否则返回-1
//
int CBlueTooth::Scan(HANDLE hRadio,BOOL fReturnAuthenticated,BOOL fReturnRemembered,BOOL fReturnUnknown
                    ,BOOL fReturnConnected,BOOL fIssueInquiry,UCHAR cTimeoutMultiplier)
{
	RemoveAllRemoteDev();
	BLUETOOTH_DEVICE_INFO           bdi =   { sizeof(BLUETOOTH_DEVICE_INFO) };
	BLUETOOTH_DEVICE_SEARCH_PARAMS  bdsp;

	ZeroMemory(&bdsp, sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS));
	bdsp.dwSize                 =   sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
	bdsp.hRadio                 =   hRadio;
	bdsp.fReturnAuthenticated   =   fReturnAuthenticated;
	bdsp.fReturnRemembered      =   fReturnRemembered;
	bdsp.fReturnUnknown         =   fReturnUnknown;
	bdsp.fReturnConnected       =   fReturnConnected;
	bdsp.fIssueInquiry          =   fIssueInquiry;
	bdsp.cTimeoutMultiplier     =   cTimeoutMultiplier;
    HBLUETOOTH_DEVICE_FIND  hbf =   BluetoothFindFirstDevice(&bdsp, &bdi);
	if(hbf == NULL)
    {
        return -1;
    }
	do
	{
		TRACE ( _T("%s ( %s )\n"), bdi.szName, AddrToStr(bdi.Address.rgBytes) );
		RemoteDev dev;
		dev.Address =   bdi.Address.ullLong;
        dev.sName   =   bdi.szName;
		m_arrRemote.Add(dev);
    }while(BluetoothFindNextDevice(hbf,&bdi));
	BluetoothFindDeviceClose(hbf);
	return m_arrRemote.GetSize();
}

//
// 用向导手工搜索附近的蓝牙设备并建立连接,得到设备的详细信息,成功时返回设备数
//
int CBlueTooth::ScanWithWnd(HWND	hwndParent
                            ,HANDLE hRadio
                            ,LPWSTR pszInfo
                            ,BOOL   fForceAuthentication
                            ,BOOL   fShowAuthenticated
                            ,BOOL   fShowRemembered
                            ,BOOL   fShowUnknown
                            ,BOOL   fAddNewDeviceWizard
                            ,BOOL   fSkipServicesPage
                            ,PFN_DEVICE_CALLBACK pfnDeviceCallback
                            ,LPVOID pvParam)
{
	RemoveAllRemoteDev ();
	BLUETOOTH_SELECT_DEVICE_PARAMS bsdp = { sizeof(bsdp) };
	bsdp.hwndParent             =   hwndParent;
	bsdp.pszInfo                =   pszInfo;
	bsdp.fForceAuthentication   =   fForceAuthentication;
	bsdp.fShowAuthenticated     =   fShowAuthenticated;
	bsdp.fShowRemembered        =   fShowRemembered;
	bsdp.fShowUnknown           =   fShowUnknown;
	bsdp.fAddNewDeviceWizard    =   fAddNewDeviceWizard;
	bsdp.fSkipServicesPage      =   fSkipServicesPage;
	bsdp.pfnDeviceCallback      =   pfnDeviceCallback;
	bsdp.pvParam                =   pvParam;

	if(BluetoothSelectDevices(&bsdp))
	{
		BLUETOOTH_DEVICE_INFO *bdi = bsdp.pDevices;
		for(ULONG cDevice = 0;cDevice < bsdp.cNumDevices;cDevice  )
		{
			//if(bdi->fAuthenticated || bdi->fRemembered)
			{
				RemoteDev dev;
				dev.Address = bdi->Address.ullLong;
                dev.sName   =   bdi->szName;
				m_arrRemote.Add(dev);
			}
			bdi   =   (BLUETOOTH_DEVICE_INFO*)((LPBYTE)bdi   bdi->dwSize);
		}
		BluetoothSelectDevicesFree( &bsdp );
	}

	return (int)m_arrRemote.GetSize();
}

/******************************************************************************\
获取字符串形式的蓝牙地址
蓝牙地址 BLUETOOTH_ADDRESS 定义如下
union
{
    BTH_ADDR ullLong;
    BYTE     rgBytes[6];
};
BTH_ADDR 是一个 64 位的整数
假定蓝牙地址为 12:34:56:78:9A:BC 则 ullLong 为 0x0000123456789ABC
rgBytes 的内容为 BC 9A 78 56 34 12
\******************************************************************************/
CString CBlueTooth::AddrToStr(const void*pAddr)
{
    CString sAddress;
    if(pAddr)
    {
	    BLUETOOTH_ADDRESS Address;
	    int         nBytes  =   sizeof(Address.rgBytes);
        TCHAR       szByte[8];
        const BYTE* pByte   =   (const BYTE*)pAddr   (nBytes - 1);

	    for(int i = 0;i < nBytes;i  )
	    {
            _stprintf_s(szByte,_T(":%02x"),*pByte--);
            sAddress    =   i ? szByte : (szByte   1);
	    }
    }
	return sAddress;
}

/******************************************************************************\
枚举本地所有蓝牙设备到 m_arrLocal,返回本地蓝牙设备数
\******************************************************************************/
int CBlueTooth::EnumLocalDev()
{
	RemoveAllLocalDev();

	HANDLE                      hRadio  =   NULL;
	BLUETOOTH_FIND_RADIO_PARAMS bfrp    =   {sizeof(bfrp)};
	HBLUETOOTH_RADIO_FIND       hFind   =   BluetoothFindFirstRadio(&bfrp,&hRadio);

	if(hFind)
	{
		do{
			if(hRadio)
			{
                m_arrLocal.Add(hRadio);
			}
		}while(BluetoothFindNextRadio(hFind,&hRadio));
		BluetoothFindRadioClose(hFind);
	}
	return (int)m_arrLocal.GetSize();
}

/******************************************************************************\
删除 m_arrLocal 内的所有本地蓝牙设备
\******************************************************************************/
void CBlueTooth::RemoveAllLocalDev()
{
	for(int i = m_arrLocal.GetUpperBound();i >= 0;--i)
	{
		const HANDLE&hRadio =   m_arrLocal[i];
		if(hRadio)
        {
            CloseHandle(hRadio);
        }
	}
	m_arrLocal.RemoveAll();
}

/******************************************************************************\
删除 m_arrRemote 内的所有远程蓝牙设备
\******************************************************************************/
void CBlueTooth::RemoveAllRemoteDev()
{
	m_arrRemote.RemoveAll();
}
int CBlueTooth::Connect(BTH_ADDR sktAddr, ULONG port, int nMSecond/* = -1*/)
{
	SOCKADDR_BTH sa = { 0 };
	sa.addressFamily = AF_BTH;
	sa.btAddr = sktAddr;
	sa.port = port;

	if (nMSecond == -1)
	{
		return connect(m_hSocket, (LPSOCKADDR)&sa, sizeof(SOCKADDR_BTH));
	}

	ULONG non_blocking = 1;
	ULONG blocking = 0;

	int nResult = ioctlsocket(m_hSocket, FIONBIO, &non_blocking);
	if (nResult == SOCKET_ERROR)
	{
		return nResult;
	}

	nResult = SOCKET_ERROR;
	if (connect(m_hSocket, (LPSOCKADDR)&sa, sizeof(SOCKADDR_BTH)) == SOCKET_ERROR)
	{
		struct timeval tv;
		fd_set writefds;

		// 设置连接超时时间
		tv.tv_sec = nMSecond / 1000; // 秒数
		tv.tv_usec = nMSecond % 1000; // 毫秒

		FD_ZERO(&writefds);
		FD_SET(m_hSocket, &writefds);

		nResult = select((int)m_hSocket   1, NULL, &writefds, NULL, &tv);
		if (nResult > 0)
		{
			if (FD_ISSET(m_hSocket, &writefds))
			{
				int error = 0;
				int len = sizeof(error);
				//下面的一句一定要,主要针对防火墙 
				if (!(getsockopt(m_hSocket, SOL_SOCKET, SO_ERROR, (char *)&error, &len) != 0 || error != 0))
				{
					nResult = 0;
				}
			}
		}
		else if (nResult == 0)
		{
			nResult = -2;
		}
	}

	if (ioctlsocket(m_hSocket, FIONBIO, &blocking) == SOCKET_ERROR)
	{
		nResult = SOCKET_ERROR;
	}
	return nResult;
}