コード例 #1
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;
            }
コード例 #2
0
        public bool Connect()
        {
            ShowMessage("Connection in progress...");
            CheckBT();

            BluetoothDevice device = mSomulBluetoothAdapter.GetRemoteDevice(address);

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

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

                ShowMessage("Connected");
                System.Console.WriteLine("Connection Complete");
                return(true);
            }
            catch (System.Exception e)
            {
                ShowMessage("Could Not Connect");
                System.Console.WriteLine("Could Not Connect " + e.Message);
                return(false);
            }
            finally
            {
                System.Console.WriteLine("Socket Created");
            }
        }
コード例 #3
0
        async public Task <bool> connectBTDevice(string bda)
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                throw new System.Exception("No Bluetooth adapter found.");
            }

            if (!adapter.IsEnabled)
            {
                throw new System.Exception("Please, turn on the bluetooth adapter.");
            }

            UUID BTSPPUUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
            var  a         = adapter.BondedDevices.Where(p => p.Address == bda.ToUpper()).ToList();

            btDevice = a.FirstOrDefault();

            btSocket = btDevice.CreateInsecureRfcommSocketToServiceRecord(BTSPPUUID);
            btSocket.Connect();

            if (btSocket.IsConnected == true)
            {
                outStream = btSocket.OutputStream;
                inStream  = btSocket.InputStream;

                connTF = true;
                cts    = new CancellationTokenSource();
                System.Threading.Thread thread = new System.Threading.Thread(() => ReadThread(this, inStream));
                thread.Start();
            }
            return(true);
        }
コード例 #4
0
        public BluetoothConnection ConnectToBluetoothDevice()
        {
            bluetoothConnection = new BluetoothConnection();
            //bluetoothConnection.deviceName = "SESTO-L1808016";
            if (SelectedBluetoothDevice == null)
            {
                Debug.WriteLine("******** NO device selected ***********");
                MessagingCenter.Send(this, Constants.MESSAGE_DEVICE_SELECTED);
                return(null);
            }
            bluetoothConnection.deviceName = SelectedBluetoothDevice;

            try
            {
                Debug.WriteLine("CONNECTION 1");
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                Debug.WriteLine("CONNECTION 2");
                BluetoothDevice bluetoothDevice = (from device in bluetoothAdapter.BondedDevices
                                                   where device.Name == bluetoothConnection.deviceName
                                                   select device).FirstOrDefault();
                Debug.WriteLine("CONNECTION 3");
                BluetoothSocket bluetoothSocket = bluetoothDevice.CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString(Constants.UUID));
                Debug.WriteLine("CONNECTION 4");
                bluetoothSocket.Connect();
                Debug.WriteLine("CONNECTION 5");
                bluetoothConnection.bluetoothSocket = bluetoothSocket;

                return(bluetoothConnection);
            }
            catch (Exception) {
                throw;
            }
        }
コード例 #5
0
        private BluetoothSocket TryGetSocket(BluetoothDevice bluetoothDevice, string uuid = null)
        {
            UUID id = UUID.FromString(uuid ?? "00001101-0000-1000-8000-00805F9B34FB");

            try
            {
                _btSocket = bluetoothDevice?.CreateRfcommSocketToServiceRecord(id);       // Secure Socket
                return(_btSocket);
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1);

                try
                {
                    _btSocket = bluetoothDevice?.CreateInsecureRfcommSocketToServiceRecord(id);       // Insecure Socket
                    return(_btSocket);
                }
                catch (Exception e2)
                {
                    Console.WriteLine(e2);
                    _btSocket?.Dispose();
                    return(null);
                }
            }
        }
コード例 #6
0
            public ConnectThread(BluetoothDevice device, BluetoothChatService service, bool secure)
            {
                this.device  = device;
                this.service = service;
                BluetoothSocket tmp = null;

                socketType = secure ? "Secure" : "Insecure";

                try
                {
                    if (secure)
                    {
                        tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    }
                    else
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
                    }
                }
                catch (Java.IO.IOException e)
                {
                    Log.Error(TAG, "create() failed", e);
                }
                socket        = tmp;
                service.state = STATE_CONNECTING;
            }
