nrf52 air upgrade

Posted by AnarKy on Wed, 08 Dec 2021 21:43:19 +0100

1, Overview

1.1 OTA DFU

DFU(Device Firmware Update) is firmware upgrade, and over the air is firmware upgrade through wireless connection. As long as the DFU is realized through wireless communication, it can be called air upgrade, including WiFi / Bluetooth / NFC/Zigbee. You can also use wired methods for air upgrade, such as serial port, USB or SPI.

1.2 DFU upgrade mode

There are two upgrade modes of DFU: rear desk DFU and non rear desk DFU. Background DFU is similar to the upgraded version of mobile phone. The device downloads a new firmware version in the background. In this process, the application can run normally, that is, the DFU upgrade does not affect the normal operation of the program. Until the download is completed, the program jumps back to BootLoader mode for upgrade. For non rear desktop DFU, when the program initiates the use of DFU request, the program will enter BootLoader mode from the application layer and complete the new version download and version upgrade coverage through BootLoader. The air upgrade mode of NRF52 is to use non rear desktop mode.

1.3 DFU Flash layout

DFU is divided into two modes: dual bank and single bank. Dual zone DFU: the new firmware and the old firmware occupy one bank (storage area) respectively. Only after the download and verification of the new firmware are successful, will it enter the bootloader, then erase the bank where the firmware is located, and then copy the bank where the new firmware is located to the bank where the firmware is located to complete the upgrade. Single zone DFU, the old and new firmware share a bank. After receiving the upgrade request, the program will enter the bootloader mode. First erase the old firmware, and then download the new firmware to the newly erased bank to complete the upgrade. If the verification fails, it will be upgraded again.

Since Nordic chip is a pure Flash product, there is no other NVM in it, and all non-volatile data are placed in Flash, including Bluetooth protocol stack, Nordic Bluetooth protocol stack can also be OTA.

1.4 meaning of upgrade file

Bootloader.hex: the firmware version of the device entering the bootloader mode. You can select the corresponding chip to compile in the DFU official sample (SDK\examples\dfu\secure_bootloader) where the public key is replaced, and change the generated hex to bootloader.hex. more bootloader information

app.hex: the hex generated by your own project can also directly use the generated name. There is no requirement for this.

setting.hex: used to boot the bootloader to the setting file of the application layer after the device is started, which is equivalent to a verification. After entering bootloader from the protocol stack, the program will check bank0 in Settings_ bank_ code,bank0_img_crc, only when the two are correct can the application be executed, otherwise it will stay in the bootloader to run DFU. more Settings information

Protocol stack: the version number of the upgrade package is used back. It can be viewed through the command line (nrutil PKG generate -- help), online documents, official forums, or in the doc information of the protocol stack version of the SDK (SDK \ components \ softdevice \ S140 \ doc \ s140_nrf52_7.2.0_release notes. Pdf)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-QGI5vlCH-1638968071103)(G:\study \ duplicate disk \ blog picture \ protocol stack id.png)]

Upgrade package: it includes manifest.json (file list) and nrf52833_ Xxaa.bin (new firmware) and nrf52833_xxaa.dat(init packet), where init packet Contains meta information - the type, size, version, and signature of the new firmware.

2, Tool installation

2.1 gcc-arm-none-eabi

Function: compile micro ECC.

Download address: https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads

2.2 MinGW

Function: implement Makefile under Windows platform.

Download address: https://osdn.net/projects/mingw/releases/ perhaps https://sourceforge.net/projects/mingw/files/latest/download?source=files

2.3 Python

Function: PC nrfutil needs python-2.7 environment. I don't think 2.7 or 3.7 has much impact.

Download address: https://www.python.org/downloads/

2.4 pc-nrfutil

Function: the PC side tool released by Nordic supports DFU and encryption functions.

Download address: https://github.com/NordicSemiconductor/pc-nrfutil/

You can select pip install nrfutil from the command line to install nrfutil, Download python setup.py install from the code source, or directly download the exe installer. Finally, use nrutil version to check whether the installation is successful. A display indicates success.

2.5 nrfgo (or programmer of nrf connect)

Function: burn hex and nrfgo, and nrfgo can be used for all that can be identified; Otherwise, you need to use Programmer and update nrf command line tools to install it.

