I'm having issues with random disconnects caused by the Android BLE stack.
Right after calling device.connectGatt I receive a disconnect with status 133 in my onConnectionStateChange method.
I've tested this on multiple devices running all kinds of Android versions and it happens on most of them. (More or less frequently)
I read about other cases where this behaviour seems to be caused by too many requests or faulty registered indications, but in my case there isn't even an active connection before the disconnect happens. Also I made sure nothing else but the connect request was sent to the device before this happens.
Hope someone can help me with this.
BLE support on "old" Android version can be quite hazardous, and BLE mechanisms are not easy to grasp.
I had the same issue as you did. I'm currently using RxAndroidBle, but it's basically a wrapper for the OS APIs, and highly facilitate the work, so I recommend it.
There are some things that you must remember when dealing with BLE:
- One command at a time
- Always close connections
On older version, you have to (quite mystically) set the boolean autoConnect parameter to true when trying to connect to a device while you are not scanning.
I just wasn't able to connect on my BLE device with Android < 6, set this parameter, and voilĂ , the magic happened.
Related
I am creating an app that communicates through Bluetooth Low Energy with a device, mostly to have the phone display the data from the device. I need to implement functionality where if the device and phone are moved into range, they will automatically identify as a pair and will connect without user interaction. I have been looking into Bonding to accomplish this.
I am currently trying to take the currently connected device and create a bond with it when the user clicks a ListItem. I call BluetoothDevice.createBond() on a reference to the connected BluetoothDevice variable. The Android Developer site says that for BluetoothDevice.createBond(), false will be returned if there is an error, and that I should register for ACTION_BOND_STATE_CHANGED to be informed when Bonding has started and is completed.
I have a few problems with createBond(), which is where my questions lie:
Most of the time createBond() returns false, indicating that it has failed to start bonding. What are some possible reasons for this? (My phone runs Android 4.4.2, API19 which is where createBond() is introduced - so it isn't that.)
Sometimes, bonding apparently succeeds because the code inside the ACTION_BOND_STATE_CHANGED receiver will be called. I may misunderstand what is involved in maintaining and using a bond, but the BLE device does not automatically connect to the phone when it is in range, so I am probably missing some code. After establishing a bond, what else do I need to do?
In the event that createBond() is no good for whatever reason (e.g. I have to make the app work for API18 when createBond() is introduced in API19), what alternatives are there?
Examples would be incredibly helpful. Finding information about bonding with BLE has been frustrating. Self-teaching this stuff has been difficult, especially with no tutorials lying around. On top of that, some people say it's impossible due to being "Just Works" when others say it's certainly possible. BLE is still a big cloud of confusion for me, so for now, some clarity with createBond() would be much appreciated.
I have developed an Android app that connects to a CC2540 BLE peripheral.
When I do a Characteristic write of type no response (WRITE_TYPE_NO_RESPONSE), I still get the callback onCharacteristicWrite at the app level. Is this behavior correct?
I understand there is probably a low level acknowledgement that occurs between the Android device and the peripheral.
But the reason I am asking is because this is causing an issue where I can only send a write once I have received this callback, which is slowing things down in the app.
Any light on this behavior would be appreciated it.
Thanks,
I did run into the same problem when I was trying to do some performance testing and found that when I used the WRITE_TYPE_DEFAULT specifically I stopped getting a response. There might be a bug with the android constants that is causing inverse behavior, but I am not quite not sure.
you can only make 1 transfer at a time on the low level so you need a callback to tell when the stack is ready to send another command.
If you try to send several after each other without waiting for the air-interface to be ready you can seriously crash the BLE stack! This was happening a lot on earlier iOS CoreBluetooth.
If one app crashes the BLE Stack then the phone need a reset or Bluetooth must be turned off and on again to reset the stack.
The callback just tells you that the stack has send a request over the air-interface, not that it was acknowledged by the recipient. For that you would use the other api which will make the BLE Stack re-transmit several times (depending on how the connection parameters has been negotiated).
It's stated clearly in the BLE specification that only 1 transfer can be made at a time.
If you just bang the API with write requ
I am working on a fitness app that is to supports two BLE sensors (heart rate, stride). I ended up with two bounded services (one for each sensor) called and bounded by my main activity. This is running on Nexus 7 II, with KitKat. I have spent days trying to get the app to stable state. The Gatt connections, and notifications work perfectly right after a clean reboot. The problem I am having is getting things back to a working state after one or both of the devices get disconnected and needs to be reconnected. Since similar issues have been reported by others, I have developed and tested various scenarios which included keeping the service and the connections going when the activity is restarted, closing the connections and the server and then starting fresh, closing only and not disconnecting, waiting before reconnecting, etc. Currently, with one sensor, I can get the app to reconnect most of the time. With two sensors, the connections do not get re-established most of the time. It is such a shame that android BLE API is so fragile considering that there are many new BLE devices every week. I am wondering if anyone else has had much luck with multiple BLE sensors and if they would share their approach to get it working.
This isn't a very question-y question but your comment indicates knowing what 0x85 means would help. The Android BLE API was taken from Samsung's second BLE API, but not all of the constants Samsung had defined made it over.
0x85 = 133 (which you also see in the logs) is GATT_ERROR. Basically this means that something went wrong, it could be the peripheral went out of range of the device, or the Bluetooth chip just messed up. I've found calling connect() on the BluetoothGatt in onConnectionStateChange is a decent solution since that will wait for things to get sorted out and connect when it can.
0x8D = 141 GATT_ALREADY_OPEN This one is pretty self-explanatory.
The other thing to watch out for is making sure anything happening to Bluetooth happens sequentially. Multiple threads sending commands to a BluetoothGatt before the result of the previous action happens tends to not be a good thing.
I have an android app i am developing. It's a BTLE app, i have some BTLE tags i need to talk to.
I do all by the book, discover device, GATT connect (subsequent bonding), write/read characteristics... it works.
Now the weird is that it will stop working if i close and open the application two times.
Let's say i have already one tag correctly connected, bonded and working properly.
phone reboot.
Open app the first time -> everything works.
close app, open again -> everything works.
close app again, open -> unable to receive any readCharacteristic from the GATT callbacks.
In the logs, there is NOTHING DIFFERENT from each attempt. I log each call and print return statuses: no difference. Just the readChar callback is never called.
Android is 4.3, same issue on different phones (S3, S4, Note3)
(note: on app shutdown i properly disconnect all the GATT stuff)
Do you have any ideas on what to check? Or is this a known android bug? I have searched, but could not find anything....
The bluetooth stack on Android 4.3(at least) specially for BTLE definitely has quite some issues. I don't know if it's a specific vendor implementation, driver issues, or what else, but it's honestly a nightmare for developers.
This is what i found out does help to improve things:
- disable Wifi
- forcefully enable/disable bluetooth by code (BluetoothAdapter methods enable() and disable())
In fact, cyclying bluetooth on and off when things start getting "unstable" do fix it. This requires the BLUETOOTH_ADMIN capability and might clearly not be desired, since it will briefly shut down ALL you bluetooth conencted gadgets AND will popup some dialogs to the user where he/she can disable the ongoing restart.
Now i am getting more stable results.
Still, shame on Google (or whoever i don't know) for letting such poor software out in the wild.
I am currently developing an application that will use Bluetooth Low Energy (testing on the Nexus 4). After getting started with the official BLE APIs in Android 4.3, I have noticed that after I connect a device for the first time I am rarely able to successfully connect to / communicate with that device or any other device again.
Following the guide here, I can successfully connect to a device, scan services and characteristics, and read/write/receive notifications without any issues. However, after disconnecting and re-connecting, I am often unable to either scan services/characteristics or unable to complete a read/write. I can't find anything in the logs to indicate why this is happening.
Once this happens I have to uninstall the application, disable Bluetooth, and restart the phone before it will start working again.
Whenever a device is disconnected I make sure to call close() on the BluetoothGatt object and set it to null. Any insights?
EDIT:
Log dumps: For these logs I rooted my phone and upped the trace levels of related items in /etc/bluetooth/bt_stack.conf
Successful connection - First attempt after rebooting the phone and installing the app. I am able to connect, discover all services/characteristics, and read/write.
Failed Attempt 1 - This is the next attempt after disconnecting from the successful connection above. It seems I was able to discover characteristics, but the first attempt to read returned a null value and disconnected soon thereafter.
Failed Attempt 2 - An example where I am not even able to discover services/characteristics.
EDIT 2:
The device to which I am trying to connect is based on TI's CC2541 chip. I obtained a TI SensorTag (also based on the CC2541) to play around with and discovered that TI released an android app for the SensorTag yesterday. However, this app has the same problem. I tested this on two other Nexus 4s with the same result: Connection to the SensorTag is successful the first or second time, but (according to the logs) fails to discover services thereafter, causing all sorts of crashes. I'm starting to wonder if it's an issue with this specific chip?
Important implementation hints
(Perhaps some of those hints aren't necessary anymore due to Android OS updates.)
Some devices like Nexus 4 with Android 4.3 take 45+ seconds to connect using an existing gatt instance. Work around: Always close gatt instances on disconnect and create a fresh instance of gatt on each connect.
Don't forget to call android.bluetooth.BluetoothGatt#close()
Start a new thread inside onLeScan(..) and then connect. Reason: BluetoothDevice#connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback) always fails, if called inside LeScanCallback() {...}.onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) in the same thread on Samsung Galaxy S3 with Android 4.3 (at least for build JSS15J.I9300XXUGMK6)
Most devices filter advertising
Better not use android.bluetooth.BluetoothAdapter#startLeScan(UUID[] serviceUuids, LeScanCallback callback) with the parameter to filter for certain service UUIDs because this is broken completely in Samsung Galaxy S3 with Android 4.3 and doesn't work for 128bit UUIDs in general.
Gatt always can process one command at a time. If several commands get called short after another, the first one gets cancelled due to the synchronous nature of the gatt implementation.
I often see even on modern devices with Android 5, that Wifi interferes withs bluetooth and vice versa. As a last resort, turn off wifi to stabilize bluetooth.
Tutorial for beginners
A pretty OK entry point for newcomers could be this video tutorial: Developing Bluetooth Smart Applications for Android http://youtu.be/x1y4tEHDwk0
The issue and work around described below is probably fixed now by OS updates
Work around: I could "stabilize" my app doing that...
I provide the user a setting "Restart Bluetooth". If that setting is enabled, I restart Bluetooth at some points that indicate the begin of BLE stack becoming unstable. E.g. if startScan returns false. A good point may also be if serviceDiscovery failes. I just turn Bluetooth off and on.
I provide another setting "Turn off WiFi". If that setting is enabled, my app turns off Wifi when the app is running (and turns it back on afterwards)
This work around is based on follwoing experiences...
Restarting Bluetooth helps to fix problems with BLE in most cases
If you turn off Wifi, the BLE stack gets much more stable. However, it also works fine on most devices with wifi turned on.
If you turn off Wifi, restarting Bluetooth fully recovers the BLE stack without the need to reboot the device in most cases.
Turning WIFI OFF:
I can confirm too, that turning WIFI OFF makes Bluetooth 4.0 more stable especially on Google Nexus (I have a Nexus 7).
The problem
is that the application I am developing needs both WIFI and continous Bluetooth LE scanning. So turning WIFI OFF was no option for me.
Moreover I have realised is that continous Bluetooth LE scanning can actually kill WIFI connection and make the WIFI adapter unable to re-connect to any WIFI network until BLE scan is ON. (I'm not sure about mobile networks and mobile internet).
This definitely happened on the following devices:
Nexus 7
Motorola Moto G
However BLE scanning with WIFI on seemed pretty stable on:
Samsung S4
HTC One
My workaround
I scan BLE for a short period of time 3-4 seconds then I turn scan OFF for 3-4 seconds. Then ON again.
Obviously I always turn BLE scan OFF when I'm connecting to a BLE device.
When I disconnect from a device I restart BLE (turn adapter OFF and then ON) to reset the stack before starting scan again.
I also reset BLE when discovering services or characteristics fails.
When I get advertisement data from a device that the app should connect to (lets say 500 times without being able to connect - thats about 5-10 seconds of advertising) I reset BLE again.
Make sure your Nexus is paired to the device. I can't verify whether or not the communication works properly, but you will be able to connect more than once without a reboot. It seems the first connect is not requiring pairing but all subsequent attempts do.
I will update this answer in a couple of days when I test service discovery and gatt read and write requests without a reboot.
EDIT:
It turns out I was testing on a development firmware version (our sensor) that was causing issues if not paired. Our latest production firmware build works fine on the 2540s and 2541s.
EDIT:
I did notice that on the Nexus 7 2013, connections are more stable when WiFi is turned off. I'd like to know if this helps anyone else.
EDIT:
I seem to have had it backwards with pairing. Everything works fine when not paired. After pairing, I am experiencing the exact same symptoms as the OP. It's just not known yet if this is related to our firmware or the Android BLE API. Be careful if testing this because once paired, you may not be able to unpair due to a bug explained in 3b of this post.
In some models there is a defect:
https://code.google.com/p/android/issues/detail?id=180440
On the other hand in my case the problem was, that my connection was not properly closed in onDestroy method. After correct closing, problem for me is not existing, not matter that wifi is turned on or off.
btGatt.disconnect();
btGatt.close();
I was facing a similar issue. My fix was
if (Build.VERSION.SDK_INT >= 23) {
mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
} else {
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
}
& calling close after disconnect.