Why does Android Bluetooth stop receiving bytes after a few minutes? - android

I'm having trouble maintaining a Bluetooth connection (from Android to a device I'm developing) for longer than a few minutes.
The scenario is:
Device is paired successfully.
Device transmits to Android for somewhere between 1-7 minutes (varies by device or possibly Android version).
Android stops receiving bytes although device is still transmitting.
So: why does Android BT stop receiving?
This is very similar to the issue/observation described in bboydflo's answer to this question:
Application using bluetooth SPP profile not working after update from Android 4.2 to Android 4.3
Some more background:
The BT device I'm working with continually emits measurement packets containing ~200 characters, once per second. I am certain that the device-side is still transmitting when the issue occurs.
This sympom happens in my app on two Android devices: an Android 5.0.1 Acer tablet, and an Android 7.1.1 Moto Play X
I've tested with an app called Serial Bluetooth Terminal. This app does not experience the same issue; the connection is stable for as long as I've tested. Therefore, this issue is probably caused by something in my application code.
I've seen various responses to Android BT questions directing the user to use asynchronous streams rather than polling for received bytes. This seems to be a red herring; if you feel that the threading model is causing a probelm in this case, please clearly describe why switching to async would resolve this issue.
I would like to pre-emptively address reasons that this question may be closed:
This is not a duplicate. There are other questions on SO about BT connections dropping (i.e. Real-time Bluetooth SPP data streaming on Android only works for 5 seconds) but this is not the same issue. I have already added a keep-alive outgoing char transmitted every 1s, and my issue remains.
I'm not asking about an issue specific to my application; at least one other user on SO has encountered this problem.
I've reviewed the Android Bluetooth documentation in detail, and I can't see any obvious reason for this to happen.
I'm not asking for an opinion; I'm asking for an objective answer as to why the bytes stop being received.

Ok, I have a partial answer for this one. First, a bit more background:
I was running the BT stream polling on a thread which executed a runnable every 2s
The buffer being used to read the stream was 1024 elements long
I had a suspicious that this might be some background buffer running out of space. So, I changed the 2s to 500ms and the 1024-length to 10024. Now, I've had about 20 minutes of connectivity without any trouble (and still going).
It would be nice to find the smoking gun for this. I initially thought that stream.Available() would be sufficient to tell if a buffer was getting filled up, but in this scenario, stream.Available() is actually returning 0 when the Android device stops receiving. So I'm not really sure which queue to check to prove that this issue is related to a buffer becoming filled.

Related

Communication Timeout Disconnect status 8 after Notifications Enabled (Android 7.1.2)

I'm developing a Android Application to control a small device over BLE. The app is more or less finished, but during testing we noticed some weird behaviour. On most phones there are no issues, but on Android 7.1.2 the app keeps disconnecting after notifications are enabled.
The App works perfectly on most phones we tested on, but on Android 7.1.2 the phones disconnect with status 8 (connection timeout) once notifications are enabled.
We are using the RN4870 michrochip module, which might have some issues with it, seeing as when we wrote a simulated peripheral app to run on another phone, the problem phone connected and remained connected after notifications were enabled.
From further reading, the primary issue seems to be with the connection parameters being set to 20 seconds for supervision timeout on the problem phones, which appeared to cause issues for other developers and has appeared in various bug reports for google.
-- edit --
A link to the hci snoop file,
https://drive.google.com/open?id=1XzzwfhVGoZ__sP7R4BkMwnU-ahOgR8-a
Thanks for advance for any help, and if anyone requires anything to be edited feel free to let me know (my first forum post).
Bluetooth error code 0x08 (Connection Timeout) simply means that the two Bluetooth chips lost each other. It has nothing to do with the Android software since Android runs on the main CPU (in another chip). Having notifications enabled or not should also not make any difference, other than the fact that some data is being sent over the link to set that up.
The timeout of 20 seconds has been reduced to 5 seconds in newer Android versions since as you noticed 20 seconds are too much for most cases. It is however not a bug, just a feature.
If you get a BLE sniffer you should be able to figure out which device you should blame.

Google Nearby Connections 2.0 capabilities

