首页 > 解决方案 > Android 蓝牙连接到 ELM327/OBD2 设备

问题描述

我尝试创建一个简单的 android 应用程序来连接到我的 ELM327 设备以获取一些汽车诊断数据。但我无法在我的安卓手机和我的 ELM327 设备上设置蓝牙连接。

我的代码非常简单,如下所示:

公共类蓝牙 { 受保护的蓝牙适配器 mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter(); 私有连接线程 mConnectThread = null; 私有AcceptThread mAcceptThread = null; 私有 WorkerThread mWorkerThread = null; 私有蓝牙设备 mOBDDevice = null; 私有蓝牙套接字 mSocket = null; 私有字符串 uuid;

Bluetooth() {
    mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices;


    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())
        return;

    pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        // There are paired devices. Get the name and address of each paired device.
        for (BluetoothDevice device : pairedDevices) {
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            //TODO: check whether this is OBD and whether it is connected
            //by sending a command and check response
            if (deviceName.contains("OBD")) {
                mOBDDevice = device;
                uuid = device.getUuids()[0].toString();
                break;
            }
        }
    }
    mBluetoothAdapter.cancelDiscovery();
}

/**
 * Start the chat service. Specifically start AcceptThread to begin a session
 * in listening (server) mode. Called by the Activity onResume()
 */
public synchronized void connect()
{
    try {
        // Get a BluetoothSocket to connect with the given BluetoothDevice.
        // MY_UUID is the app's UUID string, also used in the server code.
        mSocket = mOBDDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
    } catch (IOException e) {
        Log.e(TAG, "Socket's create() method failed", e);
    }

    try {
        // Connect to the remote device through the socket. This call blocks
        // until it succeeds or throws an exception.
        mSocket.connect();
    } catch (IOException connectException) {
        // Unable to connect; close the socket and return.
        try {
            mSocket.close();
        } catch (IOException closeException) {
            Log.e(TAG, "Could not close the client socket", closeException);
        }
        return;
    }
}

}

在 mainactivity 中,我将首先新建一个蓝牙类,然后调用 bluetooth.connect():

mBluetooth = 新蓝牙();mBluetooth.connect();

当我调试程序时,我可以通过查询所有名为“OBD”的绑定设备来获得我的 ELM327 蓝牙设备。我还能够获取设备的 uuid 并使用 createRfcommSocketToServiceRecord 创建一个套接字。但是在 connect 函数中,mSocket.connect() 总是失败,返回值为 -1 并得到一个 IOexception。

我的问题是:

  1. 当我的android应用程序连接到ELM327设备时,我的android手机是蓝牙客户端,我的ELM327设备是蓝牙服务器,这个理解正确吗?
  2. 在我的 ELM327 设备上运行的服务器程序是否正在侦听并接受传入连接?这是 ELM327 协议的定义行为吗?
  3. 知道为什么 mSocket.connect() 失败了吗?关于如何调查这个问题的任何想法?或者我的程序中有任何明显的错误?谢谢。

标签: androidbluetoothobd-ii

解决方案


问题解决了。请参阅下面的源代码:

public synchronized void connect() throws IOException {
        try {
            // Get a BluetoothSocket to connect with the given BluetoothDevice.
            // MY_UUID is the app's UUID string, also used in the server code.
            mSocket = mOBDDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
        } catch (IOException e) {
            Log.e(TAG, "Socket's create() method failed", e);
        }

        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mSocket.connect();
        } catch (IOException e1) {
            Log.e(TAG, "There was an error while establishing Bluetooth connection. Falling back..", e1);
            Class<?> clazz = mSocket.getRemoteDevice().getClass();
            Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
            try {
                Method m = clazz.getMethod("createRfcommSocket", paramTypes);
                Object[] params = new Object[]{Integer.valueOf(1)};
                mFallbackSocket = (BluetoothSocket) m.invoke(mSocket.getRemoteDevice(), params);
                mFallbackSocket.connect();
                mSocket.close();
                mSocket = mFallbackSocket;
            } catch (Exception e2) {
                Log.e(TAG, "Couldn't fallback while establishing Bluetooth connection.", e2);
                mSocket.close();
                //throw new IOException();
            }
        }
        inputStream = mSocket.getInputStream();
        outputStream = mSocket.getOutputStream();
    }

推荐阅读