Application to run on a Windows 7 PC to connect to a phone and can dial, answer or hangup

Topics: Bluetooth - Microsoft
Sep 14, 2012 at 5:20 PM
Edited Sep 14, 2012 at 5:23 PM
Hello,

I need to make an application to run on a Windows 7 PC with a Microsoft Bluetooth stack, wich connects to a phone and can dial, answer or hangup. The application needs to behave like an hands free device.
I need to get events from the phone, for example, when i make a call (ATDxxxxxxxxx\r) i need to know if the call has been started with success, the other side answers it, or if it fails.

I've made the following approach:

Connect to the device using the Handsfree profile:

var bluetoothAddress = new BluetoothAddress(251445135662948);
var bluetoothClient = bluetoothRadio.StackFactory.CreateBluetoothClient();
if (!bluetoothClient.Connected)
	bluetoothClient.Connect(bluetoothAddress, BluetoothService.Handsfree);
var bluetoothStream = bluetoothClient.GetStream();

Send the CMER command to have the +CIEV unsolicited events:

const string atCmer = "AT+CMER=3,0,0,1\r";
var cmdBytes = Encoding.ASCII.GetBytes(cmdStr);
bluetoothStream.Write(cmdBytes, 0, cmdBytes.Length);

Listen to the stream for the +CIEV events to know what is happening:

public void DoRead(NetworkStream bluetoothStream)
{
	var theBuffer = new byte[1024];
	try
	{
		bluetoothStream.BeginRead(theBuffer, 0, theBuffer.Length, BeginReadCallBack, new BluetoothStreamReaderAsyncHelper { TheBuffer = theBuffer, TheStream = bluetoothStream });
	}
	catch (Exception ex)
	{
		Log.Error(ex);
		throw;
	}	
}

private void BeginReadCallBack(IAsyncResult ar)
{
	try
	{                
		var theHelper = ar.AsyncState as BluetoothStreamReaderAsyncHelper;

		if (theHelper == null) return;
		var endRead = theHelper.TheStream.EndRead(ar);
		var theResponseString = Encoding.ASCII.GetString(theHelper.TheBuffer, 0, endRead);
		FireEvent(theResponseString);

		if (!_stopRead)                    
			DoRead(theHelper.TheStream);
	}
	catch (Exception ex)
	{
		Log.Error(ex);
		throw;
	}            
}

Is this the right way to do this? Or is there any other way to listen to those events.
The problem is i'me getting some erratic behavior, sometimes the ATDxxxxxxxx\r, AT+CHUP\r or ATA\r  commands responds ok, some other times error. Sometimes it blocks writing the ATD command to the stream.

Thanks in advance,
João Capelo.