Download address: nrfgonrf connectnrf command line tools

3, Modify bootloader project

3.1 creating public and private keys

::generate private key
nrfutil keys generate priv.pem

::generate public key related with private key: priv.pem
nrfutil keys display --key pk --format code priv.pem --out_file dfu_public_key.c

Put the generated dfu_public_key.c replaces the file with the same name under the SDK\examples\dfu folder.

3.2 adding micro ECC master source code

Unzip the downloaded micro-ecc-master.zip, copy it to the SDK / external / micro ECC file, and rename it micro ECC, as shown in the following figure:

3.3 micro_ecc_lib_nrf52.lib file generation

Specific view Secure DFU environment setup Step 2.4

3.4 trigger bootloader with no key

Then compile the program and rename hex to bootloader.hex

4, Application add DFU

4.1 configuring sdk_config file

Enable DFU service

NRF_SDH_BLE_VS_UUID_COUNT + 1, add 1 to the original

Modify RAM space, Start + 0x10, Size - 0x10

4.2 adding files

4.3 add code

Header file

#if NRF_MODULE_ENABLED(BLE_DFU)
#include "nrf_power.h" 		// dfu service
#include "ble_srv_common.h"
#include "nrf_dfu_ble_svci_bond_sharing.h"
#include "nrf_svci_async_function.h"
#include "nrf_svci_async_handler.h"
#include "ble_dfu.h"
#include "nrf_bootloader_info.h"
#endif

Add functions required for DFU

#if NRF_MODULE_ENABLED(BLE_DFU)

