Beispiel #1
0
        private void BtnConnect_Click(object sender, EventArgs e)
        {
            if (adapter == null)
            {
                Toast.MakeText(Context, Resource.String.error_no_bluetooth, ToastLength.Long).Show();
                return;
            }

            if (!adapter.IsEnabled)
            {
                return;
            }

            BtnConnect.Enabled = false;

            ProgressBar.Visibility = ViewStates.Visible;

            if (adapter.IsDiscovering)
            {
                adapter.CancelDiscovery();
            }

            CheckBTPermission();

            adapter.StartDiscovery();
        }
Beispiel #2
0
        /**
         * Método para lanzar el escaneo de dispositivos BT
         * **/
        public async Task <List <string> > scanDevices()
        {
            if (bluetoothAdapter.IsDiscovering)
            {
                bluetoothAdapter.CancelDiscovery();
            }


            bluetoothAdapter.StartDiscovery();
            System.Console.WriteLine("Comienza el descubrimiento");
            Thread.Sleep(2000);
            List <string> list = new List <string>();

            await Task.Delay(8000);

            foreach (BluetoothDevice currentDevice in discoveredDevices)
            {
                // if (currentDevice.Name.Equals("OBDII")){
                list.Add(currentDevice.Address.ToString());
                // }
            }


            return(list);
        }
Beispiel #3
0
        private void RequestDevices()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            var task = Task.Run(async() =>
            {
                if (adapter.IsEnabled)
                {
                    if (adapter.IsDiscovering)
                    {
                        adapter.CancelDiscovery();
                    }
                    adapter.StartDiscovery();

                    int timeout = 20000;
                    await Task.Delay(TimeSpan.FromMilliseconds(timeout));

                    adapter.CancelDiscovery();

                    TaskCompletionSource.SetResult(false);
                }
                else
                {
                    TurnBluetoothOn();
                }
            });
        }
Beispiel #4
0
 public void DoCancelDiscovery()
 {
     if (_btAdapter.IsEnabled && _btAdapter.IsDiscovering)
     {
         _btAdapter?.CancelDiscovery();
     }
 }
        private void FlushData()
        {
            try
            {
                if (mbtSocket != null)
                {
                    mbtSocket.Close();
                    mbtSocket = null;
                }

                if (mBluetoothAdapter != null)
                {
                    mBluetoothAdapter.CancelDiscovery();
                }

                if (btDevices != null)
                {
                    btDevices.Clear();
                    btDevices = null;
                }

                if (mArrayAdapter != null)
                {
                    mArrayAdapter.Clear();
                    mArrayAdapter.NotifyDataSetChanged();
                    mArrayAdapter.NotifyDataSetInvalidated();
                    mArrayAdapter = null;
                }

                Finish();
            }
            catch (Exception ex)
            {
            }
        }
 public static void StartDiscovery()
 {
     BluetoothDevices.Clear();
     if (BluetoothAdapter.IsDiscovering)
     {
         BluetoothAdapter.CancelDiscovery();
     }
     BluetoothAdapter.StartDiscovery();
 }
        public void StartAdapter()
        {
            CancelAllThreads();
            lock (_foundDevices) { _foundDevices.Clear(); }
            if (Adapter.IsDiscovering)
            {
                Adapter.CancelDiscovery();
            }
            State = BluetoothAdapterState.Created;

            var missingPermissions = new List <string>();

            if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
            {
                missingPermissions.Add(Manifest.Permission.AccessCoarseLocation);
            }
            if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.AccessFineLocation) != Permission.Granted)
            {
                missingPermissions.Add(Manifest.Permission.AccessFineLocation);
            }
            if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.Bluetooth) != Permission.Granted)
            {
                missingPermissions.Add(Manifest.Permission.Bluetooth);
            }
            if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.BluetoothAdmin) != Permission.Granted)
            {
                missingPermissions.Add(Manifest.Permission.BluetoothAdmin);
            }

            if (missingPermissions.Any())
            {
                SAMLog.Warning("ABTA::MissingPerms", string.Join("|", missingPermissions.Select(p => p.Split('.').Last())));

                if ((int)Build.VERSION.SdkInt >= 23)
                {
                    // With API>23 I can request them here
                    // https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
                    _activity.RequestPermissions(missingPermissions.ToArray(), REQUEST_ENABLE_PERM);
                }

                State = BluetoothAdapterState.PermissionNotGranted;
                return;
            }

            if (Adapter.IsEnabled)
            {
                State = BluetoothAdapterState.Active;
            }
            else
            {
                State = BluetoothAdapterState.RequestingEnable;

                Intent enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                _activity.StartActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            }
        }
