Пример #1
0
 public async Task <bool> Init()
 {
     btAdapter = BluetoothAdapter.DefaultAdapter;
     if (btAdapter != null)
     {
         if (btAdapter.IsEnabled)
         {
             var bondedDevices = btAdapter.BondedDevices;
             if (bondedDevices.Count > 0)
             {
                 var             devices = bondedDevices.ToList();
                 BluetoothDevice device  = devices
                                           .FirstOrDefault(x => x.Name.Equals("DSD TECH HC-05"));
                 if (device == null)
                 {
                     return(false);
                 }
                 ParcelUuid[] uuids = device.GetUuids();
                 socket = device.CreateRfcommSocketToServiceRecord(uuids[0].Uuid);
                 try
                 {
                     await socket.ConnectAsync();
                 }
                 catch (Exception)
                 {
                     throw new Exception("Fehler beim Aufbau einer Bluetoothverbindung");
                 }
                 OutputStream = socket.OutputStream;
                 InputStream  = socket.InputStream;
             }
         }
     }
     return(true);
 }
        private void ConnectToBluetoothDevice()
        {
            ICollection <BluetoothDevice> pairedDevices = btAdapter.BondedDevices;

            if (pairedDevices.Count > 0)
            {
                foreach (BluetoothDevice device in pairedDevices)
                {
                    string name    = device.Name;
                    string address = device.Address;
                    Logger.Log($"Name: {name}\nAddress: {address}");
                    if (name == "AKO SI BLUETOOTH")
                    {
                        btDevice = device;
                        break;
                    }
                }
            }

            // TODO AUTO ON NARIN UNG BLUETOOTH BAGO GAWIN TO PARA DIRE-DIRETSO
            handler          = new BluetoothHandler(this);
            btService        = new BluetoothService(this, handler);
            btService.BtUUID = btDevice.GetUuids()[0].Uuid;

            // connect na
            //btService.StartClient(btDevice);
        }
        private BluetoothSocket BtConnect(BluetoothDevice device)
        {
            BluetoothSocket socket = null;

            ParcelUuid[] uuids = null;
            if (device.FetchUuidsWithSdp())
            {
                uuids = device.GetUuids();
            }
            if ((uuids != null) && (uuids.Length > 0))
            {
                foreach (var uuid in uuids)
                {
                    try
                    {
                        socket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        socket.Connect();
                        break;
                    }
                    catch (System.Exception ex)
                    {
                        socket = null;
                    }
                }
            }
            return(socket);
        }
Пример #4
0
        private void BT_SocketConnection(BluetoothDevice btDevice)
        {
            ParcelUuid[] uuids = null;
            if (btDevice.FetchUuidsWithSdp())
            {
                uuids = btDevice.GetUuids();
            }
            if ((uuids != null) && (uuids.Length > 0))
            {
                BluetoothSocket btSocket = null;
                foreach (var uuid in uuids)
                {
                    try
                    {
                        btSocket = btDevice.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        btSocket.Connect();
                        if (btSocket.IsConnected)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("ex: " + ex.Message);
                    }
                }

                if (btSocket.IsConnected)
                {
                    Toast.MakeText(this, "Bluetooth socket is connected!", ToastLength.Long).Show();
                }
            }
        }
Пример #5
0
 private void OnBluetoothConnectClicked(object sender, EventArgs e)
 {
     Logger.Log("Conect to bluetooth");
     Logger.Log("Device: " + btDevice.Name);
     btService.BtUUID = btDevice.GetUuids()[0].Uuid;
     btService.StartClient(btDevice);
 }
Пример #6
0
            public ConnectThread(BluetoothDevice device, BluetoothFeedService service)
            {
                this.device  = device;
                this.service = service;
                BluetoothSocket tmp = null;

                ParcelUuid[] supportedUuids = device.GetUuids();
                try
                {
                    if (supportedUuids.Length > 0)
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(supportedUuids[0].Uuid);
                    }
                    else
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                    }
                }
                catch (Java.IO.IOException e)
                {
                    Log.Error(TAG, "create() failed", e);
                }
                socket        = tmp;
                service.state = STATE_CONNECTING;
            }
Пример #7
0
        /// <summary>
        /// Add a device to the list if it supports a service with the required UUID
        /// </summary>
        /// <param name="device">The Bluetooth Device</param>
        public static void AddDevice(BluetoothDevice device)
        {
            ParcelUuid[] supportedUuids;
            bool         supported = false;

            BluetoothSummaryInfo info = new BluetoothSummaryInfo
            {
                Address = device.Address,
                Name    = device.Name ?? "Unknown",
            };

            if (AvailableDevices.Contains(info))
            {
                return;
            }

            supportedUuids = device.GetUuids();
            if (supportedUuids != null)
            {
                foreach (ParcelUuid id in supportedUuids)
                {
                    if (id.ToString() == AppConst.uuid.ToString())
                    {
                        supported = true;
                        break;
                    }
                }
            }

            if (supported)
            {
                AvailableDevices.Add(info);
                listAdapter.NotifyDataSetChanged();
            }
        }
Пример #8
0
        private void OnItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e)
        {
            TextView        view            = (TextView)e.View;
            string          address         = view.Text.Split('\n')[1];
            BluetoothDevice bluetoothDevice = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(address);

            BuildConnection(bluetoothDevice, bluetoothDevice.GetUuids()[0].Uuid.ToString());
        }
Пример #9
0
        private static async Task <bool> OpenDevice(BluetoothConnection bc)
        {
            try
            {
                if (isDebug)
                {
                    Debug.WriteLine("Opening Device Name: {0} Address: {1}", bc.device_name, bc.device_address);
                }

                BluetoothDevice oBthDevice = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(bc.device_address);

                if (oBthDevice == null)
                {
                    throw new Exception("Unable to connect to device");
                }

                ParcelUuid[] puids = oBthDevice.GetUuids();

                if (puids == null || puids.Length == 0)
                {
                    throw new Exception("Invalid device UUID's");
                }

                BluetoothSocket oBthSocket = oBthDevice.CreateRfcommSocketToServiceRecord(puids[0].Uuid);

                if (oBthSocket == null)
                {
                    throw new Exception("Unable to create connection socket");
                }

                await oBthSocket.ConnectAsync();

                if (!oBthSocket.IsConnected)
                {
                    throw new Exception("Unable to connect to socket");
                }

                bc.oBthDevice = oBthDevice;
                bc.oBthSocket = oBthSocket;

                //status_message = string.Format("Device {0} Connected!", bc.device_name);

                return(true);
            }
            catch (Exception e)
            {
                SetErrorMessage("Error Opening Device " + bc.device_name, e);
                return(false);
            }
        }
