I am having trouble connecting to a specific UUID of a Bluetooth device:
private void initBt() {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
blueAdapter.enable();
if (blueAdapter.isEnabled()) {
BluetoothDevice device = blueAdapter.getRemoteDevice("B0:00:00:00:00:F3");
UUID uuid = UUID.fromString("0000fff1-0000-0000-0000-00805f9b34fb");
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
outputStream = socket.getOutputStream();
} else {
Log.e("error", "Bluetooth is disabled.");
}
} else {
throw new IOException("BluetoothAdapter failure");
}
}
I want to get an output stream to this UUID so I can send messages to it.
I got the UUID from the App LightBlue.
I cannot pair the device (and I think I don't have to, if LightBlue can send messages to the UUID without manual pairing).
An IOException is thrown on socket.connect(); stating:
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
Where am I going wrong?
Thanks for your help.
UPDATE:
I also tried it with
device.createInsecureRfcommSocketToServiceRecord(uuid);
and also double checked that I have all the permissions to do so (Bluetooth, BluetoothAdmin and AccessFineLocation).
Related
I tried to create a simple android application to connect to my ELM327 device to get some car diagnostic data. But I wasn't able to set up the bluetooth connection b/t my android phone and my ELM327 device.
My code is very simple as below:
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<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;
}
}
}
In the mainactivity, I will first new a Bluetooth class then call bluetooth.connect():
mBluetooth = new Bluetooth();
mBluetooth.connect();
When I debug the program, I was able to get my ELM327 bluetooth device by querying all the bonded devices with a name of "OBD". I also was able to get the device's uuid and create a socket using createRfcommSocketToServiceRecord. But in the connect function, mSocket.connect() always fail with a return value of -1 and get a IOexception.
My questions are:
When my android application connect to the ELM327 device, my android phone is the bluetooth client and my ELM327 device is the bluetooth server, is this understanding correct?
Is there a server program running on my ELM327 device listening and accept incoming connection? Is this defined behavior of ELM327 protocol?
Any idea why mSocket.connect()has failed? Any idea on how to look into this issue? Or any obvious error in my program? Thanks.
problem solved. see source codes below:
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();
}
I don't know much about Android, although I know about OBD2 and the lot.
It depends on the type of your adapter. If you have a WiFi adapter, you can consider the adapter being the server and you the client. You connect to a socket and then read from it. In the case of a Bluetooth adapter, it's different. If you connect via rfcomm, it's a serial protocol and neither is the server nor the client. If you connect via BTLE, the OBD2 dongle is the Peripheral and you are the Central.
On WiFi adapters, yes. This behavior is not part of ELM327 though. ELM327 only specifies the serial commands. How you transfer these is not part of the spec, since it happens on the layer above (WiFi, rfcomm, BTLE, USB, etc.).
Are you sure that rfcomm works via the socket interface? It's a serial interface, so I would have expected file-like operations.
I have two apps: one acting as a Server in a device with Android 7.1.2 (a camera) ,and another one acting as Client in Android 7.0. (Samsung Galaxy S7). I did the pairing so they both appear in each other discovery method.
Client does:
...
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mmSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
...
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
}
...
And Server does:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mmServerSocket = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name",UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
...
BluetoothSocket socket = null;
boolean connected = false;
// Keep listening until exception occurs or a socket is returned.
while (true) {
if(!connected) {
try {
MyLog.d(TAG, "accepting");
socket = mmServerSocket.accept();
} catch (IOException e) {
MyLog.e(TAG, "Socket's accept() method failed");
break;
}
}
...
}
Everything works fine when I test my apps in two normal Android phones, and when I use my server in a phone and my camera as a client.
But if I try to run the server in the camera and the client in the phone then the camera gets stuck in
socket = mmServerSocket.accept();
and the client returns an IOException in
mmSocket.connect();
java.io.IOException: read failed, socket might closed or timeout, read
ret: -1
I guess it's something to do with the camera Bluetooth not accepting connections but I don't know that much about it and everything works fine when the roles are switched and the camera runs the client app.
Any ideas?
Thanks!
I am trying to create a connection between an Android smartphone (Client) with a Bluetooth app (server) running on a PC.
Below is the code snippet for Client
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
try {
//tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "create() failed", e);
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
mAdapter.cancelDiscovery();
try {
mmSocket.connect();
}
catch (IOException e) {
//Exception caught
//java.io.IOException: read failed, socket might closed or timeout, read ret: -1
...
}
...
}
Below is the server code (Uses BlueCover jar)
private void waitForConnection() {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
String uuidstr = "00001101-0000-1000-8000-00805F9B34FB";
String uuid_wo_space = uuidstr.replaceAll("-", "");
String url = "btspp://localhost:" + uuid_wo_space + ";authenticate=false;encrypt=false;name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
}
catch (Exception e) {
e.printStackTrace();
return;
}
// waiting for connection
while(true) {
try {
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
I have read several links suggesting to change the UUID to "00001101-0000-1000-8000-00805F9B34FB", which i have already tried. I have also tried creating a not secure socket using createInsecureRfcommSocketToServiceRecord, which still fails with the same result.
Below is the IOException stack trace
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:900)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:912)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:531)
Sorry for writing a new answer but this way the information is more visible than the reply. Here's an example list of UUIDs for my device:
UUID: 0000xxxx-0000-1000-8000-00805f9b34fb
i xxxx Status Mode
0 110a N.A.
1 1105 Connected Serial Port Protocol (SPP)
2 1106 Connected File transfer (FTP)
3 1116 N.A.
4 112d Connected Remote SIM mode
5 112f Connected Phone book request
6 1112 Connected
7 111f Connected
8 1132 Connected Message access request
There are usually a set of UUIDs that denote different modes of operation like File Transfer (FTP), Remote SIM, Phone book request etc.
You may query and try all the UUIDs on your interface like this:
device = (from bd in adapter.BondedDevices
where bd.Name == "YourDeviceName"
select bd).FirstOrDefault();
Android.OS.ParcelUuid[] parcel = device.GetUuids();
for (int i = 0; i < parcel.Length; i++) {
socket = device.CreateRfcommSocketToServiceRecord(parcel[i].Uuid);
try {
socket.Connect();
break;
}
catch {
throw new Exception("Unsupported UUID");
}
}
Also make sure no other device is connected to PC/Android and have an open socket because only one socket can be serviced at a time. You can have as many pairs as you want but only one socket running.
The Bluetooth tutorials i read all mentioned that i need to have the same UUID on both sides (Server and Client) to establish a connection between two devices. But what if i dont know the UUID of my Client and if i dont care?
Background information: I have over 1000 microcontrollers with bluetooth. Each microcontroller has a fix and unchangeable UUID. Smartphones should be able to send string messages to that micrcontrollers (single connection, one smartphone is controlling one microcontroller). It should not matter which Smartphone is controlling which microcontroller. So in fact i really dont care about the UUID of the Client.
So my Smartphone is the Server and is opening a listening thread for incoming Bluetooth connections but i have to put in a UUID here:
tempBluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
But when i have thousand different UUID's and i really dont care about the UUID what should i put in there? Also the BluetoothSocket:
tempBluetoothSocket = this.bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
How to know which UUID?
So the core question is: How can i connect to any microcontroller?
I've been using this:
// Unique UUID for this application
private static final UUID UUID_ANDROID_DEVICE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID UUID_OTHER_DEVICE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
And it's uses:
public AcceptThread(boolean isAndroid) {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
if(isAndroid)
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_ANDROID_DEVICE);
else
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_OTHER_DEVICE);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if(BluetoothService.this.isAndroid)
tmp = device.createRfcommSocketToServiceRecord(UUID_ANDROID_DEVICE);
else
tmp = device.createRfcommSocketToServiceRecord(UUID_OTHER_DEVICE);
} catch (IOException e) { }
mmSocket = tmp;
}
Which allows my devices to connect to any bluetooth device I've tested with. For the sake of testing, it has only been varying bluetooth barcode scanners. Although I believe this is a generic RFCOMM UUID.
It hasn't failed me yet.
I'm struggling with getting consistent bluetooth connections in a star topology. I have one master phone which is a Samsung Galaxy S4 running API 10. All of the phones that connect to the bluetoothserver socket on the S4 are LG Dynamic Tracfones also running API 10.
Over the past few days, I have seen a LOT of conflicting information on the web about what type of connection to use.
This is my current set up:
MASTER CODE
public void acceptConnection() {
.... (enable bt adapter) ...
// initializes a Bluetooth server socket
bluetoothServerSocket = bc.createBluetoothServerSocket();
//connection made to Master, discovery no longer needed
bluetoothAdapter.cancelDiscovery();
BluetoothSocket bluetoothSocket;
// loops until the thread is interrupted or an exception occurs
while (!isInterrupted()) {
try {
// attempts to accept the slave application's connection
bluetoothSocket = bluetoothServerSocket.accept();
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
Log.v("Default Thread", "Connection to slave failed.");
// breaks out of the while loop
return;
}
try {
... (enumerate all input and output streams, and all bt sockets) ...
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
}
}
This is the method that is called when creating a blueToothServerSocket, and this is where half of my confusion is. How should I listen on the adapter? Currently, I'm doing it insecurely.
public BluetoothServerSocket createBluetoothServerSocket() {
// gets the name of the application
String name = "PVCED";
// gets a common UUID for both the master and slave applications
UUID uuid = UUID.fromString("23ea856c-49da-11e4-9e35-164230d1df67");
// initializes an empty Bluetooth server socket
serverSocket = null;
try {
// creates a Bluetooth socket using a common UUID
serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(name, uuid);
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
}
return serverSocket;
}
SLAVE CODE
And this is where the other half of my confusion is, how should I create a socket? Currently I'm doing it insecurely.
private BluetoothSocket createBluetoothSocket(Set<BluetoothDevice> pairedDevices) {
// gets a common UUID for both the master and slave applications
UUID uuid = UUID.fromString("23ea856c-49da-11e4-9e35-164230d1df67");
// initialises an empty Bluetooth socket
BluetoothSocket bluetoothSocket = null;
// checks to see if there are any paired devices
if (pairedDevices.size() > 0) {
// loops through each paired device
for (BluetoothDevice device : pairedDevices) {
// checks to see if the name of the paired device is MASTER
if (device.getName().equals("MASTER")) {
try {
master = device;
// creates a Bluetooth socket using a common UUID
//bluetoothSocket = master.createRfcommSocketToServiceRecord(uuid);
//Method m = master.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[] {int.class});
//bluetoothSocket = (BluetoothSocket) m.invoke(master, 1);
bluetoothSocket = master.createInsecureRfcommSocketToServiceRecord(uuid);
} catch(Exception e){
Log.v("Connect Exception", e.getMessage());
}
}
}
}
//check if we paired succesfully to a master, if not, prompt user to do so.
if (master == null){
... (tell user to pair with master via toast) ...
}
return bluetoothSocket;
}
My logcat is often filled with errors such as "Bad File Descriptor", "Unable to start Service Discovery", or "Service Discovery has failed."
What is the best connection scheme to use for my scenario? If you guys need more details on how I'm enabling/disabling bt adapters, or closing bt connections, I can supply more code.