Beispiel #8
0
        protected override void OnDestroy()
        {
            base.OnDestroy();

            if (btAdapter != null)
            {
                btAdapter.CancelDiscovery();
            }
            UnregisterReceiver(receiver);
        }
        protected override void OnDestroy()
        {
            base.OnDestroy();

            // Make sure we're not doing discovery anymore
            if (btAdapter != null)
            {
                btAdapter.CancelDiscovery();
            }

            // Unregister broadcast listeners
            UnregisterReceiver(receiver);
        }
Beispiel #10
0
        private void Lv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            var    dev       = _arrayDevice[e.Position];
            Intent newIntent = new Intent();

            newIntent.PutExtra("BT_DEVICE", dev);
            SetResult(Result.Ok, newIntent);

            _progressDialog = ProgressDialog.Show(this, "Connection", "Connecting to " + dev.Name, true, true);
            if (_bluetoothAdapter.IsDiscovering)
            {
                _bluetoothAdapter.CancelDiscovery();
            }
            Finish();
        }
        public void Connect()
        {
            BluetoothDevice device = (from bd in this.mBluetoothAdapter.BondedDevices where bd.Name == "DESKTOP-SHHL6ED" select bd).FirstOrDefault();

            foreach (var ff in this.mBluetoothAdapter.BondedDevices)
            {
                Result.Text += ff.Address + "\n";
            }
            System.Console.WriteLine("Conexion en curso" + device);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    // dataToSend = new Java.Lang.String("0");
                    // writeData(dataToSend);
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            beginListenForData();
            //dataToSend = new Java.Lang.String("0");
            // writeData(dataToSend);
        }
Beispiel #12
0
        private BluetoothSocket CreateConnection(String uuid, String address)
        {
            BluetoothDevice pairedBTDevice = null;
            BluetoothSocket btSocket       = null;

            // Preparando ...
            try
            {
                // Iniciamos a conexão com o dispositivo solicitado
                pairedBTDevice = mBluetoothAdapter.GetRemoteDevice(address);

                // Indicamos ao adaptador que não seja visível
                mBluetoothAdapter.CancelDiscovery();
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Erro ao encontrar o Robô.", e);
            }

            // Conectando ...
            try
            {
                // Inicamos o socket de comunicação com o Raspberry
                btSocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuid));

                // Tentar conectar ao socket (processo assíncrono)
                btSocket.ConnectAsync();

                // 5 tentativas
                for (int try_conn = 0; try_conn < 5; try_conn++)
                {
                    // Esperar por 1 segundo
                    Thread.Sleep(1000);

                    // Checar o resultado da tentativa
                    if (btSocket.IsConnected)
                    {
                        // Sucesso! Retorna o socket e finaliza o processo
                        return(btSocket);
                    }
                }

                // Esgotando as 5 tentativas, fecha-se o socket e retorna um erro
                btSocket.Close();
                throw new System.ApplicationException("Falha ao tentar conectar ao Robô.");
            }
            catch (Exception e)
            {
                // Em caso de erro, fechamos o socket
                try
                {
                    btSocket.Close();
                }
                catch (Exception ex)
                {
                    // Ignore
                }
                throw new System.ApplicationException("Erro ao tentar conectar ao Robô.", e);
            }
        }
Beispiel #13
0
        private void DoDiscovery()
        {
            // Indicate scanning
            var status = FindViewById <TextView>(Resource.Id.textView2);

            status.Append("\nScanning...");

            // If we're already discovering, stop it
            if (btAdapter.IsDiscovering)
            {
                btAdapter.CancelDiscovery();
            }

            // Request discover from BluetoothAdapter
            btAdapter.StartDiscovery();
        }
