none
Crash when connecting to Bluetooth device via Socket (Access violation reading location 0x00000004) RRS feed

  • Question

  • Hi,
    I think you are my last hope. I have got here a Bluetooth device (it is a sensor to be more precisely) which I want to connect to and read data from. The device offers SPP (Serial Port Profile). To avoid the problem of reliable mapping from Bluetooth addresses and virtual serial ports (COM Ports), I am going to use sockets.
    Unfortunately the application always crashes before returning from WinAPI function connect(...) with:  0xC0000005: Access violation reading location 0x00000004, so I get no error code.
    BUT, and that is weird, when I right-click on the Bluetooth System Tray Icon to to show available devices, my device shows up being authenticated and connected. This list was empty before, of course. 
    My OS is Windows 7 64 Bit, the IDE is Visual Studio 2010, Microsoft Bluetooth Stack. Code to find and connect to my only device:
     
    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <cassert>
    
    #define WIN32_LEAN_AND_MEAN
    
    #include <Windows.h>
    #include <BluetoothAPIs.h>
    #include <Winsock2.h>
    #include <Ws2bth.h>
    
    
    
    BOOL auth_callback_ex(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS authParams)
    {
    	BLUETOOTH_AUTHENTICATE_RESPONSE response;
    	response.bthAddressRemote = authParams->deviceInfo.Address;
    	response.authMethod = authParams->authenticationMethod; // == BLUETOOTH_AUTHENTICATION_METHOD_LEGACY
    	
    	UCHAR pin[] = "1234";
    	std::copy(pin, pin+sizeof(pin), response.pinInfo.pin);
    	response.pinInfo.pinLength = sizeof(pin)-1;	//excluding '\0'
    
    	response.negativeResponse = false;
    
    
    	HRESULT err = BluetoothSendAuthenticationResponseEx(NULL, &response);
    	if (err)
    	{
    		std::cout << "BluetoothSendAuthenticationResponseEx error = " << err << std::endl;
    	}
    
    	return true;
    }
    
    
    int main()
    {
    	BLUETOOTH_DEVICE_SEARCH_PARAMS btSearchParams;
    
    	btSearchParams.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    	btSearchParams.cTimeoutMultiplier = 5;	//5*1.28s search timeout
    	btSearchParams.fIssueInquiry = true;	//new inquiry
    	
    	//return all known and unknown devices
    	btSearchParams.fReturnAuthenticated = true;
    	btSearchParams.fReturnConnected = true;
    	btSearchParams.fReturnRemembered = true;
    	btSearchParams.fReturnUnknown = true;
    	
    	btSearchParams.hRadio = NULL;	//search on all local radios
    
    
    
    	BLUETOOTH_DEVICE_INFO btDeviceInfo;
    	ZeroMemory(&btDeviceInfo, sizeof(BLUETOOTH_DEVICE_INFO));	//"initialize"
    	
    	btDeviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
    
    	HBLUETOOTH_DEVICE_FIND btDeviceFindHandle = NULL;
    	
    	btDeviceFindHandle = BluetoothFindFirstDevice(&btSearchParams, &btDeviceInfo);
    	if(btDeviceFindHandle)
    	{
    		
    		HBLUETOOTH_AUTHENTICATION_REGISTRATION authCallbackHandle = NULL;
    	
    		DWORD err = BluetoothRegisterForAuthenticationEx(&btDeviceInfo, &authCallbackHandle, &auth_callback_ex, NULL);
    
    		
    		if (err != ERROR_SUCCESS)
    		{
    			DWORD err = GetLastError();
    			std::cout << "BluetoothRegisterForAuthentication Error" << err << std::endl; 
    		}
    
    		/////////////// Socket
    		WSADATA wsaData;
    		err = WSAStartup(MAKEWORD(2,2), &wsaData);
    		if (err)
    		{
    			std::cout << "WSAStartup error = " << err << std::endl;
    		}
    		
    		
    		// create BT socket
    		SOCKET s = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
    		assert(s != INVALID_SOCKET);	//WSAGetLastError //throw // runtime check release?
    
    		SOCKADDR_BTH btSockAddr;
    		btSockAddr.addressFamily = AF_BTH;
    		btSockAddr.btAddr = btDeviceInfo.Address.ullLong;
    		btSockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; //SerialPortServiceClass_UUID (no difference)
    		btSockAddr.port = BT_PORT_ANY;
    
    
    		err = connect(s, reinterpret_cast<SOCKADDR*>(&btSockAddr), sizeof(SOCKADDR_BTH));
    		
    		/* <--- never got so far --> */
    		
    		if (err)
    		{
    			DWORD wsaErr = WSAGetLastError();
    			std::cout << "connect error = " << wsaErr << std::endl;
    			
    		}
    		else
    		{
    			//err = shutdown(s, SD_BOTH);
    		
    			err = closesocket(s);
    			if (err)
    			{
    				std::cout << "closesocket error = " << err << std::endl;
    			}
    		}
    
    		WSACleanup();
    		///////////////Socket
    
    
    		BOOL ok = BluetoothUnregisterAuthentication(authCallbackHandle);
    		if (!ok)
    		{
    			DWORD err = GetLastError();
    			std::cout << "BluetoothUnregisterAuthentication Error" << err << std::endl; 
    		}
    
    
    
    		ok = BluetoothFindDeviceClose(btDeviceFindHandle);
    		if (!ok)
    		{
    			DWORD err = GetLastError();
    			std::cout << "BluetoothDeviceClose Error" << err << std::endl; 
    		}
    	}
    	else
    	{
    		DWORD err = GetLastError();
    		std::cout << "BluetoothFindFirstDevice Error" << err << std::endl; 
    	}
    
    
    	std::cin.get();
    }
    

    I made a few more observations:
    • The authentication callback and the BluetoothSendAuthenticationResponseEx function are working fine, there is no error given back.
    • If I do not install the authentication callback (BluetoothRegisterForAuthenticationEx) and therefore have to manually enter the PIN (the UI shows up while trying to connect), connect function returns properly and everything works fine, too. I even got data (the recv part is omitted in this snippet). 
    • If I search and pair completely manually (Bluetooth Tray Icon -> Add Device), everything is fine, too. A service and a virtual serial port is installed. Data come via putty.
    So somewhere between calling the authentication callback and end of the connect function something is going wrong. Maybe when trying to get a certain structure data via a pointer, which should not be NULL, plus offset.

     

    Or am I doing something wrong? Is there something missing?

    Thanks...
     
    • Moved by Rob Pan Friday, July 1, 2011 2:40 AM for better support (From:Visual C++ General)
    Wednesday, June 29, 2011 5:02 PM

Answers

  • Thanks to stackoverflow I found a solution. There is a bug in the "BluetoothAPIs.h" header. The calling convention of PFN_AUTHENTICATION_CALLBACK_EX Callback Function must be CALLBACK (= __stdcall).
    • Marked as answer by WDev Sunday, July 3, 2011 10:47 AM
    Sunday, July 3, 2011 10:47 AM

All replies

  • Hi,

    According to your description, it seems that your thread is about Windows Socket. So I will move it to the correct forum for better support. Thanks for your understanding.

     

    Best Regards,

    Rob


    Rob Pan [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, July 1, 2011 2:39 AM
  • That is perfectly okay ;-)
    Saturday, July 2, 2011 5:07 PM
  • Thanks to stackoverflow I found a solution. There is a bug in the "BluetoothAPIs.h" header. The calling convention of PFN_AUTHENTICATION_CALLBACK_EX Callback Function must be CALLBACK (= __stdcall).
    • Marked as answer by WDev Sunday, July 3, 2011 10:47 AM
    Sunday, July 3, 2011 10:47 AM