使用Xamarin Android连接到蓝牙扫描仪 [英] Connecting to a Bluetooth Scanner with Xamarin Android

查看:422
本文介绍了使用Xamarin Android连接到蓝牙扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,我需要连接到蓝牙扫描仪(Motorola CS3070).我需要捕获输入流,并使用它来将扫描的条形码填充到列表框中.我试图创建一个安全套接字并连接到它,但是套接字无法连接. (设备已打开且已配对.如果光标在可编辑的字段中,则它可以用作物理键盘并填充扫描的代码).这是我的代码:

I am working on a project where I need to connect to a bluetooth scanner(Motorola CS3070). I need to capture the input stream and use it to populate a list box with the scanned barcode. I tried to create a secure socket and connect to it, but the socket fails to connect. (The device is ON and paired. Its working as a physical keyboard and populates the scanned code if cursor is in a editable field). This is my code:

 private static BluetoothAdapter bluetoothAdapter = null;
 private const int REQUEST_ENABLE_BT = 2;
 public static ParcelUuid UUID;
 public static Dictionary<string, string> deviceDictionary = new Dictionary<string, string>();
 public static int STATE = 0;
 public static BluetoothSocket mySocket;
 public static Activity _activity;
 private static BluetoothReceiver receiver;
 private static BluetoothDevice pairedBTDevice;

 public void InitializeBluetooth()
    {
        // Get local Bluetooth adapter
        bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

        // If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null)
        {
            Toast.MakeText(this, "Bluetooth is not available", ToastLength.Long).Show();
            Finish();
            return;
        }

        // If bluetooth is not enabled, ask to enable it
        if (!bluetoothAdapter.IsEnabled)
        {
            var enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
            StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        // Get connected devices
        var listOfDevices = bluetoothAdapter.BondedDevices;
        if (listOfDevices.Count > 0)
        {
            foreach (var bluetoothDevice in listOfDevices)
            {
                UUID = bluetoothDevice.GetUuids().ElementAt(0);
                if (!deviceDictionary.ContainsKey(bluetoothDevice.Name))
                    deviceDictionary.Add(bluetoothDevice.Name, bluetoothDevice.Address);
            }
        }
        else
        {
            connectButton.Text = "Scanner Not connected";
            connectButton.Clickable = false;
        }

        if (bluetoothAdapter.IsEnabled && listOfDevices.Count > 0)
        {
            if (listOfDevices.ElementAt(0).BondState == Bond.Bonded)
            {
                pairedBTDevice = listOfDevices.ElementAt(0);
                mySocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.Uuid);
                var thread = new Thread(BTConnect);
                thread.Start();
            }
        }
    }

    public static void BTConnect()
    {
        try
        {
            mySocket.Connect();
            _activity.RunOnUiThread(() => connectButton.Text = " Scanner Connected");
            _activity.RunOnUiThread(() => connectButton.Clickable = false);
            receiver.loop = true;
            var thread = new Thread(BTRead, "BTRead");
            thread.Start();
        }
        catch (Exception e)
        {
            _activity.RunOnUiThread(() => Toast.MakeText(_activity.ApplicationContext, "Couldn't connect. Is the device on and paired?", ToastLength.Long).Show());
            _activity.RunOnUiThread(() => connectButton.Text = "Scanner Not connected");
            _activity.RunOnUiThread(() => connectButton.Clickable = true);
            receiver.loop = false;
        }
    }

代码在mySocket.Connect();行给出了一个异常,该异常是Java.IO.IOException: "read failed, socket might closed or timeout, read ret: -1". 我还尝试使用一些我发现

The code gives an exception at the line mySocket.Connect(); The exception is Java.IO.IOException: "read failed, socket might closed or timeout, read ret: -1". I also tried to create a fallback socket with some example I found on StackOverflow here but that didn't help me. Can someone please help me resolve this.

谢谢

编辑* :我的应用程序具有以下蓝牙权限:

Edit* My application has the following bluetooth permissions:

  • android.permission.BLUETOOTH_ADMIN
  • android.permission.BLUETOOTH

推荐答案

Graham对我的的评论Xamarin论坛主题帮助了我,并朝着正确的方向推进了我. 我的代码的问题在于,我假设第一个可用的Uuid将是我需要连接到设备的那个Uuid

Graham's comment on my Xamarin Forum Thread helped me and pushed me in the right direction. The problem with my code was that I was assuming that the first available Uuid would be the one that I need to connect to the device

UUID = bluetoothDevice.GetUuids().ElementAt(0);

但是我需要做的是首先检查Uuid是否与Bluetooth串行端口配置文件匹配,从而过滤支持SPP的设备.

But What I needed to do was to first check if the Uuids matches the Bluetooth Serial Port Profile and thus filter devices which support SPP.

BluetoothService.SerialPort是所有SPP设备的标准字符串00001101-0000-1000-8000-00805f9b34fb.

BluetoothService.SerialPort is the standard string 00001101-0000-1000-8000-00805f9b34fb for all SPP devices.

这还帮助我弄清楚了我的设备已配置为使用HID蓝牙配置文件,而我需要在SPP模式下使用它.因此,我更新了代码以仅过滤支持SPP的设备,然后使用ConnectAsync()连接到该设备.现在,我可以读取InputStream了.

It also helped me figure out that my device was configured to use the HID Bluetooth profile while I needed to use it in SPP mode. So I updated my code to filter only devices supporting SPP and then used ConnectAsync() to connect to the device. And now I'm able to read the InputStream.

这篇关于使用Xamarin Android连接到蓝牙扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