Beispiel #14
0
            private async Task <ConnectionEstablishState> establishConnectionAsync()
            {
                if (_Device == null)
                {
                    return(ConnectionEstablishState.Failed);
                }
                BluetoothSocket tmp = null;

                if (_BluetoothAdapter == null)
                {
                    _BluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                }
                try
                {
                    tmp = _Device.CreateInsecureRfcommSocketToServiceRecord(_SdpUuid);
                }
                catch (Java.IO.IOException)
                {
                    return(ConnectionEstablishState.Failed);
                }
                _BluetoothSocket = tmp;
                _BluetoothAdapter.CancelDiscovery();
                try
                {
                    await _BluetoothSocket.ConnectAsync();

                    System.Diagnostics.Debug.WriteLine("BLUETOOTH::SUCCESSFUL ");
                }
                catch (Exception)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                try
                {
                    _InputStream  = _BluetoothSocket.InputStream;
                    _OutputStream = _BluetoothSocket.OutputStream;
                }
                catch (Java.IO.IOException)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                _LastSendDateTime = DateTime.Now;
                return(ConnectionEstablishState.Succeeded);
            }
Beispiel #15
0
        private void OnConnect()
        {
            mAdapter.CancelDiscovery();

            try
            {
                if (mSocket.IsConnected == false)
                {
                    Thread.Sleep(2000);
                    // a to the bluetooth device
                    mSocket.Connect();
                }
            }
            catch (Java.Lang.Exception ex)
            {
                Log.Debug(TAG, "Connection could not be created (" + ex.Message + ")");
            }

            if (mSocket.IsConnected)
            {
                mSocketReader = new BTSocketReader(new DataInputStream(mSocket.InputStream), PrintLastMsg);
                mSocketWriter = new BTSocketWriter(new DataOutputStream(mSocket.OutputStream));

                RunOnUiThread(() =>
                {
                    mBtAnalyse.Text    = "Send";
                    mBtAnalyse.Enabled = true;
                });
            }
        }
Beispiel #16
0
        public bool Connect()
        {
            ShowMessage("Connection in progress...");
            CheckBT();

            BluetoothDevice device = mSomulBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Connection in progress... " + device);

            mSomulBluetoothAdapter.CancelDiscovery();
            try
            {
                BTSocket = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID);
                BTSocket.Connect();

                ShowMessage("Connected");
                System.Console.WriteLine("Connection Complete");
                return(true);
            }
            catch (System.Exception e)
            {
                ShowMessage("Could Not Connect");
                System.Console.WriteLine("Could Not Connect " + e.Message);
                return(false);
            }
            finally
            {
                System.Console.WriteLine("Socket Created");
            }
        }
Beispiel #17
0
        private async Task <bool> InitConnection()
        {
            //Start connecting to arduino device
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Connecting to device:" + device);

            //We indicate to the adapter that it is no longer visible
            mBluetoothAdapter.CancelDiscovery();
            try {
                //We initiate the communication socket with the arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);

                //We connect the socket
                await btSocket.ConnectAsync();

                System.Console.WriteLine("Connection Initiated");
                IsConnected = true;
            } catch (System.Exception e) {
                //In case of generating errors, we close the socket
                Console.WriteLine("Fail to connect");
                Console.WriteLine(e.Message);
                await DisconnectAsync();
            }

            return(IsConnected);
        }
 private void Connect()
 {
     mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
     device            = mBluetoothAdapter.GetRemoteDevice(address);
     Toast.MakeText(this, "Conectando a " + device.Name, ToastLength.Short).Show();
     mBluetoothAdapter.CancelDiscovery();
     try
     {
         btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
         btSocket.Connect();
         Toast.MakeText(this, "Conexión establecida", ToastLength.Short).Show();
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.Message);
         try
         {
             btSocket.Close();
         }
         catch (Exception)
         {
             Toast.MakeText(this, "Imposible conectar", ToastLength.Short).Show();
         }
     }
     BeginListenForData();
 }
