Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GATT error with 133 on onConnectionStateChange #18

Closed
prasanthmurugan opened this issue Oct 27, 2017 · 45 comments
Closed

GATT error with 133 on onConnectionStateChange #18

prasanthmurugan opened this issue Oct 27, 2017 · 45 comments
Labels
Bluetooth migrated googlesamples Migrated from old googlesamples repos

Comments

@prasanthmurugan
Copy link

My Problem

i am stuck with this problem for more then a week if any Googler out there can you help me !

After few attempt the GATT service is getting disconnected i don't know the reason.I found that the onConnectionStateChange i got the status as 62 and 133.But i don't know the exact reason or solution to solve the problem.

Connection Code:

 public boolean connectDevice(final BluetoothDevice device) {
    
    try {
        broadcastUpdate(MyUtils.ACTION_GATT_REQUEST,"Before connect called " + mContext);
        if (mContext != null) {

            mBluetoothGatt = device.connectGatt(mContext, false,
                    mGattCallback);

            setmBluetoothGatt(mBluetoothGatt);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

CallBack

 @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        String intentAction;
        Log.e(TAG, "onConnectionStateChange: status=>"+status+" newState=>"+newState);
        if (newState == BluetoothProfile.STATE_CONNECTED) {
          
            
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

         }
}
@joe-skb7
Copy link

Do you have any luck with this issue so far? I'm also having it on my OnePlus 5 (Android-N) + HM10 BLE module. Never had it on Nexus 5 (Android-M). All I managed to find on that matter is this:

https://www.reddit.com/r/androiddev/comments/4ofnbp/bluetooth_ble_development_is_miserable_on_android/?sort=top

@prasanthmurugan
Copy link
Author

prasanthmurugan commented Nov 22, 2017

Hi @joe-skb7
I managed to solve the problem like this if you get the 133 GATT error try to reconnect it again and if still the you get the error for more then 2 count then close the GATT and then start the new process for discover services .Some how this solved my problem

My code

         if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            if (status!=133&&status!=62||disconnectCount>=2) { /*If more then 2 count gatt close process*/
                disconnectCount=0;
                setConnected(false);
                intentAction = MyUtils.ACTION_GATT_DISCONNECTED;
                if (getmBluetoothGatt() != null)
                    refreshDeviceCache(mBluetoothGatt);
                getmBluetoothGatt().close();
                setmBluetoothGatt(null);

            }else { /*reconnection goes here*/
                disconnectCount++;
                if (isConnected) {
                    disconnectDevice();
                }
                connectDevice(mDevice);
            }
         }

hope it may help you B-).

@joe-skb7
Copy link

Thanks for your suggestion, @prasanthmurugan . Unfortunately, this workaround doesn't help in my case. I will try to dig further, and will provide update here if I find something.

@joe-skb7
Copy link

joe-skb7 commented Dec 6, 2017

@prasanthmurugan

I managed to fix my "status 133" error. In my case, it was happening in case when I was trying to connect to device just after doing stopScan(). Probably somewhere deep in Android frameworks the scanning wasn't finished yet. Anyway, adding 500 msec delay before connecting to GATT fixed the issue for me. Though I understand that "sleep-based synchronization" is just a workaround and we probably should wait for some STOP event in ScanCallback, before trying to connect to device.