I am evaluating Google Nearby connections2.0 more specifically evaluating the synergy effect of it. For this I am evaluating it against Wifi, Bluetooth and BLE in totally offline scenario, without any router.
Scenario
One device is advertising, all others (8 devices in total) are discovering. On successful connection, I am sending simple Files of 20B, 200B and 33KB sizes for 30 secs straight to each connected device.
I am using android Samsung S6 SM-G920F devices with android version: 6.0.1 and playservices version 12.8.74
I have following issues/questions
Q1: First of all at max 3 to 4 devices could be connected simulatenously more than this results into disconnect event of other devices. Even if only 3 devices are connected, and I am continuously sending message for 30seconds, one of them disconnected ? In simpler words, cannot sustain connectivity with any device for more than 45 secs. usually disconnection occur between 25 - 45 secs
Q2: I cannot send message/file continuously for 30 seconds like we can do with the Wifi like this
While(30sec){
bluetoothSocket.outputStream.write(bytes)
}
Because if I try to do this then I got the exception of too much work.I have to wait for the the callback in onTransferPayLoadUpdate()
Q3: If I try to send the file of 1MB or more to other peers, peer received the file successfully in onPayloadReceived callback but server/sender receive the successful status after too much delay. In my case it's between 1 mins to 5 mins after client callback. And I cannot send new file until I got the success callback on server. If I try to send it before getting the callback, nothing happens. Literally nothing. So In essence I can only send file of 1MB once then I have to resent both the devices to send another file.
This should be broken up into 3 separate questions. It helps future developers search easier. So if you get the time to do that, let me know and I'll split up my answer as well. But anyway, let's get into it!
A1: Nearby Connections has 3 separate strategies. The more limited the strategy, the more types of mediums we can use. So with that in mind, and with no router involved, P2P_CLUSTER will only use Bluetooth. It's the most general strategy, so it has the fewest mediums available.
All Android devices use mobile Bluetooth chips, which are unfortunately weak (but small and power sensitive), and that causes them to have a theoretical 7 device limit but a practical 3~4 device limit. To make things worst, that limit is eaten up by smart watches and paired headphones as well. That's why you're running into problems.
P2P_STAR and P2P_POINT_TO_POINT are both much more limited, because you can't connect in any direction. You need to choose who the host is beforehand and have everyone scan for and connect to that host. But you get the added benefit of WiFi hotspots, which have higher bandwidth and a larger number of simultaneous devices supported. I've seen 7 devices happily connected to a Lollipop device.
If you want to go beyond that, into the 10s and 100s, and a router isn't available, you'll have to build a mesh network. I can link you to examples of how to do that if you're interested. We don't offer support for that within Connections, but others have built meshes on top of us so we can point you in the right direction.
A2: Can you include a stack trace of the error you're seeing? Payload.Type.STREAM was built for continuously sending data. The other payload types should also work too, baring some rare but potential issues like BYTE payloads filling up the phones RAM.
A3: Both devices need to wait for onPayloadTransferUpdate(SUCCESS). onPayloadReceived is only a header, and means that there's an incoming file or stream but that the data hasn't been received yet. For byte payloads, we actually send the full byte payload inside the header so that's the only time data is immediately available.

Android BLE, Writing and Reading from the same device, without loss throughput and time

I'm currentily developing an application which uses Bluetooth Low Energy to communicate with a BLE device. The problem is that the project require an high continuous exchange of data for working.
Currently i've developed 4 fragments which share the same BluetoothGatt istance and the same data array. When i connect to the BLE device, i set the connection priority to high, then i start a writing loop which writes the data, usually just 4 bytes, every 50 mls.
At the same time i start reading and i update my interface.
I've noticed that if i stop the writing i receive a packet of data every 50 mls, but if i let the writing loop working the reading time increase from 50mls to 100 or more.
That's not a real big problem but it reduce all the sistem performances.
I looked on the internet for solutions but i didn't find nothing, except the connection priority that already helped me a lot, i'd like to know if someone have never managed such problems and how he did it. thanks
BLE Device that you are using has something which is called "connection interval". It is set in firmware of device. Minimal value for it is 7.5ms, but usually is set to 30ms or more (iOS even will not work with intervals lower than 20-30ms or it will simply miss the packets).
So when BLE device firmware is designed, connection interval is set to some value which is safe and will work with most mobile devices, and also very important to save the battery.
Al this means that you can transfer to, or from device once per connection interval, no mater if it is read, write or notification.
Some devices has configuration settings which allows changing of connection interval, but if you just wanted to know what happens, thats it.

Android Bluetooth Low Energy (BLE) API Not Ready for Prime Time

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.

Huge UDP delay/lag with Android

I'm working on an Android application which sends/receives a high volume of UDP traffic to a Windows endpoint over a WLAN (and no, I can't use TCP).
The problem is that when I ramp up the traffic, I begin to see HUGE delays between when I call sendto (the app is written with the NDK) and when I see the packet arrive at the Windows endpoint. In the neighborhood of 10 seconds! The same thing happens in reverse too: I see huge delays between the packet being sent by the Windows endpoint and being picked up by recvfrom().
Changing SO_SNDBUF has no effect, so I don't think it's an issue with the application-level buffering control.
I've verified that the problem exists on a variety of Android devices, so I don't think it's an issue with the hardware/wireless drivers
Using a sniffer and correlating the timestamps, I confirmed that the delay is occurring between calling sendto() and the packet being sent from the Android device, so the buffering isn't happening in the AP or Windows endpoint
So at this point I'm all but out of ideas. The facts would lead me to believe that the buffering is happening on the Android OS layer, but 10 seconds of 10Mbps traffic? That seems too high to be feasible for an OS where memory footprint is such a huge concern.
Also, if the issue is that I'm sending data too fast and overwhelming the OS, then I would expect sendto() to return ENOMEM or ENOBUFS... But there are no indications that anything is wrong on the Android application level.
So my question is: what's causing this delay? And is there a way to mitigate it, or do I need to alter my application to have longer timeouts or some way of detecting this condition before it gets bad?
You are sending too much.. how much are you sending? 10Mbps is definitely way too high. Bear in mind:
Every UDP datagram you send has an additional 28 byte header (UDP + IP over IPv4)
Connection link speeds are theoretical maximum limits that you will never be able to achieve
The Phone OS could be limiting you, Phone OS's need to conserve battery and try to minimise socket comms to do so.
OR
You say your CPU is at 20%, how many cores do you have - you could be maxing out the core that is doing the sending, i.e. processing speed is the bottleneck.
For people with the same problem:
Try reusing the DatagramSocket. That solved it for me.
I've seen reports of very similar behavior on the linux-rt list lately, which may be related.
http://comments.gmane.org/gmane.linux.rt.user/10163
For a several months I was haunted with spurious jitter, detected on
UDP messages - multicast UDP messages where received on originating
node without any delay, but on other nodes a delay in range of 10s of
milliseconds was detected. Simply, it looked like a message was stuck
in kernel before finally getting transmitted.
Finally, thanks to LTTng tool, I was able to locate the problem down to
this peace of code in net/sched/sch_generic.c:
There appears to be a locking issue on transmit that causes the tx stall.

Categories

Resources