Beispiel #19
0
        private void BtComm()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            string           address = adapter.BondedDevices.FirstOrDefault(device => device.Name.Contains("Rover1"))?.Address;

            try
            {
                BluetoothDevice device = adapter.GetRemoteDevice(address);
                adapter.CancelDiscovery();
                BluetoothSocket socket =
                    device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                socket.Connect();
                Stream output = socket.OutputStream;
                _readerThread = new Thread(() => ReaderLoop(socket.InputStream));
                _readerThread.Start();
                foreach (string message in _messageBuffer.GetConsumingEnumerable())
                {
                    byte[] data = Encoding.ASCII.GetBytes(message);
                    output.Write(data, 0, data.Length);
                    output.Flush();
                }
                _readerThread.Abort();
                Thread.Sleep(2000);
                output.Close();
                socket.Close();
                socket.Dispose();
                device.Dispose();
            }
            catch (Exception e)
            {
                Log.Error("RoverController", $"Exception {e}");
            }
        }
Beispiel #20
0
        private void RunConnect()
        {
            Task.Run(() => {
                BluetoothSocket socket = null;
                try
                {
                    var uuid = (_isAndroid ? UUID_ANDROID_DEVICE : UUID_OTHER_DEVICE);
                    socket   = _socket.RemoteDevice.CreateRfcommSocketToServiceRecord(uuid);
                }
                catch
                {
                }

                _adapter.CancelDiscovery();

                try
                {
                    socket.Connect();
                }
                catch
                {
                    try
                    {
                        socket.Close();
                    }
                    catch
                    {
                        this.ConnectionFailed();
                    }
                }

                _socket = socket;
                this.Connected();
            });
        }
Beispiel #21
0
        public List <RoomVoiceControl.Bluetooth.BluetoothDevice> GetBluetoothDevices()
        {
            mBluetoothAdapter.StartDiscovery();

            List <RoomVoiceControl.Bluetooth.BluetoothDevice> list = new List <RoomVoiceControl.Bluetooth.BluetoothDevice>();

            try
            {
                var devices = mBluetoothAdapter.BondedDevices;
                foreach (var device in devices)
                {
                    list.Add(new RoomVoiceControl.Bluetooth.BluetoothDevice()
                    {
                        Name = device.Name, Address = device.Address
                    });
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                mBluetoothAdapter.CancelDiscovery();
            }

            return(list);
        }
        public void Connect()
        {
            bluetoothConn.Text += "Cautare dispozitiv remote";
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            bluetoothConn.Text += "Comexiune in curs" + device.Name + "\n";

            //Thread.Sleep(20000);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                bluetoothConn.Text = bluetoothConn.Text + "Conexiune Creata";
            }
            catch (System.Exception e)
            {
                bluetoothConn.Text += e.Message;
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    bluetoothConn.Text += "Conexiune nereusita";
                }
                bluetoothConn.Text += "Socket creat";
            }
            beginListenForData();

            //writeData(dataToSend);
        }
 /// <summary>
 /// Tries to connect to a specific device
 /// </summary>
 //public override void Run()
 public override void Run()
 {
     // Cancels the discovery due to better performance
     m_BtAdapter.CancelDiscovery();
     try
     {
         // Checks if device is already connected
         if (!m_Socket.IsConnected)
         {
             m_Socket.Connect();
         }
     }
     catch (Java.Lang.Exception connectException)
     {
         m_FailedCon = true;
         // Could not connect to device
         Console.WriteLine(connectException.Message);
         try
         {
             m_Socket.Close();
         }
         catch (Java.Lang.Exception e)
         {
             Console.WriteLine(e.Message);
         }
         return;
     }
     //   ManageConnectedSocket(m_Socket);
 }
