BLE Android - onConnectionStateChange not being called - java

I have a problem trying to connect to a peripheral. Sometimes the callback onConnectionStateChange(...) is not called after BluetoothDevice#connectGatt(...). What I'm trying to achieve is fast and short connections triggered by user action.
This situation occurs about 1 every 10 times without specific prior action. It lasts about 20 to 30 seconds or until the application is killed and reopened. The normal sequence of steps I follow is:
Scan devices to find the peripheral.
Call BluetoothDevice#connectGatt(...). If it takes longer than 1 second to connect, it means that the connection is "stuck" and therefore it won't connect, so BluetoothDevice#connectGatt(...) is called again. This is done with a limit of 5 attempts.
onConnectionStateChange(...) is called with newState CONNECTED and begins the services discovery.
The rest of the operations are performed without problems.
After disconnection BluetoothGatt#close() is called.
The problem occurs at point 3. Sometimes onConnectionStateChange(...)is not called. I have noticed that most of the times the problem starts with a specific behavior. After calling BluetoothDevice#connectGatt(...), onConnectionStateChange(...) is called with newState CONNECTED, but almost immediately afterwards (~40 milliseconds) is called again with newStatus DISCONNECTED. Due to the short time of the status change, I can deduce that the device does not even tried to make the connection and changed the state to DISCONNECTED.
The problem ends when:
20-30 seconds have passed. During this time onConnectionStateChange(...) is never called. When the problem ends, onConnectionStateChange(...) is called the number of times that the app tried to connect. For example, if BluetoothDevice#connectGatt(...) is called 15 times, onConnectionStateChange(...) is called 15 times with newState equal to DISCONNECTED. This is curious because never in any of those connection attempts the status changed to CONNECTED.
The app is killed and started again.
This error occurs in SDK18 and SDK 21.
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
String deviceName = device.getName();
if (deviceName == null) return;
Log.d("BLUETOOTH CONNECTION", "Device found: " + device.getName());
if (mMode == SCAN_MODE) {
mListener.deviceFound(device, rssi, scanRecord);
}
else {
mDevices.put(device.hashCode(), device);
stopScan();
// Samsung devices with SDK 18 or 19 requires that connectGatt is called in main thread.
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("BLUETOOTH CONNECTION", "Executing first device.connectGatt()");
BluetoothGatt gatt = device.connectGatt(mContext, false, mGattCallback);
retryIfNecessary(device, gatt);
mTryingToConnect = true;
}
});
}
}
private void retryIfNecessary(final BluetoothDevice device, final BluetoothGatt gatt) {
if (isRetryLimitReached()) {
Log.d("BLUETOOTH CONNECTION", "Try count limit reached");
finishConnection(gatt);
mRetryCount = 0;
mListener.error(TIMEOUT);
return;
}
mRetryCount++;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("BLUETOOTH CONNECTION", "Check if it is frozen.");
if (isWorking()) {
Log.d("BLUETOOTH CONNECTION", "Frozen, create new connection.");
BluetoothGatt gatt = device.connectGatt(mContext, false, mGattCallback);
retryIfNecessary(device, gatt);
}
}
}, RETRY_INTERVAL_MS);
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) {
Log.d("BLUETOOTH CONNECTION", "On connection state changed. Device: "+ gatt.getDevice().getAddress());
if (!mConnected && BluetoothGatt.STATE_CONNECTED == newState) {
Log.d("BLUETOOTH CONNECTION", "Connected");
mTryingToConnect = false;
mTryingToDiscoverServices = true;
mConnected = true;
gatt.discoverServices();
}
else if(BluetoothGatt.STATE_DISCONNECTED == newState) {
Log.d("BLUETOOTH CONNECTION", "Disconnected and closing gatt.");
mConnected = false;
gatt.close();
if (!mConnectionFinished && mRetryCount == 0) {
finishConnection(gatt);
}
}
}
I think that the peripheral is not relevant, because the iOS app can always connect without this problem.
Any ideas? Thanks in advance.
Edit!
This answer say that:
Direct connection has interval of 60ms and window of 30ms so
connections complete much faster. Additionally there can only be one
direct connection request pending at a time and it times out after 30
seconds. onConnectionStateChange() gets called with state=2,
status=133 to indicate this timeout.
So in this 30 seconds interval there is a pending connection request and times out at the second 30. It's unlikely but, is there anything I can do to make this time shorter? Or maybe there is an explanation for the connection failure that I am not seeing. Thanks.
EDIT 02/03/2016
A new information that may help. When the problem starts (when onConnectionStateChange(...) is called with newState=DISCONNECTED after ~40ms of being called with newState=CONNECTED), the status is 62 = 0x03E. Looking here that status code means GATT_CONN_FAIL_ESTABLISH. When I detect this status I'm closing the gatt connection, but the problem persists. I also tried disconnecting and closing. Ideas? Thanks.