static void disconnect(uint16_t conn_handle, void* p_context)
{
    UNUSED_PARAMETER(p_context);

    ret_code_t err_code = sd_ble_gap_disconnect(conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
    if(err_code != NRF_SUCCESS)
    {
        NRF_LOG_WARNING("Failed to disconnect connection. Connection handle: %d Error: %d", conn_handle, err_code);
    }
    else
    {
        NRF_LOG_DEBUG("Disconnected connection handle %d", conn_handle);
    }
}

static void advertising_config_get(ble_adv_modes_config_t* p_config)
{
    memset(p_config, 0, sizeof(ble_adv_modes_config_t));

    p_config->ble_adv_fast_enabled  = true;
    p_config->ble_adv_fast_interval = APP_ADV_INTERVAL;
    p_config->ble_adv_fast_timeout  = APP_ADV_DURATION;
}

/**@brief Function for handling dfu events from the Buttonless Secure DFU service
 *
 * @param[in]   event   Event from the Buttonless Secure DFU service.
 */
static void ble_dfu_evt_handler(ble_dfu_buttonless_evt_type_t event)
{
    switch(event)
    {
    case BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE:
    {
//        NRF_LOG_INFO("Device is preparing to enter bootloader mode.");

        // Prevent device from advertising on disconnect.
        ble_adv_modes_config_t config;
        advertising_config_get(&config);
        config.ble_adv_on_disconnect_disabled = true;
        ble_advertising_modes_config_set(&m_advertising, &config);

        // YOUR_JOB: Disconnect all other bonded devices that currently are connected.
        // 		   This is required to receive a service changed indication
        // 		   on bootup after a successful (or aborted) Device Firmware Update.
        uint32_t conn_count = ble_conn_state_for_each_connected(disconnect, NULL);
	    NRF_LOG_INFO("Disconnected %d links.", conn_count);
        break;
    }

    case BLE_DFU_EVT_BOOTLOADER_ENTER:
        // YOUR_JOB: Write app-specific unwritten data to FLASH, control finalization of this
        //           by delaying reset by reporting false in app_shutdown_handler
        break;

    case BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED:
        NRF_LOG_ERROR("Request to enter bootloader mode failed asynchroneously.");
        // YOUR_JOB: Take corrective measures to resolve the issue
        //           like calling APP_ERROR_CHECK to reset the device.
        break;

    case BLE_DFU_EVT_RESPONSE_SEND_ERROR:
        NRF_LOG_ERROR("Request to send a response to client failed.");
        // YOUR_JOB: Take corrective measures to resolve the issue
        //           like calling APP_ERROR_CHECK to reset the device.
        APP_ERROR_CHECK(false);
        break;

    default:
        NRF_LOG_ERROR("Unknown event from ble_dfu_buttonless.");
        break;
    }
}

/**@brief Handler for shutdown preparation.
 *
 * @details During shutdown procedures, this function will be called at a 1 second interval
 *          untill the function returns true. When the function returns true, it means that the
 *          app is ready to reset to DFU mode.
 *
 * @param[in]   event   Power manager event.
 *
 * @retval  True if shutdown is allowed by this power manager handler, otherwise false.
 */
static bool app_shutdown_handler(nrf_pwr_mgmt_evt_t event)
{
    switch(event)
    {
    case NRF_PWR_MGMT_EVT_PREPARE_DFU:
        break;

    default:
        // YOUR_JOB: Implement any of the other events available from the power management module:

        return true;
    }

//    NRF_LOG_INFO("Power management allowed to reset to DFU mode.");
    return true;
}

/**@brief Register application shutdown handler with priority 0.
 */
NRF_PWR_MGMT_HANDLER_REGISTER(app_shutdown_handler, 0);

static void buttonless_dfu_sdh_state_observer(nrf_sdh_state_evt_t state, void* p_context)
{
    if(state == NRF_SDH_EVT_STATE_DISABLED)
    {
        // Softdevice was disabled before going into reset. Inform bootloader to skip CRC on next boot.
        nrf_power_gpregret2_set(BOOTLOADER_DFU_SKIP_CRC);

        //Go to system off.
        nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
    }
}

/* nrf_sdh state observer. */
NRF_SDH_STATE_OBSERVER(m_buttonless_dfu_state_obs, 0) =
{
    .handler = buttonless_dfu_sdh_state_observer,
};

#endif

In services_ Add DFU service in init()

#if NRF_MODULE_ENABLED(BLE_DFU)		
	ble_dfu_buttonless_init_t dfus_init = {0};	
	// Initialize dfu.
    dfus_init.evt_handler = ble_dfu_evt_handler;
    err_code = ble_dfu_buttonless_init(&dfus_init);
    APP_ERROR_CHECK(err_code);
#endif

If you are upgrading with IOS, you need to add a function at the beginning of the main function

err_code = ble_dfu_buttonless_async_svci_init();
APP_ERROR_CHECK(err_code);

Compilation error

Add these two definitions in the project settings option, C/C + + option: Preprocessor Symbols

NRF_DFU_TRANSPORT_BLE=1 BL_SETTINGS_ACCESS_ONLY 

5, Upgrade package

1. Generate zip package


According to the official information in the figure above, it seems that only BL+APP can not be upgraded at the same time, and others can be selected according to their own needs, but most developers only need to upgrade APP.

Some upgrade commands (nrf52832 as an example):

Protocol stack

nrfutil pkg generate --hw-version 52 --sd-req 0x0101 --softdevice s132_nrf52_7.3.0_softdevice.hex --sd-id 0x0124 --key-file priv.pem dfu_softdevice.zip
//Remack: -- SD req 0x0101 refers to the protocol stack version running on the chip, -- SD ID 0x0124 is the protocol stack ID you want to upgrade

bootloader

nrfutil pkg generate --hw-version 52 --bootloader bootloadery.hex --bootloader-version 2 --sd-req 0x0124 --key-file priv.pem dfu_bootloader.zip

application

nrfutil pkg generate --application app_new.hex --application-version 2 --hw-version 52 --sd-req 0xCB --key-file priv.pem dfu_application.zip

2.DFU test (Android)

SDK17.1 serial port transparent transmission example, protocol stack version s140_nrf52_7.3.0_softdevice, chip nrf52833 for dfu test, the process is as follows

Select the DFU upgrade button or send an upgrade request in the DFU service.

Wait for the upgrade to complete.

Before the upgrade, the name has changed after the upgrade is successful.

6, Brain map

7, Reference link

Getting started with Nordic's Secure DFU bootloader, a step by step guide
Explain the principle and steps of Bluetooth over the air upgrade (BLE OTA)
Qingfeng Forum
nrf52832 learning notes (6) -- use of ota dfu interface
SYQ blog

Download address

Topics: bluetooth