Powered By Blogger
Wednesday, February 25, 2009

Monitoring for bluetooth events

Here is a sample code for monitoring incoming connection and authentication requests on a microsoft bluetooth stack:



DWORD BTActivityMonitor ( LPVOID lpParam )
{
MSGQUEUEOPTIONS mqOptions;
memset (&mqOptions, 0, sizeof(mqOptions));

mqOptions.dwFlags = 0;
mqOptions.dwSize = sizeof(mqOptions);
mqOptions.dwMaxMessages = 10;
mqOptions.cbMaxMessage = sizeof(BTEVENT);
mqOptions.bReadAccess = TRUE;

// Create message queue to receive BT events on
HANDLE hMsgQ = CreateMsgQueue(NULL, &mqOptions);
if (! hMsgQ) {
wprintf(L"Error creating message queue.\r\n");
goto exit_bt;
}

// Listen for all Bluetooth notifi cations
HANDLE hBTNotif = RequestBluetoothNotifications(
BTE_CLASS_CONNECTIONS | BTE_CLASS_DEVICE | BTE_CLASS_PAIRING,
hMsgQ);
if (! hBTNotif) {
wprintf(L"Error in call to RequestBluetoothNotifications.\r\n");
goto exit_bt;
}

wprintf(L"Waiting for Bluetooth notifications...\r\n");

while (FALSE == bStop) {
DWORD dwWait = WaitForSingleObject (hMsgQ, INFINITE);
if (WAIT_OBJECT_0 == dwWait) {
//
// We have got a Bluetooth event!
//

BTEVENT btEvent;
DWORD dwFlags = 0;
DWORD dwBytesRead = 0;

BOOL fRet = ReadMsgQueue (hMsgQ, &btEvent, sizeof(BTEVENT), &dwBytesRead, 10, &dwFlags);
if (! fRet) {
wprintf(L"Error - Failed to read message from queue!\r\n");
goto exit_bt;
} else {
wprintf(L"----------------------------------------\r\n");
wprintf(L"Got event with id=%d.\r\n", btEvent.dwEventId);
}
} else {
wprintf(L"Error - Unexpected return value from WaitForSingleObject!\r\n");
goto exit_bt;
}

}


exit_bt:
// Stop listening for Bluetooth notifications
if (hBTNotif && (! StopBluetoothNotifications(hBTNotif))) {
wprintf(L"Warning! StopBluetoothNotifications returned FALSE.\r\n");
}

if (hMsgQ) {
CloseMsgQueue(hMsgQ);
}

return 0;
}