Подключение Android Bluetooth к устройству ELM327/OBD-IIAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Подключение Android Bluetooth к устройству ELM327/OBD-II

Сообщение Anonymous »

Я попытался создать простое приложение для Android для подключения к моему устройству ELM327 и получения некоторых диагностических данных автомобиля. Но мне не удалось настроить соединение Bluetooth между моим телефоном Android и устройством ELM327.
Мой код очень прост, как показано ниже:

Код: Выделить всё

public class Bluetooth {
protected BluetoothAdapter mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
private ConnectThread mConnectThread = null;
private AcceptThread mAcceptThread = null;
private WorkerThread mWorkerThread = null;
private BluetoothDevice mOBDDevice = null;
private BluetoothSocket mSocket = null;
private String uuid;

Bluetooth() {
mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
Set 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;
}
}
}
В основном действии я сначала создам новый класс Bluetooth, а затем вызову bluetooth.connect():

Код: Выделить всё

mBluetooth = new Bluetooth();
mBluetooth.connect();
Во время отладки программы я смог получить свое Bluetooth-устройство ELM327, запросив все подключенные устройства с именем «OBD». Мне также удалось получить UUID устройства и создать сокет с помощью createRfcommSocketToServiceRecord. Но в функции подключения mSocket.connect() всегда терпит неудачу с возвращаемым значением -1, и я получаю исключение IO.
  • Когда мое приложение Android подключается к устройству ELM327, мой телефон Android является клиентом Bluetooth, а мое устройство ELM327 — сервером Bluetooth. Верно ли это понимание?
  • Есть ли серверная программа, работающая на моем устройстве ELM327, которая прослушивает и принимает входящее соединение? Это определенное поведение протокола ELM327?
  • Почему произошел сбой mSocket.connect()? Как я могу разобраться в этом вопросе? Или в моей программе очевидная ошибка?


Подробнее здесь: https://stackoverflow.com/questions/575 ... -ii-device
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»