DFU SDK
The dfu module updates the firmware of a Corsano bracelet (DFU: Device Firmware Update). The firmware images ship inside the SDK, so an update needs no download and no network connection. You give the SDK the address and the hardware ID of the bracelet, and it uploads the image over Bluetooth.
implementation platform("com.corsano.sdk:bom:3.0.0")
implementation "com.corsano.sdk:dfu"
The dfu module needs the data module and its licence key too. See Installing SDK to your project and Licence Key.
From SDK 3.0.0:
- The 287-2B is updated to firmware 9.50 (it was 8.65). The 287-1B stays on 4.20.
- An update does not start when the bracelet's battery is below 30 %.
- Older 287-2B firmware is in a second artefact,
com.corsano.sdk:dfu-archive, whichdfubrings by default. See Firmware versions.
A 287-2B on firmware 9.42 or later cannot go back to firmware 8.x or older. The default update of SDK 3.0.0 installs 9.50, so read No way back from firmware 9.42 or later before you ship an app that updates bracelets.
Before you start
| What | Why |
|---|---|
CorsanoSdk.initialize() has run | It initializes the DFU module. A CorsanoDfu.Config is optional. See Setting up. |
| The bracelet is a 287-1B or a 287-2B | Firmware is bundled for these two only. See The hardwareId parameter. |
BLUETOOTH_CONNECT is granted (Android 12 and later) | The same runtime permission you need to connect. See Pairing. |
Your app is in the foreground when you call startDfu | Android can refuse to start the DFU service for an app in the background. The update then fails with DfuError.START_FAILED. |
| The bracelet's battery is at 30 % or more | Below 30 % the update is refused with DfuError.BRACELET_BATTERY_TOO_LOW. Ask the user to charge the bracelet first. |
| The SDK is not locked by the licence check | A locked SDK refuses the update with DfuError.LICENCE_LOCKED. See Licence Key. |
The module's manifest is merged into your app at build time. It declares the DfuService and these permissions: BLUETOOTH, BLUETOOTH_CONNECT, BLUETOOTH_SCAN, FOREGROUND_SERVICE and FOREGROUND_SERVICE_CONNECTED_DEVICE. You do not have to declare the service or these permissions yourself. See Upload behaviour for the foreground service and its notification.
Setting up
The DFU module is initialized by CorsanoSdk.initialize(). To set its parameters, add a CorsanoDfu.Config to the CorsanoSdkConfig. See Getting Started.
CorsanoDfu.Config
| Parameter | Type | Default | Description |
|---|---|---|---|
notificationTarget | Class<out Activity>? | null | The activity opened when the user taps the notification shown during an update. With null, a tap does nothing. |
logger | SdkLogger? | null | A logger for the DFU module alone. With null, the module uses the logger of CorsanoSdkConfig. |
Once the SDK is initialized, everything goes through the singleton:
val dfu = CorsanoDfu.getInstance()
getInstance() throws IllegalArgumentException ("Not initialized") when CorsanoSdk.initialize() has not run yet. It does not need a CorsanoDfu.Config: without one, the module is initialized with the default values above.
Updating a bracelet
- Read the bracelet's hardware ID and firmware version.
- Ask
needDfuwhether the SDK has a newer firmware. - Register a
DfuListenerand callstartDfu. - Wait for
onDfuCompleted,onDfuFailedoronDfuAborted.
import com.corsano.sdk.ble.BleSdk
import com.corsano.sdk.ble.command.request.GetFwVersionRequest
import com.corsano.sdk.ble.command.request.GetHwIdRequest
import com.corsano.sdk.ble.data.HardwareId
import com.corsano.sdk.data.util.awaitCommandV2
import com.corsano.sdk.dfu.CorsanoDfu
// address: the MAC address of a connected and initialized bracelet
val bleDevice = BleSdk.getInstance().getDevice(address)
val hardware: HardwareId =
bleDevice.awaitCommandV2(GetHwIdRequest(), timeout = 10_000).getOrNull() ?: HardwareId.UNKNOWN
val firmwareVersion = bleDevice.awaitCommandV2(GetFwVersionRequest(), timeout = 10_000).getOrNull()
val supported = hardware == HardwareId.BRACELET_287N || hardware == HardwareId.BRACELET_287N_2B
if (supported && firmwareVersion != null) {
val dfu = CorsanoDfu.getInstance()
if (dfu.needDfu(hardware.value, firmwareVersion)) {
dfu.addDfuListener(listener) // a DfuListener, see below
dfu.startDfu(address, hardware.value) // returns at once; installs 9.50 on a 287-2B
}
}
awaitCommandV2 is a suspend function of the data module; see BLE commands for the callback style. The scan also gives the hardware ID before you connect: BleScanRecord.advertisementData?.hardwareId.
What you get, and where it arrives:
| You want | Where it arrives |
|---|---|
| Each step of the update | DfuListener.onDfuStatusChanged(address, status). See DfuStatus. |
| The upload progress | DfuListener.onUploadProgress(address, percentage, part, totalParts) |
| The end of the update | onDfuCompleted, onDfuFailed(address, error) or onDfuAborted. Exactly one of them is called. |
| The reason of a failure | DfuError.errorCode and DfuError.message. See DfuError. |
| The current state at any time | CorsanoDfu.getInstance().getDfuState(). See DfuState. |
After onDfuCompleted the bracelet restarts on the new firmware. Read GetFwVersionRequest() again once the bracelet is connected to confirm the version.
Keep the phone near the bracelet and keep your app running until the update ends. An update that is interrupted (Bluetooth switched off, the app removed from the recent apps) can leave the bracelet in its bootloader. See DFU recovery.
The hardwareId parameter
Every method below takes a hardwareId as an Int, not as the enum. Pass the value of the HardwareId:
val hardwareId: Int = hardware.value // hardware is a HardwareId
GetHwIdRequest returns the HardwareId of a connected bracelet (see Updating a bracelet). In the sample app, currentDevice.deviceInfo.hardwareId is filled this way; DeviceManager and deviceInfo are sample-app helpers, not SDK API.
HardwareId | Value | Device |
|---|---|---|
WATCH_284N | 38 | Watch 284N |
WATCH_287N | 50 | Watch 287N |
BRACELET_287N | 51 | CardioWatch 287-1B ("B1") |
BRACELET_287N_2B | 54 | CardioWatch 287-2B ("B2") |
UNKNOWN | -1 | Unrecognised |
Firmware images are bundled only for B1 (51) and B2 (54). Any other value, UNKNOWN included, makes needDfu, getLatestFirmwareVersion, getAvailableVersion and startDfu(address, hardwareId) throw an Error (java.lang.Error, which catch (e: Exception) does not catch). Always check that the hardware ID is one of the two bracelets before you call them.
Firmware versions
| Bracelet | Default version | Other versions you can install |
|---|---|---|
| 287-1B (51) | 4.20 | None |
| 287-2B (54) | 9.50 (since SDK 3.0.0; 8.65 in SDK 2.3.0) | See below |
The default version is the one startDfu(address, hardwareId) installs, getLatestFirmwareVersion and getAvailableVersion return, and needDfu compares with.
For the 287-2B, startDfu(address, hardwareId, specificVersion) accepts these versions:
| Artefact | 287-2B versions |
|---|---|
com.corsano.sdk:dfu | 6.87, 8.65, 9.42, 9.50 |
com.corsano.sdk:dfu-archive | 5.39, 5.72, 5.82, 6.45, 6.65, 7.14, 7.20, 7.23, 7.34, 7.48, 7.65, 7.97, 8.12, 8.26, 8.48, 9.43, 9.44, 9.45, 9.48, 9.49 |
com.corsano.sdk:dfu-archive is new in SDK 3.0.0. It holds firmware zips only, no code. com.corsano.sdk:dfu brings it by default, so your app keeps every version of SDK 2.3.0 without a change to its build.
No way back from firmware 9.42 or later
From firmware 9.42, the 287-2B does not allow a downgrade to a lower major version. A bracelet that runs 9.42 or later cannot be taken back to 8.x, 7.x, 6.x or 5.x. Moving between 9.x versions is not affected.
This is a rule of the bracelet's firmware. The SDK does not check it before an update starts, so do not rely on startDfu to refuse such a version.
| Bracelet runs | You can install |
|---|---|
| Below 9.42 | The rule does not apply |
| 9.42 or later | 9.x versions only: 9.42, 9.43, 9.44, 9.45, 9.48, 9.49, 9.50 |
What this means for your app:
- Validate firmware 9.42 or later with your product before you roll it out. Once a bracelet is on it, you cannot return that bracelet to 8.x.
- The default update crosses this point. In SDK 3.0.0 the default for the 287-2B is 9.50:
startDfu(address, hardwareId)installs it, andneedDfuistruefor every bracelet below it. An app that updates wheneverneedDfuistruemoves every 287-2B to 9.50 as soon as it runs on SDK 3.0.0. - To stay on 8.x for now, do not call
startDfu(address, hardwareId)and do not followneedDfu. Compare the bracelet's version with the version you validated, and install that one withstartDfu(address, hardwareId, specificVersion), for exampleFirmwareVersion(8, 65).
Leaving out the archive
If your app never installs a version of the dfu-archive row, you can leave the artefact out. Your APK becomes about 7 MB smaller. Exclude it on the dfu dependency:
implementation("com.corsano.sdk:dfu") {
exclude group: "com.corsano.sdk", module: "dfu-archive"
}
A version whose zip you left out is then unknown to the SDK: startDfu with that version throws IllegalArgumentException. The default versions and 6.87, 8.65 and 9.42 are not affected.
Checking that a version is available
FirmwareConfig.getSpecificVersion(hardwareId, version) returns a FirmwareConfig, or null when you cannot install that version:
import com.corsano.sdk.dfu.FirmwareConfig
val available = FirmwareConfig.getSpecificVersion(hardwareId, FirmwareVersion(8, 26)) != null
It returns null:
- for every hardware other than the 287-2B, also for 4.20 on a 287-1B;
- for a version the SDK does not have;
- for a version of
dfu-archivewhen your app excludes that artefact; - for a version of
dfu-archivebeforeCorsanoSdk.initialize()has run, also when your app includes the artefact. The SDK finds the archived zips by name, and it can only do that once it is initialized. In SDK 2.3.0 these versions were answered at any time.
FirmwareConfig.getLatest(hardwareId) and CorsanoDfu.getAvailableVersion(hardwareId) answer for a 287-1B and a 287-2B at any time, also before initialization.
A result other than null only says that the SDK has the firmware. It does not say that the bracelet accepts it, see No way back from firmware 9.42 or later.
Methods
needDfu
fun needDfu(hardwareId: Int, currentVersion: FirmwareVersion): Boolean
Whether the default firmware for this hardware is newer than currentVersion. Equivalent to currentVersion < getLatestFirmwareVersion(hardwareId).
| Parameter | Type | Description |
|---|---|---|
hardwareId | Int | Hardware ID of the bracelet |
currentVersion | FirmwareVersion | Firmware currently on the bracelet |
Returns Boolean: true if an update is available. From SDK 3.0.0 it is true for every 287-2B below 9.50. Updating to 9.50 cannot be undone, see No way back from firmware 9.42 or later.
Throws Error if hardwareId is not a supported bracelet.
val needsUpgrade = CorsanoDfu.getInstance().needDfu(hardwareId, firmwareVersion)
getLatestFirmwareVersion
fun getLatestFirmwareVersion(hardwareId: Int): FirmwareVersion
The default firmware version for this hardware: 9.50 for the 287-2B, 4.20 for the 287-1B.
Returns FirmwareVersion.
Throws Error if hardwareId is not a supported bracelet.
val latest = CorsanoDfu.getInstance().getLatestFirmwareVersion(hardwareId)
Log.d("Corsano-SDK", "Latest available: ${latest.text}")
getAvailableVersion
@JvmStatic
fun getAvailableVersion(hardwareId: Int): FirmwareVersion
The same result as getLatestFirmwareVersion, but static: you can call it before the SDK is initialized.
Returns FirmwareVersion.
Throws Error if hardwareId is not a supported bracelet.
val latest = CorsanoDfu.getAvailableVersion(hardwareId)
startDfu
fun startDfu(address: String, hardwareId: Int)
Installs the default firmware for this hardware: 9.50 on a 287-2B, 4.20 on a 287-1B. A 287-2B that was on 8.x or older cannot go back afterwards, see No way back from firmware 9.42 or later.
| Parameter | Type | Description |
|---|---|---|
address | String | MAC address of the bracelet |
hardwareId | Int | Hardware ID of the bracelet |
Returns nothing, at once. Progress and the result arrive through DfuListener.
Throws IllegalStateException if an update is already in progress; Error if hardwareId is not a supported bracelet. Every other problem is reported through onDfuFailed, not thrown.
CorsanoDfu.getInstance().startDfu(address, hardwareId)
What startDfu does before it uploads anything:
- It sets the state to
DfuStatus.INITIATED. - It checks the licence state. A locked SDK ends the update with
DfuError.LICENCE_LOCKED. - It reads the bracelet's battery. This happens when the bracelet is connected through
BleSdk(the deviceBleSdk.getInstance().getDevice(address)gave you). The reading takes at most 20 seconds;getDfuState()isINITIATEDmeanwhile. Below 30 % the update ends withDfuError.BRACELET_BATTERY_TOO_LOWand nothing is sent to the bracelet. Without a reading (the bracelet is not connected throughBleSdk, or it does not answer in time) the update starts without this check. The SDK uses a reading for 3 minutes: after a refusal, wait 3 minutes before you start again, or the same reading refuses the update again. - It starts the DFU service. If Android refuses, the update ends with
DfuError.START_FAILED, and you can callstartDfuagain.
Sample app: DfuFragment.kt in the sample module (sdk/sample/src/main/java/com/corsano/sdk/sample/screens/dfu/) is a complete working example. It calls startDfu(address, hardwareId) from the start button's click listener, and shows the surrounding lifecycle you need:
override fun onStart() {
super.onStart()
val corsanoDfu = CorsanoDfu.getInstance()
// restore the UI from the current state, in case a DFU is already running
renderState(corsanoDfu.getDfuState())
corsanoDfu.addDfuListener(this)
binding.startButton.setOnClickListener {
corsanoDfu.startDfu(args.address, args.hardwareId)
}
}
override fun onStop() {
CorsanoDfu.getInstance().removeDfuStatusListener(this)
super.onStop()
}
The fragment implements DfuListener, and every callback re-reads getDfuState() and renders it. This gives one rendering path for live updates and for the state restored after the screen is recreated.
startDfu (specific version)
fun startDfu(address: String, hardwareId: Int, specificVersion: FirmwareVersion)
Installs a specific firmware version instead of the default. Use it to keep a group of bracelets on a release you validated.
| Parameter | Type | Description |
|---|---|---|
address | String | MAC address of the bracelet |
hardwareId | Int | Hardware ID of the bracelet |
specificVersion | FirmwareVersion | The exact version to install |
Returns nothing, at once.
Throws IllegalStateException if an update is already in progress; IllegalArgumentException if you cannot install that version on that hardware. The message says why: the version is unknown, it is in com.corsano.sdk:dfu-archive which your app excludes, or the hardware is not a 287-2B.
Specific versions are available for B2 only. Calling this for a B1 always throws IllegalArgumentException, whatever version you ask for. Use startDfu(address, hardwareId) for a B1.
Do not use this method to take a bracelet on firmware 9.42 or later back to 8.x or older: from 9.42 the firmware does not allow a downgrade to a lower major version. You can still install another 9.x version, also an older one. The SDK does not check this for you. See No way back from firmware 9.42 or later.
The versions are listed in Firmware versions. The battery check, the licence check and the errors are the same as for startDfu(address, hardwareId).
CorsanoDfu.getInstance().startDfu(address, hardwareId, FirmwareVersion(8, 26))
Sample app: the same DfuFragment.kt carries this overload as a commented-out alternative next to the call to the default-version one.
getDfuState
fun getDfuState(): DfuState
The current state. Use it when you need to poll rather than listen, for example to restore your UI after a configuration change.
Returns DfuState. Before any update has run, its status is DfuStatus.NONE. After an update it keeps the final state (DFU_COMPLETED, DFU_FAILED or DFU_ABORTED) until the next startDfu. The state is kept in memory: it is NONE again after your app's process restarts.
val state = CorsanoDfu.getInstance().getDfuState()
if (state.isInProgress) showProgress(state.progressPercentage)
addDfuListener / removeDfuStatusListener
fun addDfuListener(listener: DfuListener)
fun removeDfuStatusListener(listener: DfuListener)
Register and unregister a DfuListener. Note the different names: you add a DfuListener but remove a DfuStatusListener. Both take the same listener object.
override fun onStart() {
super.onStart()
CorsanoDfu.getInstance().addDfuListener(this)
}
override fun onStop() {
CorsanoDfu.getInstance().removeDfuStatusListener(this)
super.onStop()
}
A listener only receives what happens while it is registered. Read getDfuState() when you register, as the sample app does, so you do not miss an update that already runs or has ended.
extractDfuDeviceAddress
@JvmStatic
fun extractDfuDeviceAddress(intent: Intent?): String?
Reads the bracelet's MAC address out of the intent delivered when the user taps the notification of a running update. The activity named by notificationTarget uses it to open the right screen.
Returns the MAC address, or null if the intent carries none (for example a normal launch of the activity).
val address = CorsanoDfu.extractDfuDeviceAddress(intent)
if (address != null) {
// the user tapped the DFU notification: show the update screen for this bracelet
}
Sample app: MainActivity.handleDfuIntent.
DfuListener
interface DfuListener {
fun onDfuStatusChanged(address: String, status: DfuStatus)
fun onUploadProgress(address: String, percentage: Int, part: Int, totalParts: Int)
fun onDfuCompleted(address: String)
fun onDfuFailed(address: String, error: DfuError)
fun onDfuAborted(address: String)
}
| Callback | Parameters | When |
|---|---|---|
onDfuStatusChanged | address, status | Every time the status changes to a different DfuStatus. For a final status it is called just before the matching callback below. |
onUploadProgress | address, percentage (0–100), part, totalParts | Repeatedly while an image uploads. A firmware zip can hold more than one part: part is the part being uploaded, totalParts the number of parts, and percentage is the progress of the current part. |
onDfuCompleted | address | The update finished successfully. |
onDfuFailed | address, error | The update failed, or was refused before it started. See DfuError. |
onDfuAborted | address | The update was aborted. |
The callbacks of a running upload arrive on the main thread. INITIATED and a failure before the upload starts (DfuError -30, -31, -32) can arrive on the thread that called startDfu or on an SDK thread, so switch to the main thread before you touch views.
From SDK 3.0.0 an aborted update calls onDfuAborted. Up to SDK 2.3.0 it called onDfuCompleted instead, and onDfuAborted was never called. If your code checks getDfuState().isAborted inside onDfuCompleted to work around this, it keeps working: getDfuState() is DFU_ABORTED after an abort, as before. CorsanoDfu has no method to abort an update.
DfuState
data class DfuState(
val status: DfuStatus,
val address: String? = null,
val error: DfuError? = null,
val progressPercentage: Int = 0
)
| Member | Type | Description |
|---|---|---|
status | DfuStatus | Where the process currently is |
address | String? | MAC address of the bracelet being updated. null while status is NONE. |
error | DfuError? | Set when status is DFU_FAILED, otherwise null |
progressPercentage | Int | Upload progress of the current part, 0–100, while status is DFU_UPLOADING. 100 when status is DFU_COMPLETED, 0 in every other status. |
isInProgress | Boolean | The process is still running (status.inProgress) |
isSuccessful | Boolean | status == DFU_COMPLETED |
isFailed | Boolean | status == DFU_FAILED |
isAborted | Boolean | status == DFU_ABORTED |
DfuStatus
Each value carries inProgress, which is what DfuState.isInProgress reports. The table lists the statuses in the order they occur in a successful update.
| Status | In progress | Meaning |
|---|---|---|
NONE | no | No update has been started since your app's process started |
INITIATED | yes | startDfu accepted the request. The SDK checks the licence and reads the bracelet's battery (at most 20 seconds). Nothing has been sent to the bracelet yet. |
CONNECTING | yes | The DFU service connects to the bracelet |
CONNECTED | yes | Connected. DFU_STARTING follows at once. |
DFU_STARTING | yes | The update is being prepared |
ENABLING_DFU_MODE | yes | The bracelet is told to restart in its bootloader. CONNECTING, CONNECTED and DFU_STARTING then occur again, for the connection to the bootloader. |
DFU_STARTED | yes | The upload of a part starts |
DFU_UPLOADING | yes | Uploading the image; progressPercentage updates |
VALIDATING_FIRMWARE | yes | The bracelet validates the uploaded image. Do not wait for this status: an update can complete without reporting it. |
DISCONNECTING | yes | The DFU service disconnects from the bracelet |
DISCONNECTED | yes | Disconnected. One of the three final statuses follows at once. |
DFU_COMPLETED | no | Final: finished successfully |
DFU_FAILED | no | Final: failed; DfuState.error holds the DfuError |
DFU_ABORTED | no | Final: aborted |
Things to know about the order:
- When a firmware zip has more than one part, the statuses from
CONNECTINGtoDISCONNECTINGoccur once per part. - An update that is refused before it starts (battery, licence, DFU service not started) goes from
INITIATEDstraight toDFU_FAILED. - A failure during the update reports
DISCONNECTEDand thenDFU_FAILED. - Do not build your logic on one intermediate status. Use
isInProgressfor "busy", and the three final statuses or the three final callbacks for the result.
DfuError
data class DfuError(val errorCode: Int, val message: String)
| Member | Type | Description |
|---|---|---|
errorCode | Int | A negative code of the SDK (the constants below), or the error code of the Nordic DFU library the SDK uses |
message | String | Description of the error, in English, for your logs |
The SDK's own codes. In all three cases nothing was sent to the bracelet, the bracelet still runs its old firmware, and you can call startDfu again:
| Constant | Code | Meaning | What your app should do |
|---|---|---|---|
DfuError.BRACELET_BATTERY_TOO_LOW | -30 | The bracelet's battery is below 30 %. A bracelet whose battery runs out during an update can be left in its bootloader. From SDK 3.0.0. | Ask the user to charge the bracelet. Start again after at least 3 minutes: the SDK uses a battery reading for that long. |
DfuError.START_FAILED | -31 | Android refused to start the DFU service, for example because your app was in the background. message holds Android's reason. Up to SDK 2.3.0 startDfu threw Android's exception. From SDK 3.0.0. | Start again while your app is in the foreground. |
DfuError.LICENCE_LOCKED | -32 | The SDK is locked by the licence check. From SDK 3.0.0. | Retrying does not help. Handle the licence state, see Licence Key. |
Every other code comes from the Nordic DFU library (no.nordicsemi.android:dfu), after the update started. message names the error. The most common ones:
| Code | Meaning | What your app should do |
|---|---|---|
| 4096 | The bracelet disconnected during the update | Bring the phone close to the bracelet and start again. |
| 4102 | The DFU service was not found on the device at this address | Check that the address is the bracelet's, then start again. |
| 4106 | Bluetooth is switched off | Ask the user to switch Bluetooth on, then start again. |
| Other values | A Bluetooth or bootloader error | Log errorCode and message, then start again. |
After a failure during the update, scan before you start again: if the bracelet now shows up as needing recovery, follow DFU recovery.
override fun onDfuFailed(address: String, error: DfuError) {
when (error.errorCode) {
DfuError.BRACELET_BATTERY_TOO_LOW -> showChargeBracelet()
DfuError.START_FAILED -> showTryAgain()
DfuError.LICENCE_LOCKED -> showLicenceProblem()
else -> showUpdateFailed(error.message) // offer to try again
}
}
FirmwareVersion
FirmwareVersion comes from the ble module (com.corsano.sdk.ble.data.FirmwareVersion) and is Comparable, so versions can be compared directly.
| Member | Type | Description |
|---|---|---|
major | Int | Major number |
minor | Int | Minor number |
number | Int | major * 10000 + minor, used for ordering and equality |
text | String | "major.minor", e.g. "8.48". toString() returns the same. |
FirmwareVersion.parse(text) | FirmwareVersion? | From SDK 3.0.0. Turns "8.65" into a FirmwareVersion. Returns null for null and for text that is not a version, see below. |
if (currentVersion < FirmwareVersion(8, 26)) {
// firmware predates 8.26
}
FirmwareVersion.parse is for a version you hold as text, for example BraceletInfo.firmwareVersion of the Data SDK:
val version: FirmwareVersion? = FirmwareVersion.parse("9.50") // 9.50
FirmwareVersion.parse("9.23.1") // 9.23, a third number is ignored
FirmwareVersion.parse("9") // null: at least major and minor are needed
FirmwareVersion.parse("9.23.b") // null: every part must be a number
It also returns null for a negative number and for a minor of 10000 or more.
Upload behaviour
The upload is configured by the SDK and is not adjustable:
- The existing bond is kept, so the bracelet does not need re-pairing afterwards.
- A failed attempt is retried up to 3 times before
onDfuFailed. - From SDK 3.0.0 the upload is paced for phones that send faster than the bracelet can write: the bracelet confirms every 12 packets, the SDK waits 300 ms after each data object is created, and it gives the bracelet 5 seconds to restart. You do not have to do anything for this.
Foreground service and notification
The update runs in the SDK's DfuService. From SDK 3.0.0 it runs as a foreground service (type connectedDevice) where Android allows it, so that a locked screen does not pause the update:
| Android version | The service runs in the foreground |
|---|---|
| Below Android 14 | Always |
| Android 14 and later | When FOREGROUND_SERVICE_CONNECTED_DEVICE and BLUETOOTH_CONNECT are granted. Otherwise it runs in the background, as it did up to SDK 2.3.0. |
FOREGROUND_SERVICE_CONNECTED_DEVICE comes from the module's manifest and needs no request. BLUETOOTH_CONNECT is a runtime permission (Android 12 and later) that your app already asks for to connect, see Pairing.
A foreground service shows a notification while it runs:
- It is posted on the notification channel
dfu, named "Corsano DFU Service". The SDK creates the channel (Android 8 and later) when an update starts. - A tap opens the activity you gave as
notificationTarget. Read the bracelet's address from that activity's intent with extractDfuDeviceAddress. - On Android 13 and later the user sees it only when your app holds the
POST_NOTIFICATIONSruntime permission. The sample app asks for it inMainActivity. The update itself does not need this permission.
DFU recovery
A recovery is necessary if an update started but was interrupted midway (Bluetooth switched off, app killed, bracelet battery empty). It is rare but it happens. The bracelet stays in its bootloader and appears dead: lights off, even on the charger. A new update restores it.
Scenarios:
- Update interrupted, or app killed. Prompt the user to restart the update.
- The patient uninstalled the app during the update. During scanning, look for a bracelet that needs recovery and prompt the user to start the update.
How to detect and recover such a bracelet:
- Scan.
BleScanner.startScanlooks for bracelets that need recovery by default. See Pairing for the scanning flow. - A bracelet in its bootloader is reported with
BleScanRecord.scanTypeScanDeviceType.BRACELET_1B_NEED_RECOVERYorScanDeviceType.BRACELET_2B_NEED_RECOVERY.ScanDeviceType.needsRecoveryistruefor both andfalsefor every other type. - Such a record has no
advertisementData, so take the hardware ID from the scan type. - Call
startDfuwith the address of the scan record. Do not connect or pair first.
import com.corsano.sdk.ble.data.HardwareId
import com.corsano.sdk.ble.scan.BleScanRecord
import com.corsano.sdk.ble.scan.ScanDeviceType
import com.corsano.sdk.dfu.CorsanoDfu
fun onScanRecord(record: BleScanRecord) {
if (record.scanType.needsRecovery) {
val hardwareId =
if (record.scanType == ScanDeviceType.BRACELET_2B_NEED_RECOVERY) HardwareId.BRACELET_287N_2B
else HardwareId.BRACELET_287N
// after the user confirmed:
CorsanoDfu.getInstance().startDfu(record.address, hardwareId.value)
}
}
Recovery is an ordinary startDfu call: the same listener, statuses and errors apply. The battery check of startDfu does not apply, because the bracelet is not connected through BleSdk, so ask the user to put the bracelet on its charger first.
Sample app: WatchScanFragment.kt (sdk/sample/src/main/java/com/corsano/sdk/sample/screens/scan/) opens the DFU screen when the user selects a bracelet that needs recovery.