The fix is in DeviceControlActivity.java:

    // Start GATT delay (wait for BLE scan to actually finish)
    private static final long START_GATT_DELAY = 500; // msec

    private final Handler mStartGattHandler = new Handler();
    private final Runnable mStartGattRunnable = new Runnable() {
        @Override
        public void run() {
            Intent gattServiceIntent = new Intent(DeviceControlActivity.this,
                    BluetoothLeService.class);
            bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...

        /* Start BluetoothLeService (GATT), so that mGattUpdateReceiver can receive events.
         * Start with delay: wait for BLE scan to actually finish; this eliminates "status 133"
         * connection error.
         */
        mStartGattHandler.postDelayed(mStartGattRunnable, START_GATT_DELAY);
    }

So instead of calling bindService() directly from onCreate(), I'm calling it with delay.

Btw, after fixing that issue, I found out similar solution here.

@designerMichael
Copy link

hey ,I always have the same problem,after serveral times test, I get the way to avoid "the status = 133":
1、set mBluetoothGatt = device.connectGatt(mContext, false,
mGattCallback); to
mBluetoothGatt = device.connectGatt(mContext, true,
mGattCallback);
the second param [autoconnect] to true, according to the docs,it says it would automatically connect as soon as the remote device becomes available (true)
2、just as @joe-skb7 say ,adding 500 msec delay before connecting to GATT

but I was no idea after "the status =133 " has happened, I tried to use " mBluetoothGatt.close()" but it not worked ,when I retry to scan the device ,it cannot find this device only I interrupt the power of the device, have someone meet this problem?

@joe-skb7
Copy link

joe-skb7 commented Mar 20, 2018

@designerMichael Just for your information: adding the delay is just a workaround, and frankly is a dirty hack. It doesn't fix "status 133" error in all cases, just makes it harder to reproduce. This issue is a real curse... If somebody knows the proper solution (or at least a root cause for that error), please share it with us!

@pedrovarela86
Copy link

pedrovarela86 commented Mar 20, 2018

add TRANSPORT_LE for Android greater than N.

@joe-skb7
Copy link

@pedrovarela86 Can you please share more details, like the link to relevant documentation? I wasn't able to find TRANSPORT_LTE mentioning anywhere...

@pedrovarela86
Copy link

pedrovarela86 commented Mar 20, 2018

@joe-skb7 . ConnectGATT has 4 parameters. The last one is BluetoothDevice.TRANSPORT_LE. that will fix it.

@joe-skb7
Copy link

@pedrovarela86 Cool! Thank you very much for the input, Pedro, I'll try it! Found relevant article here:

https://android.jlelse.eu/lessons-for-first-time-android-bluetooth-le-developers-i-learned-the-hard-way-fee07646624

@joe-skb7
Copy link

joe-skb7 commented Apr 4, 2018

@pedrovarela86 Seems like your hint helped, finally I'm not seeing "status 133" error anymore... Thanks again, Pedro!

@paulpv
Copy link

paulpv commented May 11, 2018

I tried TRANSPORT_LE on my personal Pixel XL and continued to fail to connect due with a status=133 error.
I reluctantly factory reset my phone and re-setup all of my [Google] accounts and then re-ran this test app and it continued to fail.
For educational purposes, I rewrote this failing Java app in Kotlin (updated to handle permissions):
https://github.com/paulpv/android-BluetoothLeGatt/tree/kotlin
It continued to fail (I didn't expect this to fix the problem).
I factory reset my phone a second time and did not re-setup any of my [Google] accounts and then ran both the Java and Kotlin test apps and they both worked...with and without the TRANSPORT_LE tweak!
I then re-setup my primary Google account and I then got 2 sequential status=133 errors, but none since then and now everything seems to be working fine.
I found it odd that I got the status=133 errors while Facebook was installing!
Reminds me of the old Android BLE scanning a max of 1,990 device mac addresses before it stopped working (https://issuetracker.google.com/issues/36991824) that required factory resets until RadiusNetworks discovered a simpler fix (http://developer.radiusnetworks.com/2014/04/02/a-solution-for-android-bluetooth-crashes.html https://github.com/RadiusNetworks/bluetooth-crash-resolver).
Android still has a big Bluetooth problem that they seem to still be in denial about.

@paulpv
Copy link

paulpv commented Aug 6, 2018

I am still fighting this shit.
(Sorry for the profanity; I'm trying to remain professional but this has been a problem for years and it is getting old how much this is crippling the company I work for.)

Similar to my above post, while debugging my non-trivial [location, maps, network, etc] private production app's use of my private BLE library and getting gatt 133 status errors, I went off and wrote a very simple [no location, maps, network, etc] stand-alone test/demo app in Kotlin to work with my same BLE library.
(Sorry, the BLE library is private, but I have made public a fairly recent copy of the code at https://github.com/SmartFoo/smartfoo/blob/master/android/smartfoo-android-lib-core/src/main/java/com/smartfoo/android/core/bluetooth/gatt/FooGattHandler.java)
The production app has started to always gets a gatt 133 status error whenever it tries to connect to a BLE device.
On the same phone to the same BLE device, the test app almost never gets a gatt 133 status error whenever it tries to connect.

Same phone, same BLE devices, different apps that use the same BLE library almost identically, consistent results that the production app fails and the test app succeeds.
It doesn't matter which app I launch after a reboot or how often I launch them and try to connect; the test app [almost] always succeeds, the production app always fails.

The production app used to work.
The test app will eventually stop working after a few weeks of use.
A factory reset gets the test app to start working again, whether or not I add my user account back to the phone.
(FYI: 3rd party apps also fail on a regular basis and start to work for awhile after a factory reset).
The production app uses Location/Maps, so requires Google Play Services, which requires Google Play, which requires an account, thus I cannot test this app without adding my user account back to the phone.

I still have a theory that restoring my user account to the phone somehow restores some problematic meta-data that causes my production app to stop working.

I have no idea [yet] why the only variation that matters for BLE connection success or failure is which of two seemingly identically performing apps the code runs from.
My only theory is user app specific meta-data that seems to be out of my control. :/

@pedrovarela86
Copy link

@paulpv check your email.

@joe-skb7
Copy link

joe-skb7 commented Aug 6, 2018

@pedrovarela86 Sorry to intrude, but if your mail has solution to this problem, can I have it too? Despite all tried workarounds, I'm still observing this "status 133" issue, and frankly it seems like some race condition inside of Android's Bluetooth framework (judging from how not related stuff can influence the bug reproducing)... If it's so, I'm not sure it could be fixed in app code. Do you have any new ideas? Thanks!

@pedrovarela86
Copy link

@joe-skb7 I didn't want to post my code because it is private, and it doesn't work like a 100% android bluetooth stack is a pain in the ass and behaves different in every phone and android every android version.

I kinda solved it making the connection calls on the main thread, and implemented some delays while communicating to the ble device. Still, my code it is not the best either, but at least.

Nevertheless, check your email.

@paulpv
Copy link

paulpv commented Aug 7, 2018

Update: I have factory reset my phone (Nexus 6P) and added a virgin account to it and my production app still cannot connect to my BLE device, but my "stand-alone" test app (that uses my same library as the production app) can.
I install both apps on a relatively new ["to me"] Pixel 2 XL and both apps work fine.
I use a second BLE device, and the production app on the Nexus 6P cannot connect to it, but the test app can, and on my Pixel 2 XL both apps can connect to either BLE device.

I am leaning toward thinking there is some sort of working "timebomb" on the phone, that after a certain amount of time/usage the BLE stops working for some devices and/or for some apps.
A mutant version of this bug on steroids:
https://issuetracker.google.com/issues/36991824
If that issue is Godzilla, this issue is Mechagodzilla.

@paulpv
Copy link

paulpv commented Aug 9, 2018

Occam's razor: Upon changing the batteries in my BLE devices the apps/library/software are performing much close to as expected.
The theory on this is that connecting to a BLE device demands more power from the battery and on weaker batteries drops the voltage to a only partially usable level during which behavior is almost non-deterministic.
This also explains why "this has been working for months".
To anyone [including myself 6 months from now] that stumbles over this issue during a search, spend 30 seconds replacing the batteries in your devices to see if anything changes.
Be safe out there!

@barmouta
Copy link

Guys,
I've found these two blogs that show how to alleviate the problem:

https://hellsoft.se/bluetooth-low-energy-on-android-part-1-1aa8bf60717d
https://hellsoft.se/bluetooth-low-energy-on-android-part-2-8fdb8ee3bfe9

Hope this helps you. It did for me.

@ened
Copy link

ened commented Sep 3, 2018

@paulpv You could try installing the SweetBlue Toolbox app to check as well.. I'm doing similar testing at the moment and found error 133 with this library but not with the toolbox app.

@ened
Copy link

ened commented Sep 4, 2018

@paulpv in fact, on my Samsung S5 it seems to be related to the scan. When scan is active, I can connect without error (and very fast). When the scan has been stopped, the connection will not always establish.

@pkeno
Copy link

pkeno commented Dec 4, 2018

Another non solution that worked for me was to restart the BLE peripheral device i was trying to connect to.

Hope it helps someone.

@HesselM
Copy link

HesselM commented Jan 4, 2019

Hi all,
Based on information here and at other places I found that the following approach gave me the best result on tackling the 133 status

When errors are persistent (you only need to do this once if the software is properly managing the connections):

  1. Turn off bluetooth
  2. Clear cache/data of your bluetooth (in settings > application manager)

Ensures faulty/incorrect connection information is removed from the device/database

  1. Wait a couple of more seconds before turning on bluetooth

this allows peripherals to mark their side of the connection as a failure/timeout.

  1. Turn on bluetooth and restart your application

Additionally, setup a connection in your software as follows:

  1. Scan for devices with startScan().
  2. Once a device is found, do connectGatt()

Schedule connectGatt() to be executed on the main-thread

  1. When encountering a 133 status error, close() connection, retry connection with connectGatt with a delay of 150ms.

Schedule this retry also on the main connection.

  1. Once max retries are reached, give up and close connection.
  2. When either services are discovered, or when given up, schedule next device for connectGatt().

Make sure only 1 device is being discovered at a time! Possible reason: discovery seems to have a low priority in the Android OS and hence is not given much resources during operation. When multiple discoveries are done simultaneously, we decrease the amount of available resources per scan, hence increasing the likelihood of a timeout / internal err

If found out that I can do a .startScan() and connectGatt() simultaneously, but connecting several devices with connectGatt() increased the amount of 133 statuses to almost 100%.

I use android studio and have configured: minSdkVersion=21 and targetSdkVersion=28

Hope this helps some of you!

@audetto
Copy link

audetto commented Mar 17, 2019

I am having the same issue.

I have create a BLE peripheral running on my Linux PC and trying to connect from an Android 7 tablet.

Eventually I would like to make it a MIDI peripheral, but I cannot even connect.
The first message to the BluetoothGattCallback is a status = 133. Tried to wait after a stop scan, added TRANSPORT_LE, but nothing works.

The funny thing is that other apps, (GATTBrowser, Bluetooth LE Gatt) can connect and browse my peripheral.

The same happens from a Samsung Tab 2 and Moto G4.

Has anyone reached a robust conclusion?

@RayChungTW
Copy link

I am having the same issue and solved by manually clear Bluetooth data & cache in "Setting -> Applications"

Device: HUAWEI Mate10 (Android 8.0.0)

Try to connect to my company's device but got 133. (But my app got SUCCESS before....)
I don't know why it happened, tried to restart APP and device but didn't work.
Finally this issue fixed by clear Bluetooth data & cache manually.

@vanitu
Copy link

vanitu commented Jun 12, 2019

Hi. In my case When I start receive 133, issue was solved by phisically restarting BLE device. So I also assume this error may caused when BLE device got some freeze.

@RayChungTW
Copy link

RayChungTW commented Jun 17, 2019 via email

@MarcusWolschon
Copy link

Guys,
I've found these two blogs that show how to alleviate the problem:

https://hellsoft.se/bluetooth-low-energy-on-android-part-1-1aa8bf60717d
https://hellsoft.se/bluetooth-low-energy-on-android-part-2-8fdb8ee3bfe9

Hope this helps you. It did for me.

404, both blog postings no longer exist.

@anilOVYO
Copy link

anilOVYO commented Aug 8, 2019

  • On some devices, it got fixed with
    mBluetoothDevice.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE);

  • on some devices like Samsung S7, A8, it was a problem with the ScanSettings.Builder().setReportDelay(400) // or 500ms. it should not be 0 or more like 1000ms.
    ScanSettings settings = new ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
    .setReportDelay(400)
    .build();`

@codingjeremy codingjeremy transferred this issue from googlearchive/android-BluetoothLeGatt Sep 17, 2019
@codingjeremy codingjeremy added the migrated googlesamples Migrated from old googlesamples repos label Sep 18, 2019
@KonovalovaKV
Copy link

Hi guys!
Is there any news to solve this problem? It is very important!

@nullbeans
Copy link

Hi Guys,

I also faced similar issues. While I didn't manage to fix the issue, I managed to work around it to avoid it. I noticed that my issues disappeared when I did the following:

  • Do not do a cancelDiscovery. Let the discovery finish by itself. For some reason when I did a cancel, my subsequent BLE connect attempts were buggy.
  • Keep your interactions with the BluetoothGatt in Android's main thread (disconnect, close, discoverServices, etc..). Yup, I know it kind of sucks, but when I did that, 99% of my issues disappeared. for example: new Handler(ctx.getMainLooper()).post( () -> gatt.close()); .

My only explaination for this behavior is buggy implementations on the phone vendor's side. Some phones are more buggy than others. Hope this info helps someone.

geeksville added a commit to geeksville/Meshtastic-Android that referenced this issue Apr 11, 2020
@QasimWani
Copy link

@joe-skb7 . ConnectGATT has 4 parameters. The last one is BluetoothDevice.TRANSPORT_LE. that will fix it.

this didn't fix my issue.

@Stan14
Copy link

Stan14 commented Apr 19, 2020

My two cents. Was working with Heart Rate BLE device, device was advertising, had no problems with scanning it but always got 133 when trying to connect.
Turned out connection is allowed ONLY when device is functioning, that is, when it is attached to the earlobe and transmits heart rate data. If I disconnect, then took it off, re-scan and try to connect - get 133, put it on my ear, try connect again - no problems whatsoever.

@M201370367
Copy link

M201370367 commented Sep 16, 2020

If 133 happens, then use the existing gatt to connect again, do not try to create a new gatt.

@lior13
Copy link

lior13 commented Sep 17, 2020

I see you all are still facing this nightmare.
We used to have a Bluetooth library that caused many troubles. We decided to write a new clean library, so I made a little research and found this article VERY useful.
The new library is already in use and it works almost flawless.

@isaidamier
Copy link
Contributor

We have recently updated our samples. Have you been able to resolve the issue you had encountered? If not might you be able to clarify based on our latest samples?

  • The specific project that pertains to the issue (for example: the 'BluetoothLeGatt' project)
  • Steps to repro the issue, the API version and Android device model
  • If the issue is not about a sample, would you please file on Stackoverflow or the issue tracker and we will take a look there?
  • Please include code snippets as appropriate

Also we have a blog post series that may be helpful

@Shimingli
Copy link

Seeing such a little friend fighting against this shit, I was so cool in my heart, hey, god, help me

@timethernom
Copy link

I was having this problem consistently whenever there were 2 BLE devices nearby. Changing the autoconnect parameter on connectGatt() to true fixed the problem.

@stevenwsg
Copy link

Many years later, does this proble have new solutation?

@timethernom
Copy link

2 thing I have learned:

  1. setting autoconnect to true causes fewer connection failures, but can be very slow, like 10's of seconds, which is not acceptable in my case
  2. Stopping scanning before attempting to connect improves reliability

@hoangvu-healthRFID
Copy link

After testing and trying many scenarios, to solve this issue I need to restart the device's BT programming:

  1. set autoconnect to false.
  2. When receiving error code 133, stop all BT scans or discovery, and also close BTGatt
  3. Turn off BT then turn on BT after at least 30s (I found out that some forums mention that after turning off the BT, it need time to completly release all old connection and catch)
  4. Start scan/discovery process (this process needs to run to re-connect)
  5. Create a new BTGatt to connect

Normally this solution can help to reconnect in the first attempt. sometimes in the third attempt

@mecoFarid
Copy link

Many years later, does this proble have new solutation?

No and will never have fixed solution. Different chips on different devices are not easy to handle since Google have decided to give manufacturers freedom on their chipset design. So this will always be "resolves my problem on XXX devices but still have the same problem on million other devices"

@Darshanr5051
Copy link

Hello,
I am a Newbie Here.

I am facing an error regarding Bluetooth.
"BT_GATT : No Resources"

ca anyone suggest me what should i do ?

@ibrahimaydindev
Copy link

Thanks Mr Pedro, it was Soluted my problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bluetooth migrated googlesamples Migrated from old googlesamples repos
Projects
None yet
Development

No branches or pull requests