Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin/Android and the dread Bluetooth LE error 133 (GATT_ERROR)

I'm trying to write a cross-platform Xamarin Forms application (in C#) to talk to Bluetooth LE devices. I've downloaded a few packages (Plugin.BLE and Acr.Ble) and neither one works (they both scan but won't connect), so I thought I would try using the Android API directly to see if that would help me understand what's failing. BTW, I'm running on a Nexus 7 tablet running Android version 6.0.1.

I'm successfully scanning for devices:

BluetoothManager bluetoothManager = (BluetoothManager)Forms.Context.GetSystemService (Android.Content.Context.BluetoothService);
m_adapter = bluetoothManager.Adapter;
if ((m_adapter == null) || (!m_adapter.IsEnabled))
    return false;
m_scanCallback = new BlueCallback (this);
m_adapter.BluetoothLeScanner.StartScan (m_scanCallback);

and I see the device I want to talk to (in this case, a TI development board MSP-EXP430F5438 in Server mode, running their SPPLE demo application). So I stop the scan:

m_adapter.BluetoothLeScanner.StopScan (m_scanCallback);

and then I connect to the desired device:

m_gattCallback = new BlueGattCallback ();
m_gatt = m_selectedDevice.ConnectGatt (Forms.Context, false, m_gattCallback);

and I pretty much immediately get a call back saying the connection failed:

BlueGattCallback.OnConnectionStateChange(gatt, status=133, newState=Disconnected)

I read this Google bug report so in my callback I tried calling Connect() directly in my callback:

if ( ((int)status == 133) && (numRetries < 10) )
{
    numRetries++;
    bool connect = gatt.Connect ();
    Debug.WriteLine ("   gatt.Connect() returned " + connect);
}

This code fails with error 133 repeatedly and quite quickly (all 10 retries take about 3 seconds).

Any idea what's going wrong here?

like image 214
Betty Crokker Avatar asked Nov 08 '22 05:11

Betty Crokker


1 Answers

As this is dependant on the BLE stack which each vendor develops, the error generally occurs on Samsung devices more than any other type, Android 6 being the most unstable.

So for anyone running into the 133 error and having many sleepless nights because of it. I would recommend using the Sweetblue wrapper, you will however need to wrap the library yourself for use in C#. It abstracts many of the unstable parts of BLE and provides good retry mechanisms as well as graceful degradation in certain cases.

But in the end this does not solve all problems and you will need to handle some of the instability yourself.

like image 103
MarkovskI Avatar answered Nov 14 '22 21:11

MarkovskI