Skip to main content

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, which dfu brings by default. See Firmware versions.
warning

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​

WhatWhy
CorsanoSdk.initialize() has runIt initializes the DFU module. A CorsanoDfu.Config is optional. See Setting up.
The bracelet is a 287-1B or a 287-2BFirmware 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 startDfuAndroid 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 moreBelow 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 checkA 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​

ParameterTypeDefaultDescription
notificationTargetClass<out Activity>?nullThe activity opened when the user taps the notification shown during an update. With null, a tap does nothing.
loggerSdkLogger?nullA 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()
note

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​

  1. Read the bracelet's hardware ID and firmware version.
  2. Ask needDfu whether the SDK has a newer firmware.
  3. Register a DfuListener and call startDfu.
  4. Wait for onDfuCompleted, onDfuFailed or onDfuAborted.
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 wantWhere it arrives
Each step of the updateDfuListener.onDfuStatusChanged(address, status). See DfuStatus.
The upload progressDfuListener.onUploadProgress(address, percentage, part, totalParts)
The end of the updateonDfuCompleted, onDfuFailed(address, error) or onDfuAborted. Exactly one of them is called.
The reason of a failureDfuError.errorCode and DfuError.message. See DfuError.
The current state at any timeCorsanoDfu.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.

warning

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.

HardwareIdValueDevice
WATCH_284N38Watch 284N
WATCH_287N50Watch 287N
BRACELET_287N51CardioWatch 287-1B ("B1")
BRACELET_287N_2B54CardioWatch 287-2B ("B2")
UNKNOWN-1Unrecognised
warning

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​

BraceletDefault versionOther versions you can install
287-1B (51)4.20None
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:

Artefact287-2B versions
com.corsano.sdk:dfu6.87, 8.65, 9.42, 9.50
com.corsano.sdk:dfu-archive5.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​

warning

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 runsYou can install
Below 9.42The rule does not apply
9.42 or later9.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, and needDfu is true for every bracelet below it. An app that updates whenever needDfu is true moves 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 follow needDfu. Compare the bracelet's version with the version you validated, and install that one with startDfu(address, hardwareId, specificVersion), for example FirmwareVersion(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-archive when your app excludes that artefact;
  • for a version of dfu-archive before CorsanoSdk.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).

ParameterTypeDescription
hardwareIdIntHardware ID of the bracelet
currentVersionFirmwareVersionFirmware 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.

ParameterTypeDescription
addressStringMAC address of the bracelet
hardwareIdIntHardware 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:

  1. It sets the state to DfuStatus.INITIATED.
  2. It checks the licence state. A locked SDK ends the update with DfuError.LICENCE_LOCKED.
  3. It reads the bracelet's battery. This happens when the bracelet is connected through BleSdk (the device BleSdk.getInstance().getDevice(address) gave you). The reading takes at most 20 seconds; getDfuState() is INITIATED meanwhile. Below 30 % the update ends with DfuError.BRACELET_BATTERY_TOO_LOW and nothing is sent to the bracelet. Without a reading (the bracelet is not connected through BleSdk, 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.
  4. It starts the DFU service. If Android refuses, the update ends with DfuError.START_FAILED, and you can call startDfu again.

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.

ParameterTypeDescription
addressStringMAC address of the bracelet
hardwareIdIntHardware ID of the bracelet
specificVersionFirmwareVersionThe 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.

warning

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.

warning

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)
}
CallbackParametersWhen
onDfuStatusChangedaddress, statusEvery time the status changes to a different DfuStatus. For a final status it is called just before the matching callback below.
onUploadProgressaddress, percentage (0–100), part, totalPartsRepeatedly 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.
onDfuCompletedaddressThe update finished successfully.
onDfuFailedaddress, errorThe update failed, or was refused before it started. See DfuError.
onDfuAbortedaddressThe 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.

note

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
)
MemberTypeDescription
statusDfuStatusWhere the process currently is
addressString?MAC address of the bracelet being updated. null while status is NONE.
errorDfuError?Set when status is DFU_FAILED, otherwise null
progressPercentageIntUpload progress of the current part, 0–100, while status is DFU_UPLOADING. 100 when status is DFU_COMPLETED, 0 in every other status.
isInProgressBooleanThe process is still running (status.inProgress)
isSuccessfulBooleanstatus == DFU_COMPLETED
isFailedBooleanstatus == DFU_FAILED
isAbortedBooleanstatus == 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.

StatusIn progressMeaning
NONEnoNo update has been started since your app's process started
INITIATEDyesstartDfu 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.
CONNECTINGyesThe DFU service connects to the bracelet
CONNECTEDyesConnected. DFU_STARTING follows at once.
DFU_STARTINGyesThe update is being prepared
ENABLING_DFU_MODEyesThe bracelet is told to restart in its bootloader. CONNECTING, CONNECTED and DFU_STARTING then occur again, for the connection to the bootloader.
DFU_STARTEDyesThe upload of a part starts
DFU_UPLOADINGyesUploading the image; progressPercentage updates
VALIDATING_FIRMWAREyesThe bracelet validates the uploaded image. Do not wait for this status: an update can complete without reporting it.
DISCONNECTINGyesThe DFU service disconnects from the bracelet
DISCONNECTEDyesDisconnected. One of the three final statuses follows at once.
DFU_COMPLETEDnoFinal: finished successfully
DFU_FAILEDnoFinal: failed; DfuState.error holds the DfuError
DFU_ABORTEDnoFinal: aborted

Things to know about the order:

  • When a firmware zip has more than one part, the statuses from CONNECTING to DISCONNECTING occur once per part.
  • An update that is refused before it starts (battery, licence, DFU service not started) goes from INITIATED straight to DFU_FAILED.
  • A failure during the update reports DISCONNECTED and then DFU_FAILED.
  • Do not build your logic on one intermediate status. Use isInProgress for "busy", and the three final statuses or the three final callbacks for the result.

DfuError​

data class DfuError(val errorCode: Int, val message: String)
MemberTypeDescription
errorCodeIntA negative code of the SDK (the constants below), or the error code of the Nordic DFU library the SDK uses
messageStringDescription 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:

ConstantCodeMeaningWhat your app should do
DfuError.BRACELET_BATTERY_TOO_LOW-30The 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-31Android 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-32The 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:

CodeMeaningWhat your app should do
4096The bracelet disconnected during the updateBring the phone close to the bracelet and start again.
4102The DFU service was not found on the device at this addressCheck that the address is the bracelet's, then start again.
4106Bluetooth is switched offAsk the user to switch Bluetooth on, then start again.
Other valuesA Bluetooth or bootloader errorLog 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.

MemberTypeDescription
majorIntMajor number
minorIntMinor number
numberIntmajor * 10000 + minor, used for ordering and equality
textString"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 versionThe service runs in the foreground
Below Android 14Always
Android 14 and laterWhen 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_NOTIFICATIONS runtime permission. The sample app asks for it in MainActivity. 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:

  1. Scan. BleScanner.startScan looks for bracelets that need recovery by default. See Pairing for the scanning flow.
  2. A bracelet in its bootloader is reported with BleScanRecord.scanType ScanDeviceType.BRACELET_1B_NEED_RECOVERY or ScanDeviceType.BRACELET_2B_NEED_RECOVERY. ScanDeviceType.needsRecovery is true for both and false for every other type.
  3. Such a record has no advertisementData, so take the hardware ID from the scan type.
  4. Call startDfu with 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.