[Bluetooth] - How to Host a RFCOMM Service in C++

Introduction

Bluetooth is an industry-standard protocol that enables wireless connectivity for computers, handheld devices, mobile phones, and other devices.

RFCOMM emulates RS-232 (ITU-T V.24) serial ports. The emulation includes transfer of the state of the non-data circuits. RFCOMM has a built-in scheme for null modem emulation.

Service Definition Model

 

 

This blog will introduce how to use Windows Sockets functions to host a Bluetooth RFCOMM service, and use the Windows Runtime API to consume this service.

Steps:

#1 ask for Windows Sockets API (WSA) 2.2

The socket initialization only be required once for one process, so I put the initialization code in a static function.

#2 create a Windows socket

#3 create a Bluetooth address and bind to Windows socket

#4 register a Bluetooth service (SDP)

#5 listen to the Windows socket

 

# CODE #

RFCOMM Server (C++):

 #include "stdafx.h"
#include "Winsock.h"
#include <WinSock2.h>
#include <ws2bth.h>
#include <bthsdpdef.h>
#include <bluetoothapis.h>

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "irprops.lib")

int main()
{
 if (!Winsock::InitialzedForCurrentProcess())
  {
       return 1;
   }

   Winsock winsock = Winsock(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

   if (!winsock.IsValid())
    {
       return 1;
   }

   winsock.Bind();

 winsock.Listen();

   winsock.RegisterServcie(_T("RFCOMM Server Demo Instance"), _T("Pushing data to PC"), OBEXObjectPushServiceClass_UUID);

  winsock.OnConnected([](SOCKET s){
       char buffer[1024] = { 0 };

     memset(buffer, 0, sizeof(buffer));

      int r = 0;

     do
      {
           r = recv(s, (char*)buffer, sizeof(buffer), 0);

            printf("result:%d, %s\n", r, buffer);

        } while (r != 0);

      closesocket(s);
 });

 winsock.Accept();

   WSACleanup();

    return 0;
}

Code on Github: https://github.com/dream-365/winapp/tree/master/BluetoothPlay