Beispiel #24
0
        public void Connect()
        {
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Connect" + device);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                System.Console.WriteLine("Connection Okay");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Connect");
                }
                System.Console.WriteLine("Socket Create");
            }
            beginListenForData();
            dataToSend = new Java.Lang.String("e");
            writeData(dataToSend);
        }
        private async void ScanOnClick(object sender, EventArgs eventArgs)
        {
            _bluetoothDevices = new ObservableCollection <BluetoothDevice>();
            _pickedDevice     = null;

            _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            if (_bluetoothAdapter == null)
            {
                Toast.MakeText(this, "Wrong device", ToastLength.Short).Show();
                return;
            }
            if (!_bluetoothAdapter.IsEnabled)
            {
                _bluetoothAdapter.Enable();
            }

            _bluetoothAdapter.StartDiscovery();

            await Task.Run(() =>
            {
                Task.Delay(2000);
                _bluetoothAdapter.CancelDiscovery();
            });

            var pairedDevices = _bluetoothAdapter.BondedDevices;

            foreach (var pairedDevice in pairedDevices)
            {
                _bluetoothDevices.Add(pairedDevice);
            }
            _devicesList.Adapter = new BluetoothsAdapter(_bluetoothDevices);
        }
Beispiel #26
0
 ///
 void Button_Click(object sender, EventArgs e)
 {
     if (toStart)
     {
         textview.Text = String.Empty;
         ba.StartDiscovery();
         button.Text = "Идет поиск..";
         toStart     = false;
         BluetoothDevice[] device = new BluetoothDevice[ba.BondedDevices.Count];
         ba.BondedDevices.CopyTo(device, 0);
         // Если список спаренных устройств не пуст
         if (ba.BondedDevices.Count > 0)
         {
             textview.Text += "Сохраненные:" + "\n";
             // проходимся в цикле по этому списку
             for (int i = 0; i < ba.BondedDevices.Count; i++)
             {
                 // Добавляем имена и адреса в mArrayAdapter, чтобы показать
                 // через ListView
                 textview.Text += device[i].Name + "\n" + device[i].Address;
             }
         }
         else
         {
             Toast.MakeText(this, "Сопряженных нет", ToastLength.Long).Show();
         }
     }
     else
     {
         ba.CancelDiscovery();
         toStart       = true;
         textview.Text = "Начать поиск!";
         button.Text   = "Поиск..";
     }
 }
Beispiel #27
0
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode)
            {
            case CheckPermissionsId:
                if (CheckSelfPermission(Manifest.Permission.Bluetooth) == Permission.Granted &&
                    CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) == (int)Permission.Granted)
                {
                    //continue
                    RequestDevices();
                }
                else
                {
                    BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
                    adapter.CancelDiscovery();
                    TaskCompletionSource.SetResult(false);
                    Toast.MakeText(this, "You must to grant Bluetooth and Location permissions to use this app",
                                   ToastLength.Long).Show();
                }
                break;

            default:
                break;
            }
        }
Beispiel #28
0
        public async Task <bool> Connect(string deviceName)
        {
            if (!_bluetoothAdapter.Enable())
            {
                return(false);
            }

            try
            {
                var device = _bluetoothAdapter.GetRemoteDevice(deviceName);
                _bluetoothAdapter.CancelDiscovery();
                _btSocket = device.CreateRfcommSocketToServiceRecord(MyUuid);

                await _btSocket.ConnectAsync();

                if (_btSocket.IsConnected)
                {
                    Connected = true;
                }
            }
            catch (Exception ex)
            {
                Connected = false;
                var error = $"Cannot connect to bluetooth device ({deviceName}):, {ex.Message}, {ex.StackTrace}.";
                Log.Info(_tag, error);
            }

            return(Connected);
        }
Beispiel #29
0
 /// <summary>
 /// 取消搜索蓝牙设备
 /// </summary>
 /// <param name="adapter"></param>
 public static void CancelDiscovery(BluetoothAdapter adapter)
 {
     if (null != adapter)
     {
         adapter.CancelDiscovery();
     }
 }
Beispiel #30
0
        //Evento de conexion al Bluetooth
        public void Connect()
        {
            //Iniciamos la conexion con el arduino
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Conexion en curso" + device);

            //Indicamos al adaptador que ya no sea visible
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                //Inicamos el socket de comunicacion con el arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                //Conectamos el socket
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                //en caso de generarnos error cerramos el socket
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            //Una vez conectados al bluetooth mandamos llamar el metodo que generara el hilo
            //que recibira los datos del arduino
            beginListenForData();
        }