Пример #10
0
        public async void Connect(object sender, EventArgs args)
        {
            BluetoothAdapter adapterbt = BluetoothAdapter.DefaultAdapter;
            BluetoothDevice  device    = (from bd in adapterbt.BondedDevices
                                          where bd.Name == list.SelectedItem.ToString()
                                          select bd).FirstOrDefault();

            Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            AlertDialog alert = dialog.Create();

            alert.SetTitle("Title");
            ParcelUuid[] uuids = device.GetUuids();
            if ((uuids != null) && (uuids.Length > 0))
            {
                foreach (var uuid in uuids)
                {
                    try
                    {
                        btSocket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        if (!btSocket.IsConnected)
                        {
                            await btSocket.ConnectAsync();
                        }
                        if (btSocket.IsConnected)
                        {
                            Mutex  mut   = new Mutex();
                            byte[] Login =
                            { 0x01, 0x30, 0x30, 0x32, 0x3A, 0x20, 0x30, 0x30, 0x34, 0x3A, 0x05, 0x30, 0x31, 0x3B, 0x3F, 0x03 };
                            byte[] RapX = { 0x01, 0x30, 0x30, 0x32, 0x3C, 0x2E, 0x30, 0x30, 0x34, 0x35, 0x58, 0x09, 0x05, 0x30, 0x32, 0x32, 0x3B, 0x03 };
                            DevUID = uuid;

                            Console.WriteLine("conected to:" + uuid.Uuid.ToString());
                            Talk2BTsocket(btSocket, Login, mut);

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(this, ex.Message, ToastLength.Short);
                    }

                    //var _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(device.GetUuids().ToString()));
                    //await _socket.ConnectAsync();
                }
            }
        }
Пример #11
0
        private void OnSelectedBluetoothDevice(object sender, SelectedItemChangedEventArgs e)
        {
            _clientMode = true;

            KeyValuePair <string, string> selectedBTDevice = (KeyValuePair <string, string>)(((Xamarin.Forms.ListView)sender).SelectedItem);

            ParcelUuid[] guids = null;
            if (_bluetoothAdapter != null)
            {
                _bluetoothAdapter.Enable();
            }

            if (selectedBTDevice.Value != null && _bluetoothAdapter != null)
            {
                _bluetoothDevice = _bluetoothAdapter.GetRemoteDevice(selectedBTDevice.Value);
                guids            = _bluetoothDevice.GetUuids();
                _state           = STATE_CONNECTED;
            }

            System.Console.WriteLine(guids[3].Uuid);

            //foreach(ParcelUuid uuid in guids)
            //{
            //    System.Console.WriteLine(uuid.Uuid);
            //}
            if (_bluetoothDevice != null)
            {
                _bluetoothSocket = _bluetoothDevice.CreateRfcommSocketToServiceRecord(_myUUID);

                if (_bluetoothSocket != null)
                {
                    _bluetoothSocket.Connect();
                    _outStream       = _bluetoothSocket.OutputStream;
                    _outStreamWriter = new OutputStreamWriter(_outStream);
                    _writeBuffer     = new BufferedWriter(_outStreamWriter);

                    _testLabel.Text = "Bluetooth: Connected";
                }
                else
                {
                    _testLabel.Text = "Bluetooth: Failed Socket";
                }
            }
        }
Пример #12
0
 public BluetoothDeviceWrapper(BluetoothDevice bluetoothDevice)
 {
     this.BluetoothDevice = bluetoothDevice;
     IsFetchingUuids      = false;
     _Receiver            = new Receiver(this);
     this.Name            = bluetoothDevice.Name;
     this.Address         = bluetoothDevice.Address;
     ParcelUuid[] uuids = bluetoothDevice.GetUuids();
     if (uuids != null)
     {
         Guid[] guids = new Guid[uuids.Length];
         for (int i = 0; i < uuids.Length; i++)
         {
             Guid guid = Guid.Parse(uuids[i].Uuid.ToString());
             guids[i] = guid;
         }
         LastestFetchedUuids = guids;
     }
 }
Пример #13
0
        /// <summary>
        /// Initizalizes the socket connection.
        /// Throws an exception if the device is not available.
        /// </summary>
        public void Init(BluetoothDevice device)
        {
            try
            {
                Init();
                BluetoothSocket tmp = null;
                tmp = device.CreateInsecureRfcommSocketToServiceRecord(device.GetUuids()[0].Uuid);
                Class              helpClass  = tmp.RemoteDevice.Class;
                Class[]            paramTypes = new Class[] { Integer.Type };
                Method             m          = helpClass.GetMethod("createRfcommSocket", paramTypes);
                Java.Lang.Object[] param      = new Java.Lang.Object[] { Integer.ValueOf(1) };

                mSocket = (BluetoothSocket)m.Invoke(tmp.RemoteDevice, param);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception();
            }
        }
Пример #14
0
            public override void OnReceive(Context context, Intent intent)
            {
                try
                {
                    string action = intent.Action;

                    // When discovery finds a device
                    if (action == BluetoothDevice.ActionFound)
                    {
                        // Get the BluetoothDevice object from the Intent
                        BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                        // If it's already paired, skip it, because it's been listed already
                        if (device.BondState != Bond.Bonded)
                        {
                            ParcelUuid[] uuids = device.GetUuids();
                            if ((uuids == null) || (uuids.Any(uuid => SppUuid.CompareTo(uuid.Uuid) == 0)))
                            {
                                _newDevicesArrayAdapter.Add(device.Name + "\n" + device.Address);
                            }
                        }
                        // When discovery is finished, change the Activity title
                    }
                    else if (action == BluetoothAdapter.ActionDiscoveryFinished)
                    {
                        _chat._scanButton.Enabled = true;
                        //_chat.SetProgressBarIndeterminateVisibility (false);
                        _chat.FindViewById <ProgressBar>(Resource.Id.progress_bar).Visibility = ViewStates.Invisible;
                        _chat.SetTitle(Resource.String.select_device);
                        if (_newDevicesArrayAdapter.Count == 0)
                        {
                            var noDevices = _chat.Resources.GetText(Resource.String.none_found);
                            _newDevicesArrayAdapter.Add(noDevices);
                        }
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
Пример #15
0
        private bool ActivateBluetoothStreams(string selectedBluetoothID)
        {
            BluetoothAdapter blueAdapter = BluetoothAdapter.DefaultAdapter;

            BluetoothDevice device = FindSelectedDevice(blueAdapter, selectedBluetoothID);

            // Verify that a device was found
            if (device == null)
            {
                Toast.MakeText(this, "Selected Bluetooth device was not found.", ToastLength.Long).Show();
                return(false);
            }

            // Activate the Input and Output streams
            bool success = false;

            try
            {
                ParcelUuid[]    uuids  = device.GetUuids();
                BluetoothSocket socket = device.CreateRfcommSocketToServiceRecord(uuids[0].Uuid);
                socket.Connect();

                // Store the output stream in a static variable
                BluetoothConnection.OutputStream = socket.OutputStream;

                //inStream = socket.getInputStream();

                success = true;
            }
            catch (IOException e)
            {
                // TODO: Log this exception somewhere

                Toast.MakeText(this, "Failure initializing steams.", ToastLength.Long).Show();
            }

            return(success);
        }
Пример #16
0
        ServiceRecord[] IBluetoothDeviceInfo.GetServiceRecords(Guid service)
        {
#if !ANDROID_API_LEVEL_15
            throw new NotSupportedException("A basic GetServiceRecords may be possible at API level 15.");
#else
            // HAC.K Just call FetchUuidsWithSdp and don't wait for the Intent
            // that signals that it has completed. So for now the user MUST
            // call this function, wait a wee while and call it again. The
            // first will return zero records.
            if (!_doneFetchSdp)
            {
                bool ok;
                try {
                    ok = _dev.FetchUuidsWithSdp();
                } catch (Java.Lang.NullPointerException npex) {
                    throw new InvalidOperationException("Device Discovery failed; maybe Bluetooth is disabled.", npex);
                } catch (Exception ex) {
                    throw new InvalidOperationException("Device Discovery failed; maybe Bluetooth is disabled.", ex);
                }
                if (!ok)
                {
                    throw new InvalidOperationException("GetServiceRecords failed; maybe Bluetooth is disabled.");
                }
                _doneFetchSdp = true;
            }
            var /*ParcelUuid[]*/ list = _dev.GetUuids();
            if (list == null) // Or in current hack: we've not called FetchUuidsWithSdp previously.
            {
                throw new InvalidOperationException("Device Discovery failed; maybe Bluetooth is disabled.");
            }
            var recList = from pu in list
                          let u                 = pu.Uuid
                                          let g = _fcty.FromJavaUuid(u)
                                                  select CreateRecordContainingOnlyClassId(g);

            return(recList.ToArray());
#endif
        }
Пример #17
0
        private async void Imprimir()
        {
            try
            {
                IsEnabled = false;
                IsRunning = true;
                var mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

                if (mBluetoothAdapter == null)
                {
                    IsRunning = false;
                    IsEnabled = true;
                    await Application.Current.MainPage.DisplayAlert(
                        "Bluetooth",
                        "No se encuentra adaptador bluetooth",
                        "Aceptar");

                    return;
                }

                if (!mBluetoothAdapter.IsEnabled)
                {
                    mBluetoothAdapter.Enable();
                }

                BluetoothDevice device = (from bd in mBluetoothAdapter.BondedDevices
                                          where bd.Name.StartsWith("PT200")
                                          select bd).FirstOrDefault();
                if (device == null)
                {
                    throw new Exception("Dispositivo no encontrado");
                }

                ParcelUuid      uuid      = device.GetUuids().ElementAt(0);
                BluetoothSocket mmsSocket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                await mmsSocket.ConnectAsync();

                var Detalle = App.Data.GetCompraDetalle(Compra.IdCompra);

                string Reporte = string.Empty;
                Reporte += "\n";
                Reporte += "====NEXPIRION====" + "\n";
                Reporte += "Compra # " + Compra.Codigo + "\n";
                Reporte += "Fecha # " + DateTime.Now.ToString() + "\n";
                Reporte += "Recolector: " + Compra.IdUsuario + "\n";
                Reporte += "Equipo: " + CrossDeviceInfo.Current.Id + "\n";
                Reporte += "Proveedor: " + Compra.ProvNombre + "\n";
                Reporte += "Producto: " + Compra.prDescripcion + "\n";
                foreach (var item in Detalle)
                {
                    Reporte += item.Descripcion + ": " + item.Valor.ToString("n2") + "\n";
                }
                Reporte += "Calificacion: " + Compra.Calificacion.ToString("n2") + "\n";
                Reporte += "\n";
                Reporte += "Cantidad: " + Compra.Cantidad.ToString("n2") + "\n";
                Reporte += "Precio: " + _Compra.Precio.ToString("n2") + "\n";
                Reporte += "Total: " + _Compra.Total.ToString("n2") + "\n";
                Reporte += "\n";
                Reporte += "\n";
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Reporte);
                mmsSocket.OutputStream.Write(buffer, 0, buffer.Length);
                mmsSocket.Close();

                IsEnabled = true;
                IsRunning = false;
            }
            catch (Exception ex)
            {
                IsRunning = false;
                IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Alerta",
                    ex.Message,
                    "Aceptar");

                return;
            }
        }
Пример #18
0
        /**
         * Método para establecer la conexión con el dispositivo BT
         * **/
        protected bool Connect(BluetoothDevice device)
        {
            ParcelUuid[] uuids     = null;
            bool         connected = false;

            if (device.FetchUuidsWithSdp())
            {
                uuids = device.GetUuids();
            }
            if ((uuids != null) && (uuids.Length > 0))
            {
                // Check if there is no socket already
                foreach (var uuid in uuids)
                {
                    // if (bs == null)
                    if (!connected)
                    {
                        try
                        {
                            socket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        }
                        catch (IOException ex)
                        {
                            throw ex;
                        }
                        //  }

                        try
                        {
                            System.Console.WriteLine("Attempting to connect...");

                            // Create a socket connection
                            socket.Connect();

                            connected = true;
                        }
                        catch
                        {
                            System.Console.WriteLine("Connection failed...");
                            connected = false;
                            System.Console.WriteLine("Attempting to connect...");
                            try
                            {
                                socket = device.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);
                                socket.Connect();

                                connected = true;
                            }
                            catch
                            {
                                System.Console.WriteLine("Connection failed...");
                                connected = false;
                            }
                        }
                    }
                }
            }
            if (connected)
            {
                System.Console.WriteLine("Client socket is connected!");
                initializedOBD2();
            }
            return(connected);
        }
Пример #19
0
        public static IBluetoothDevice GetIDevice(this BluetoothDevice bluetoothDevice)
        {
            System.Diagnostics.Debug.WriteLine("-" + bluetoothDevice.Name + " " + bluetoothDevice.Address);
            var device = new AndroidBluetoothDevice()
            {
                Name = bluetoothDevice.Name, Address = bluetoothDevice.Address
            };

            device.BluetoothDevice = bluetoothDevice;
            try
            {
                switch (bluetoothDevice.Type)
                {
                case global::Android.Bluetooth.BluetoothDeviceType.Classic:
                    device.Type = BluetoothDeviceType.Classic;
                    break;

                case global::Android.Bluetooth.BluetoothDeviceType.Dual:
                    device.Type = BluetoothDeviceType.Dual;
                    break;

                case global::Android.Bluetooth.BluetoothDeviceType.Le:
                    device.Type = BluetoothDeviceType.Le;
                    break;

                case global::Android.Bluetooth.BluetoothDeviceType.Unknown:
                    device.Type = BluetoothDeviceType.Unknown;
                    break;
                }
            }
            catch (Exception ex)
            {
            }

            try
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth getting Uuids with SDP");
                device.BluetoothDevice.FetchUuidsWithSdp();

                System.Diagnostics.Debug.WriteLine("Bluetooth Android: Getting UUIDs");
                var array = bluetoothDevice.GetUuids();
                if (array != null)
                {
                    var uuids = array.ToList();

                    System.Diagnostics.Debug.WriteLine("Bluetooth Android: " + uuids.Count + " found");

                    foreach (var uuid in uuids)
                    {
                        System.Diagnostics.Debug.WriteLine(device.Name + " Adding uuid " + uuid.Uuid.ToString());
                        var stringUUID = uuid.ToString();
                        device.UniqueIdentifiers.Add(Guid.Parse(stringUUID));
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Bluetooth Android: No Paired devices");
                }
            }
            catch (Java.Lang.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(device);
        }
Пример #20
0
        private async void BtnScan_Clicked(object sender, EventArgs e)
        {

          //  BluetoothDevice mmDevice;
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (mBluetoothAdapter == null)
            {
                // await MyFavHelper.InformUser("No bluetooth adapter found", "Bluetooth");
                await DisplayAlert("Scanned Barcode", "not ok", "OK");

                return;
            }
            else
            {
                await DisplayAlert("Αdαpter  ΟΚ", " ok", "OK");
            }

            if (!mBluetoothAdapter.IsEnabled)
            {mBluetoothAdapter.Enable();}
            else
            {await DisplayAlert("is enabled", " not ok", "OK");}

            ICollection<BluetoothDevice> pairedDevices = mBluetoothAdapter.BondedDevices;

            if (pairedDevices.Count > 0)
            {
                foreach (BluetoothDevice device in pairedDevices)
                {

                    await DisplayAlert(device.Name, " not ok", "OK");

                    if (device.Name.Contains("ADT"))
                    {
                        mmDevice = device;

                        Stream outStream;

                        Android.OS.ParcelUuid uuid = mmDevice.GetUuids().ElementAt(0);
                        BluetoothSocket socket = mmDevice.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);
                        try
                        { socket.Connect();


                        
                        outStream = socket.OutputStream;



                        //Printing
                        
                        byte[] toBytes;// = Encoding.UTF8.GetBytes("αβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ  MY TEXT TO PRINT");
                                       //  outStream.Write(toBytes, 0, toBytes.Length);
                           // char[] ccc;

                          //  string llll = Convert.ToChar(921) + Convert.ToChar(922)+ "ελληνικα ΕΛΛΗΝΙΚΑ";
                           
                            //= Convert.ToChar(915);// + Convert.ToChar(916) + Convert.ToChar(917);
                         //  toBytes =     Encoding.Unicode.GetBytes("lowew aα bβ cγ dδ eε zζ hη uθ iι kκ lλ mμ nν xξ oο pπ rρ sσ tτ yυ fφ cχ psψ oω lower");
                       // outStream.Write(toBytes, 0, toBytes.Length);
                          //  string b = "\u03a0";// ι
                          //  string c = "\u03a1";  // κ
                          //  string d = "\u03a3";  // μ
                                                     //  Ρ     Σ    Τ     Υ      β    γ      δ
                           // llll ="///"+ b + c + d+ "/\u0390\u0391\u0392\u0393\u0399\u039a\u039b //";
                          //  Encoding unicode = Encoding.Unicode;
                            // Convert the string into a byte array.
                           
                            
                          //  byte[] unicodeBytes = unicode.GetBytes(llll);
                          //  outStream.Write(unicodeBytes, 0, unicodeBytes.Length);



                            string fff=toGreek ("ΠΑΜΕ ΠΟΛΥ ΚΑΛΑ ΚΑΛΗΝΥΧΤΑ ΑΒΓΔ\n");

                            toBytes = Encoding.Unicode.GetBytes(fff);
                            outStream.Write(toBytes, 0, toBytes.Length);

                            outStream.Write(toBytes, 0, toBytes.Length);
                            outStream.Write(toBytes, 0, toBytes.Length);


                            //string ddd = (char)920+(char)921+ (char)922 + (char)923 + "--ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ PRINT/n";
                            //toBytes = Encoding.GetEncoding("windows-1253").GetBytes(ddd);
                            //   string eee = Encoding.GetEncoding("windows-1253").GetString(toBytes);

                            //   outStream.Write( toBytes, 0, toBytes.Length);
                            // toBytes = Encoding.UTF8 .GetBytes("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ PRINT/n");
                            //  outStream.Write(toBytes, 0, toBytes.Length);




                        }
                        catch
                        {
                            await DisplayAlert("αδυναμια εκτυπωσης", " ok", "OK");
                        };


                        //    toBytes = Encoding.Default .GetBytes("αβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ   MY TEXT TO PRINT");
                        //   outStream.Write(toBytes, 0, toBytes.Length);
                        try
                        { 

                        socket.Close(); }
                         catch
                        {

                         }
                        //
                        

                        break;
                    }


                }
            }
            else
            {

                await DisplayAlert("Paired Devices not found", " not ok", "OK");
               // await MyFavHelper.InformUser("Paired Devices not found", "Bluetooth");
                return;
            }



            /*
            UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");

            if (mmDevice == null)
            {
                await DisplayAlert("NO DEVICE FOUND", " not ok", "OK");
              //  await MyFavHelper.InformUser("No Device Found", "Sorry");
            }

          BluetoothSocket   mmsSocket = mmDevice.CreateRfcommSocketToServiceRecord(uuid);

            mmsSocket.Connect();

            if (mmsSocket.IsConnected)
            {
                await DisplayAlert("socket ok", " not ok", "OK");
                //await MyFavHelper.InformUser("Socket Connected Successfully", "Success");
            }
            else
            {
                await DisplayAlert("NO DEVICE FOUND", " not ok", "OK");
              //  await MyFavHelper.InformUser("Socket Not Connected Successfully", "Sorry");
            }

            System.IO.Stream datastream = mmsSocket.OutputStream;

            byte[] byteArray = Encoding.ASCII.GetBytes("Sample Text");

            datastream.Write(byteArray, 0, byteArray.Length);

            */







            /*   ParcelUuid uuid = mmDevice.GetUuids().ElementAt(0);

               if (mmDevice == null)
               {
                   await MyFavHelper.InformUser("No Device Found", "Sorry");
               }

               mmsSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);

               mmsSocket.Connect();


               if (mmsSocket.IsConnected)
               {
                   await DisplayAlert("Socket  Connected Successfully", "not ok", "OK");
                   //await MyFavHelper.InformUser("Socket Connected Successfully", "Success");
               }
               else
               {
                   await DisplayAlert("Socket Not Connected Successfully", "not ok", "OK");
                   // await MyFavHelper.InformUser("Socket Not Connected Successfully", "Sorry");
               }

               var datastream = mmsSocket.OutputStream;

               byte[] byteArray = Encoding.ASCII.GetBytes("Sample Text");

               datastream.Write(byteArray, 0, byteArray.Length);

               */






            //devicelist.Clear();
            //adapter.DeviceDiscovered += (s, a) =>
            //{
            //    devicelist.Add(a.Device);
            //};
            //await adapter.StartScanningForDevicesAsync();
        }
Пример #21
0
        private async void Request_AccessAsync(object sender, EventArgs e)
        {
            byte[]          buffer = new byte[256];
            MySqlConnection myConn = new MySqlConnection(Resources.GetString(Resource.String.myConnectionString));

            if (myConn.State == System.Data.ConnectionState.Closed)
            {
                myConn.Open(); // connection timeout is set to 60 ,check strings.xml
            }

            string access_code = Login.GetPass();      //storing password in order to check the access code with arduino
            string numberCar   = Login.GetNumberCar(); // this will be set  if the user has a car

            //check if bluetooth is on
            if (!(adapter.IsEnabled))
            {
                Console.WriteLine("Enabling bluetooth");
                Toast.MakeText(ApplicationContext, "Enabling bluetooth first", ToastLength.Long).Show();
                adapter.Enable();
                Thread.Sleep(2000); // if bluetooth is not up
            }

            // this will connect to bluetooth
            if (adapter == null)
            {
                throw new Exception("No bluetooth adapter found.");
            }
            if (!adapter.IsEnabled)
            {
                throw new Exception("Bluetooth adapter is not enabled");
            }


            BluetoothDevice device = (from bd in this.adapter.BondedDevices
                                      where bd.Name == "HC-05"
                                      select bd).FirstOrDefault();


            Console.WriteLine("\n\n" + device.Name);

            if (device == null)
            {
                throw new Exception("Named device not found.");
            }

            _socket = CreateRfcommSocket(device); // used another function for creating the socket
            Console.WriteLine(device.GetUuids().ToString());
            string       InsertSql = "Update Angajat_Intrare SET Marca=@marca, Nume=@nume, Prenume=@prenume, Poza=@poza, Divizia=@divizie";
            MySqlCommand cmdInsert = new MySqlCommand(InsertSql, myConn);

            cmdInsert.Parameters.AddWithValue("@marca", Login.GetUser());
            cmdInsert.Parameters.AddWithValue("@nume", Login.GetNume());
            cmdInsert.Parameters.AddWithValue("@prenume", Login.GetPrenume());
            cmdInsert.Parameters.AddWithValue("@poza", null);
            cmdInsert.Parameters.AddWithValue("@divizie", Login.GetDivizie());
            cmdInsert.ExecuteNonQuery();
            cmdInsert.Dispose();
            try
            {
                await _socket.ConnectAsync();


                Toast.MakeText(ApplicationContext, "Connected with bluetooth", ToastLength.Short).Show();
                // Write data to the device
                await _socket.OutputStream.WriteAsync(Encoding.ASCII.GetBytes(access_code));  //send Marca


                Console.WriteLine("Access code sent...");

                //var receivedString = Encoding.UTF8.GetString(buffer); //convert the bytes received to string

                //Console.WriteLine($"Converted string is {receivedString}");
                //if(receivedString.Equals("Yes"))
                //    Toast.MakeText(ApplicationContext, "Access Granted", ToastLength.Short).Show(); //arduino will lift the barrier
            }
            catch (Exception ex)
            {
                Toast.MakeText(ApplicationContext, "couldn't connect with bluetooth", ToastLength.Short).Show();
                Console.WriteLine("\n\n Error is -- " + ex.ToString() + "\n\n");
                // this is the function that overwrites the socket in case of failure
            }
            finally
            {
                adapter.Disable(); // disable bluetooth
                _socket.Close();   //closing communication socket
            }
        }
Пример #22
0
        private void ProbeConnection()
        {
            ParcelUuid[] parcelUuids;
            parcelUuids = Device.GetUuids();
            bool isConnected = false;



            if (parcelUuids == null)
            {
                parcelUuids    = new ParcelUuid[1];
                parcelUuids[0] = new ParcelUuid(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            }

            foreach (var parcelUuid in parcelUuids)
            {
                mBluetoothAdapter.CancelDiscovery();
                //METHOD A

                try
                {
                    var method = Device.GetType().GetMethod("createRfcommSocket");
                    mmSocket = (BluetoothSocket)method.Invoke(Device, new object[] { Port });
                    mmSocket.Connect();
                    isConnected = true;
                    DoDeviceConnected();
                    break;
                }
                catch (Exception)
                {
                }

                //METHOD B

                try
                {
                    var method = Device.GetType().GetMethod("createInsecureRfcommSocket");
                    mmSocket = (BluetoothSocket)method.Invoke(Device, new object[] { Port });
                    mmSocket.Connect();
                    isConnected = true;
                    DoDeviceConnected();
                    break;
                }
                catch (Exception)
                {
                }
            }

            if (!isConnected)
            {
                //METHOD C

                try
                {
                    IntPtr createRfcommSocket = JNIEnv.GetMethodID(Device.Class.Handle, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
                    IntPtr _socket            = JNIEnv.CallObjectMethod(Device.Handle, createRfcommSocket, new global::Android.Runtime.JValue(Port));
                    mmSocket = Java.Lang.Object.GetObject <BluetoothSocket>(_socket, JniHandleOwnership.TransferLocalRef);

                    mmSocket.Connect();
                    DoDeviceConnected();
                }
                catch (IOException connectException)
                {
                    // Unable to connect; close the socket and get out
                    try
                    {
                        mmSocket.Close();
                    }
                    catch (IOException closeException)
                    {
                    }
                    DoDeviceConnectionFailed();
                }
            }
        }
Пример #23
0
        private void ProbeConnection()
        {
            ParcelUuid[] parcelUuids;
            parcelUuids = Device.GetUuids();
            bool isConnected = false;

            if (parcelUuids == null)
            {
                throw new System.Exception("No Unique Identifiers found");
            }
            else
            {
                Debug.WriteLine("Connecting...");
                foreach (var parcelUuid in parcelUuids)
                {
                    mBluetoothAdapter.CancelDiscovery();
                    //METHOD A

                    try
                    {
                        var method = Device.GetType().GetMethod("createRfcommSocket");
                        mmSocket = (BluetoothSocket)method.Invoke(Device, new object[] { Port });
                        mmSocket.Connect();
                        Debug.WriteLine("Connected...");
                        isConnected = true;
                        DoDeviceConnected();
                        break;
                    }
                    catch (Exception)
                    {
                    }

                    //METHOD B

                    try
                    {
                        var method = Device.GetType().GetMethod("createInsecureRfcommSocket");
                        mmSocket = (BluetoothSocket)method.Invoke(Device, new object[] { Port });
                        mmSocket.Connect();
                        Debug.WriteLine("Connected...");
                        isConnected = true;
                        DoDeviceConnected();
                        break;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (!isConnected)
                {
                    //METHOD C

                    try
                    {
                        IntPtr createRfcommSocket = JNIEnv.GetMethodID(Device.Class.Handle, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
                        // JNIEnv.GetMethodID(device.Class.Handle, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
                        IntPtr _socket = JNIEnv.CallObjectMethod(Device.Handle, createRfcommSocket, new global::Android.Runtime.JValue(Port));
                        mmSocket = Java.Lang.Object.GetObject <BluetoothSocket>(_socket, JniHandleOwnership.TransferLocalRef);

                        /*
                         * mmSocket =
                         *  mBluetoothAdapter.GetRemoteDevice(Device.Address)
                         *      .CreateRfcommSocketToServiceRecord(
                         *          UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                         */
                        mmSocket.Connect();
                        DoDeviceConnected();
                    }
                    catch (IOException connectException)
                    {
                        Debug.WriteLine("IO Error: " + connectException.Message);
                        // Unable to connect; close the socket and get out
                        try
                        {
                            mmSocket.Close();
                        }
                        catch (IOException closeException)
                        {
                            Debug.WriteLine("Error: " + closeException.Message);
                        }
                        throw new BluetoothDeviceNotFoundException(connectException.Message);
                        return;
                    }
                }
            }
        }
Пример #24
0
        protected override async Task <bool> ConnectPairedDevice(string deviceNameToConnect)
        {
            var deviceList = this.SearchPairedDevices();

            if (null == deviceList)
            {
                return(false);
            }

            BluetoothDevice targetDevice = null;

            foreach (var bluetoothDevice in deviceList)
            {
                if (bluetoothDevice.Name == deviceNameToConnect)
                {
                    targetDevice = bluetoothDevice;
                    break;
                }
            }

            if (null == targetDevice)
            {
                return(false);
            }

            try
            {
                var uuids =
                    targetDevice.GetUuids()
                    .Where(uuid => uuid.Uuid.Equals(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
                    .ToList();

                if (uuids.Count <= 0)
                {
                    throw new Exception("Target UUID not available in the device.");
                }

                // Check if discovery is on, then turn it off.

                if (BluetoothAdapter.DefaultAdapter.IsDiscovering)
                {
                    BluetoothAdapter.DefaultAdapter.CancelDiscovery();
                    System.Threading.Thread.Sleep(2000);
                }

                this.socket = targetDevice.CreateRfcommSocketToServiceRecord(uuids.First().Uuid);
                ////this.socket = targetDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
                this.socket.Connect();
                return(true);
            }
            catch (IOException connectException)
            {
                try
                {
                    this.socket.Close();
                }
                catch (Exception ex)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
            }

            return(false);
        }
Пример #25
0
            public override void OnReceive(Context context, Intent intent)
            {
                try
                {
                    string action = intent.Action;

                    switch (action)
                    {
                    case BluetoothDevice.ActionFound:
                    case BluetoothDevice.ActionNameChanged:
                    {
                        // Get the BluetoothDevice object from the Intent
                        BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                        // If it's already paired, skip it, because it's been listed already
                        if (device.BondState != Bond.Bonded)
                        {
                            ParcelUuid[] uuids = device.GetUuids();
                            if ((uuids == null) || (uuids.Any(uuid => SppUuid.CompareTo(uuid.Uuid) == 0)))
                            {
                                // check for multiple entries
                                int index = -1;
                                for (int i = 0; i < _newDevicesArrayAdapter.Count; i++)
                                {
                                    string item = _newDevicesArrayAdapter.GetItem(i);
                                    if (!ExtractDeviceInfo(_newDevicesArrayAdapter.GetItem(i), out string _, out string address))
                                    {
                                        return;
                                    }
                                    if (string.Compare(address, device.Address, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        _newDevicesArrayAdapter.Remove(item);
                                        index = i;
                                        break;
                                    }
                                }
                                string newName = device.Name + "\n" + device.Address;
                                if (index < 0)
                                {
                                    _newDevicesArrayAdapter.Add(newName);
                                }
                                else
                                {
                                    _newDevicesArrayAdapter.Insert(newName, index);
                                }
                            }
                        }
                        break;
                    }

                    case BluetoothAdapter.ActionDiscoveryFinished:
                        // When discovery is finished, change the Activity title
                        _chat._scanButton.Enabled = true;
                        //_chat.SetProgressBarIndeterminateVisibility (false);
                        _chat.FindViewById <ProgressBar>(Resource.Id.progress_bar).Visibility = ViewStates.Invisible;
                        _chat.SetTitle(Resource.String.select_device);
                        if (_newDevicesArrayAdapter.Count == 0)
                        {
                            var noDevices = _chat.Resources.GetText(Resource.String.none_found);
                            _newDevicesArrayAdapter.Add(noDevices);
                        }
                        break;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
Пример #26
0
        private void ProbeConnection()
        {
            ParcelUuid[] parcelUuids;
            parcelUuids = m_device.GetUuids();
            bool isConnected = false;

            if (parcelUuids == null)
            {
                parcelUuids    = new ParcelUuid[1];
                parcelUuids[0] = new ParcelUuid(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            }

            m_bluetoothAdapter.CancelDiscovery();


            //METHOD A

            try
            {
                var method = m_device.GetType().GetMethod("createRfcommSocket");
                Socket = (BluetoothSocket)method.Invoke(m_device, new object[] { m_port });
                Socket.Connect();
                isConnected = true;
                DoDeviceConnected();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Faield to createRfcommSocket {ex}");
            }

            if (!isConnected)
            {
                //METHOD B

                try
                {
                    var method = m_device.GetType().GetMethod("createInsecureRfcommSocket");
                    Socket = (BluetoothSocket)method.Invoke(m_device, new object[] { m_port });
                    Socket.Connect();
                    isConnected = true;
                    DoDeviceConnected();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Faield to createInsecureRfcommSocket {ex}");
                }
            }

            if (!isConnected)
            {
                //METHOD C

                try
                {
                    IntPtr createRfcommSocket = JNIEnv.GetMethodID(m_device.Class.Handle, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
                    IntPtr _socket            = JNIEnv.CallObjectMethod(m_device.Handle, createRfcommSocket, new global::Android.Runtime.JValue(m_port));
                    Socket = Java.Lang.Object.GetObject <BluetoothSocket>(_socket, JniHandleOwnership.TransferLocalRef);
                    Socket.Connect();
                    isConnected = true;
                    DoDeviceConnected();
                }
                catch (IOException ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Faield to createRfcommSocket JNI, {ex}");
                }
            }

            if (!isConnected)
            {
                // Unable to connect; close the socket and get out
                if (Socket != null)
                {
                    try
                    {
                        Socket.Close();
                    }
                    catch (IOException e)
                    {
                        System.Diagnostics.Debug.WriteLine($"Faield to close socket, {e}");
                    }
                }
                DoDeviceConnectionFailed();
            }
        }
Пример #27
0
        public async Task <bool> Connect(string name)
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            checkDefaultAdapter(adapter);

            BluetoothDevice device = (from bd in adapter.BondedDevices
                                      where bd.Name == name
                                      select bd).FirstOrDefault();

            if (device == null)
            {
                throw new Exception(name + " device was not found.");
            }

            ParcelUuid[] uuids = null;
            if (device.FetchUuidsWithSdp())
            {
                uuids = device.GetUuids();
            }

            Thread.Sleep(200);

            if ((uuids != null) && (uuids.Length > 0))
            {
                foreach (var uuid in uuids)
                {
                    try
                    {
                        if ((int)Android.OS.Build.VERSION.SdkInt >= 10)
                        {
                            _socket = device.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);
                        }
                        else
                        {
                            _socket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        }

                        await _socket.ConnectAsync();

                        break;
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Source + "\n" + e.Message);
                    }
                }
            }
            else
            {
                if (uuids == null)
                {
                    throw new Exception("uuids is NULL!");
                }
                if (uuids.Length == 0)
                {
                    throw new Exception("uuids.Length == 0!");
                }
            }

            if (_socket == null)
            {
                throw new Exception("socket is NULL!");
            }

            if (!_socket.IsConnected)
            {
                throw new Exception("_socket is not connected!");
            }

            return(_socket.IsConnected);
        }
Пример #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            String targetUuid       = "19397893-76dc-4485-8f7c-f43e209ad881";
            String currentSelection = "";

            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.activity_main);
            const int locationPermissionsRequestCode = 1000;

            var locationPermissions = new[]
            {
                Manifest.Permission.AccessCoarseLocation,
                Manifest.Permission.AccessFineLocation
            };

            // check if the app has permission to access coarse location
            var coarseLocationPermissionGranted =
                ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessCoarseLocation);

            // check if the app has permission to access fine location
            var fineLocationPermissionGranted =
                ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation);

            // if either is denied permission, request permission from the user
            if (coarseLocationPermissionGranted == Permission.Denied ||
                fineLocationPermissionGranted == Permission.Denied)
            {
                ActivityCompat.RequestPermissions(this, locationPermissions, locationPermissionsRequestCode);
            }

            BluetoothAdapter adapter           = BluetoothAdapter.DefaultAdapter;
            ObservableCollection <string> outS = new ObservableCollection <string>();

            if (adapter == null)
            {
                outS.Add("No Bluetooth adapter found.\n");
            }

            else if (!adapter.IsEnabled)
            {
                outS.Add("Bluetooth adapter is not enabled.\n");
            }

            List <int> indexes = new List <int>();
            int        index   = 0;

            foreach (var dev in adapter.BondedDevices)
            {
                dev.FetchUuidsWithSdp();
                ParcelUuid[] ids     = dev.GetUuids();
                bool         foundID = false;
                foreach (var i in ids)
                {
                    if (i.Uuid.ToString() == targetUuid)
                    {
                        foundID = true;
                    }
                }
                if (foundID)
                {
                    indexes.Add(index);
                    outS.Add(dev.Name + " " + dev.Address);
                }
                else
                {
                    outS.Add(dev.Name + " " + dev.Address);
                }
                index++;
            }

            EditText ssid     = FindViewById <EditText>(Resource.Id.ssid);
            EditText password = FindViewById <EditText>(Resource.Id.password);

            ListView menu = FindViewById <ListView>(Resource.Id.DeviceList);

            foreach (var ind in indexes)
            {
                //Mark the right device;
            }
            ArrayAdapter <string> initialAdapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, outS);

            menu.Adapter = initialAdapter;

            menu.ItemClick += (parent, args) =>
            {
                currentSelection = ((TextView)args.View).Text;
            };

            Button send = FindViewById <Button>(Resource.Id.send);

            send.Click += (parent, args) =>
            {
                var network = ssid.Text;
                var passwd  = password.Text;
                try
                {
                    BluetoothDevice target = null;
                    foreach (var dev in adapter.BondedDevices)
                    {
                        if (currentSelection == dev.Name + " " + dev.Address)
                        {
                            target = dev;
                        }
                    }
                    if (target != null && target.FetchUuidsWithSdp())
                    {
                        ParcelUuid[] uuids     = target.GetUuids();
                        ParcelUuid   foundUuid = null;
                        bool         found     = false;
                        foreach (var id in uuids)
                        {
                            if (targetUuid == id.Uuid.ToString())
                            {
                                foundUuid = id;
                                found     = true;
                            }
                        }



                        if (foundUuid != null && found)
                        {
                            Toast.MakeText(Application, "Trying to connect...", ToastLength.Short).Show();
                            Wait(100);
                            BluetoothSocket bSocket = null;
                            try
                            {
                                bSocket = target.CreateRfcommSocketToServiceRecord(ParcelUuid.FromString(foundUuid.Uuid.ToString()).Uuid);
                                var connection = bSocket.ConnectAsync();
                                connection.Wait(5000);
                                if (bSocket != null && bSocket.IsConnected)
                                {
                                    byte[] msg   = Encoding.UTF8.GetBytes(network + " " + passwd);
                                    var    write = bSocket.OutputStream.WriteAsync(msg, 0, msg.Length);
                                    write.Wait();
                                    Toast.MakeText(Application, "Credentials were sent succesfully.", ToastLength.Short).Show();
                                }
                                else
                                {
                                    Toast.MakeText(Application, "Connection timed out.", ToastLength.Short).Show();
                                }
                            }
                            catch
                            {
                                Toast.MakeText(Application, "Connection error.", ToastLength.Short).Show();
                            }
                        }
                        else
                        {
                            Toast.MakeText(Application, "Make sure your raspberrypi is turned on and it is selected from the list.", ToastLength.Long).Show();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, ex.Message, ToastLength.Short);
                }
            };

            Button refresh = FindViewById <Button>(Resource.Id.refresh);

            refresh.Click += (parent, args) =>
            {
                ObservableCollection <string> newOut = new ObservableCollection <string>();

                if (adapter == null)
                {
                    newOut.Add("No Bluetooth adapter found.\n");
                }

                else if (!adapter.IsEnabled)
                {
                    newOut.Add("Bluetooth adapter is not enabled.\n");
                }

                List <int> newIndexes = new List <int>();
                int        newIndex   = 0;
                foreach (var dev in adapter.BondedDevices)
                {
                    dev.FetchUuidsWithSdp();
                    ParcelUuid[] ids     = dev.GetUuids();
                    bool         foundID = false;
                    foreach (var i in ids)
                    {
                        if (i.Uuid.ToString() == targetUuid)
                        {
                            foundID = true;
                        }
                    }
                    if (foundID)
                    {
                        newIndexes.Add(newIndex);
                        newOut.Add(dev.Name + " " + dev.Address);
                    }
                    else
                    {
                        newOut.Add(dev.Name + " " + dev.Address);
                    }
                    newIndex++;
                }

                Toast.MakeText(Application, "Refreshed devices", ToastLength.Short).Show();

                ArrayAdapter <string> newAdapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, newOut);

                menu.Adapter = newAdapter;
                foreach (var ind in newIndexes)
                {
                    //Mark the right device
                }
            };
        }