7 minute read

Firmware updates over UDP MCUboot & Zephyr

Walkthrough Video

Previously I showcased adding a DFU udates to an embedded device over serial while this works it does present a limitation by requiring a serial connection which would be limited by distance and other factors. This time around I’d like to showcase another kind of connection. UDP which would be nice considering this is standard connection fields like robotics and automotive.

To keep this simple and to add some constraints I’ll use the same board I used. One caveat is that the FRDM_MCXN236 does not feature an Ethernet peripheral, this becomes an opportunity to use USB CDC ECM virtual Ethernet controller from Zephyr.

The goal today would be to

  • Setup Virtual USB Etnernet controller
  • Enable Networking and Assign an IP Address
  • Add MCUboot and MCUMgr to this setup
  • Use smpmgr from our Host to update the firmware over UDP

Add A USB Class for CDC ECM

Zephyr comes with a robust and dare I say a mature USB stack, so it’s quite standard to setup USB Classes and Device

The few items we need to pay to in this setup are

  • The Product ID USBD_DESC_PRODUCT_DEFINE(sample_product, CONFIG_SAMPLE_USBD_PRODUCT);

  • The Vendor ID

    USBD_DESC_MANUFACTURER_DEFINE(sample_mfr, CONFIG_SAMPLE_USBD_MANUFACTURER);

You can use the zephyr test ones for this, however for actual products you will need acquire these from the USB IF. The USB Module should look something like

USBD_DESC_MANUFACTURER_DEFINE(usbd_manufacturer, "Zacck");
USBD_DESC_PRODUCT_DEFINE(usbd_product, "blimp");
USBD_DESC_LANG_DEFINE(usbd_lang);
USBD_DESC_CONFIG_DEFINE(usbd_fs_cfg_desc, "FullSpeed Configuration");
USBD_DESC_CONFIG_DEFINE(usbd_hs_cfg_desc, "HighSpeed Configuration");

USBD_CONFIGURATION_DEFINE(usbd_config_fs, USB_SCD_SELF_POWERED, 100, &usbd_fs_cfg_desc);
USBD_CONFIGURATION_DEFINE(usbd_config_hs, USB_SCD_SELF_POWERED, 100, &usbd_hs_cfg_desc);
IF_ENABLED(CONFIG_HWINFO, (USBD_DESC_SERIAL_NUMBER_DEFINE(usbd_sn)));
USBD_DEVICE_DEFINE(usbd,
		   DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)),
		   0xDEAD, 0xBEEF);


int app_usb_init(void) 
{
	int ret; 

	ret = usbd_add_descriptor(&usbd, &usbd_lang);
	if (ret) {
		LOG_ERR("Failed to initialize language descriptor (%d)", ret);
		return ret;
	}

	ret = usbd_add_descriptor(&usbd, &usbd_manufacturer);
	if (ret) {
		LOG_ERR("Failed to initialize manufacturer descriptor (%d)", ret);
		return ret;
	}

	ret = usbd_add_descriptor(&usbd, &usbd_product);
	if (ret) {
		LOG_ERR("Failed to initialize product descriptor (%d)", ret);
		return ret;
	}

	IF_ENABLED(CONFIG_HWINFO, (ret = usbd_add_descriptor(&usbd, &usbd_sn);))
	if (ret) {
		LOG_ERR("Failed to initialize SN descriptor (%d)", ret);
		return ret;
	}

	LOG_DBG("Adding USB configuration");
	ret = usbd_add_configuration(&usbd, USBD_SPEED_FS, &usbd_config_fs);
	if (ret < 0) {
		LOG_ERR("failed to add FullSpeed, configuration");
		return ret;
	}
	ret = usbd_add_configuration(&usbd, USBD_SPEED_HS, &usbd_config_hs);
	if (ret < 0) {
		LOG_ERR("failed to add HighSpeed, configuration");
		return ret;
	}

	usbd_device_set_code_triple(&usbd, USBD_SPEED_FS, USB_BCC_MISCELLANEOUS, 0x02, 0x01);
	usbd_device_set_code_triple(&usbd, USBD_SPEED_HS, USB_BCC_MISCELLANEOUS, 0x02, 0x01);

	LOG_DBG("Adding USB classes");
	ret = usbd_register_all_classes(&usbd, USBD_SPEED_FS, 1, NULL);
	if (ret < 0) {
		LOG_ERR("failed to register FullSpeed USB classes");
		return ret;
	}
	ret = usbd_register_all_classes(&usbd, USBD_SPEED_HS, 1, NULL);
	if (ret < 0) {
		LOG_ERR("failed to register HighSpeed USB classes");
		return ret;
	}

LOG_DBG("Finalize USB configuration");
	ret = usbd_init(&usbd);
	if (ret < 0) {
		LOG_ERR("failed to initialize USB");
		return ret;
	}

	LOG_DBG("Starting USB operation");
	ret = usbd_enable(&usbd);
	if (ret < 0) {
		LOG_ERR("failed to enable the USB device");
		return ret;
	}

	return 0;
}