コード例 #7
0
            public ConnectThread(BluetoothChatService chatService, BluetoothDevice device, bool secure)
            {
                this.chatService = chatService;
                mmDevice         = device;
                BluetoothSocket tmp = null;

                mSocketType = secure ? "Secure" : "Insecure";

                // Get a BluetoothSocket for a connection with the
                // given BluetoothDevice
                try
                {
                    if (secure)
                    {
                        tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    }
                    else
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
                    }
                }
                catch (IOException e)
                {
                    Log.E(TAG, "Socket Type: " + mSocketType + "create() failed", e);
                }
                mmSocket = tmp;
            }
コード例 #8
0
            private async Task <ConnectionEstablishState> establishConnectionAsync()
            {
                if (_Device == null)
                {
                    return(ConnectionEstablishState.Failed);
                }
                BluetoothSocket tmp = null;

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

                    System.Diagnostics.Debug.WriteLine("BLUETOOTH::SUCCESSFUL ");
                }
                catch (Exception)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                try
                {
                    _InputStream  = _BluetoothSocket.InputStream;
                    _OutputStream = _BluetoothSocket.OutputStream;
                }
                catch (Java.IO.IOException)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                _LastSendDateTime = DateTime.Now;
                return(ConnectionEstablishState.Succeeded);
            }
コード例 #9
0
        /// <summary>
        /// Default uuid for Bluetoothmodule = <c>00001101-0000-1000-8000-00805F9B34FB</c>
        /// </summary>
        /// <param name="btDevice"></param>
        /// <param name="uuid"></param>
        /// <returns></returns>
        public async Task DoConnectionInsecure(BluetoothDevice btDevice, UUID uuid)
        {
            DoCancelDiscovery();

            if (btDevice == null)
            {
                await _page.DisplayAlert("Error CustomBluetoothManager.DoConnectionInsecure", "btDevice == null", "OK");

                return;
            }
            if (!_btAdapter.IsEnabled)
            {
                await _page.DisplayAlert("State", "Bluetooth is turned off", "OK");

                return;
            }

            if (_btSocket == null)
            {
                goto GOTOSocketIsNull;                          // _btSocket will be set inside this method. // NullreferenceException cause of calling "_btSocket.IsConnected"
            }
            if (_btSocket.IsConnected)
            {
                await _page.DisplayAlert("State", "Device is already connected", "OK");

                return;
            }
GOTOSocketIsNull:

            try
            {
                _btSocket = btDevice.CreateInsecureRfcommSocketToServiceRecord(uuid);
                _btSocket.Connect();
            }
            catch (Exception e1)
            {
                await _page.DisplayAlert("Exception", $"CustomBluetoothManager.DoConnectionInsecure => e1 => {e1}", "OK");

                try
                {
                    await DoCloseDispose(_btSocket);
                    await DoCloseDispose(btDevice);
                }
                catch (Exception e2)
                {
                    await _page.DisplayAlert("Excdeption", $"CustomBluetoothManager.DoConnectionInsecure => e2 => {e2}", "OK");

                    return;
                }
            }

            if (_btSocket != null && _btSocket.IsConnected)
            {
                await _page.DisplayAlert("Status", "Device Connected", "OK");
            }
            else if (_btSocket != null && _btSocket.IsConnected)
            {
                await _page.DisplayAlert("Status", "Device not Connected", "OK");
            }
        }
