Fitbit Gatt (Bitgatt) Documentation

Table of Contents
- Setting up the dependency
- Original Contributors
- Purpose
- Threading
- Diagram
- Architectural Overview
- Transactions
- Validation
- Pre/Post Commit (Deprecated)
- Composite Transactions
- Gatt Server
- Sample Code
- Bitgatt Scanner
- Always Connected Scanner
- Bluetooth State on Android Device
- Runtime Mocking
- Bitgatt Transaction Manual
- License
Purpose
The FitbitGatt API is designed to provide a strong state machine around
all Android gatt operations with the aim to make Android BLE development
as bomb-proof as possible.
We created a blog post to explain further why we need such a significant
abstraction on top of the Android Low Energy API : medium.com/fitbit-tech-blog/what-is-bitgatt-and-why-do-we-need-it-b884ba2ebf6d
Setting up the dependency
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.Fitbit:bitgatt:TAG'
}
Where TAG can be any of the following
- a release tag such as
v0.9.1
- a snapshot from master
master-SNAPSHOT
- a specifici commit
53ebed0415
Original Contributors
Fitbit Maintainers
Irvin Owens Jr iowens@fitbit.com, 0xbadbeef@sigsegv.us - Creator
Ionut Lepadatescu - ilepadatescu@fitbit.com - Maintainer
Fitbit Contributors
Andy Branscomb abranscomb@fitbit.com
Adriana Draghici - adraghici@fitbit.com
Cristian Ichimescu - cichimescu@fitbit.com
Murtuza Khan - murtuza.kahn@fitbit.com
Ionut Lepadatescu - ilepadatescu@fitbit.com
Irvin Owens Jr - iowens@fitbit.com
Getting Started
To use Bitgatt, you will need to add the permission for bluetooth ( and maybe admin ) into your
manifest.
To allow flexibility each component can be started individually
Starting the gatt server
The gatt server allows your application to host it's own gatt server stack that can be accessed by external bluetooth devices.
You can started in 2 ways:
FitbitGatt.startGattServer(@NonNull Context context)
or
FitbitGatt.startGattServerWithServices(@NonNull Context context, @Nullable List<BluetoothGattService> services)
In both cases the server is started asynchronously and once finished will call all FitbitGattCallback registered listeners on onGattServerStarted(GattServerConnection serverConnection) or onGattServerStartError(BitGattStartException error) depending on the success state
In component is already started when toggling bluetooth it will try automatically starting the gatt server again. It will call the same apis on success/failure
Starting the FitbitGatt scanner
The ble scanner from FitbitGatt allows discovery of any ble devices based on provided filters.
The scanner component can be started in 2 ways:
FitbitGatt.initializeScanner(@NonNull Context context)
This call is synchronous. If there is an error while trying to initialize it will call FitbitGattCallback.onScannerInitError(BitGattStartException error) for the registered listeners.
This method will not start any active scan. It will just initialize the scanner and allowing you to set filters and then start a scan type.
or
FitbitGatt.startPeriodicalScannerWithFilters(@NonNull Context context, List<ScanFilter> filters)
This second method besides initializing the scanner component it will also setup a periodical scan with the given filters.
If the filter list is empty or the gatt scanner is already it will error out.
If there is an error while trying to initialize it will call FitbitGattCallback.onScannerInitError(BitGattStartException error) for the registered listeners.
Starting the bitgatt client
If your connection is already present you may wish to start only the gatt client. This can be done by calling FitbitGatt.startGattClient(@NonNull Context context).
This will call FitbitGattCallback.onGattClientStarted() or FitbitGattCallback.onGattClientStartError(BitGattStartException error) if an error occurs.
If your app is only the client in BLE connection you will use only this component and the scanner to more reliably fetch the device.
Threading
The threading model of the Android gatt is extremely fraught with landmines.
It was very easy to end up processing data on one of the JNI binder
threads when a gatt callback returned, or in our legacy implementation
it was so limited as we had only a single execution thread that required
pre-emption.
Bitgatt does this differently, instead of providing callbacks on the JNI binder
thread, Bitgatt intentionally delivers results on the main thread while dispatching
transactions on a connection thread held by the client or server connection object
in this way dispatches are not blocked by receipts, and any I/O on the main thread
issues are caught right away (because it's I/O on the main thread). This is the same
pattern as an Android broadcast receiver so it is wise to get off of the main thread as
soon as possible to create a responsive system.
Responses will be copies of characteristics, descriptors, and services. These copies are not
able to be handed back to the system as instantiating new characteristics, descriptors and
services, then utilizing them with GATT instances will often wedge the stack. The reason
for this is that native GATT objects have an instance id inside of them. When you create a new
instance, it did not originate from the GATT DB so the instance is null. By forcing the use of
copies, bitgatt eliminates the possibility of this error from the developer.
Diagram
╔════════════════════════════════╗ ┌──────────────────────────────────────────┐
║ FitbitGatt hosts instances of ║ │FitbitGatt │
║the GattConnection, they do not ║ │Looper for asynchronous operations │
║ interfere with each other and ║ │characteristic notifications and such │
║ transactions execute serially ║ │ │
║ per connection, but ║ ┌┬┬─────────────────────────│ │──────────┐
║ asynchronously with other ║ │││ │ │ │
║ connections ║ │││ │ │ │
╚════════════════════════════════╝ │││ │ │ │
│││ │ │ │
│││ └──────────────────────────────────────────┘ │
│││ ▲ │
││▼ │ │
┌────────────────┼▼───────────────────┐ │ │
┌┴────────────────▼───────────────────┐│ │ ▼
┌┴────────────────────────────────────┐││ │ ┌───────────────────────────────────────┐
│GattConnection │││ │ │GattServerConnection │
│Looper per connection object │││ │ │Looper for the gatt server │
│Looper for gatt transaction timeout │││ │ │ │
│ │││ │ │ │
│ │││ │ │ │
│ │││ │ │ │
│ │││ │ │ │
│ │├┘ │ │ │
│ ├┘ │ │ │
└─────────────────────────────────────┘ │ └───────────────────────────────────────┘
│
│
│
┌─────────────────────────────────────┐ │
│TrackerScanner │ │
│ Main Looper │ │
│ │ │
│ │ Pushes candidate │
│ │────────devices into ─────────┘
│ │ FitbitGatt
│ │
│ │
└─────────────────────────────────────┘
╔════════════════════════════════╗
║ The tracker scanner will find ║
║devices that match a filter and ║
║will add them into the cache in ║
║ the gatt. They will only be ║
║connected if the business logic ║
║ dictates ║
║ ║
╚════════════════════════════════╝
Created with Monodraw
Architectural Overview
The general idea behind this is that we want to use the right number of threads.
This means that we will keep the serial execution nature of the legacy implementation
at the GATT level, but allow the business logic to execute gatt commands in any way
desired. This has the effect of matching the best of concurrency with the stability
of single-threadedness. In short it's an effort to limit the concurrency only where
we actually have to, but allowing concurrency anywhere else as the business logic requires.
Where necessary bitgatt provides primitives for deploying strategies around hooks to deal with
specific OEM incompatibilities or bad behavior. The intent behind this is to keep the bitgatt
core code free of "hacks" around bugs in the Android BLE code, or peripheral issues.
NOTE The present API is not stable as the library is still at 0.8.x. Improvements in the API
may still occur, especially around the scanner.
Transactions
Gatt transactions are single gatt operations such as enable characteristic notifications
on x characteristic, or write to characteristic, etc... transactions can
only be executed if the prior transaction has not ended in failure with notable
exceptions, those exceptions will be enumerated in the manual section. This will
force a developer to deal with errors explicitly and will not try to hide or to automatically
deal with errors by disconnecting and reconnecting, etc ...
Everything about the execution of gatt operations should be intentional to prevent
side effects that adjust the operation of higher-level functions, as an example
if you have implicit connection attempts, then you have to deal with the situation
where two different higher level operations could start a connection
attempt. If you make connecting explicit on a single-threaded implementation,
then this is by nature impossible, and the errors caused by it are eliminated.
Transactions are atomic. A subsequent transaction provided to the connection transaction queue
will not be executed until the prior running transaction completes in success, failure, or timeout.
Transaction Strategies
The strategies are meant to be used by bitgatt for dealing with the odd phone, tablet, or chromebook
that does not seem to want to play nice with standard GATT operations. In this case a strategy
should be hooked directly into a transaction wherever it makes sense to mitigate the adverse
behavior against the GATT ( usually in these scenarios a bug should be filed against the OEM ).