CartrackBleLock Android SDK
- How to Install
- Release Notes
- Class BleService
- Class BleTerminal
- Class BleListener
- How to Use
- Possible error in Ble
How to Install
- Add latest version of CartrackBleLock_Android_SDK .aar to your android project
- Open Project level
build.gradle
and addflatDir{dirs 'libs'}
{
allprojects {
repositories ...
{
flatDir 'libs'
dirs }
}
}
- And now open app level
build.gradle
file and add.aar file
{
dependencies (include: ['*.aar'], dir: 'libs')
implementation fileTree(name: 'blesdk-release_v3.0.3.aar', ext: 'aar')
implementation}
- For Android SDK 31 or higher, it must declare bluetooth permissions.
- Open app level
androidManifest.xml
manifest>
<uses-permission android:name="android.permission.BLUETOOTH"
< android:maxSdkVersion="30" />
uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<
...manifest> </
Release Notes
V3.0.3
New Features
- Implemented
reverse gear
inVehicle Status
- Created an enum class
GattError
to represent GATT errors with descriptive names and descriptions
Bug Fixes
- Corrected the
VehicleStatus.lightIsOn
to display the accurate value - Resolved slow connection issues
- Addressed ANR (Application Not Responding) problems related to connection
- Prevented heartbeat calls when an action hasn't received a response to avoid timeout
Improvements
- Added new log message for
onConnectionStateChange
to provide information about the GATT status and connection state:GattStatus = [gatt description], Connection State = [Connect/Disconnect]
Download 📦
V3.0.2
New Features
- Reintroduced
BleTerminal.hasKey()
- Added
BleError.LocationUnauthorised
to return an error when the user disallows location permission - Added
BleError.CtgError.TooManyRequest
to return an error when exceeding more than 3 concurrent commands - Added
BleError.GATTError
to return Bluetooth Gatt errors
Bug Fixes
- Fixed SDK failure to compile
- Fixed
BleListener.onSignalStrength
to read the RSSI for a connected remote device
Download 📦
V3.0.1
- Added
BleError.LocationUnauthorised
to return an error when the user disallows location permission
Download 📦
V3.0
Notice: This version has breaking changes
Before
The management of BlueTooth keys was handled by the SDK, which communicated with the Cartrack servers from the initial version to version 2.4.:
- Obtaining the key
- Key randomisation
This led to over-complicating the mobile implementation, and you could only get the key (or randomise it) while the smartphone has your app opened. In many instances, the smartphone user is in a parking lot with limited access to the cellular network. This made the whole process cumbersome.
After
This new SDK is more straightforward, and we have exported the key management into the Cartrack Fleet API. Using the API, you can now fetch the BlueTooth keys ahead of time and reuse them for multiple bookings. Have a look at the following endpoints:
-
GET /mikey/:registration, to get the key for a given vehicle registration
-
GET /mikey, to get the keys for all your vehicles
-
POST /mikey/:registration, to randomise the key for a given vehicle registration
-
API documentation: https://developer.cartrack.com/fleet-api
To enhance security, it's advisable to randomise your keys from time to time. We suggest changing the keys when there is enough time between two customers, allowing the vehicle to receive the new key and while giving enough time for the user to load that same key on their phone.
Now, you can pass the key to the user's smartphone using the SDK key function.
BleListener.onSaveAuthKeySuccess
called when save authentication key successfullyBleTerminal.saveAuthKey
,BleTerminal.getAuthKey
andBleTerminal.removeAuthKey
to handle authentication key
Release details
- Remove
VendorId
,API key
andcountry code
- Remove
Random Key
,Fetch Key
,Save Key
andRemove Key
from API - Combine
BleConnectionError
,BleActionError
andBleKeyError
toBleError
- Remove unused
Error
- Added connection timeout parameter for
scanAndConnectToPeripheral
Download 📦
V2.4.2
- Added
ErrorHandler.BleConnectionError.LocationUnauthorised
to return an error when the user disallows location permission
Download 📦
V2.4.1
- Reintroducing
BleTerminal.hasKey()
Download 📦
2.4
- Added
ErrorHandler
to handle all possible errors - Added
ErrorHandler.BleConnectionError
to indicate bluetooth connection and authentication failures and provide an error type - Added
ErrorHandler.BleActionError
to indicate when a BLE action failed and provide an error type - Added
ErrorHandler.CtgError
to indicate when a terminal action failed and provide an error type - Added
BleListener.onError
to return all error fromBleListener
- Added
BleAction.VEHICLE_GET_STATUS
to get the current state of the vehicle's ignition - Removed
BleListener.onTerminalConnectionFailed
and merge it toBleListener.onError
- Changed
BleListerner.onGetAuthKey
toBleListener.onGetAuthKeySuccess
to return success API, failure will return inBleListener.onError
- Changed
BleListerner.onRemoveAuthKey
toBleListener.onRemoveAuthKeySuccess
to return success API, failure will return inBleListener.onError
- Changed
BleListerner.onRandomAuthKey
toBleListener.onRandomAuthKeySuccess
to return success API, failure will return inBleListener.onError
- Moved errors so that they are returned in
BleListener.onError
- Added
BleListener.onTerminalDidGetVehicleStatus
for showingIgnitionState
- Updated error code and localized description for Error Handler
Download 📦
V2.3
- Added a function
BleAction.unlockNoKeyFob
to send an unlock commandUnlock_0
that doesn't activate the key fob. The driver won't be able to start the engine. - Receive
BleAction.unlockNoKeyFob
response inBleTerminalDelegate.bleTerminalDidAction(terminal:action:error:)
Download 📦
V2.2.1
- Add BleTerminal.removeAuthKey() to remove authentication key from local memory
- Add BleListener.onRemoveAuthKey(error: String?, success: Boolean?) to receive a call back when removeAuthKey() called
- Add BleTerminal.randomAuthKey() to random the terminal authentication key , call back will be received in BleListener.onGetAuthKey (error: String?, success: Boolean?)
- We now have two separate functions removeAuthKey and randomAuthKey, please consider it when upgrading to this new version.
- The Shared Preference will only save one authentication key with a static name. If you want to use another it for a different vehicle or a new authentication key, you will need to remove the current authentication key before fetching the new one.
- Bugfix for the default url
Download 📦
V2.2
- Add a new parameter apiUrl in BleService.configure().
- Add BleService.setApiUrl(apiUrl: String) for changing the apiUrl at runtime.
- Add BleService.setDefaultApiUrl() for changing the apiUrl to the default apiUrl at runtime.
Download 📦
V2.1
- Fix unicode characters which fail to convert to proper bytes.
Download 📦
V2.0
- Add a new parameter countryCode in BleService.configure().
- Please refer to iban.com/country-codes for the country code alpha-2 format.
- Add BleService.clear() for clearing BleService instance.
Download 📦
V1.5
- Fix a situation where the terminal name is null on specific smartphones, causing a crash
Download 📦
V1.4
- Fix an issue where the SDK fails to fetch the key, when the smartphone does not have stable connection
Download 📦
V1.3
- Fix a crash when phone goes outside of the terminal BLE antenna's range
Download 📦
V1.2
- Add BleTerminal.getBleConnectionState() to indicate the state of the BLE
- Fix an intermittent CRC fail at the connection between smartphone and terminal
Download 📦
V1.1
- Add BleTerminal.getLockState() to indicate vehicle's lock state
- Add BleAction.GET_LOCK_STATE action to get the latest vehicle's lock state
Download 📦
V1.0
- Initial release
Download 📦
Class BleService
The entry point of CartrackBleLock SDKs
Methods:
- BleService.configure(Context): Initialize CartrackBleLock SDK
- BleService.getTerminal(terminalID) : Get an instance of BleTerminal
- BleService.isConfigured() : Check is instance of BleTerminal configured
- BleService.clear() : Clear instance
Class BleTerminal
Provide interaction to BleTerminal
Methods:
- BleTerminal.saveAuthKey() : Encrypts the authentication key and saves it to Shared Preferences
- BleTerminal.getAuthKey() : Retrieves the encrypted authentication key from Shared Preferences, decrypts it, and returns it.
- BleTerminal.removeAuthKey() : Removes the authentication key from Shared Preferences
- BleTerminal.scanAndConnectToPeripheral() : Connects to a BleTerminal device
- BleTerminal.disconnect() : Disconnects the peripheral from the BleTerminal
- BleTerminal.sendAction(BleAction) : Executes a Bluetooth Low Energy (BLE) action on the connected peripheral
- BleTerminal.getBleConnectionState() : Retrieves the Bluetooth Low Energy (BLE) connection state of the device
- BleTerminal.getLockState() : Gets the current lock state of the vehicle
- BleTerminal.hasKey() : Checks if a terminal authentication key is available for secure communication
Class BleListener
Provide callback on BleTerminal process
Methods:
- BleListener.onTerminalConnected(BleTerminal) : Called when the BleTerminal successfully connects to a device
- BleListener.onTerminalCommandResult(BleTerminal) : Called when a terminal command returns a result
- BleListener.onTerminalDidGetVehicleStats(Command,GetVehicleStats) : Called when fetching vehicle stat
- BleListener.onTerminalDidGetVehicleStatus(Command,GetVehicleStatus) : Called when fetching vehicle status
- BleListener.onTerminalDisconnected(BleTerminal) : Called when terminal is disconnected
- BleListener.onSaveAuthKeySuccess() : Called when the authentication key is successfully saved
- BleListener.onSignalStrength() : Called when the signal strength changes
- BleListener.onRemoveAuthKeySuccess() : Called when the authentication key is successfully removed
- BleListener.onError(ErrorHandler) : Called when an error occurs during a BleTerminal operation
- BleListener.onReconnect() : Called when bluetooth gatt return GATT_ERROR or GATT_FAILURE, after reconnect 3 times then return BleError.GATTError
How to Use
All examples require
import CartrackBleLockSDK
somewhere in the source file.
Initialize CartrackBleLockSDK
Initialize CartrackBleLockSDK with Context:
V2.4
.configure(Context, vendorId, apiKey, countryCode) BleService
V3.0
.configure(Context) BleService
Before starting to get the authentication key, you can create a BleTerminal
variable outside the function:
var bleTerminal: BleTerminal
Get an instance of BleTerminal:
= BleService.getTerminal(terminalID) bleTerminal
Save Authentication Key
Save the authentication key with BleTerminal.saveAuthKey()
:
.saveAuthKey() bleTerminal
Get Authentication Key
Get the authentication key with BleTerminal.getAuthKey()
:
.getAuthKey() bleTerminal
This action requires network connection thus performing it earlier is encouraged before connecting to terminal.
Connect to Ble Terminal
Connect to Ble Terminal with BleTerminal.scanAndConnectToPeripheral()
:
V2.4
.scanAndConnectToPeripheral() bleTerminal
Under the hood, this scans peripherals around, connects and authenticates If successful, then you will get a response through BleListener.onTerminalConnected Else BleListener.onError if anything wrong happens:
- ErrorHandler.BleConnectionError.KeyNotFound
- ErrorHandler.BleConnectionError.KeyInvalid
- ErrorHandler.BleConnectionError.BluetoothUnsupported
- ErrorHandler.BleConnectionError.BluetoothUnauthorized > only if you didn't ask permission into your app
- ErrorHandler.BleConnectionError.LocationUnauthorized > only if you didn't ask permission into your app
- ErrorHandler.BleConnectionError.BluetoothPairingFailed > system return an error at the connection
- ErrorHandler.BleConnectionError.TerminalNotFound > 30 seconds timeout
V3.0
.scanAndConnectToPeripheral() bleTerminal
Under the hood, this scans peripherals around, connects and authenticates If successful, then you will get a response through BleListener.onTerminalConnected Else BleListener.onError if anything wrong happens:
- BleError.KeyNotFound
- BleError.KeyInvalid
- BleError.BluetoothUnsupported
- BleError.BluetoothUnauthorized > only if you didn't ask permission into your app
- BleError.LocationUnauthorized > only if you didn't ask permission into your app
- BleError.TerminalNotFound > system return an error at the connection
- BleError.TerminalNotFound > 30 seconds timeout
- BleError.GATTError > BluetoothGattCallback.onConnectionStateChange return other than GATT_SUCCESS
Connect to Ble Terminal with Timeout
Set connection timeout by add duration (second) in Long
. Default timeout is 10 seconds:
.scanAndConnectToPeripheral(20) bleTerminal
Disconnect from Ble Terminal
Disconnect from Ble Terminal with BleTerminal.disconnect()
:
.disconnect() bleTerminal
This function will send a disconnect command to the terminal.
Fetch Authentication Key
Fetch authentication key from API BleTerminal.fetchAuthKey()
from shared preferences:
.fetchAuthKey() bleTerminal
Remove Authentication Key
Remove the authentication key with BleTerminal.removeAuthKey()
from shared preferences:
.removeAuthKey() bleTerminal
This function will not affect the authentication key on the server side.
Terminal Signal Update
Called periodically to update the BLE signal strength to Ble Terminal:
.onSignalStrength(BleSignalStrength, rssiValue) bleListener
Check Authentication Key
Called to checks if a terminal authentication key is available for secure communication:
.hasKey() bleListener
Send Ble Action to Terminal
Send lock action to terminal BleAction.LOCK
:
.sendAction(BleAction.LOCK) bleTerminal
Send unlock action to terminal with BleAction.UNLOCK
:
.sendAction(BleAction.UNLOCK) bleTerminal
Send headlight action to terminal with BleAction.HEADLIGHT
:
?.sendAction(BleAction.HEADLIGHT) bleTerminal
Send horn action to terminal with BleAction.HORN
:
.sendAction(BleAction.HORN) bleTerminal
Get the current state of vehicle's lock status - possible value - locked
/unlocked
with BleAction.GET_LOCK_STATE
:
.sendAction(BleAction.GET_LOCK_STATE) bleTerminal
Send unlock with no key fob action to terminal with BleAction.UNLOCK_NOKEYFOB
:
.sendAction(BleAction.UNLOCK_NOKEYFOB) bleTerminal
Get the current state of vehicle's status with BleAction.VEHICLE_GET_CONFIG
:
.sendAction(BleAction.VEHICLE_GET_CONFIG) bleTerminal
Consist of
odometer
,engineHours
,engineRPM
,fuelLevel
,hazardsIsOn
,indicators
,brakesIsActive
,handBrakeIsActive
,lightsIsOn
,driverDoorIsOpen
,passengerDoorIsOpen
,driverSeatbeltIsEngage
,passengerSeatbeltIsEngage
,hornIsActive
field.
Get the current state of vehicle's ignition status - possible value - on
/off
with BleAction.VEHICLE_GET_STATUS
:
.sendAction(BleAction.VEHICLE_GET_STATUS) bleTerminal
V2.4
The response for all BleAction
will be in BleListener.onTerminalCommandResult(bleAction: BleAction)
and BleListener.onError(ErrorHandler.BleActionError/ErrorHandler.CtgError)
V3.0
The response for all BleAction
will be in BleListener.onTerminalCommandResult(bleAction: BleAction)
and BleListener.onError(BleError/BleError.CtgError)
BleError
Error Handler related to BLE Connection.
- BluetoothUnauthorized: Bluetooth permission is not granted. Ask user to grant permission from phone settings
- BluetoothDisabled: Bluetooth is disabled
- BluetoothUnsupported: Device does not support Bluetooth Low Energy
- SaveAuthKeyFailed: Failed to save authentication key in Shared Preference
- KeyNotFound: Authentication key not found in Shared Preference
- KeyInvalid: Authentication key in Shared Preference is invalid
- TerminalNotFound: Unable to discover Ble Terminal, terminal might be out of range
- NotConnected: Not connected to Ble Terminal. Call BleTerminal.connect() to connect first
- LocationUnauthorized: Location permission is not granted
- GattError: Gatt Error. Called when BluetoothGatt onConnectionStateChange return other than GATT_SUCCESS.
- CtgError: Failed due to Terminal action, refer to CtgError
CtgError
Error Handler related to CTG Terminal.
- InvalidKey: Terminal response failed with invalid key
- Timeout: Terminal response failed with time out
- Fail: Terminal response failed, default return value
- NoKey: Terminal response failed with no key
- Unsuccessful: Terminal response failed with unsuccessful
- ScriptFail: Terminal response failed with script fail
- NoScript: Terminal response failed with no script
- TooManyRequest: Terminal response failed with exceed maximum 3 concurrent commands. Any additional commands can be sent once one of the 3 previously sent commands is completed
GattError
Gatt Error. Called when BluetoothGatt onConnectionStateChange return other than GATT_SUCCESS.
- GattReadNotPermitted: GATT read operation is not permitted
- GattWriteNotPermitted: GATT write operation is not permitted
- GattInsufficientAuthentication: Insufficient authentication for a given operation
- GattRequestNotSupported: The given request is not supported
- GattInvalidOffset: A read or write operation was requested with an invalid offset
- BleHciConnectionTimeout: Could not establish a connection in specified period. Maybe when distance for connect is so long or device is currently connected to something else.
- BleHciStatusCodeCommandDisallowed: The BLE device doesn't allow the command you're trying to send
- GattInvalidAttributeLength: The data you're trying to send or receive is the wrong length
- GattInsufficientEncryption: The connection to the BLE device isn't secure enough
- BleHciStatusCodeInvalidBtleCommandParameters: The parameters you're using for the BLE command are invalid
- BleHciRemoteUserTerminatedConnection: The user on the other end terminated the BLE connection
- BleHciRemoteDevTerminationDueToLowResources: The BLE device terminated the connection because it's low on resources
- BleHciRemoteDevTerminationDueToPowerOff: The BLE device terminated the connection because it's powering off
- BleHciLocalHostTerminatedConnection: Your device terminated the BLE connection
- BleHciUnsupportedRemoteFeature: The BLE device doesn't support a feature that your device needs
- BleHciStatusCodeInvalidLmpParameters: The parameters for the Link Manager Protocol (LMP) are invalid
- BleHciStatusCodeUnspecifiedError: An unspecified error occurred with the BLE connection
- BleHciStatusCodeLmpResponseTimeout: The LMP response timed out
- BleHciStatusCodeLmpPduNotAllowed: The LMP Protocol Data Unit (PDU) isn't allowed
- BleHciInstantPassed: The instant you specified has already passed
- BleHciPairingWithUnitKeyUnsupported: The BLE device doesn't support pairing with a unit key
- BleHciDifferentTransactionCollision: A different BLE transaction collided with the current one
- BleHciControllerBusy: The BLE controller is busy and can't handle your request
- BleHciConnIntervalUnacceptable: The connection interval you requested is unacceptable to the BLE device
- BleHciDirectedAdvertiserTimeout: The directed advertising procedure timed out before a connection could be established
- BleHciConnTerminatedDueToMicFailure: The BLE connection was terminated due to a microphone failure. This could indicate a hardware issue with the microphone or a problem with the audio processing on the device.
- BleHciConnFailedToBeEstablished: The BLE connection failed to be established. This could be due to a variety of reasons, such as the device being out of range, the device being turned off, or a problem with the BLE stack on either device
- GATTNoRessources: The BLE device does not have enough resources to complete the request. This could be due to the device being low on memory or processing power
- GATTInternalError: An internal error occurred on the BLE device. This is a generic error that could indicate a variety of problems
- GATTWrongState: The BLE device is in the wrong state to complete the request. This could be due to the device not being connected or not being in the correct mode
- GATTDbFull: The BLE device's database is full. This could prevent the device from storing new data or updating existing data
- GATTBusy: The BLE device is busy and cannot handle the request at this time. This could be due to the device processing other requests or performing other tasks
- GATTError: A generic GATT error occurred. This is a catch-all error that could indicate a variety of problems
- GattIllegalParameter: An illegal parameter was passed to the GATT function. This could be due to an incorrect value being passed or a parameter being missing
- GattAuthFail: Authentication failed when attempting to connect to the BLE device. This could be due to an incorrect password or pairing key
- GattConnectionCongested: The BLE connection is congested. This could be due to too many devices being connected to the device or too much data being transferred
- GattConnectionTimeout: The BLE connection timed out. This could be due to the device being out of range or the device being turned off
- GattFailure: A generic GATT failure occurred. This is a catch-all error that could indicate a variety of problems
- Error: GATT error did not recover