private void openDeviceConnection(BluetoothDevice btDevice)
 {
     try
     {
         mSocket = btDevice.CreateRfcommSocketToServiceRecord(getUUIDFromString());
         mSocket.Connect();
         mStream = mSocket.InputStream;
         mReader = new InputStreamReader(mStream);
     }
     catch (IOException e)
     {
         throw e;
     }
 }
Example #2
0
        public void Connect()
        {
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);
            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
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            beginListenForData();

            var ac = FindViewById<Button>(Resource.Id.ac);
            var kapa = FindViewById<Button>(Resource.Id.kapa);
            dataToSend = new Java.Lang.String("1");

            ac.Click += delegate
            {
                dataToSend = new Java.Lang.String("1");
                writeData(dataToSend);

            };
            kapa.Click += delegate
            {
                dataToSend = new Java.Lang.String("2");
                writeData(dataToSend);

            };

            writeData(dataToSend);
        }
Example #3
0
		public void Connect() {
			BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);
			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 {
					btSocket.Close();
				} catch (System.Exception) {
					System.Console.WriteLine("Imposible Conectar");
				}
				System.Console.WriteLine("Socket Creado");
			}
			beginListenForData();
			dataToSend = new Java.Lang.String("e");
			writeData(dataToSend);
		}
Example #4
0
 private bool TrytoConnect(BluetoothSocket mmSocket)
 {
     bool TrytoConnect = true;
     int count = 0;
     while (TrytoConnect) {
         try {
             Thread.Sleep(400);
             mmSocket.Connect ();
             TrytoConnect = false;
         } catch {
             count += 1;
             if (count==5)
                 TrytoConnect = false;
         }
     }
     return !TrytoConnect;
 }
Example #5
0
        public string PrintInvSumm(BluetoothSocket mmSocket,BluetoothDevice mmDevice,DateTime printDate1,DateTime printDate2)
        {
            msg = "";
            Stream mmOutputStream;
            try {
                UUID uuid = UUID.FromString ("00001101-0000-1000-8000-00805F9B34FB");
                mmSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord (uuid);
                if (mmSocket == null) {
                    msg = "Error creating sockect";
                    return msg;
                }
                if (mmDevice.BondState == Bond.Bonded) {
                    mmSocket.Connect ();
                    Thread.Sleep (300);
                    mmOutputStream = mmSocket.OutputStream;
                    byte[] charfont;
                    if (apara.PaperSize == "58mm") {
                        charfont = new Byte[] { 27, 33, 1 }; //Char font 9x17
                        mmOutputStream.Write (charfont, 0, charfont.Length);
                    }

                    if (apara.PaperSize == "80mm") {
                        charfont = new Byte[] { 27, 33, 0 }; //Char font 12x24
                        mmOutputStream.Write (charfont, 0, charfont.Length);
                    }

                    string text = GetInvoiceSumm (printDate1, printDate2);
                    //byte[] cc = ASCIIEncoding.ASCII.GetBytes(text);

                    byte[] cc = Encoding.GetEncoding ("GB18030").GetBytes (text);
                    int rem;
                    int result = Math.DivRem (cc.Length, 2048, out rem);
                    int pos = 0;
                    for (int line = 0; line < result; line++) {
                        IsStreamCanWrite (mmOutputStream);
                        mmOutputStream.Write (cc, pos, 2048);
                        pos += 2048;
                    }
                    if (rem > 0)
                        mmOutputStream.Write (cc, pos, rem);

                    //mmOutputStream.Write (cc, 0, cc.Length);
                    Thread.Sleep (3000);
                    mmOutputStream.Flush ();
                    mmOutputStream.Close ();
                    mmSocket.Close ();
                }

            } catch (Exception ex) {
                msg = ex.Message;
            }

            return msg;
        }
        /// <summary>
        /// Connect to the device given host name
        /// </summary>
        /// <param name="deviceHostName">Raw host name of the device</param>
        /// <returns>True if connected successfully. Else False</returns>
        public async Task<bool> ConnectAsync(string deviceHostName)
        {
            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (!_adapter.IsEnabled)
            {
                throw new Exception("Bluetooth is off. Please turn it on from settings.");
            }

            SelectedDevice = _adapter.BondedDevices.FirstOrDefault(d => d.Address == deviceHostName);
           
            if (SelectedDevice != null)
            {
                var uuids = SelectedDevice.GetUuids();
                if (uuids != null && uuids.Length > 0)
                {
                    return await Task.Run<bool>(() => 
                        {
                            _socket = SelectedDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuids[0].ToString()));
                            _socket.Connect();
                            return IsConnected;
                        });
                }
            }

            return IsConnected;
        }
		private void TryToConnect(){
			System.Threading.ThreadPool.QueueUserWorkItem (o => {
				BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
				SetStatusText("acquiring adapter...");
				if (bluetoothAdapter == null) {
					SetStatusText("No Bluetooth Adapter found.");
					return;
				} else if (!bluetoothAdapter.IsEnabled) {
					SetStatusText("BlueTooth Adapter disabled.");
					return;
				}
				SetStatusText("finding Shelly's Garage");
				var device = bluetoothAdapter.BondedDevices.FirstOrDefault (x => x.Name == "Shelly'sGarage");
				if (device == null) {
					SetStatusText("You ain't paired with Shelly's Garage.");
					return;
				}
				SetStatusText("connecting...");
				socket = device.CreateRfcommSocketToServiceRecord (Java.Util.UUID.FromString ("00001101-0000-1000-8000-00805f9b34fb"));
				try {
					socket.Connect ();
					bluetoothAdapter.Dispose();
					SetStatusText("Connected to Shelly's Garage");
					RunOnUiThread(()=>{
						connectorButton.Text = "Disconnect";
					});
				} catch {//Exception ex) {
					SetStatusText("Connection failt.");
				}
			});
		}
Example #8
0
        //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);
        }