/// Start the ConnectedThread to begin managing a Bluetooth connection
        public void Connected(BluetoothSocket socket, BluetoothDevice device, bool initiator)
        {
            lock (_locker)
            {
                #if DEBUG
                Log.Debug (Tag, "Connected");
                #endif

                // Cancel all the threads
                stopThreads();

                // Set the address of the device we are connected to
                _deviceAddress = device.Address;

                // Start the thread to manage the connection and perform transmissions
                _connectedThread = new ConnectedThread (socket, this);
                _connectedThread.Start ();

                if(initiator)
                    setState (StateEnum.Connected, (int) Network.ConnectionRole.Master);
                else
                    setState (StateEnum.Connected, (int) Network.ConnectionRole.Slave);
            }
        }
        private void stopThreads()
        {
            // Cancel the thread that completed the connection
            if (_connectThread != null)
            {
                _connectThread.Cancel ();
                _connectThread = null;
            }

            // Cancel any thread currently running a connection
            if (_connectedThread != null)
            {
                _connectedThread.Cancel ();
                _connectedThread = null;
            }

            // Cancel the accept thread because we only want to connect to one device
            if (_acceptThread != null)
            {
                _acceptThread.Cancel ();
                _acceptThread = null;
            }

            _deviceAddress = string.Empty;
        }
        /// Start the ConnectThread to initiate a connection to a remote device.
        public void Connect(BluetoothDevice device)
        {
            lock (_locker)
            {
                #if DEBUG
                Log.Debug (Tag, "Connecting to : " + device);
                #endif

                // Cancel any thread attempting to make a connection
                if (_state == StateEnum.Connecting)
                {
                    if (_connectThread != null) {
                        _connectThread.Cancel ();
                        _connectThread = null;
                    }
                }

                // Cancel any thread currently running a connection
                if (_connectedThread != null)
                {
                    _connectedThread.Cancel ();
                    _connectedThread = null;
                }

                // Start the thread to connect with the given device
                _connectThread = new ConnectThread (device, this);
                _connectThread.Start ();

                setState (StateEnum.Connecting);
            }
        }