If someone is having a similar issue, the problem was finally solved by changing the BLE chip used by the peripheral (arduino). Before that change, a workaround I found was turning off and on the BLE after each connection. The solution was not perfect, but improved the connection rate a lot.

Android Bluetooth needs to be recycled occasionally, have you tried restarting the BLE on the device when you encounter this timeount?
Here's a snippet I've used to restart the BLE when strange things start happening.
static Handler mHandler = new Handler();
public static void restartBle() {
final BluetoothManager mgr = (BluetoothManager) ApplicationBase.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE);
final BluetoothAdapter adp = mgr.getAdapter();
if (null != adp) {
if (adp.isEnabled()) {
adp.disable();
// TODO: display some kind of UI about restarting BLE
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!adp.isEnabled()) {
adp.enable();
} else {
mHandler.postDelayed(this, 2500);
}
}
}, 2500);
}
}
}

I am not sure if you're still looking for an answer for this question. Personally, I would not advise making "fast and short connections triggered by user action" for low energy devices. Instead you could set the autoConnect option to "true" in your connectGatt method.
device.connectGatt(mContext, true, mGattCallback); [instead of false]
Hope it helps!

Related

Bluetooth connected but not sending data

I'm working on a project connecting my Android phone to an Arduino bluetooth transceiver. It works fine until the phone goes into suspend (sleep?) mode; when that happens, the bluetooth connection I establish seems to still exist, but no data is transferred. I'm using Android Sdk 30.
Here's what I do: I have a UI list with BT devices for the user to choose; after one is selected, this is called to connect:
// in my BluetoothService class
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
public void connect(BluetoothDevice device) {
try {
bluetoothDevice = device;
String uuid = getString(R.string.bluetooth_uuid);
bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));
bluetoothSocket.connect();
if (bluetoothSocket.isConnected()) {
Log.i(TAG, "connected to " + device + " with socket " + bluetoothSocket);
} else {
Log.w(TAG, "still not connected to " + device + " with socket " + bluetoothSocket);
}
} catch (IOException e) {
Log.e(TAG, "failed to connect to device", e);
}
}
So again, this works fine; the connection is established and data is sent/received.
Now, I send data every 30 seconds, and on the receiver side light an led until 60 seconds have passed with no data received.
private ScheduledFuture<?> sendScheduler; // canceled in onDestroy()
public void onCreate() {
sendScheduler = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
sendData(lastLevelSent); // i can post sendData, but it works in normal state
}, 30, 30, TimeUnit.SECONDS);
}
Now when the phone goes into sleep (ie I press the power button once), the led turns off after 60 seconds, ie no data is being received. However, the connection itself seems to still be established (I can tell by how the receiver led blinks).
When I wake the device back up, it does not resume sending data. The disconnect button in my app doesn't work (bluetoothSocket.close()), and trying to connect to the device again doesn't either. I have to kill the app, then I can disconnect.
The check I'm using whether the connection is still valid is bluetoothSocket != null && bluetoothSocket.isConnected().
I did add my app to the "don't put into standby" in the Android settings.
So how can I either convince the app to continue sending data while in sleep mode, or at least reliably check the connection status?

Internet Connection Check behaving weirdly

