2

I have a problem using In the Hand library for writing a byte and reading data from a bluetooth device Below you will find the simple code I use.

I discover the device, I pair the device, I create a local client connection and I connect to the device by

BluetoothEndPoint endPoint = new BluetoothEndPoint(addr, BluetoothService.SerialPort,1);
localClient.Connect(endPoint);

Everything is ok until I write the byte to the device, when I try to do that a red led should switch on the device but nothing happen....so I think that the byte has not been written.....

Anyway the code continue to run until

int n = stream.Read(newdata[kn], numBytesRead, 1);

here the code stops and wait an infinite time without any error....

What am I doing wrong ? Why the byte I send has not been written? Thank you for your help!

BluetoothClient localClient = new BluetoothClient();
BluetoothDeviceInfo[] dev;
BluetoothDeviceInfo td = null;

addr = BluetoothAddress.Parse(Addr);

dev = localClient.DiscoverDevices();
foreach (BluetoothDeviceInfo d in dev)
{                      
    if (d.DeviceName == "Device_name")//my device name
    {
        td = d;
        break;
    }
}

try
{
    addr = td.DeviceAddress;

    if (!BluetoothSecurity.PairRequest(addr, null)) 
    {
        Console.WriteLine("Request failed");
    }
}
catch (Exception e)
{
    Console.WriteLine("Exception : " + e.Message);
    Console.Read();
}

BluetoothEndPoint endPoint = new BluetoothEndPoint(addr, BluetoothService.SerialPort,1);
localClient.Connect(endPoint);

Console.WriteLine(localClient.Connected);
NetworkStream stream = localClient.GetStream();

string config = "";
config = "240";

if (stream.CanWrite)
{
     byte[] data_conf = System.Text.Encoding.ASCII.GetBytes(config);              
     stream.Write(data_conf , 0, data_conf .Length);
     stream.Flush();
 }

 System.Threading.Thread.Sleep(100);

 int numBytesToRead = newdata[0].Length;
 int numBytesRead = 0;
 int nBytesRead = 0; // number of bytes read on each cycle

 //stream.ReadTimeout = 5;
 try
 {
      ////////read incoming bytes
      while (numBytesToRead > 0)
      {                        
          int n = stream.Read(newdata[kn], numBytesRead, 1);
          numBytesRead += n;
          numBytesToRead -= n;
      }
 }
 catch (Exception ex)
 {
       Console.Write(ex.Message);
 }
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
user3872226
  • 21
  • 1
  • 3

0 Answers0