Additionlly we will need to specify the class in our device tree overlay.

 &zephyr_udc0 {
         cdc_ecm_eth0: cdc_ecm_eth0 {
                  compatible = "zephyr,cdc-ecm-ethernet";
                  remote-mac-address = "00005E005301";
        };
};	
		

And add some USB Kconfigs in prj.conf

# USB
CONFIG_UDC_DRIVER=y
CONFIG_USB_DEVICE_STACK_NEXT=y
CONFIG_USBD_THREAD_STACK_SIZE=2048
CONFIG_USBD_CDC_ECM_CLASS=y
CONFIG_USBD_CDC_ECM_LOG_LEVEL_WRN=y
CONFIG_USBD_LOG_LEVEL_WRN=y

Networking and Setup

Now in order to utilize UDP we need to have a working ethernet connection. With an IP address and a port we can communicate over. Lets and networking module and set this up.

Setup a coupleof callbacks

The first one watches the link state and reacts to the cable being connected and being disconneted.

static void connection_status_changed(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, struct net_if *iface)
{
	// Device IP
	struct in_addr addr;
	// 192.168.68.167
	addr.s4_addr[0] = 192;
	addr.s4_addr[1] = 168;
	addr.s4_addr[2] = 68; 
	addr.s4_addr[3] = 167;

	char buf[NET_IPV4_ADDR_LEN]; 

	struct net_if_addr *ret;


	if(mgmt_event == NET_EVENT_IF_UP){
		LOG_INF(">>> LINK UP - Cable Connected, Assigning address \n");
		ret = net_if_ipv4_addr_add(iface, &addr, NET_ADDR_MANUAL, 24);
		if(ret == NULL) {
			LOG_INF("IP ADDR  ADD FAILED\n"); 
		} else {
			LOG_INF("IP ADDR ADD Worked \n"); 
		}
	} else if (mgmt_event == NET_EVENT_IF_DOWN){
		LOG_INF(">>> LINK DOWN - Cable Disconnected!\n");
		net_if_ipv4_addr_rm(iface, &addr);
	} else if(mgmt_event == NET_EVENT_IPV4_ADDR_ADD){
		// Log assigned IP
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->unicast[0].ipv4.address.in_addr, 
				buf, sizeof(buf)); 
		LOG_INF("IP Address: %s\n", buf); 

		//Log the subnet mask 
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->unicast[0].netmask, 
				buf, sizeof(buf));
		LOG_INF("Netmask: %s\n", buf); 

		//Log  the default gateway
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->gw, buf, sizeof(buf)); 
		LOG_INF("Gateway: %s\n", buf);
		LOG_INF("Ready for smp\n");
	}
}

This way we get a notification whenever the connection is updates and if need be we can react to it. Also gives us some good logs for when we need to debug the application.

Let’s add one more separate call back to watch for when the IP address assignment succeeds. This also also logs the IP, the gateway and the network mask we have.

static void ipv4_evt_cb(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, struct net_if *iface)
{
	char buf[NET_IPV4_ADDR_LEN]; 
	if(mgmt_event == NET_EVENT_IPV4_ADDR_ADD){
		// Log assigned IP
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->unicast[0].ipv4.address.in_addr, 
				buf, sizeof(buf)); 
		printk("IP Address: %s\n", buf); 

		//Log the subnet mask 
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->unicast[0].netmask, 
				buf, sizeof(buf));
		printk("Netmask: %s\n", buf); 

		//Log  the default gateway
		net_addr_ntop(NET_AF_INET, &iface->config.ip.ipv4->gw, buf, sizeof(buf)); 
		printk("Gateway: %s\n", buf);
	}
}

In addition to this we will need some KConfig for the Networking

# Ethernet
CONFIG_NETWORKING=y
CONFIG_NET_L2_ETHERNET=y
CONFIG_NET_MGMT=y
CONFIG_NET_MGMT_EVENT=y
CONFIG_NET_IPV4=y
CONFIG_NET_UDP=y
CONFIG_NET_SOCKETS=y

With this we should be able to connect to a Host and ping the device

ping 192.168.68.167
PING 192.168.68.167 (192.168.68.167) 56(84) bytes of data.
64 bytes from 192.168.68.167: icmp_seq=1 ttl=64 time=0.421 ms
64 bytes from 192.168.68.167: icmp_seq=2 ttl=64 time=0.700 ms

Setup MCUboot and MCUMgr

As for MCUboot and MCUMgr this is largely the same as the previous time, We need the following

  • sysbuild.conf: To configure sysbuild properties
  • sysbuild/
    mcuboot.conf
    mcuboot.overlay
    To configure and provide device tree for MCUboot

Then largely the same addendums to prj.conf

# Enable MCUMGR 
CONFIG_MCUMGR=y

# Enable MCUMGR management for both OS and Images
CONFIG_MCUMGR_GRP_OS=y
CONFIG_MCUMGR_GRP_IMG=y