I've been needing a way to check if the user has Internet. I used this approach:
public class InternetCheck extends AsyncTask<Void, Void, Boolean> {
private Consumer mConsumer;
public interface Consumer {
void accept(Boolean internet);
}
public InternetCheck(Consumer consumer) {
mConsumer = consumer;
execute();
}
#Override
protected Boolean doInBackground(Void... voids) {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
Log.w("INTERNET CHECK", "has Internet");
return true;
} catch (IOException e) {
Log.w("INTERNET CHECK", "NO Internet");
return false;
}
}
#Override
protected void onPostExecute(Boolean internet) {
mConsumer.accept(internet);
}
}
... the following way:
new InternetCheck(hasInternet -> { /* do something with boolean response */ });
However, it seems like it isn't as robust as one would think: sometimes (not so often) my phone is connected to WiFi and yet this method returns false.
What are the possible scenarios/diagnostics as of why this behaviour might happen?
My personal experience is that it seems to happen when my phone has my application open and is connected to a WiFi. Then, the phone goes to sleep and I move places and open it back up to the application on a new WiFi connection. The check returns false despite my phone displaying that it clearly has established the new WiFi connection (since it was a saved network).
However, this is not the only way this method seems to have failed. Another developer had it happen while he didn't change his WiFi connection.
Wifi connections are disconnected when the phone goes to sleep. It takes time for the connection to be re-established when the phone wakes up again.
Your 1.5 second connection timeout is too short to accommodate that extra delay.
Also, the DNS server, or the intermediate network, may simply be busy. Again, the connection timeout is too short.
Before inventing your own way to check internet connectivity, you should read these:
Android Developer Guide: Determine and monitor the connectivity status
StackOverflow: Android check internet connection

Android to BLE write fails when writing more than a few bytes in quick succession

I can successfully write to an RN4020 module from my Android device. An LED lights up on the module to indicate successful receipt of transmission and I can see the ASCII character transmitted to RN4020 on an Arduino terminal.
The problem is: when I try to send characters in quick succession (for example, each time when a button on my Android app is pressed very quickly) then after 5 to 10 successful transmissions:
RN4020 stops receiving: the LED to indicate Rx never turns on and I can't see transmitted characters on the terminal.
Most times Android device doesn't recognize that the write failed but sometimes I get the following error:
D/BluetoothGatt: writeCharacteristic: mDeviceBusy = true, and return false
My code to write to BLE (everytime a button is clicked I call sendDataToRN4020):
public boolean sendDataToRN4020(char instruction){
//check mBluetoothGatt is available
if (mBluetoothGatt == null) {
Log.e(TAG, "lost connection");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID.fromString("<address uuid>"));
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic charac = Service.getCharacteristic(UUID.fromString("<service uuid>"));
if (charac == null) {
Log.e(TAG, "char not found!");
return false;
}
byte[] value = new byte[1];
value[0] = (byte) (instruction);
charac.setValue(value);
boolean status = mBluetoothGatt.writeCharacteristic(charac);
return status;
}
This is my callback for writeCharacteristic:
#Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "Successful transmission");
}
}
This may not be an Answer to your problem but I have not enough reputation to comment so I made an answer, I worked in an application using BLE to transfer data, I ran into a problem similar in which the app stops transmission even when the BLE device it's displaying that there's connection, this was because I had a scanner for compatible BLE devices, sometimes the app connects to a device multiple times because the app is constantly scanning for signals, don't know if you are doing something similar but I would recommend the following, before making a connection make sure that if there's a previous one, disconnect:
public static void connect(final String address, final String devicename, Context context) {
mContext = context;
if (mBluetoothAdapter != null && address != null) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device != null) {
forceDisconnect();
Log.i(TAG,"starting connection");
mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
}
}
This is the method to disconnect:
public static void forceDisconnect(){
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect(); // from any connected device
if (mBluetoothGatt != null) mBluetoothGatt.close();
mBluetoothGatt = null;
}
I'm not sure if this is going to be of any help, what I can tell you is that after I did this adjustments to my code I was able to send data from the BLE device without issues, perhaps it's worth knowing how is your connection code to the BLE device, anyways hope it helps.
The problem was eventually resolved. The code in the question runs perfectly on a recently released Android device. The reason the failure was happening was that the device being used for testing at the time of posting this question was at least 3 years old. Newer devices have more robust support for BLE.

