mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-18 08:52:45 +00:00
adding commands and code related to flashing
This commit is contained in:
parent
38d3c17ee8
commit
6d12008a80
5 changed files with 243 additions and 7 deletions
|
|
@ -8,6 +8,7 @@ Usage examples:
|
|||
"""
|
||||
|
||||
import argparse
|
||||
from re import sub
|
||||
import sys
|
||||
|
||||
# Subcommand imports
|
||||
|
|
@ -16,16 +17,31 @@ from commands.monitor import cmd_monitor
|
|||
from commands.flash import cmd_flash
|
||||
from commands.doctor import cmd_doctor
|
||||
from commands.build import cmd_build
|
||||
from commands.artifacts import cmd_artifacts
|
||||
from commands.update_all import cmd_update_all
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(prog="bao.py")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
# artifacts
|
||||
a = sub.add_parser("artifacts", help="List newest UF2 images (release only)")
|
||||
a.add_argument("--json", action="store_true")
|
||||
a.set_defaults(func=cmd_artifacts)
|
||||
|
||||
# ports
|
||||
s = sub.add_parser("ports", help="List serial ports")
|
||||
s.add_argument("-v", "--verbose", action="store_true")
|
||||
s.set_defaults(func=cmd_ports)
|
||||
|
||||
# update-all
|
||||
ua = sub.add_parser("update-all", help="Return true if board Xous/loader version differs from local")
|
||||
ua.add_argument("-p", "--port", required=True, help="Monitor serial port")
|
||||
ua.add_argument("-b", "--baud", type=int, default=115200)
|
||||
ua.add_argument("--timeout", type=float, default=3.0, help="Seconds to wait for version response")
|
||||
ua.add_argument("--json", action="store_true", help='Emit {"updateAll": bool, "current": "...", "board": "..."}')
|
||||
ua.set_defaults(func=cmd_update_all)
|
||||
|
||||
# monitor
|
||||
m = sub.add_parser("monitor", help="Open a serial monitor")
|
||||
m.add_argument("-p", "--port", required=True)
|
||||
|
|
@ -46,12 +62,10 @@ def main():
|
|||
d = sub.add_parser("doctor", help="Check Python environment and ports")
|
||||
d.set_defaults(func=cmd_doctor)
|
||||
|
||||
# flash (stub)
|
||||
f = sub.add_parser("flash", help="Flash a built image (stub)")
|
||||
f.add_argument("-p", "--port", required=True)
|
||||
f.add_argument("-b", "--baud", type=int, default=115200)
|
||||
f.add_argument("--addr", type=lambda x: int(x, 0), default=0x0)
|
||||
f.add_argument("--file", help="Binary to flash")
|
||||
# flash
|
||||
f = sub.add_parser("flash", help="Copy UF2 file(s) to a mounted drive")
|
||||
f.add_argument("--dest", required=True, help="Mount path of the UF2 boot drive (e.g., D:\\ or /Volumes/BAOBOOT)")
|
||||
f.add_argument("files", nargs="+", help="One or more UF2 files to copy (e.g., loader.uf2 xous.uf2 app.uf2)")
|
||||
f.set_defaults(func=cmd_flash)
|
||||
|
||||
args = ap.parse_args()
|
||||
|
|
|
|||
51
tools-bao/commands/artifacts.py
Normal file
51
tools-bao/commands/artifacts.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""
|
||||
Return release UF2 images for flashing:
|
||||
|
||||
<xous-core>/target/riscv32imac-unknown-xous-elf/release/{loader.uf2,xous.uf2,app.uf2}
|
||||
|
||||
JSON:
|
||||
{ "images": [
|
||||
{ "path": ".../loader.uf2", "role": "loader" },
|
||||
{ "path": ".../xous.uf2", "role": "xous" },
|
||||
{ "path": ".../app.uf2", "role": "app" }
|
||||
] }
|
||||
|
||||
Only files that actually exist are included.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Dict
|
||||
|
||||
TRIPLE = "riscv32imac-unknown-xous-elf"
|
||||
FILENAMES = [
|
||||
("loader.uf2", "loader"),
|
||||
("xous.uf2", "xous"),
|
||||
("app.uf2", "app"),
|
||||
]
|
||||
|
||||
def cmd_artifacts(args):
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
release_dir = root / "target" / TRIPLE / "release"
|
||||
|
||||
images: List[Dict[str, str]] = []
|
||||
if not release_dir.exists():
|
||||
# No error: just report empty so callers can prompt “build first”
|
||||
print(json.dumps({"images": images}) if getattr(args, "json", False)
|
||||
else f"[bao] release dir not found: {release_dir}")
|
||||
sys.exit(0)
|
||||
|
||||
for fname, role in FILENAMES:
|
||||
p = release_dir / fname
|
||||
if p.exists() and p.is_file():
|
||||
images.append({"path": str(p), "role": role})
|
||||
|
||||
if getattr(args, "json", False):
|
||||
print(json.dumps({"images": images}))
|
||||
else:
|
||||
if not images:
|
||||
print(f"[bao] no UF2 images found in {release_dir}")
|
||||
else:
|
||||
for i in images:
|
||||
print(f"{i['path']} ({i['role']})")
|
||||
|
|
@ -1,2 +1,46 @@
|
|||
import sys, shutil
|
||||
from pathlib import Path
|
||||
|
||||
def _is_dir_writable(p: Path) -> bool:
|
||||
try:
|
||||
test = p / ".bao_write_test"
|
||||
test.write_text("ok", encoding="utf-8")
|
||||
test.unlink(missing_ok=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def cmd_flash(args):
|
||||
print(f"[bao] (stub) would flash '{args.file}' to addr {hex(args.addr)} on {args.port} @ {args.baud}")
|
||||
dest = Path(args.dest)
|
||||
if not dest.exists() or not dest.is_dir():
|
||||
print(f"[bao] destination not found or not a directory: {dest}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
if not _is_dir_writable(dest):
|
||||
print(f"[bao] destination is not writable: {dest}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
files = [Path(f) for f in args.files]
|
||||
if not files:
|
||||
print("[bao] no files to copy", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
print(f"[bao] Flash destination: {dest}")
|
||||
copied = 0
|
||||
for src in files:
|
||||
if not src.exists() or not src.is_file():
|
||||
print(f"[bao] skip (not found): {src}", file=sys.stderr)
|
||||
continue
|
||||
dst = dest / src.name
|
||||
print(f"[bao] copy {src} -> {dst}")
|
||||
try:
|
||||
shutil.copyfile(src, dst)
|
||||
copied += 1
|
||||
except Exception as e:
|
||||
print(f"[bao] copy failed for {src}: {e}", file=sys.stderr)
|
||||
|
||||
if copied == 0:
|
||||
print("[bao] nothing copied", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"[bao] copied {copied} file(s)")
|
||||
sys.exit(0)
|
||||
|
|
|
|||
31
tools-bao/commands/update_all.py
Normal file
31
tools-bao/commands/update_all.py
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import json, sys
|
||||
from pathlib import Path
|
||||
from utils.version_utils import read_local_versions, query_board_versions
|
||||
|
||||
def cmd_update_all(args):
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
|
||||
local_semver, local_ts = read_local_versions(root)
|
||||
if not local_semver:
|
||||
print("[bao] could not parse SEMVER from services/xous-ticktimer/src/version.rs", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
board_semver, board_ts = query_board_versions(args.port, args.baud, timeout_s=args.timeout)
|
||||
if board_semver is None:
|
||||
print("[bao] could not read board version (is the board connected and running?)", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
# Decision uses SEMVER vs SEMVER (timestamps are logged but not decisive)
|
||||
needs = (local_semver.strip() != board_semver.strip())
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({
|
||||
"updateAll": needs,
|
||||
"localSemver": local_semver,
|
||||
"localTimestamp": local_ts,
|
||||
"boardSemver": board_semver,
|
||||
"boardTimestamp": board_ts
|
||||
}))
|
||||
else:
|
||||
print("true" if needs else "false")
|
||||
sys.exit(0)
|
||||
96
tools-bao/utils/version_utils.py
Normal file
96
tools-bao/utils/version_utils.py
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import re, time, sys
|
||||
from pathlib import Path
|
||||
from typing import Optional, Tuple
|
||||
import serial
|
||||
|
||||
BOOKEND_START = "_|TT|_"
|
||||
BOOKEND_END = "_|TE|_"
|
||||
|
||||
SEMVER_RE = re.compile(r'pub\s+const\s+SEMVER\s*:\s*&\'static\s+str\s*=\s*"([^"]+)"')
|
||||
TS_RE = re.compile(r'pub\s+const\s+TIMESTAMP\s*:\s*&\'static\s+str\s*=\s*"([^"]+)"')
|
||||
|
||||
def read_local_versions(repo_root: Path) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
Returns (semver, timestamp) parsed from services/xous-ticktimer/src/version.rs.
|
||||
"""
|
||||
f = repo_root / "services" / "xous-ticktimer" / "src" / "version.rs"
|
||||
if not f.exists():
|
||||
return None, None
|
||||
text = f.read_text(encoding="utf-8", errors="ignore")
|
||||
semver = (SEMVER_RE.search(text).group(1).strip()
|
||||
if SEMVER_RE.search(text) else None)
|
||||
ts = (TS_RE.search(text).group(1).strip()
|
||||
if TS_RE.search(text) else None)
|
||||
return semver, ts
|
||||
|
||||
def _between_bookends(buf: str) -> Optional[str]:
|
||||
start_idx = buf.find(BOOKEND_START)
|
||||
if start_idx == -1:
|
||||
return None
|
||||
end_idx = buf.find(BOOKEND_END, start_idx + len(BOOKEND_START))
|
||||
if end_idx == -1:
|
||||
return None
|
||||
return buf[start_idx + len(BOOKEND_START): end_idx]
|
||||
|
||||
def parse_board_version_blob(buf: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
Given full serial output, extract the substring between bookends and split it
|
||||
into (semver, timestamp), matching get_version() which returns:
|
||||
SEMVER + "\\n" + TIMESTAMP
|
||||
Returns (semver, timestamp) or (None, None) if not found.
|
||||
"""
|
||||
blob = _between_bookends(buf)
|
||||
if blob is None:
|
||||
return None, None
|
||||
# normalize line endings and whitespace
|
||||
blob = blob.replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||
# Expect two lines: first SEMVER, second TIMESTAMP (but be tolerant)
|
||||
lines = [ln.strip() for ln in blob.split("\n") if ln.strip() != ""]
|
||||
if not lines:
|
||||
return None, None
|
||||
semver = lines[0]
|
||||
ts = lines[1] if len(lines) > 1 else None
|
||||
return semver, ts
|
||||
|
||||
def query_board_versions(port: str, baud: int = 115200, timeout_s: float = 3.0) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
Open the serial port, send 'ver xous', read for a short window, and return
|
||||
(semver, timestamp) parsed from the bookended payload.
|
||||
"""
|
||||
try:
|
||||
ser = serial.Serial(port, baud, timeout=0.2)
|
||||
except Exception as e:
|
||||
print(f"[bao] cannot open {port}: {e}", file=sys.stderr)
|
||||
return None, None
|
||||
|
||||
try:
|
||||
try:
|
||||
ser.reset_input_buffer()
|
||||
ser.reset_output_buffer()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ser.write(b"ver xous\r\n")
|
||||
ser.flush()
|
||||
|
||||
deadline = time.time() + timeout_s
|
||||
chunks = []
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
data = ser.read(4096)
|
||||
if data:
|
||||
chunks.append(data.decode(errors="replace"))
|
||||
joined = "".join(chunks)
|
||||
if BOOKEND_START in joined and BOOKEND_END in joined:
|
||||
break
|
||||
except Exception:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
finally:
|
||||
try:
|
||||
ser.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
buf = "".join(chunks) if chunks else ""
|
||||
return parse_board_version_blob(buf)
|
||||
Loading…
Reference in a new issue