コード例 #10
0
        public void OpenConnection(string address)
        {
            if (!_bluetoothAdapter.IsEnabled)
            {
                throw new InvalidOperationException("The bluetooth adapter is not enabled");
            }
            if (!Android.Bluetooth.BluetoothAdapter.CheckBluetoothAddress(address))
            {
                throw new InvalidOperationException("The given address is not valid");
            }

            _bluetoothDevice = _bluetoothAdapter.GetRemoteDevice(address);

            try
            {
                // Create the socket using reflection
                Method m = _bluetoothDevice.Class.GetMethod("createRfcommSocket", Integer.Type);
                _bluetoothSocket = (BluetoothSocket)m.Invoke(_bluetoothDevice, 1);
            }
            catch (Exception)
            {
                try
                {
                    // When the first method failed try to connect using the public method
                    _bluetoothSocket = _bluetoothDevice?.CreateInsecureRfcommSocketToServiceRecord(RfCommUuid);
                }
                catch (Exception e)
                {
                }
            }

            _bluetoothSocket?.Connect();
        }
コード例 #11
0
        private bool Connect()
        {
            // Early out if we already have a socket and a reader thread
            if (btSocket != null && rdThread != null && rdThread.IsAlive)
            {
                return(true);
            }

            // Tidy up if necessary
            if (btSocket != null)
            {
                btSocket.Close();
                btSocket = null;
            }
            if (rdThread != null)
            {
                if (rdThread.IsAlive)
                {
                    rdThread.Abort();
                }
                rdThread = null;
            }

            // If we don't have an SPP UID then initialisation failed
            if (sppUUID == null)
            {
                return(false);
            }

            // Create the socket and try to connect
            btSocket = btDevice.CreateInsecureRfcommSocketToServiceRecord(sppUUID);
            if (btSocket == null)
            {
                return(false);
            }

            try
            {
                btSocket.Connect();
            }
            catch (Exception)
            {
                btSocket = null;
                return(false);
            }

            // Start the receive thread
            rdThread = new Thread(SocketReaderWorker);
            rdThread.Start();
            while (!rdThread.IsAlive)
            {
                ;
            }

            return(true);
        }
コード例 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="uuid"></param>
        public void ConnectToPairedDevice(string name, UUID uuid)
        {
            BluetoothDevice device = GetPairedDevice(name);

            if (device != null)
            {
                BluetoothSocket socket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
                socket.Connect();
                _pairedSocket = socket;
            }
        }
コード例 #13
0
        protected override void OpenConnection()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            BluetoothDevice  device  = adapter.GetRemoteDevice(BluetoothAddress);

            Socket = device.CreateInsecureRfcommSocketToServiceRecord(mSPP_UUID);
            adapter.CancelDiscovery();
            Socket.Connect();
            output = new Java.IO.DataOutputStream(Socket.OutputStream);
            input  = new Java.IO.DataInputStream(Socket.InputStream);
        }
コード例 #14
0
        public void Connect(BondedDevice device)
        {
            // Cancel discovery because it will slow down a connection.
            BluetoothAdapter.DefaultAdapter.CancelDiscovery();

            BluetoothDevice remoteDevice = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(device.Address);

            socket = remoteDevice.CreateInsecureRfcommSocketToServiceRecord(connectionId);

            socket.Connect();
        }
コード例 #15
0
        private BluetoothSocket CreateBluetoothSocket(BluetoothDevice device)
        {
            UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");

            if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
            {
                return(device.CreateInsecureRfcommSocketToServiceRecord(uuid));
            }
            else
            {
                return(device.CreateRfcommSocketToServiceRecord(uuid));
            }
        }
コード例 #16
0
 /// <summary>
 /// Connects to the device's bluetooth socket.
 /// </summary>
 /// <returns>The to socket.</returns>
 private bool ConnectInternal()
 {
     Disconnect();
     try {
         socket = device.CreateInsecureRfcommSocketToServiceRecord(SPP);
         socket.Connect();
         input  = new StreamReader(socket.InputStream);
         output = socket.OutputStream;
         return(true);
     } catch (Exception e) {
         Log.E(this, "Failed to connect to the class device", e);
         return(false);
     }
 }
コード例 #17
0
 public void Connect(Device device, Action onSuccess, Action <Exception> onError)
 {
     try
     {
         var adapter = BluetoothAdapter.DefaultAdapter;
         _btDevice = adapter.GetRemoteDevice(device.Address);
         _btSocket = _btDevice.CreateInsecureRfcommSocketToServiceRecord(_uuid);
         BluetoothAdapter.DefaultAdapter.CancelDiscovery();
         _btSocket.Connect();
         onSuccess();
     }
     catch (Exception e)
     {
         onError(e);
     }
 }