Android application is hanged and showing black screen for 5-6 seconds when checking if a server port is open or not using ThreadPoolExecutor

I need to run a service if a server port is open. I am doing this by using below method.
public Future<Boolean> ifPortIsOpenThenStartIridiumService(final Context context, final String device_mac, final String device_imei, final String input_mobile) {
return Executors.newFixedThreadPool(20).submit(new Callable<Boolean>() {
#Override
public Boolean call() {
try {
String SERVER_IP = "IP Address";
int SERVER_PORT = Server_port;
int DURATION = 1000;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), DURATION);
socket.close();
Log.d(TAG, "Port is Open");
runIridiumService(context, device_mac, device_imei, input_mobile);
return true;
} catch (Exception ex) {
Log.d(TAG, "Port is not Open");
CustomToast.showToast(context, "No Internet Access.", "If in flight, please switch to \"Aeroplane Mode\" and connect to the airline's Wi-Fi network.", 1);
return false;
}
}
});
}
Above code is working but when I run this method the application is getting hanged and black screen is shown for 5-6 seconds.
I found below message on Logcat.
W/ActivityManager: Launch timeout has expired, giving up wake lock!
After that service is started and application is working well. How can I get rid of this problem?
Thanks in advance.
After some study, as far as I understood,
Android application is hanged and showing black screen for 5-6 seconds Because,
Future -
A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
So, it waits until operation is finished. You can get more info from here.
newFixedThreadPool -
At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.
Get more info from here.
The possible solution of your problem is to use ScheduledExecutorService.
Before that you can check Future is completed or not using
if (YOUR_FUTURE.isDone()){
result = (String) YOUR_FUTURE.get();
}
to avoid unwanted or extra loop.

Network request timeout or network lost or slow network not getting handle properly in codenameone

I have tried to call no of web services in a sequential manner like one by one as below. Once all web services run successfully task is over. If not then there must be showing the alert to the user.
Code:
Dialog progressDialog = ComponentUtils.getFormattedDialog(new Dialog());
progressDialog.showModeless();
boolean allDone = true;
for(int i=0;i<serviceList.size();i++){
String serviceUrl = serviceList.get(i);
boolean service = getServiceResponse(serviceUrl);
if(service==false){
progressDialog.dispose();
allDone = false;
break;
}
}
if(allDone){
progressDialog.dispose();
Dialog.show("SUCCESS","Process Done","OK",null);
}
else{
Dialog.show("FAIL","Process Failed","OK",null)
}
...
public static boolean getServiceResponse(String serviceUrl){
boolean isSuccess = false;
ConnectionRequest connectionRequest = new ConnectionRequest() {
#Override
protected void handleErrorResponseCode(int code, String message) {
this.kill();
LogUtil.setErrorLog(message,page_name+ " > handleErrorResponseCode");
isSuccess = false
}
#Override
protected void handleException(Exception err) {
this.kill();
LogUtil.setErrorLog(err,page_name + " > handleException");
isSuccess = false
}
#Override
protected void readResponse(InputStream input) {
isSuccess = true
}
};
connectionRequest.setUrl(serviceUrl);
connectionRequest.setContentType("application/x-www-form-urlencoded");
connectionRequest.setPost(true);
connectionRequest.setDuplicateSupported(true);
connectionRequest.setTimeout(100000);
NetworkManager.getInstance().addToQueueAndWait(connectionRequest);
return isSuccess;
}
Whenever I am trying to sync process in the full network it works fine as aspected.
But during the process, if network runs slow or lost then it will not tend to alert the user to the issue. instead, it just sticks on process dialog.
I have added error log in one file to check later on for the issue. But that also not showing any error in this case.
Any help will be more appreciable.
Timeout in Codename One is currently limited to connection timeout and doesn't apply to read timeout so once a connection is made it will last. You can use a progress listener on the NetworkManager to detect such situations and kill the connection.

Categories