# Configure MCUMGR transport to UDP
CONFIG_MCUMGR_TRANSPORT_UDP=y
CONFIG_MCUMGR_TRANSPORT_UDP_IPV4=y
CONFIG_MCUMGR_TRANSPORT_UDP_PORT=1337

# Configure dependencies for CONFIG_MCUMGR  
CONFIG_NET_BUF=y
CONFIG_ZCBOR=y
CONFIG_CRC=y

# Configure dependencies for CONFIG_MCUMGR_GRP_IMG  
CONFIG_FLASH=y
CONFIG_IMG_MANAGER=y

# Configure dependencies for CONFIG_IMG_MANAGER  
CONFIG_STREAM_FLASH=y
CONFIG_FLASH_MAP=y

Same as last time except we swap the transport for UDP and IPv4 plus provoide a port.

Testing from Host & Demo

Now that we have all this setup we can test this from the host. After building the application and flashing lets do the following

  1. Connect the device to the host.
  2. Assign the host an ip address.
  3. List the images on the device
    smpmgr --ip 192.168.68.167        --mtu 256        image state-read
    [12:19:34] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                     flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                     smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
    ⠋ Connecting to 192.168.68.167... OK
    ⠋ Waiting for image states... OK
    ImageState(
     slot=0,
     version='0.0.0',
     image=None,
     hash=HashBytes('B9EABA4404759EAF97DB1FE3349CD32607336028791745C486B43240F5B08186'),
     bootable=True,
     pending=False,
     confirmed=True,
     active=True,
     permanent=False
    )
    splitStatus: 0
    
  4. Change the application so we and build an update
  5. Upload an update to the device
    smpmgr --ip 192.168.68.167       --mtu 256        image upload build/usb_ecm/zephyr/zephyr.signed.bin
    [12:22:14] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                     flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                     smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
    ⠋ Connecting to 192.168.68.167... OK
    build/usb_ecm/zephyr/zephyr.signed.bin ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 192.6/192.6 kB • 163.5 kB/s • 0:00:00
    (.venv) zacck@bigbox:zephyrproject$ smpmgr --ip 192.168.68.167       --mtu 256        image state-read
    [12:22:26] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                     flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                     smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
    ⠋ Connecting to 192.168.68.167... OK
    ⠋ Waiting for image states... OK
    
  6. Read the images again to see both slots
    smpmgr --ip 192.168.68.167       --mtu 256        image state-read
    [12:22:26] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                     flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                     smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
    ⠋ Connecting to 192.168.68.167... OK
    ⠋ Waiting for image states... OK
    ImageState(
     slot=0,
     version='0.0.0',
     image=None,
     hash=HashBytes('B9EABA4404759EAF97DB1FE3349CD32607336028791745C486B43240F5B08186'),
     bootable=True,
     pending=False,
     confirmed=True,
     active=True,
     permanent=False
    )
    ImageState(
     slot=1,
     version='0.0.0',
     image=None,
     hash=HashBytes('0C24E77A3948D3FFD333D8D5514982FAF4E0677AB92CD73C38833D7B05D9C9B0'),
     bootable=True,
     pending=False,
     confirmed=False,
     active=False,
     permanent=False
    )
    splitStatus: 0
    
  7. Confirm the new Image
smpmgr --ip 192.168.68.167 --mtu 256 \
image state-write 0C24E77A3948D3FFD333D8D5514982FAF4E0677AB92CD73C38833D7B05D9C9B0
[12:26:06] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                    flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                    smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
⠋ Connecting to 192.168.68.167... OK
⠋ Waiting for image state write... OK
  1. Reset the device
    smpmgr --ip 192.168.68.167        --mtu 256        os reset
    [12:26:49] WARNING  Error reading MCUMgr parameters: header=Header(op=<OP.READ_RSP: 1>, version=<Version.V2: 1>,                    __init__.py:566
                     flags=<Flag.UNUSED: 0>, length=6, group_id=0, sequence=0, command_id=6) version=<Version.V2: 1> sequence=0
                     smp_data=b'\t\x00\x00\x06\x00\x00\x00\x06\xbfbrc\x08\xff' rc=<MGMT_ERR.ENOTSUP: 8> rsn=None - __init__:566
    ⠋ Connecting to 192.168.68.167... OK
    ⠋ Waiting for response to ResetWrite... OK
    ResetWriteResponse(
     header=Header(op=<OP.WRITE_RSP: 3>, version=<Version.V2: 1>, flags=<Flag.UNUSED: 0>, length=2, group_id=0, sequence=1, command_id=5),
     version=<Version.V2: 1>,
     sequence=1,
     smp_data=b'\x0b\x00\x00\x02\x00\x00\x01\x05\xbf\xff'
    )
    

And voila we have Firmware updates working over UDP. If you already have an ethernet connection to your device such a ROS2 Setup this would be a quick and easy way to and firmware updates.

Happy Debugging.