コード例 #18
0
        public bool SocketConnect()
        {
            BluetoothSocket tmpSocket;

            // Set up socket
            try
            {
                UUID id = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
                tmpSocket = mbarBotDevice.CreateInsecureRfcommSocketToServiceRecord(id);
            }
            catch (System.IO.IOException e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine("Socket's listen() method failed");
                ShowToastMessage("Found BarBot bond", ToastLength.Short);
                return(false);
            }

            mSocket = tmpSocket;


            // Drive on a diffrent Socket
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                mSocket.Connect();
            }
            catch (Exception e)
            {
                try
                {
                    System.Console.WriteLine("\n\nClosing connection:\n");
                    System.Console.WriteLine(e.Message);
                    mSocket.Close();
                    return(false);
                }
                catch (Exception r)
                {
                    System.Console.WriteLine("Could not close the client socket");
                    System.Console.WriteLine(r.Message);
                    return(false);
                }
            }
            Thread.Sleep(1500);
            return(true);
        }
コード例 #19
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();
            }
        }
コード例 #20
0
 public async Task ConnectAsync(Device device, Action OnSuccess, Action <Exception> OnError)
 {
     await Task.Factory.StartNew(() =>
     {
         try
         {
             var adapter = BluetoothAdapter.DefaultAdapter;
             _btDevice   = adapter.GetRemoteDevice(device.Address);
             _btSocket   = _btDevice.CreateInsecureRfcommSocketToServiceRecord(_uuid);
             BluetoothAdapter.DefaultAdapter.CancelDiscovery();
             _btSocket.Connect();
             OnSuccess();
         }
         catch (Exception e)
         {
             OnError(e);
         }
     });
 }
コード例 #21
0
 public bool Connect(string deviceName)
 {
     if (!string.IsNullOrEmpty(deviceName) && IsEnabled)
     {
         BluetoothDevice dev = _bluetoothAdapter.BondedDevices.FirstOrDefault(x => x.Name == deviceName);
         _bluetoothSocket =
             dev?.CreateInsecureRfcommSocketToServiceRecord(
                 UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
         try
         {
             _bluetoothSocket?.Connect();
         }
         catch (Java.IO.IOException)
         {
             App.MessageService.DisplayMessage("Could not connect to specified device. Please try again");
         }
     }
     return(_bluetoothSocket != null && _bluetoothSocket.IsConnected);
 }
コード例 #22
0
        public ConnectThread(BluetoothService service, BluetoothDevice device)
        {
            this.service = service;
            this.device  = device;
            BtAdapter    = this.service.BtAdapter;

            BluetoothSocket tempSocket = null;

            try
            {
                tempSocket = device.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                //tempSocket = device.CreateRfcommSocketToServiceRecord(service.BtUUID);
            }
            catch (IOException e)
            {
                Logger.Log("Socket's create() method failed " + e.Message);
            }

            socket = tempSocket;
        }
コード例 #23
0
        internal BluetoothSocket CreateSocket(BluetoothEndPoint remoteEP, bool auth, bool encr)
        {
            BluetoothSocket s;

            if (remoteEP.HasPort)
            {
                s = CreateSocketToPort(_dev, remoteEP.Port, auth, encr);
            }
            if (auth || encr)
            {
                s = _dev.CreateRfcommSocketToServiceRecord(
                    _fcty.ToJavaUuid(remoteEP.Service));
            }
            else
            {
                s = _dev.CreateInsecureRfcommSocketToServiceRecord(
                    _fcty.ToJavaUuid(remoteEP.Service));
            }
            return(s);
        }
コード例 #24
0
 protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
 {
     Java.Lang.Object[] qparams = @params;
     try
     {
         if (btSocket == null || !isBtConnected)
         {
             myBluetooth = BluetoothAdapter.DefaultAdapter;                      //get the mobile bluetooth device
             BluetoothDevice sppBtDevice = myBluetooth.GetRemoteDevice(address); //connects to the device's address and checks if it's available
             btSocket = sppBtDevice.CreateInsecureRfcommSocketToServiceRecord(sppUUID);
             BluetoothAdapter.DefaultAdapter.CancelDiscovery();
             btSocket.Connect();
         }
     }
     catch (IOException e)
     {
         ConnectSuccess = false;//if the try failed, you can check the exception here
     }
     return(qparams);
 }
コード例 #25
0
        public string Connect()
        {
            try
            {
                if (mAdapter == null)
                {
                    return("No Bluetooth Adapter Found");
                }

                if (!mAdapter.IsEnabled)
                {
                    Intent intent = new Intent(BluetoothAdapter.ActionRequestEnable);
                    Android.App.Application.Context.StartActivity(intent);
                }
            }
            catch (Exception ex)
            {
                return("Please check that Bluetooth permissions are granted and Bluetooth is turned on in the device!");
            }
            if (mAdapter.StartDiscovery())
            {
                BluetoothDevice mDevice = mAdapter.GetRemoteDevice(_address);

                if (mDevice == null)
                {
                    return("Unable to find printer. Please check for the printer address and try again");
                }

                mSocket = mDevice.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString(UU_ID));

                try
                {
                    mSocket.Connect();
                }
                catch (Exception ex)
                {
                    return("Unable to pair with printer with the device");
                }
            }
            return(string.Empty);
        }
