Wednesday 25 April 2007

Bluetooth (serial) SPP using Sockets...!

If you wondered how to connect to a BT serial device using SPP over sockets... heres how!

// create your BT socket
SOCKET s = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

// Create the connection information, this is the RFComm protocol for SPP
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.btAddr = device;
sa.port = BT_PORT_ANY;
sa.serviceClassId = RFCOMM_PROTOCOL_UUID;
// connect...
connect (s, (SOCKADDR *)&sa, sizeof(sa))


Once connected you can use send/recieve to send over the SPP connection:

send (connectedSocket, (char*)str, len,0)
recv( connectedSocket, str, len,0)

This way you don't have to map serial ports, this was tested on Windows XP but should also work on windows CE.

It was tested printing GPS information from a TOMTOM reciever.

9 comments:

noel said...

i need to know what is "device" in your code.

sa.btAddr = device;

thanks

GraemeW said...

BT_ADDR device;

Which is basically a 64 bit unsigned (a longlong)

typedef ULONGLONG bt_addr, *pbt_addr, BT_ADDR, *PBT_ADDR;

Anonymous said...

It says
error LNK2001: unresolved external symbol RFCOMM_PROTOCOL_UUID

GraemeW said...

Building against Win32 or WinCE ?

From bthdef.h the GUID is defined as:

DEFINE_GUID(RFCOMM_PROTOCOL_UUID, 0x00000003, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB);

Anonymous said...

Thanks for reply.
I'm using Windows CE 5.0.

One more question:

Can I use sockets in such way for establishing bluetooth dun connection , or I must create virtual serial port and create mapping of bluetooth modem to this port?

GraemeW said...

You could dial a data connection, but then you'd just have a direct data feed but very useful, make a virtual serial connection and use RAS to dial it up using the normal *99# to get a data connection, then the IP stack will be attached to the data feed afterwards.

GraemeW said...

Also for WinCE I defined the GUID in my app:

GUID RFCOMM_PROTOCOL_UUID = {0x00000003, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};

QuickOK said...

Would this work on Windows Mobile? My company uses the Intermec SF51 bluetooth barcode scanner and I have an LXE 8650 that uses SPP instead of sockets. This looks like it would fit the bill if I could somehow get it to work.

GraemeW said...

yes it should work, you will need to turn on bluetooth through winmo apis if it turned off but otherwise yes it should be the same as CE