blob: 1fa188e18046c596dacbbbd71a9d5640eca8522c [file] [log] [blame]
# Copyright 2023 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Flash Gonk via dfu-util."""
import argparse
from pathlib import Path
import shutil
import signal
import subprocess
import sys
from typing import Optional
import pw_cli.color
from gonk_tools.firmware_files import bundled_bin_path
_COLOR = pw_cli.color.colors()
DFU_SERIAL_STRING = 'STM32FxSTM32'
def _parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--dfu-serial-string',
default=DFU_SERIAL_STRING,
help=f'Serial string to pass to dfu-util. Default: {DFU_SERIAL_STRING}',
)
parser.add_argument(
'--bin-file',
help='Binary to flash with dfu-util',
type=Path,
)
return parser.parse_args()
def main(
dfu_serial_string: str,
bin_file: Optional[Path],
) -> int:
"""Flash Gonk via dfu-util."""
dfu_util_binary = shutil.which('dfu-util')
if not dfu_util_binary or not Path(dfu_util_binary).is_file():
raise FileNotFoundError('Unable to find "dfu-util"')
if not bin_file:
bin_file = bundled_bin_path()
if not bin_file or not bin_file.is_file():
raise FileNotFoundError(
f'Unable to find the binary file to flash: "{bin_file}"'
)
dfu_flash_args = [
dfu_util_binary,
'--device',
'0483:df11',
'--dfuse-address',
'0x08000000:leave',
'--serial',
dfu_serial_string,
'--alt',
'0',
'--download',
str(bin_file),
]
print(
_COLOR.cyan('Running ==>'),
' '.join(dfu_flash_args),
)
# Ignore Ctrl-C to allow dfu-util to handle normally.
signal.signal(signal.SIGINT, signal.SIG_IGN)
return subprocess.run(dfu_flash_args, check=False).returncode
def dfu_flash() -> None:
sys.exit(main(**vars(_parse_args())))
if __name__ == '__main__':
dfu_flash()