基于Windows的蓝牙虚拟串口通信

一、枚举本地蓝牙设备

/******************************************************************************\
枚举本地所有蓝牙设备到 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();
}

二、搜索远程蓝牙设备

//
// 用蓝牙 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 nSelLocal   =   0;
        int nSelRemote  =   0;
        BLUETOOTH_DEVICE_INFO bdi;
        if(!GetSomeInfo(&nSelLocal,&nSelRemote,&bdi))
        {
            return;
        }
        CDlgPairSend dlg;
        dlg.m_sLocal    =   m_ListLocal. GetItemText(nSelLocal ,0) + _T(" - ") + m_ListLocal .GetItemText(nSelLocal ,1);
        dlg.m_sRemote   =   m_ListRemote.GetItemText(nSelRemote,0) + _T(" - ") + m_ListRemote.GetItemText(nSelRemote,1);
        if(dlg.DoModal() == IDOK)
        {

            int     nLenW   =   MultiByteToWideChar(CP_ACP,0,dlg.m_sPwd,dlg.m_sPwd.GetLength(),NULL,0);
            wchar_t*wzPwd   =   new wchar_t[nLenW + 1];
            MultiByteToWideChar(CP_ACP,0,dlg.m_sPwd,dlg.m_sPwd.GetLength(),wzPwd,nLenW);

            t_RemoteBthDevInfo RemoteBthDevInfo;
            RemoteBthDevInfo.Address.ullLong = bdi.Address.ullLong;
            m_BlueTooth.EnumerateInstalledServices ( RemoteBthDevInfo );

            if(BluetoothAuthenticateDevice(m_hWnd,m_BlueTooth.m_arrLocal[nSelLocal],&bdi,wzPwd,nLenW)==ERROR_SUCCESS)
            {
                MessageBox(_T("配对成功"));

            }
            else
            {
                MessageBox(_T("配对失败"));
            }
            delete[] wzPwd;

四、连接蓝牙设备,枚举串口,寻找蓝牙虚拟串口,发送握手指令 ,

        HKEY hKey;
        LPCTSTR lpSubKey="HARDWARE\\DEVICEMAP\\SERIALCOMM\\";

        if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &hKey)!= ERROR_SUCCESS)
        {
            return ;
        }

        char szValueName[NAME_LEN];
        BYTE szPortName[NAME_LEN];
        LONG status;
        DWORD dwIndex = 0;
        DWORD dwSizeValueName=100;
        DWORD dwSizeofPortName=100;
        DWORD Type;
        dwSizeValueName = NAME_LEN;
        dwSizeofPortName = NAME_LEN;
        do
        {
            status = RegEnumValue(hKey, dwIndex++, szValueName, &dwSizeValueName, NULL, &Type,
                szPortName, &dwSizeofPortName);
            if((status == ERROR_SUCCESS))
            {
                CString str;
                str=(char *)szPortName;
                m_SerialPort.SetCom(str);

                if (m_SerialPort.OpenConnection())
                { 
                    //发送指令,判断串口是否有回复,有回复即为蓝牙虚拟串口
                    unsigned char data[2]={0xa5,0x5a}; //握手
                    m_SerialPort.WriteComm(data,2);
                    
                    char *Buf=new char[10];
                    memset(Buf,0,10);
                    int nCount=0;
                    nCount=m_SerialPort.ReadComm(Buf,1);
                    byte bt=Buf[0];
                    if (bt==0xa5)
                    {
                        MessageBox(_T("连接成功"));
                        Start();
                        break;
                    }
                }
            }
            dwSizeValueName = NAME_LEN;
            dwSizeofPortName = NAME_LEN;
        } while((status!= ERROR_NO_MORE_ITEMS));
        RegCloseKey(hKey);

五、通过串口与远程蓝牙设备通信


源码参考:https://download.csdn.net/download/qq_23565865/10789156

在C#中使用蓝牙虚拟串口,你需要使用System.IO.Ports命名空间中的SerialPort类。但是,与传统串口不同,蓝牙串口需要使用RFCOMM协议进行通信。 首先,你需要确保你的计算机上已经安装了蓝牙适配器,并且已经成功地与目标设备进行了配对。 接下来,你需要在你的C#项目中添加System.IO.Ports命名空间。然后,你可以使用以下代码来设置蓝牙串口: ```csharp SerialPort bluetoothPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); bluetoothPort.PortName = "COM10"; // 更改为你的蓝牙串口的名称 bluetoothPort.BaudRate = 9600; // 更改为你的蓝牙串口的波特率 bluetoothPort.Parity = Parity.None; bluetoothPort.DataBits = 8; bluetoothPort.StopBits = StopBits.One; bluetoothPort.Handshake = Handshake.None; bluetoothPort.ReadTimeout = 500; bluetoothPort.WriteTimeout = 500; bluetoothPort.Open(); // 打开蓝牙串口 ``` 注意:在设置蓝牙串口之前,你需要找到你的蓝牙串口的名称。你可以在Windows设备管理器中找到它,或者在设备配对时记下它。 一旦你成功地打开了蓝牙串口,你就可以使用SerialPort类中的Read和Write方法来读取和写入数据。例如,以下代码将向蓝牙串口写入数据: ```csharp bluetoothPort.Write("Hello, Bluetooth!"); ``` 然后,你可以使用以下代码从蓝牙串口读取数据: ```csharp string message = bluetoothPort.ReadLine(); ``` 当你完成与蓝牙串口的通信后,记得关闭串口: ```csharp bluetoothPort.Close(); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值