# CartrackBleLock Android SDK
* [How to Install](#how-to-install)
* [Release Notes](#release-notes)
* [Devices we have tested with](#devices-we-have-tested-with)
* [Class BleService](#class-bleservice)
* [Class BleTerminal](#class-bleterminal)
* [Class BleListener](#class-blelistener)
* [How to Use](#how-to-use)
  + [Initialize CartrackBleLockSDK](#initialize-cartrackblelocksdk)
  + [Save Authentication Key](#save-authentication-key)
  + [Get Authentication Key](#get-authentication-key)
  + [Connect to Ble Terminal](#connect-to-ble-terminal)
  + [Disconnect from Ble Terminal](#disconnect-from-ble-terminal)
  + [Remove Authentication Key](#remove-authentication-key)
  + [Terminal Signal Update](#terminal-signal-update)
  + [Send Ble Action to Terminal](#send-ble-action-to-terminal)

<h2 id="how-to-install">How to Install</h2>

* Add latest version of **CartrackBleLock_Android_SDK** .aar to your android project
* Open Project level ``build.gradle`` and add ``flatDir{dirs 'libs'}``
```kotlin
allprojects {
   repositories {
      ...
      flatDir {
        dirs 'libs'
      }
   }
}
```
* And now open app level ``build.gradle`` file and add ``.aar file``
```kotlin
 dependencies {
    implementation fileTree(include: ['*.aar'], dir: 'libs')
    implementation(name: 'blesdk-release_v3.0.aar', ext: 'aar')
}
```

<h2 id="release-notes">Release Notes</h2>

**V3.0**
- Remove `VendorId`,`API key`and`country code`
- Remove `Random Key`,`Fetch Key`,`Save Key`and`Remove Key` from API
- Combine `BleConnectionError`,`BleActionError`and`BleKeyError` to `BleError`
- Remove unused `Error`
- Added `BleListener.onSaveAuthKeySuccess` called when save authentication key successfully
- Added `BleTerminal.saveAuthKey`, `BleTerminal.getAuthKey`and `BleTerminal.removeAuthKey` to handle authentication key 
- Added connection timeout parameter for `scanAndConnectToPeripheral`
- **Download:** [CartrackBleLock_Android_SDK_v3_0.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v3_0.zip)

**V2.4**
- Added `ErrorHandler` to handle all error
- Added `ErrorHandler.BleConnectionError` to indicate bluetooth connection and authentication failed error types
- Added `ErrorHandler.BleActionError` to indicate BLE action failed error types
- Added `ErrorHandler.CtgError` to indicate terminal action failed error types
- Added `BleListener.onError` to return all error from `BleListener`
- Added `BleAction.VEHICLE_GET_STATUS` to get the current state of vehicle’s ignition
- Removed `BleListener.onTerminalConnectionFailed` and merge it to `BleListener.onError`
- Changed `BleListerner.onGetAuthKey` to `BleListener.onGetAuthKeySuccess` to return success API, failure will return in `BleListener.onError`
- Changed `BleListerner.onRemoveAuthKey` to `BleListener.onRemoveAuthKeySuccess` to return success API, failure will return in `BleListener.onError`
- Changed `BleListerner.onRandomAuthKey` to `BleListener.onRandomAuthKeySuccess` to return success API, failure will return in `BleListener.onError`
- Removed `BleActionResult` from `BleListener.onTerminalResult` and it only called it success, failure will return in `BleListener.onError`
- Added `BleListener.onTerminalDidGetVehicleStatus` for showing `IgnitionState`
- Updated error code and localized description for Error Handler
- **Download:** [CartrackBleLock_Android_SDK_v2_4.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_4.zip)

**V2.3**
- Added a function `BleAction.unlockNoKeyFob` to send an unlock command `Unlock_0` that doesn't activate the key fob. The driver won't be able to start the engine.
- Receive `BleAction.unlockNoKeyFob` response in `BleTerminalDelegate.bleTerminalDidAction(terminal:action:error:)`
- **Download:** [CartrackBleLock_Android_SDK_v2_3.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_3.zip)

**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:** [CartrackBleLock_Android_SDK_v2_2_1.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_2_1.zip)

**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:** [CartrackBleLock_Android_SDK_v2_2.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_2.zip)
-
**V2.1**
- Fix unicode characters which fail to convert to proper bytes.
- **Download:** [CartrackBleLock_Android_SDK_v2_1.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_1.zip)

**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:** [CartrackBleLock_Android_SDK_v2_0.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v2_0.zip)

**V1.5**
- Fix a situation where the terminal name is null on specific smartphones, causing a crash
- **Download:** [CartrackBleLock_Android_SDK_v1_5.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_5.zip)

**V1.4**
- Fix an issue where the SDK fails to fetch the key, when the smartphone does not have stable connection
- **Download:** [CartrackBleLock_Android_SDK_v1_4.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_4.zip)

**V1.3**
- Fix a crash when phone goes outside of the terminal BLE antenna's range
- **Download:** [CartrackBleLock_Android_SDK_v1_3.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_3.zip)

**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:** [CartrackBleLock_Android_SDK_v1_2.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_2.zip)

**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:** [CartrackBleLock_Android_SDK_v1_1.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_1.zip)

**v1.0**
- Initial release
- **Download:** [CartrackBleLock_Android_SDK_v1_0.zip](https://development.cartrack.com/mobile-files/android/CartrackBleLock_Android_SDK_v1_0.zip)

<h2 id="devices-we-have-tested-with">Devices we have tested with</h2>

* Samsung galaxy s9
* Samsung galaxy a70
* Galaxy S8
* Samsung galaxy a9
* Huawei Nova 3i
* Huawei Mate 20 pro
* Samsung galaxy s20
* Samsung Note 10+
* Samsung J6
* Oppo A5
* Galaxy S7
* Oneplus 6
* Nexus 3
* HTC
* Oppo R9
* Note 5
* Sony Xperia XZ2
* Oppo R9s
* Redmi Note 4
* Pixel 4a
* One plus 8T

<h2 id="class-bleservice">Class BleService</h2>

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

<h2 id="class-bleterminal">Class BleTerminal</h2>

Provide interaction to BleTerminal

**Methods**
* `BleTerminal.saveAuthKey()` : Save authentication key to Shared Preferences
* `BleTerminal.getAuthKey()` : Get authentication key from Shared Preferences
* `BleTerminal.removeAuthKey()` : Remove authentication key to Shared Preferences
* `BleTerminal.scanAndConnectToPeripheral()` : Check authentication key exist and connect to Ble Terminal
* `BleTerminal.disconnect()` : Disconnect from Ble Terminal
* `BleTerminal.sendAction(BleAction)` : Send action to Ble Terminal
* `BleTerminal.getBleConnectionState()` : Indicate current connection state to Ble Terminal
* `BleTerminal.getLockState()` : Indicate current vehicle door lock state

<h2 id="class-blelistener">Class BleListener</h2>

Provide callback on BleTerminal process

**Methods**
* `BleListener.onTerminalConnected(BleTerminal)` : Called when terminal has connected to the device and ready to send action
* `BleListener.onTerminalCommandResult(BleTerminal)` : Called when terminal command returning 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 save authentication key Successfully
* `BleListener.onSignalStrength()` : Called on signal strength changed
* `BleListener.onRemoveAuthKeySuccess()` : Called when authentication key Remove Successfully
* `BleListener.onError(ErrorHandler)` : Called when error occur

<h2 id="how-to-use">How to Use</h2>

> **All examples require `import CartrackBleLockSDK` somewhere in the source file.**

<h3 id="initialize-cartrackblelocksdk">Initialize CartrackBleLockSDK</h3>

Initialize CartrackBleLockSDK with Context:

```kotlin
BleService.configure(Context)
```

Before starting to get the authentication key, you can create a `BleTerminal` variable outside the function:

```kotlin
var bleTerminal: BleTerminal
```

Get an instance of BleTerminal:

```kotlin
bleTerminal = BleService.getTerminal(terminalID)
```

<h3 id="save-authentication-key">Save Authentication Key</h3>

Save the authentication key with `BleTerminal.saveAuthKey()`:

```kotlin
bleTerminal.saveAuthKey()
```

<h3 id="get-authentication-key">Get Authentication Key</h3>

Get the authentication key with `BleTerminal.getAuthKey()`:

```kotlin
bleTerminal.getAuthKey()
```

> This action requires network connection thus performing it earlier is encouraged before connecting to terminal.

<h3 id="connect-to-ble-terminal">Connect to Ble Terminal</h3>

Connect to Ble Terminal with `BleTerminal.scanAndConnectToPeripheral()`:

```kotlin
bleTerminal.scanAndConnectToPeripheral()
```

Set connection timeout by add duration (second) in `Long`. Default timeout is 10 seconds:

```kotlin
bleTerminal.scanAndConnectToPeripheral(20)
```

<h3 id="disconnect-from-ble-terminal">Disconnect from Ble Terminal</h3>

Disconnect from Ble Terminal with `BleTerminal.disconnect()`:

```kotlin
bleTerminal.disconnect()
```
> This function will send a disconnect command to the terminal.

<h3 id="remove-authentication-key">Remove Authentication Key</h3>

Remove the authentication key with `BleTerminal.removeAuthKey()` from shared preferences:

```kotlin
bleTerminal.removeAuthKey()
```

> This function will not affect the authentication key on the server side.


<h3 id="terminal-signal-update">Terminal Signal Update</h3>

Called periodically to update the BLE signal strength to Ble Terminal:

```kotlin
bleListener.onSignalStrength(BleSignalStrength)
```

<h3 id="send-ble-action-to-terminal">Send Ble Action to Terminal</h3>

Send lock action to terminal `BleAction.LOCK`:

```kotlin
bleTerminal.sendAction(BleAction.LOCK)
```

Send unlock action to terminal with `BleAction.UNLOCK`:

```kotlin
bleTerminal.sendAction(BleAction.UNLOCK)
```

Send headlight action to terminal with `BleAction.HEADLIGHT`:

```kotlin
bleTerminal?.sendAction(BleAction.HEADLIGHT)
```

Send horn action to terminal with `BleAction.HORN`:

```kotlin
bleTerminal.sendAction(BleAction.HORN)
```

Get the current state of vehicle's lock status - possible value - `locked`/`unlocked` with `BleAction.GET_LOCK_STATE`:

```kotlin
bleTerminal.sendAction(BleAction.GET_LOCK_STATE)
```


Send unlock with no key fob action to terminal  with `BleAction.UNLOCK_NOKEYFOB`:

```kotlin
bleTerminal.sendAction(BleAction.UNLOCK_NOKEYFOB)
```

Get the current state of vehicle's status  with `BleAction.VEHICLE_GET_CONFIG`:

```kotlin
bleTerminal.sendAction(BleAction.VEHICLE_GET_CONFIG)
```
> 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`:

```kotlin
bleTerminal.sendAction(BleAction.VEHICLE_GET_STATUS)
```

The response for all `BleAction` will be in `BleListener.onTerminalCommandResult(bleAction: BleAction)` and `BleListener.onError(ErrorHandler.BleActionError/ErrorHandler.CtgError)`:


