示例#1
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();
                }
            }
        }
        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);
        }
示例#3
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
        }
示例#4
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);
        }
示例#5
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
                }
            };
        }
        public override void OnReceive(Context context, Intent intent)
        {
            // Getting specific event
            String action = intent.Action;

            //m_Main.GiveAMessage(action);

            if (BluetoothAdapter.ActionDiscoveryStarted.Equals(action))
            {
                m_Main.StartProgress();
            }
            // Checking if search is stopped
            else if (BluetoothAdapter.ActionDiscoveryFinished.Equals(action))
            {
                // Creating a copy of the list
                m_CopyList = new List <string>(m_List);
                if (m_List.Count > 0)
                {
                    m_Main.StartProgress();
                    // Getting address of the device and removing it from the list
                    String address = m_List.ElementAt(0).Split('\n')[1];
                    m_List.RemoveAt(0);

                    // Creating a BluetoothDevice by its address
                    BluetoothDevice device = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(address);
                    bool            result = device.FetchUuidsWithSdp();
                }
                else
                {
                    m_Main.Reset();
                }
            }
            // Checking if device was found
            else if ((BluetoothDevice.ActionFound.Equals(action)))
            {
                // Getting the BluetoothDevice from intent
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

                // Adding name and address to device list
                m_List.Add(device.Name + "\n" + device.Address);

                // Add the name and address to an array adapter to show in a Toast
                String derp = device.Name + " - " + device.Address;
                //m_Main.GiveAMessage(derp);
            }
            else if (BluetoothDevice.ActionUuid.Equals(action))
            {
                // This is when we can be assured that fetchUuidsWithSdp has completed
                // So get the UUIDs and call fetchUuidsWithSdp on another device in list
                BluetoothDevice device    = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                IParcelable[]   uuidExtra = intent.GetParcelableArrayExtra(BluetoothDevice.ExtraUuid);
                try
                {
                    for (int i = 0; i < uuidExtra.Length; i++)
                    {
                        if (i == 0)
                        {
                            if (!m_CompareList.Contains(uuidExtra[i].ToString()))
                            {
                                m_CompareList.Add(uuidExtra[i].ToString());
                                m_Main.AddUuid(uuidExtra[i].ToString());
                            }
                        }
                    }

                    if (m_List.Count > 0)
                    {
                        String address = m_List.ElementAt(0).Split('\n')[1];
                        m_List.RemoveAt(0);
                        BluetoothDevice device2 = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(address);
                        bool            result  = device2.FetchUuidsWithSdp();
                    }
                    else
                    {
                        m_Main.SetAdapterToListView(m_CopyList);
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
            }
        }
示例#7
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);
        }