pshaw
Posts: 7
Joined: Mon Dec 08, 2008 8:21 pm
Location: USA

EndWrite must be called error

Mon Mar 08, 2010 3:59 am

I am trying to send 2 commands to a bluetooth device but get the error message "You must call EndWrite() after BeginWrite()". This is my code that I have been trying to debug for weeks. It looks like other code posted in the forum so I don't know what is missing. Can anyone see the problem? Thank you

private void dgSavedDevices_TextBoxEdit(object sender, Resco.Controls.SmartGrid.TextBoxEditEventArgs e)
{
try
{
AsyncCallback callback;

Franson.Guide.SharedNetwork sharedNetwork = SharedNetwork.GetSharedNetwork();

string sServiceName = "Serial Interface";
string sBTAddr = Convert.ToString(e.Cell.Row["BT_Address"].ToString());
string strDeviceName = Convert.ToString(e.Cell.Row["Friendly_Name"].ToString());
string strNewFriendlyName = "" + e.NewText + "";

int iChannel = 1; //Bluetools supports only one channel, and it appears to have to be set to 1

try
{
RemoteDevice StartPac = sharedNetwork.Network.ConnectDevice(new Address(sBTAddr), strDeviceName);
RemoteService currentService = StartPac.ConnectService(iChannel, sServiceName);
Stream currentStream = null;
System.Text.ASCIIEncoding asc = new ASCIIEncoding();

currentStream = currentService.Stream;

string strNewName = "HELLO " + "\r\n";
currentStream.BeginWrite(asc.GetBytes(strNewName), 0, strNewName.Length, new AsyncCallback(writeCallback), currentStream);

strNewName = "FRIENDLYNAME " + e.NewText.ToString() + "\r\n";
currentStream.BeginWrite(asc.GetBytes(strNewName), 0, strNewName.Length, new AsyncCallback(writeCallback), currentStream);

}
catch (Exception ex)
{
MessageBox.Show("dgSavedDevices_TextBoxEdit - " + e.NewText.ToString() + " - " + ex.Message.ToString());
}
}

public void writeCallback(IAsyncResult result)
{
System.IO.Stream selectedStream = (System.IO.Stream)result.AsyncState;

try
{
// EndWrite() must always be called if BegineWrite() was used!
selectedStream.EndWrite(result);
}
catch (ObjectDisposedException ex)
{
// Thrown if stream has been closed.
MessageBox.Show(ex.Message);
}
}

Jonas
Posts: 2319
Joined: Mon Jan 09, 2006 2:20 pm
Location: Sweden

RE: EndWrite must be called error

Tue Mar 09, 2010 7:41 pm

It's not working because you are doing this:

Code: Select all

currentStream.BeginWrite(asc.GetBytes(strNewName), 0, strNewName.Length, new AsyncCallback(writeCallback), currentStream);

strNewName = "FRIENDLYNAME " + e.NewText.ToString() + "\r\n";
currentStream.BeginWrite(asc.GetBytes(strNewName), 0, strNewName.Length, new AsyncCallback(writeCallback), currentStream);
The first BeginWrite isn't finished before you execute the next one.

Regards,
Jonas

Return to “BlueTools”