|
| 1 | +# Copyright (c) 2025 Nordic Semiconductor ASA |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import shlex |
| 8 | +import subprocess |
| 9 | +from pathlib import Path |
| 10 | +from typing import Literal |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +def normalize_path(path: str) -> str: |
| 16 | + path = os.path.expanduser(os.path.expandvars(path)) |
| 17 | + path = os.path.normpath(os.path.abspath(path)) |
| 18 | + return path |
| 19 | + |
| 20 | + |
| 21 | +def run_command(command: list[str], timeout: int = 30) -> None: |
| 22 | + logger.info(f"CMD: {shlex.join(command)}") |
| 23 | + ret: subprocess.CompletedProcess = subprocess.run( |
| 24 | + command, |
| 25 | + text=True, |
| 26 | + stdout=subprocess.PIPE, |
| 27 | + stderr=subprocess.STDOUT, |
| 28 | + timeout=timeout, |
| 29 | + ) |
| 30 | + if ret.returncode: |
| 31 | + logger.error(f"Failed command: {shlex.join(command)}") |
| 32 | + logger.info(ret.stdout) |
| 33 | + raise subprocess.CalledProcessError(ret.returncode, command) |
| 34 | + |
| 35 | + |
| 36 | +def reset_board(dev_id: str | None = None): |
| 37 | + """Reset device.""" |
| 38 | + command = ["nrfutil", "device", "reset"] |
| 39 | + if dev_id: |
| 40 | + command.extend(["--serial-number", dev_id]) |
| 41 | + run_command(command) |
| 42 | + |
| 43 | + |
| 44 | +def erase_board(dev_id: str | None): |
| 45 | + """Run nrfutil device erase command.""" |
| 46 | + command = ["nrfutil", "device", "erase"] |
| 47 | + if dev_id: |
| 48 | + command.extend(["--serial-number", dev_id]) |
| 49 | + run_command(command) |
| 50 | + |
| 51 | + |
| 52 | +def provision_keys_for_kmu( |
| 53 | + keys: list[str] | list[Path] | str | Path, |
| 54 | + *, |
| 55 | + keyname: Literal["UROT_PUBKEY", "BL_PUBKEY", "APP_PUBKEY"] = "BL_PUBKEY", |
| 56 | + policy: Literal["revokable", "lock", "lock-last"] | None = None, |
| 57 | + dev_id: str | None = None, |
| 58 | +): |
| 59 | + """Upload keys with west provision command.""" |
| 60 | + logger.info("Provision keys using west command.") |
| 61 | + command = ["west", "ncs-provision", "upload", "--keyname", keyname] |
| 62 | + if policy: |
| 63 | + command += ["--policy", policy] |
| 64 | + if dev_id: |
| 65 | + command += ["--dev-id", dev_id] |
| 66 | + if not isinstance(keys, list): |
| 67 | + keys = [keys] |
| 68 | + for key in keys: |
| 69 | + assert os.path.exists(key), f"Key file does not exist: {key}" |
| 70 | + command += ["--key", normalize_path(str(key))] |
| 71 | + |
| 72 | + run_command(command) |
| 73 | + logger.info("Keys provisioned successfully") |
0 commit comments