コード例 #26
0
            public ConnectThread(BluetoothDevice device, BluetoothService service, Boolean secure)
            {
                this._device  = device;
                this._service = service;
                BluetoothSocket tmp = null;

                _socketType = secure ? "Secure" : "Insecure";

                try
                {
                    tmp = secure
                        ? device.CreateRfcommSocketToServiceRecord(Constants.MY_UUID_SECURE)
                        : device.CreateInsecureRfcommSocketToServiceRecord(Constants.MY_UUID_INSECURE);
                }
                catch (IOException e)
                {
                    Log.Error(Constants.TAG, "create() failed", e);
                }
                _socket        = tmp;
                service._state = Constants.STATE_CONNECTING;
            }
コード例 #27
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);
        }
コード例 #28
0
            public override void OnReceive(Context context, Intent intent)
            {
                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);

                    var status = _view.FindViewById <TextView>(Resource.Id.textView2);
                    status.Append("\nDevice " + device.Name + " found @ " + device.Address);
                    _view.FindViewById <ScrollView>(Resource.Id.scrollView1).FullScroll(Android.Views.FocusSearchDirection.Down);

                    if (device.Name == "HC-05")
                    {
                        HC05Found = true;
                        PairHC(_view, device);
                    }

                    // When discovery is finished, change the Activity title
                }
                else if (action == BluetoothAdapter.ActionDiscoveryFinished)
                {
                    var status = _view.FindViewById <TextView>(Resource.Id.textView2);
                    status.Append("\nFinished Scanning...");
                    _view.FindViewById <ScrollView>(Resource.Id.scrollView1).FullScroll(Android.Views.FocusSearchDirection.Down);
                    if (HC05Found == false)
                    {
                        AllClear(context);
                    }
                }
                else if (action == BluetoothDevice.ActionPairingRequest)
                {
                    BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                    String          PIN    = "1234";

                    byte[] pin = new byte[0];

                    pin = System.Text.Encoding.UTF8.GetBytes(PIN);

                    try
                    {
                        device.SetPin(pin);
                    }
                    catch (Java.Lang.IllegalAccessException)
                    {
                        YellowAlert(context);
                    }
                    catch (Java.Lang.Reflect.InvocationTargetException)
                    {
                        YellowAlert(context);
                    }
                    catch (Java.Lang.NoSuchMethodException)
                    {
                        YellowAlert(context);
                    }

                    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                    BluetoothSocket  tmp = null;

                    try
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                    }
                    catch (IOException)
                    {
                        var status = _view.FindViewById <TextView>(Resource.Id.textView2);
                        status.Append("\nFailed to create bluetooth socket...");
                        _view.FindViewById <ScrollView>(Resource.Id.scrollView1).FullScroll(Android.Views.FocusSearchDirection.Down);
                        YellowAlert(context);
                    }

                    BluetoothSocket mmSocket = tmp;
                    mBluetoothAdapter.CancelDiscovery();

                    try
                    {
                        // Connect to the remote device through the socket. This call blocks
                        // until it succeeds or throws an exception.
                        mmSocket.Connect();
                    }
                    catch (IOException)
                    {
                        YellowAlert(context);
                        // Unable to connect; close the socket and return.
                        try
                        {
                            mmSocket.Close();
                        }
                        catch (IOException)
                        {
                        }
                        return;
                    }

                    ConfirmHC(_view, mmSocket, device, context);
                }
            }
