如何让 BluetoothSocket.Connect() 成功? (读取失败,套接字可能关闭或超时,读取 ret:-1)

时间:2021-03-15 19:21:25

标签: .net-core xamarin.android android-bluetooth

我已经看过这个问题的很多版本,我已经尝试了所有建议的答案,但我和大多数海报一样,对其中任何一个都没有任何乐趣。我从在已知 UUID 上过滤的扫描中获得一个 BluetoothDevice,没有明显问题,但是当我尝试连接在该设备上创建的套接字时,连接尝试超时(似乎;它首先尝试了大约 10 秒)并抛出一个 IOException消息 读取失败,套接字可能关闭或超时,读取 ret: -1。正如您在我尝试测试建立连接的函数的代码中看到的那样,CreateRfcommSocketToServiceRecordcreateRfcommSocket 都会发生这种情况。我也尝试过两者的“不安全”版本,结果相同。

我已尝试确认设备提供了预期的 UUID,但调用 GetUuids() 会返回 null;也许这是一个线索? FetchUuidsWithSdp() 返回 true,所以我猜扫描的设备此时仍然可见。此外,两个设备都会提示确认配对,因此支持它们通信正常的想法。但是,如果该服务 UUID 不实际提供过滤的设备,我不明白如何成功扫描该设备?

这是尝试建立连接的函数:

public void Connect(BluetoothDevice device)
{
    if (device.BondState != Bond.Bonded)
    {
        device.CreateBond();
    }

    ParcelUuid[] uuids = null;
    if (device.FetchUuidsWithSdp())
    {
        uuids = device.GetUuids();
    }
    //if (null == uuids || 0 == uuids.GetLength(0))
    //{
    //    throw new System.Exception("No service UUIDs found for peripheral device");
    //}
    //UUID uuid = uuids[0].Uuid; // There should be only one service offered by one of our devices
    BluetoothSocket socket;
    try
    {
        socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(BluetoothConstants.MY_SERVICE_UUID));
        if (null == socket)
        {
            throw new Exception("Failed to create socket");
        }
        socket.Connect();
    }
    catch (IOException x)
    {
        Method method = device.Class.GetMethod("createRfcommSocket", Integer.Type);
        socket = (BluetoothSocket)method.Invoke(device, 1);
        if (null == socket)
        {
            throw new Exception("Failed to create socket");
        }
        socket.Connect();
    }
    if (false == socket.IsConnected)
    {
        throw new System.Exception(string.Format("Failed to connect to service {0}", device.Name));
    }
}

这是启动过滤扫描的代码:

    List<ScanFilter> filters = new List<ScanFilter>();
    filters.Add(new ScanFilter.Builder()
        .SetServiceUuid(new ParcelUuid(UUID.FromString(BluetoothConstants.MY_SERVICE_UUID)))
        .Build()
    );

    ScannerCallback callback = new ScannerCallback(); // inherits from ScanCallback

    BluetoothLeScanner scanner = BluetoothAdapter.DefaultAdapter.BluetoothLeScanner;

    scanner.StartScan(filters, new ScanSettings.Builder().Build(), callback);

                                                          

我很感激任何可能有帮助的建议。

编辑:我连接的设备也是我自己创建的(非常简单的)测试应用程序,而不是像心率监测器或耳机这样的标准外围设备。这可能很重要吗?

1 个答案:

答案 0 :(得分:0)

对我来说是 UUID。我不明白这些事情,但我尝试与示例 def i2d(r,c,w,h): if(h>w): return r*h + c-r+1 if(h==w): return r*h+c+1 if(h < w): return r * w + c + 1 中的一个联系起来。这是连接到我的 Arduino 上基于 HC-05 的模块并且它正在工作。