2014-10-22 01:27:33 -04:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# This file is part of the OpenMV project.
|
|
|
|
# Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com>
|
|
|
|
# This work is licensed under the MIT license, see the file LICENSE for
|
|
|
|
# details.
|
|
|
|
|
|
|
|
"""This module implements enough functionality to program the STM32F4xx over
|
2018-05-18 01:30:35 -04:00
|
|
|
DFU, without requiring dfu-util.
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
See app note AN3156 for a description of the DFU protocol.
|
2023-10-02 20:24:50 -04:00
|
|
|
See document UM0391 for a description of the DFuse file.
|
2014-10-22 01:27:33 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import argparse
|
2018-11-27 00:19:27 -05:00
|
|
|
import collections
|
2020-01-21 15:30:50 -05:00
|
|
|
import inspect
|
2014-10-22 01:27:33 -04:00
|
|
|
import re
|
|
|
|
import struct
|
|
|
|
import sys
|
|
|
|
import usb.core
|
|
|
|
import usb.util
|
|
|
|
import zlib
|
|
|
|
|
|
|
|
# USB request __TIMEOUT
|
|
|
|
__TIMEOUT = 4000
|
|
|
|
|
|
|
|
# DFU commands
|
2020-02-26 23:36:53 -05:00
|
|
|
__DFU_DETACH = 0
|
|
|
|
__DFU_DNLOAD = 1
|
|
|
|
__DFU_UPLOAD = 2
|
2014-10-22 01:27:33 -04:00
|
|
|
__DFU_GETSTATUS = 3
|
|
|
|
__DFU_CLRSTATUS = 4
|
2020-02-26 23:36:53 -05:00
|
|
|
__DFU_GETSTATE = 5
|
|
|
|
__DFU_ABORT = 6
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# DFU status
|
2020-02-26 23:36:53 -05:00
|
|
|
__DFU_STATE_APP_IDLE = 0x00
|
|
|
|
__DFU_STATE_APP_DETACH = 0x01
|
|
|
|
__DFU_STATE_DFU_IDLE = 0x02
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05
|
|
|
|
__DFU_STATE_DFU_MANIFEST_SYNC = 0x06
|
|
|
|
__DFU_STATE_DFU_MANIFEST = 0x07
|
|
|
|
__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08
|
|
|
|
__DFU_STATE_DFU_UPLOAD_IDLE = 0x09
|
|
|
|
__DFU_STATE_DFU_ERROR = 0x0A
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
_DFU_DESCRIPTOR_TYPE = 0x21
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-24 01:17:53 -05:00
|
|
|
__DFU_STATUS_STR = {
|
|
|
|
__DFU_STATE_APP_IDLE: "STATE_APP_IDLE",
|
|
|
|
__DFU_STATE_APP_DETACH: "STATE_APP_DETACH",
|
|
|
|
__DFU_STATE_DFU_IDLE: "STATE_DFU_IDLE",
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_SYNC: "STATE_DFU_DOWNLOAD_SYNC",
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_BUSY: "STATE_DFU_DOWNLOAD_BUSY",
|
|
|
|
__DFU_STATE_DFU_DOWNLOAD_IDLE: "STATE_DFU_DOWNLOAD_IDLE",
|
|
|
|
__DFU_STATE_DFU_MANIFEST_SYNC: "STATE_DFU_MANIFEST_SYNC",
|
|
|
|
__DFU_STATE_DFU_MANIFEST: "STATE_DFU_MANIFEST",
|
|
|
|
__DFU_STATE_DFU_MANIFEST_WAIT_RESET: "STATE_DFU_MANIFEST_WAIT_RESET",
|
|
|
|
__DFU_STATE_DFU_UPLOAD_IDLE: "STATE_DFU_UPLOAD_IDLE",
|
|
|
|
__DFU_STATE_DFU_ERROR: "STATE_DFU_ERROR",
|
|
|
|
}
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# USB device handle
|
|
|
|
__dev = None
|
|
|
|
|
2018-11-27 00:19:27 -05:00
|
|
|
# Configuration descriptor of the device
|
|
|
|
__cfg_descr = None
|
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
__verbose = None
|
|
|
|
|
|
|
|
# USB DFU interface
|
|
|
|
__DFU_INTERFACE = 0
|
|
|
|
|
2018-07-27 01:55:32 -04:00
|
|
|
# Python 3 deprecated getargspec in favour of getfullargspec, but
|
|
|
|
# Python 2 doesn't have the latter, so detect which one to use
|
2023-05-23 04:00:42 -04:00
|
|
|
getargspec = getattr(inspect, "getfullargspec", getattr(inspect, "getargspec", None))
|
2018-07-27 01:55:32 -04:00
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
if "length" in getargspec(usb.util.get_string).args:
|
2015-06-21 02:06:46 -04:00
|
|
|
# PyUSB 1.0.0.b1 has the length argument
|
|
|
|
def get_string(dev, index):
|
|
|
|
return usb.util.get_string(dev, 255, index)
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2015-06-21 02:06:46 -04:00
|
|
|
else:
|
|
|
|
# PyUSB 1.0.0.b2 dropped the length argument
|
|
|
|
def get_string(dev, index):
|
|
|
|
return usb.util.get_string(dev, index)
|
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2018-11-27 00:19:27 -05:00
|
|
|
def find_dfu_cfg_descr(descr):
|
|
|
|
if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE:
|
2020-01-21 15:30:50 -05:00
|
|
|
nt = collections.namedtuple(
|
2020-02-26 23:36:53 -05:00
|
|
|
"CfgDescr",
|
2020-01-21 15:30:50 -05:00
|
|
|
[
|
2020-02-26 23:36:53 -05:00
|
|
|
"bLength",
|
|
|
|
"bDescriptorType",
|
|
|
|
"bmAttributes",
|
|
|
|
"wDetachTimeOut",
|
|
|
|
"wTransferSize",
|
|
|
|
"bcdDFUVersion",
|
|
|
|
],
|
2020-01-21 15:30:50 -05:00
|
|
|
)
|
2020-02-26 23:36:53 -05:00
|
|
|
return nt(*struct.unpack("<BBBHHH", bytearray(descr)))
|
2018-11-27 00:19:27 -05:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2021-05-18 09:38:49 -04:00
|
|
|
def init(**kwargs):
|
2014-10-22 01:27:33 -04:00
|
|
|
"""Initializes the found DFU device so that we can program it."""
|
2018-11-27 00:19:27 -05:00
|
|
|
global __dev, __cfg_descr
|
2021-05-18 09:38:49 -04:00
|
|
|
devices = get_dfu_devices(**kwargs)
|
2014-10-22 01:27:33 -04:00
|
|
|
if not devices:
|
2020-02-26 23:36:53 -05:00
|
|
|
raise ValueError("No DFU device found")
|
2014-10-22 01:27:33 -04:00
|
|
|
if len(devices) > 1:
|
2020-02-26 23:36:53 -05:00
|
|
|
raise ValueError("Multiple DFU devices found")
|
2014-10-22 01:27:33 -04:00
|
|
|
__dev = devices[0]
|
2017-12-13 18:08:37 -05:00
|
|
|
__dev.set_configuration()
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Claim DFU interface
|
|
|
|
usb.util.claim_interface(__dev, __DFU_INTERFACE)
|
|
|
|
|
2018-11-27 00:19:27 -05:00
|
|
|
# Find the DFU configuration descriptor, either in the device or interfaces
|
|
|
|
__cfg_descr = None
|
|
|
|
for cfg in __dev.configurations():
|
|
|
|
__cfg_descr = find_dfu_cfg_descr(cfg.extra_descriptors)
|
|
|
|
if __cfg_descr:
|
|
|
|
break
|
|
|
|
for itf in cfg.interfaces():
|
|
|
|
__cfg_descr = find_dfu_cfg_descr(itf.extra_descriptors)
|
|
|
|
if __cfg_descr:
|
|
|
|
break
|
|
|
|
|
|
|
|
# Get device into idle state
|
|
|
|
for attempt in range(4):
|
|
|
|
status = get_status()
|
|
|
|
if status == __DFU_STATE_DFU_IDLE:
|
|
|
|
break
|
2020-02-26 23:36:53 -05:00
|
|
|
elif status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE:
|
2018-11-27 00:19:27 -05:00
|
|
|
abort_request()
|
|
|
|
else:
|
|
|
|
clr_status()
|
|
|
|
|
|
|
|
|
|
|
|
def abort_request():
|
|
|
|
"""Sends an abort request."""
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_ABORT, 0, __DFU_INTERFACE, None, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def clr_status():
|
|
|
|
"""Clears any error status (perhaps left over from a previous session)."""
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, None, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def get_status():
|
|
|
|
"""Get the status of the last operation."""
|
2020-07-01 01:01:16 -04:00
|
|
|
stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, 6, 20000)
|
2020-03-04 23:00:07 -05:00
|
|
|
|
|
|
|
# firmware can provide an optional string for any error
|
|
|
|
if stat[5]:
|
|
|
|
message = get_string(__dev, stat[5])
|
|
|
|
if message:
|
|
|
|
print(message)
|
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
return stat[4]
|
|
|
|
|
|
|
|
|
2020-02-24 01:17:53 -05:00
|
|
|
def check_status(stage, expected):
|
|
|
|
status = get_status()
|
|
|
|
if status != expected:
|
|
|
|
raise SystemExit("DFU: %s failed (%s)" % (stage, __DFU_STATUS_STR.get(status, status)))
|
|
|
|
|
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
def mass_erase():
|
2020-01-21 15:30:50 -05:00
|
|
|
"""Performs a MASS erase (i.e. erases the entire device)."""
|
2014-10-22 01:27:33 -04:00
|
|
|
# Send DNLOAD with first byte=0x41
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-07-01 01:01:16 -04:00
|
|
|
# Execute last command
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_BUSY)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Check command state
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_IDLE)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def page_erase(addr):
|
|
|
|
"""Erases a single page."""
|
|
|
|
if __verbose:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Erasing page: 0x%x..." % (addr))
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Send DNLOAD with first byte=0x41 and page address
|
2020-02-26 23:36:53 -05:00
|
|
|
buf = struct.pack("<BI", 0x41, addr)
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Execute last command
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_BUSY)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Check command state
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_IDLE)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def set_address(addr):
|
|
|
|
"""Sets the address for the next operation."""
|
|
|
|
# Send DNLOAD with first byte=0x21 and page address
|
2020-02-26 23:36:53 -05:00
|
|
|
buf = struct.pack("<BI", 0x21, addr)
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Execute last command
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("set address", __DFU_STATE_DFU_DOWNLOAD_BUSY)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Check command state
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("set address", __DFU_STATE_DFU_DOWNLOAD_IDLE)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0):
|
|
|
|
"""Writes a buffer into memory. This routine assumes that memory has
|
|
|
|
already been erased.
|
|
|
|
"""
|
|
|
|
|
|
|
|
xfer_count = 0
|
|
|
|
xfer_bytes = 0
|
|
|
|
xfer_total = len(buf)
|
|
|
|
xfer_base = addr
|
|
|
|
|
|
|
|
while xfer_bytes < xfer_total:
|
|
|
|
if __verbose and xfer_count % 512 == 0:
|
2020-02-26 23:36:53 -05:00
|
|
|
print(
|
|
|
|
"Addr 0x%x %dKBs/%dKBs..."
|
|
|
|
% (xfer_base + xfer_bytes, xfer_bytes // 1024, xfer_total // 1024)
|
|
|
|
)
|
2018-06-08 01:32:49 -04:00
|
|
|
if progress and xfer_count % 2 == 0:
|
2020-02-26 23:36:53 -05:00
|
|
|
progress(progress_addr, xfer_base + xfer_bytes - progress_addr, progress_size)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Set mem write address
|
2020-01-21 15:30:50 -05:00
|
|
|
set_address(xfer_base + xfer_bytes)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Send DNLOAD with fw data
|
2020-01-21 15:30:50 -05:00
|
|
|
chunk = min(__cfg_descr.wTransferSize, xfer_total - xfer_bytes)
|
2020-02-26 23:36:53 -05:00
|
|
|
__dev.ctrl_transfer(
|
2020-07-01 01:01:16 -04:00
|
|
|
0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf[xfer_bytes : xfer_bytes + chunk], __TIMEOUT
|
2020-02-26 23:36:53 -05:00
|
|
|
)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Execute last command
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_BUSY)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Check command state
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_IDLE)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
xfer_count += 1
|
|
|
|
xfer_bytes += chunk
|
|
|
|
|
|
|
|
|
|
|
|
def write_page(buf, xfer_offset):
|
|
|
|
"""Writes a single page. This routine assumes that memory has already
|
|
|
|
been erased.
|
|
|
|
"""
|
|
|
|
|
|
|
|
xfer_base = 0x08000000
|
|
|
|
|
|
|
|
# Set mem write address
|
2020-01-21 15:30:50 -05:00
|
|
|
set_address(xfer_base + xfer_offset)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Send DNLOAD with fw data
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Execute last command
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_BUSY)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Check command state
|
2020-02-24 01:17:53 -05:00
|
|
|
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_IDLE)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
if __verbose:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Write: 0x%x " % (xfer_base + xfer_offset))
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def exit_dfu():
|
|
|
|
"""Exit DFU mode, and start running the program."""
|
2020-01-21 15:30:50 -05:00
|
|
|
# Set jump address
|
2014-10-22 01:27:33 -04:00
|
|
|
set_address(0x08000000)
|
|
|
|
|
|
|
|
# Send DNLOAD with 0 length to exit DFU
|
2020-07-01 01:01:16 -04:00
|
|
|
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2015-06-21 02:06:46 -04:00
|
|
|
try:
|
|
|
|
# Execute last command
|
|
|
|
if get_status() != __DFU_STATE_DFU_MANIFEST:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Failed to reset device")
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2015-06-21 02:06:46 -04:00
|
|
|
# Release device
|
|
|
|
usb.util.dispose_resources(__dev)
|
|
|
|
except:
|
|
|
|
pass
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def named(values, names):
|
|
|
|
"""Creates a dict with `names` as fields, and `values` as values."""
|
|
|
|
return dict(zip(names.split(), values))
|
|
|
|
|
|
|
|
|
|
|
|
def consume(fmt, data, names):
|
|
|
|
"""Parses the struct defined by `fmt` from `data`, stores the parsed fields
|
|
|
|
into a named tuple using `names`. Returns the named tuple, and the data
|
|
|
|
with the struct stripped off."""
|
2020-01-21 15:30:50 -05:00
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
size = struct.calcsize(fmt)
|
|
|
|
return named(struct.unpack(fmt, data[:size]), names), data[size:]
|
|
|
|
|
|
|
|
|
|
|
|
def cstring(string):
|
|
|
|
"""Extracts a null-terminated string from a byte array."""
|
2020-02-26 23:36:53 -05:00
|
|
|
return string.decode("utf-8").split("\0", 1)[0]
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def compute_crc(data):
|
|
|
|
"""Computes the CRC32 value for the data passed in."""
|
|
|
|
return 0xFFFFFFFF & -zlib.crc32(data) - 1
|
|
|
|
|
|
|
|
|
|
|
|
def read_dfu_file(filename):
|
|
|
|
"""Reads a DFU file, and parses the individual elements from the file.
|
|
|
|
Returns an array of elements. Each element is a dictionary with the
|
|
|
|
following keys:
|
2020-01-21 15:30:50 -05:00
|
|
|
num - The element index.
|
2014-10-22 01:27:33 -04:00
|
|
|
address - The address that the element data should be written to.
|
2020-01-21 15:30:50 -05:00
|
|
|
size - The size of the element data.
|
2014-10-22 01:27:33 -04:00
|
|
|
data - The element data.
|
|
|
|
If an error occurs while parsing the file, then None is returned.
|
|
|
|
"""
|
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
print("File: {}".format(filename))
|
|
|
|
with open(filename, "rb") as fin:
|
2014-10-22 01:27:33 -04:00
|
|
|
data = fin.read()
|
|
|
|
crc = compute_crc(data[:-4])
|
|
|
|
elements = []
|
|
|
|
|
|
|
|
# Decode the DFU Prefix
|
|
|
|
#
|
|
|
|
# <5sBIB
|
2020-01-21 15:30:50 -05:00
|
|
|
# < little endian Endianness
|
2014-10-22 01:27:33 -04:00
|
|
|
# 5s char[5] signature "DfuSe"
|
|
|
|
# B uint8_t version 1
|
2020-01-21 15:30:50 -05:00
|
|
|
# I uint32_t size Size of the DFU file (without suffix)
|
2014-10-22 01:27:33 -04:00
|
|
|
# B uint8_t targets Number of targets
|
2020-02-26 23:36:53 -05:00
|
|
|
dfu_prefix, data = consume("<5sBIB", data, "signature version size targets")
|
|
|
|
print(
|
|
|
|
" %(signature)s v%(version)d, image size: %(size)d, "
|
|
|
|
"targets: %(targets)d" % dfu_prefix
|
|
|
|
)
|
|
|
|
for target_idx in range(dfu_prefix["targets"]):
|
2014-10-22 01:27:33 -04:00
|
|
|
# Decode the Image Prefix
|
|
|
|
#
|
|
|
|
# <6sBI255s2I
|
2020-01-21 15:30:50 -05:00
|
|
|
# < little endian Endianness
|
2014-10-22 01:27:33 -04:00
|
|
|
# 6s char[6] signature "Target"
|
|
|
|
# B uint8_t altsetting
|
2020-01-21 15:30:50 -05:00
|
|
|
# I uint32_t named Bool indicating if a name was used
|
|
|
|
# 255s char[255] name Name of the target
|
|
|
|
# I uint32_t size Size of image (without prefix)
|
2014-10-22 01:27:33 -04:00
|
|
|
# I uint32_t elements Number of elements in the image
|
2020-02-26 23:36:53 -05:00
|
|
|
img_prefix, data = consume(
|
|
|
|
"<6sBI255s2I", data, "signature altsetting named name " "size elements"
|
|
|
|
)
|
|
|
|
img_prefix["num"] = target_idx
|
|
|
|
if img_prefix["named"]:
|
|
|
|
img_prefix["name"] = cstring(img_prefix["name"])
|
2014-10-22 01:27:33 -04:00
|
|
|
else:
|
2020-02-26 23:36:53 -05:00
|
|
|
img_prefix["name"] = ""
|
|
|
|
print(
|
|
|
|
" %(signature)s %(num)d, alt setting: %(altsetting)s, "
|
|
|
|
'name: "%(name)s", size: %(size)d, elements: %(elements)d' % img_prefix
|
|
|
|
)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
target_size = img_prefix["size"]
|
2020-01-21 15:30:50 -05:00
|
|
|
target_data = data[:target_size]
|
|
|
|
data = data[target_size:]
|
2020-02-26 23:36:53 -05:00
|
|
|
for elem_idx in range(img_prefix["elements"]):
|
2014-10-22 01:27:33 -04:00
|
|
|
# Decode target prefix
|
2020-01-21 15:30:50 -05:00
|
|
|
#
|
|
|
|
# <2I
|
|
|
|
# < little endian Endianness
|
|
|
|
# I uint32_t element Address
|
|
|
|
# I uint32_t element Size
|
2020-02-26 23:36:53 -05:00
|
|
|
elem_prefix, target_data = consume("<2I", target_data, "addr size")
|
|
|
|
elem_prefix["num"] = elem_idx
|
|
|
|
print(" %(num)d, address: 0x%(addr)08x, size: %(size)d" % elem_prefix)
|
|
|
|
elem_size = elem_prefix["size"]
|
2014-10-22 01:27:33 -04:00
|
|
|
elem_data = target_data[:elem_size]
|
|
|
|
target_data = target_data[elem_size:]
|
2020-02-26 23:36:53 -05:00
|
|
|
elem_prefix["data"] = elem_data
|
2014-10-22 01:27:33 -04:00
|
|
|
elements.append(elem_prefix)
|
|
|
|
|
|
|
|
if len(target_data):
|
2020-02-26 23:36:53 -05:00
|
|
|
print("target %d PARSE ERROR" % target_idx)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
# Decode DFU Suffix
|
2020-01-21 15:30:50 -05:00
|
|
|
#
|
|
|
|
# <4H3sBI
|
|
|
|
# < little endian Endianness
|
|
|
|
# H uint16_t device Firmware version
|
2014-10-22 01:27:33 -04:00
|
|
|
# H uint16_t product
|
|
|
|
# H uint16_t vendor
|
2020-01-21 15:30:50 -05:00
|
|
|
# H uint16_t dfu 0x11a (DFU file format version)
|
|
|
|
# 3s char[3] ufd "UFD"
|
|
|
|
# B uint8_t len 16
|
|
|
|
# I uint32_t crc32 Checksum
|
2020-02-26 23:36:53 -05:00
|
|
|
dfu_suffix = named(
|
|
|
|
struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc"
|
|
|
|
)
|
|
|
|
print(
|
|
|
|
" usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, "
|
|
|
|
"dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" % dfu_suffix
|
|
|
|
)
|
|
|
|
if crc != dfu_suffix["crc"]:
|
|
|
|
print("CRC ERROR: computed crc32 is 0x%08x" % crc)
|
2014-10-22 01:27:33 -04:00
|
|
|
return
|
|
|
|
data = data[16:]
|
|
|
|
if data:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("PARSE ERROR")
|
2014-10-22 01:27:33 -04:00
|
|
|
return
|
|
|
|
|
|
|
|
return elements
|
|
|
|
|
|
|
|
|
|
|
|
class FilterDFU(object):
|
|
|
|
"""Class for filtering USB devices to identify devices which are in DFU
|
|
|
|
mode.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __call__(self, device):
|
|
|
|
for cfg in device:
|
|
|
|
for intf in cfg:
|
2020-02-26 23:36:53 -05:00
|
|
|
return intf.bInterfaceClass == 0xFE and intf.bInterfaceSubClass == 1
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def get_dfu_devices(*args, **kwargs):
|
2020-01-21 15:30:50 -05:00
|
|
|
"""Returns a list of USB devices which are currently in DFU mode.
|
|
|
|
Additional filters (like idProduct and idVendor) can be passed in
|
|
|
|
to refine the search.
|
2014-10-22 01:27:33 -04:00
|
|
|
"""
|
2020-01-21 15:30:50 -05:00
|
|
|
|
|
|
|
# Convert to list for compatibility with newer PyUSB
|
2020-02-26 23:36:53 -05:00
|
|
|
return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs))
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def get_memory_layout(device):
|
|
|
|
"""Returns an array which identifies the memory layout. Each entry
|
|
|
|
of the array will contain a dictionary with the following keys:
|
2020-01-21 15:30:50 -05:00
|
|
|
addr - Address of this memory segment.
|
2014-10-22 01:27:33 -04:00
|
|
|
last_addr - Last address contained within the memory segment.
|
2020-01-21 15:30:50 -05:00
|
|
|
size - Size of the segment, in bytes.
|
|
|
|
num_pages - Number of pages in the segment.
|
|
|
|
page_size - Size of each page, in bytes.
|
2014-10-22 01:27:33 -04:00
|
|
|
"""
|
2020-01-21 15:30:50 -05:00
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
cfg = device[0]
|
|
|
|
intf = cfg[(0, 0)]
|
2015-06-21 02:06:46 -04:00
|
|
|
mem_layout_str = get_string(device, intf.iInterface)
|
2020-02-26 23:36:53 -05:00
|
|
|
mem_layout = mem_layout_str.split("/")
|
2014-10-22 01:27:33 -04:00
|
|
|
result = []
|
2018-06-22 01:32:32 -04:00
|
|
|
for mem_layout_index in range(1, len(mem_layout), 2):
|
|
|
|
addr = int(mem_layout[mem_layout_index], 0)
|
2020-02-26 23:36:53 -05:00
|
|
|
segments = mem_layout[mem_layout_index + 1].split(",")
|
|
|
|
seg_re = re.compile(r"(\d+)\*(\d+)(.)(.)")
|
2018-06-22 01:32:32 -04:00
|
|
|
for segment in segments:
|
|
|
|
seg_match = seg_re.match(segment)
|
|
|
|
num_pages = int(seg_match.groups()[0], 10)
|
|
|
|
page_size = int(seg_match.groups()[1], 10)
|
|
|
|
multiplier = seg_match.groups()[2]
|
2020-02-26 23:36:53 -05:00
|
|
|
if multiplier == "K":
|
2018-06-22 01:32:32 -04:00
|
|
|
page_size *= 1024
|
2020-02-26 23:36:53 -05:00
|
|
|
if multiplier == "M":
|
2018-06-22 01:32:32 -04:00
|
|
|
page_size *= 1024 * 1024
|
|
|
|
size = num_pages * page_size
|
|
|
|
last_addr = addr + size - 1
|
2020-02-26 23:36:53 -05:00
|
|
|
result.append(
|
|
|
|
named(
|
|
|
|
(addr, last_addr, size, num_pages, page_size),
|
|
|
|
"addr last_addr size num_pages page_size",
|
|
|
|
)
|
|
|
|
)
|
2018-06-22 01:32:32 -04:00
|
|
|
addr += size
|
2014-10-22 01:27:33 -04:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def list_dfu_devices(*args, **kwargs):
|
2023-03-07 22:10:02 -05:00
|
|
|
"""Prints a list of devices detected in DFU mode."""
|
2014-10-22 01:27:33 -04:00
|
|
|
devices = get_dfu_devices(*args, **kwargs)
|
|
|
|
if not devices:
|
2020-02-24 01:17:53 -05:00
|
|
|
raise SystemExit("No DFU capable devices found")
|
2014-10-22 01:27:33 -04:00
|
|
|
for device in devices:
|
2020-02-26 23:36:53 -05:00
|
|
|
print(
|
|
|
|
"Bus {} Device {:03d}: ID {:04x}:{:04x}".format(
|
|
|
|
device.bus, device.address, device.idVendor, device.idProduct
|
|
|
|
)
|
|
|
|
)
|
2014-10-22 01:27:33 -04:00
|
|
|
layout = get_memory_layout(device)
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Memory Layout")
|
2014-10-22 01:27:33 -04:00
|
|
|
for entry in layout:
|
2020-02-26 23:36:53 -05:00
|
|
|
print(
|
|
|
|
" 0x{:x} {:2d} pages of {:3d}K bytes".format(
|
|
|
|
entry["addr"], entry["num_pages"], entry["page_size"] // 1024
|
|
|
|
)
|
|
|
|
)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def write_elements(elements, mass_erase_used, progress=None):
|
|
|
|
"""Writes the indicated elements into the target memory,
|
|
|
|
erasing as needed.
|
|
|
|
"""
|
|
|
|
|
|
|
|
mem_layout = get_memory_layout(__dev)
|
|
|
|
for elem in elements:
|
2020-02-26 23:36:53 -05:00
|
|
|
addr = elem["addr"]
|
|
|
|
size = elem["size"]
|
|
|
|
data = elem["data"]
|
2014-10-22 01:27:33 -04:00
|
|
|
elem_size = size
|
|
|
|
elem_addr = addr
|
2021-02-22 22:33:31 -05:00
|
|
|
if progress and elem_size:
|
2014-10-22 01:27:33 -04:00
|
|
|
progress(elem_addr, 0, elem_size)
|
|
|
|
while size > 0:
|
|
|
|
write_size = size
|
|
|
|
if not mass_erase_used:
|
|
|
|
for segment in mem_layout:
|
2020-02-26 23:36:53 -05:00
|
|
|
if addr >= segment["addr"] and addr <= segment["last_addr"]:
|
2014-10-22 01:27:33 -04:00
|
|
|
# We found the page containing the address we want to
|
|
|
|
# write, erase it
|
2020-02-26 23:36:53 -05:00
|
|
|
page_size = segment["page_size"]
|
2014-10-22 01:27:33 -04:00
|
|
|
page_addr = addr & ~(page_size - 1)
|
|
|
|
if addr + write_size > page_addr + page_size:
|
|
|
|
write_size = page_addr + page_size - addr
|
|
|
|
page_erase(page_addr)
|
|
|
|
break
|
2020-02-26 23:36:53 -05:00
|
|
|
write_memory(addr, data[:write_size], progress, elem_addr, elem_size)
|
2014-10-22 01:27:33 -04:00
|
|
|
data = data[write_size:]
|
|
|
|
addr += write_size
|
|
|
|
size -= write_size
|
|
|
|
if progress:
|
|
|
|
progress(elem_addr, addr - elem_addr, elem_size)
|
|
|
|
|
|
|
|
|
|
|
|
def cli_progress(addr, offset, size):
|
|
|
|
"""Prints a progress report suitable for use on the command line."""
|
|
|
|
width = 25
|
|
|
|
done = offset * width // size
|
2020-02-26 23:36:53 -05:00
|
|
|
print(
|
|
|
|
"\r0x{:08x} {:7d} [{}{}] {:3d}% ".format(
|
|
|
|
addr, size, "=" * done, " " * (width - done), offset * 100 // size
|
|
|
|
),
|
|
|
|
end="",
|
|
|
|
)
|
2018-09-12 02:42:06 -04:00
|
|
|
try:
|
|
|
|
sys.stdout.flush()
|
|
|
|
except OSError:
|
2020-02-26 23:36:53 -05:00
|
|
|
pass # Ignore Windows CLI "WinError 87" on Python 3.6
|
2014-10-22 01:27:33 -04:00
|
|
|
if offset == size:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("")
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
"""Test program for verifying this files functionality."""
|
|
|
|
global __verbose
|
|
|
|
# Parse CMD args
|
2020-02-26 23:36:53 -05:00
|
|
|
parser = argparse.ArgumentParser(description="DFU Python Util")
|
2014-10-22 01:27:33 -04:00
|
|
|
parser.add_argument(
|
2020-02-26 23:36:53 -05:00
|
|
|
"-l", "--list", help="list available DFU devices", action="store_true", default=False
|
2014-10-22 01:27:33 -04:00
|
|
|
)
|
2021-05-18 09:38:49 -04:00
|
|
|
parser.add_argument("--vid", help="USB Vendor ID", type=lambda x: int(x, 0), default=None)
|
|
|
|
parser.add_argument("--pid", help="USB Product ID", type=lambda x: int(x, 0), default=None)
|
2014-10-22 01:27:33 -04:00
|
|
|
parser.add_argument(
|
2020-02-26 23:36:53 -05:00
|
|
|
"-m", "--mass-erase", help="mass erase device", action="store_true", default=False
|
2014-10-22 01:27:33 -04:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
2020-02-26 23:36:53 -05:00
|
|
|
"-u", "--upload", help="read file from DFU device", dest="path", default=False
|
2014-10-22 01:27:33 -04:00
|
|
|
)
|
2020-02-24 01:17:53 -05:00
|
|
|
parser.add_argument("-x", "--exit", help="Exit DFU", action="store_true", default=False)
|
2014-10-22 01:27:33 -04:00
|
|
|
parser.add_argument(
|
2020-02-26 23:36:53 -05:00
|
|
|
"-v", "--verbose", help="increase output verbosity", action="store_true", default=False
|
2014-10-22 01:27:33 -04:00
|
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
__verbose = args.verbose
|
|
|
|
|
2021-05-18 09:38:49 -04:00
|
|
|
kwargs = {}
|
|
|
|
if args.vid:
|
|
|
|
kwargs["idVendor"] = args.vid
|
|
|
|
|
|
|
|
if args.pid:
|
|
|
|
kwargs["idProduct"] = args.pid
|
2020-02-24 01:17:53 -05:00
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
if args.list:
|
2021-05-18 09:38:49 -04:00
|
|
|
list_dfu_devices(**kwargs)
|
2014-10-22 01:27:33 -04:00
|
|
|
return
|
|
|
|
|
2021-05-18 09:38:49 -04:00
|
|
|
init(**kwargs)
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-24 01:17:53 -05:00
|
|
|
command_run = False
|
2014-10-22 01:27:33 -04:00
|
|
|
if args.mass_erase:
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Mass erase...")
|
2014-10-22 01:27:33 -04:00
|
|
|
mass_erase()
|
2020-02-24 01:17:53 -05:00
|
|
|
command_run = True
|
2014-10-22 01:27:33 -04:00
|
|
|
|
|
|
|
if args.path:
|
|
|
|
elements = read_dfu_file(args.path)
|
|
|
|
if not elements:
|
2020-02-24 01:17:53 -05:00
|
|
|
print("No data in dfu file")
|
2014-10-22 01:27:33 -04:00
|
|
|
return
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Writing memory...")
|
2014-10-22 01:27:33 -04:00
|
|
|
write_elements(elements, args.mass_erase, progress=cli_progress)
|
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
print("Exiting DFU...")
|
2014-10-22 01:27:33 -04:00
|
|
|
exit_dfu()
|
2020-02-24 01:17:53 -05:00
|
|
|
command_run = True
|
|
|
|
|
|
|
|
if args.exit:
|
|
|
|
print("Exiting DFU...")
|
|
|
|
exit_dfu()
|
|
|
|
command_run = True
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-24 01:17:53 -05:00
|
|
|
if command_run:
|
|
|
|
print("Finished")
|
|
|
|
else:
|
|
|
|
print("No command specified")
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2014-10-22 01:27:33 -04:00
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
if __name__ == "__main__":
|
2014-10-22 01:27:33 -04:00
|
|
|
main()
|