コード例 #29
0
 public static BluetoothSocket GetBluetoothSocket(BluetoothDevice device)
 {
     return(device.CreateInsecureRfcommSocketToServiceRecord(Uuid));
 }
コード例 #30
0
        private async Task loop(string name)
        {
            BluetoothDevice device = null;

            _ct = new CancellationTokenSource();
            while (_ct.IsCancellationRequested == false)
            {
                try {
                    System.Threading.Thread.Sleep(200);

                    adapter = BluetoothAdapter.DefaultAdapter;

                    if (adapter == null)
                    {
                        System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Adapter found!!");
                    }

                    if (!adapter.IsEnabled)
                    {
                        System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled.");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Adapter enabled!");
                    }


                    foreach (var bd in adapter.BondedDevices)
                    {
                        System.Diagnostics.Debug.WriteLine("Paired devices found: " + bd.Name.ToUpper());
                        if (bd.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
                        {
                            device = bd;
                            break;
                        }
                    }

                    if (device == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Named device not found.");
                    }
                    else
                    {
                        UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
                        if ((int)Android.OS.Build.VERSION.SdkInt >= 10)                        // Gingerbread 2.3.3 2.3.4
                        {
                            BthSocket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
                        }
                        else
                        {
                            BthSocket = device.CreateRfcommSocketToServiceRecord(uuid);
                        }

                        if (BthSocket != null)
                        {
                            //Task.Run ((Func<Task>)loop); /*) => {
                            await BthSocket.ConnectAsync();


                            if (BthSocket.IsConnected)
                            {
                                System.Diagnostics.Debug.WriteLine("Connected!");
                                var mReader = new InputStreamReader(BthSocket.InputStream);
                                var buffer  = new BufferedReader(mReader);
                                //buffer.re
                                while (_ct.IsCancellationRequested == false)
                                {
                                    if (buffer.Ready())
                                    {
//										string barcode =  buffer
                                        //string barcode = buffer.

                                        string barcode = await buffer.ReadLineAsync();

                                        if (barcode.Length > 0)
                                        {
                                            System.Diagnostics.Debug.WriteLine("Letto: " + barcode);
                                            Xamarin.Forms.MessagingCenter.Send <App, string> ((App)Xamarin.Forms.Application.Current, "Barcode", barcode);
                                        }
                                        else
                                        {
                                            System.Diagnostics.Debug.WriteLine("No data");
                                        }
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("No data to read");
                                    }

                                    // A little stop to the uneverending thread...
                                    System.Threading.Thread.Sleep(200);
                                    if (!BthSocket.IsConnected)
                                    {
                                        System.Diagnostics.Debug.WriteLine("BthSocket.IsConnected = false, Throw exception");
                                        throw new Exception();
                                    }
                                }

                                System.Diagnostics.Debug.WriteLine("Exit the inner loop");
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("BthSocket = null");
                        }
                    }
                }
                catch {
                }

                finally{
                    if (BthSocket != null)
                    {
                        BthSocket.Close();
                    }
                    device  = null;
                    adapter = null;
                }
            }


            System.Diagnostics.Debug.WriteLine("Exit the external loop");
        }