bool tryConnectBtAddr(string btAddrfile) { bool found = false; if (!File.Exists (btAddrfile)) return false; try{ mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; mmDevice = mBluetoothAdapter.GetRemoteDevice (File.ReadAllBytes (btAddrfile)); if (mmDevice != null) { found = true; } }catch(Exception ex) { } return found; }
//Evento de conexion al Bluetooth public void Connect() { //asignamos el sensor bluetooth con el que vamos a trabajar mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; //Verificamos que este habilitado if (!mBluetoothAdapter.Enable()) { Toast.MakeText(this, "Bluetooth Desactivado", ToastLength.Short).Show(); } //verificamos que no sea nulo el sensor if (mBluetoothAdapter == null) { Toast.MakeText(this, "Bluetooth No Existe o esta Ocupado", ToastLength.Short) .Show(); } //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(); //NOTA envio la letra e ya que el sketch esta configurado para funcionar cuando //recibe esta letra. //dataToSend = new Java.Lang.String("Hola"); //writeData(dataToSend); }