Search code examples
c#bluetooth32feet

Exception when connecting to device


I have a problem with connection to my Bluetooth device (HC-05). When call BluetoothClient.Connect(), sometimes exception occures - "An invalid argument was supplied.", or another. But sometimes device connects (usually at first connection)! Do I have to close connection when I leave app?


Solution

  • Yes you should close the connection and dispose the BluetoothClient.

    private InTheHand.Net.Sockets.BluetoothClient BTClient = 
    new InTheHand.Net.Sockets.BluetoothClient(); 
    private System.Net.Sockets.NetworkStream stream;
    

    //Somewhere on the code:

    stream = BTClient.GetStream();
    
    
    
    public void Disconnect()
        {
                if (BTClient == null )
                    return;
    
                try
                {
    
                    if (BTClient != null)
                    {
                        if (stream != null)
                        {
                            stream.ReadTimeout = 500;
                            stream.WriteTimeout = 500;
                            stream.Close();
                        }
    
                        if(BTClient.Connected)
                            BTClient.Close();
                        BTClient.Dispose();                        
                    }
    
    
                }
                catch (Exception ex)
                {
                    throw ex;
                } 
    
        }