Merge branch 'main' of github.com:betrusted-io/xous-core into serial-numbers

This commit is contained in:
bunnie 2025-11-06 13:04:33 +08:00
commit bab29616aa
9 changed files with 200 additions and 49 deletions

View file

@ -3,15 +3,15 @@ import sys
import logging
import traceback
# Subcommand imports
from commands.ports import cmd_ports
from commands.monitor import cmd_monitor
from commands.flash import cmd_flash
from commands.doctor import cmd_doctor
from commands.artifacts import cmd_artifacts
from commands.boot import cmd_boot
from commands import artifacts
from commands import ports
from commands import monitor
from commands import flash
from commands import doctor
from commands import boot
from commands import app
VERSION = "0.1.1"
VERSION = "0.1.2"
def main():
ap = argparse.ArgumentParser(
@ -22,45 +22,13 @@ def main():
ap.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output (debug logging and tracebacks)")
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.set_defaults(func=cmd_ports)
# monitor
m = sub.add_parser("monitor", help="Open a serial monitor")
m.add_argument("-p", "--port", required=True, help="Serial port (e.g., COM5, /dev/ttyUSB0)")
m.add_argument("-b", "--baud", type=int, default=1000000, help="Baud rate")
m.add_argument("--ts", action="store_true", help="Show timestamps on received lines")
m.add_argument("--save", help="Append output to a file")
m.add_argument("--reset", action="store_true", help="Toggle DTR/RTS on open")
m.add_argument("--crlf", action="store_true", help="Use CRLF as TX line ending in line mode (default LF)")
m.add_argument("--raw", action="store_true", help="Send keystrokes immediately (raw mode)")
m.add_argument("--no-echo", action="store_true", help="Do not locally echo typed input")
m.add_argument("--rtscts", action="store_true", help="Enable RTS/CTS hardware flow control")
m.add_argument("--xonxoff", action="store_true", help="Enable XON/XOFF software flow control")
m.add_argument("--dsrdtr", action="store_true", help="Enable DSR/DTR hardware flow control")
m.set_defaults(func=cmd_monitor)
# doctor
d = sub.add_parser("doctor", help="Check Python environment and ports")
d.set_defaults(func=cmd_doctor)
# 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:\\)")
f.add_argument("files", nargs="+", help="One or more UF2 files to copy (e.g., loader.uf2 xous.uf2 apps.uf2)")
f.set_defaults(func=cmd_flash)
# boot
boot = sub.add_parser("boot", help="Send 'boot' to the bootloader serial port to start run mode")
boot.add_argument("-p", "--port", required=True, help="Bootloader serial port (e.g., COM7, /dev/ttyACM0)")
boot.add_argument("-b", "--baud", type=int, default=1000000, help="Baud rate (default 1000000)")
boot.set_defaults(func=cmd_boot)
artifacts.register(sub)
ports.register(sub)
monitor.register(sub)
flash.register(sub)
doctor.register(sub)
boot.register(sub)
app.register(sub)
args = ap.parse_args()

120
tools-bao/commands/app.py Normal file
View file

@ -0,0 +1,120 @@
import argparse, re, shutil
from pathlib import Path
from typing import List, Set
from tomlkit import parse as toml_parse, dumps as toml_dumps
APPS_DIR = "apps-dabao"
TEMPLATE_APP = "helloworld"
VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
def _read(path: Path) -> str:
with path.open("r", encoding="utf-8") as f:
return f.read()
def _write(path: Path, content: str):
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="\n") as f:
f.write(content)
def _workspace_members(root: Path) -> List[str]:
doc = toml_parse(_read(root / "Cargo.toml"))
ws = doc.get("workspace")
if not ws or "members" not in ws:
return []
return [str(x) for x in ws["members"]]
def _workspace_package_names(root: Path) -> Set[str]:
names: Set[str] = set()
for rel in _workspace_members(root):
pkg_cargo = root / rel / "Cargo.toml"
if not pkg_cargo.exists():
continue
try:
pkg_doc = toml_parse(_read(pkg_cargo))
pkg = pkg_doc.get("package")
if pkg and "name" in pkg:
names.add(str(pkg["name"]))
except Exception:
# ignore malformed members
pass
return names
def _add_member_if_missing(root: Path, rel: str) -> bool:
cargo = root / "Cargo.toml"
doc = toml_parse(_read(cargo))
ws = doc.setdefault("workspace", {})
arr = ws.setdefault("members", [])
if any(str(x) == rel for x in arr):
return False
arr.append(rel) # tomlkit preserves array style & trailing commas
_write(cargo, toml_dumps(doc))
return True
def _copy_template_cargo(template: Path, dest: Path, new_name: str):
tdoc = toml_parse(_read(template))
if "package" not in tdoc:
raise RuntimeError("Template Cargo.toml missing [package]")
tdoc["package"]["name"] = new_name
_write(dest, toml_dumps(tdoc))
def _copy_template_src(root: Path, new_dir: Path):
src_template = root / APPS_DIR / TEMPLATE_APP / "src"
dest_src = new_dir / "src"
if src_template.exists():
shutil.copytree(src_template, dest_src)
else:
# Fallback minimal main.rs
_write(dest_src / "main.rs", """#![no_std]
#![no_main]
use core::panic::PanicInfo;
#[panic_handler] fn panic(_info: &PanicInfo) -> ! { loop {} }
#[no_mangle] pub extern "C" fn main() -> ! { loop {} }
""")
def cmd_app_create(args: argparse.Namespace) -> int:
root = Path(args.xous_root).resolve()
name = args.name.strip().lower()
if not VALID_NAME_RE.match(name):
print("error: invalid app name. Use lowercase [a-z][a-z0-9_-]*")
return 2
apps_dir = root / APPS_DIR
template_dir = apps_dir / TEMPLATE_APP
template_cargo = template_dir / "Cargo.toml"
if not template_cargo.exists():
print(f"error: template not found at {template_cargo}")
return 2
# crate/package name collision check
existing_pkg_names = _workspace_package_names(root)
if name in existing_pkg_names:
print(f'error: package name "{name}" already exists in workspace')
return 2
new_dir = apps_dir / name
if new_dir.exists():
print(f"error: app directory already exists: {new_dir}")
return 2
# create structure
new_dir.mkdir(parents=True)
_copy_template_cargo(template_cargo, new_dir / "Cargo.toml", name)
_copy_template_src(root, new_dir)
# add to workspace members
rel_member = f"{APPS_DIR}/{name}"
_add_member_if_missing(root, rel_member)
print(f"created: {rel_member}")
return 0
def register(sub: argparse._SubParsersAction):
ap = sub.add_parser("app", help="Bao app utilities")
sp = ap.add_subparsers(dest="app_cmd", required=True)
ap_create = sp.add_parser("create", help="Create a new Bao app")
ap_create.add_argument("--xous-root", default=".", help="path to xous-core root")
ap_create.add_argument("--name", required=True, help="new app name (crate name)")
ap_create.set_defaults(func=cmd_app_create)

View file

@ -9,7 +9,7 @@ Outputs JSON if --json is set:
"images": [
{ "path": ".../loader.uf2", "role": "loader" },
{ "path": ".../xous.uf2", "role": "xous" },
{ "path": ".../apps.uf2", "role": "apps" }
{ "path": ".../apps.uf2", "role": "apps" }
]
}
@ -59,3 +59,9 @@ def cmd_artifacts(args) -> None:
else:
for i in images:
print(f"{i['path']} ({i['role']})")
def register(subparsers) -> None:
a = subparsers.add_parser("artifacts", help="List newest UF2 images (release only)")
a.add_argument("--json", action="store_true", help="Output JSON instead of text")
a.set_defaults(func=cmd_artifacts)

View file

@ -31,3 +31,13 @@ def cmd_boot(args) -> None:
print(f"[bao] sent 'boot' on {port}")
sys.exit(0)
def register(subparsers) -> None:
boot = subparsers.add_parser(
"boot",
help="Send 'boot' to the bootloader serial port to start run mode"
)
boot.add_argument("-p", "--port", required=True, help="Bootloader serial port (e.g., COM7, /dev/ttyACM0)")
boot.add_argument("-b", "--baud", type=int, default=1000000, help="Baud rate (default 1000000)")
boot.set_defaults(func=cmd_boot)

View file

@ -13,3 +13,8 @@ def cmd_doctor(_args):
print(" Hint: On Linux/macOS you may need to add your user to the dialout/uucp group or adjust permissions.")
except Exception as e:
print(f"[bao] Doctor failed: {e}")
def register(subparsers) -> None:
d = subparsers.add_parser("doctor", help="Check Python environment and ports")
d.set_defaults(func=cmd_doctor)

View file

@ -52,3 +52,18 @@ def cmd_flash(args) -> None:
print(f"[bao] copied {copied} file(s)")
sys.exit(0)
def register(subparsers) -> None:
f = subparsers.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/BOOT/)"
)
f.add_argument(
"files",
nargs="+",
help="One or more UF2 files to copy (e.g., loader.uf2 xous.uf2 apps.uf2)"
)
f.set_defaults(func=cmd_flash)

View file

@ -159,3 +159,24 @@ def cmd_monitor(args) -> None:
except Exception:
pass
safe_close(ser)
def register(subparsers) -> None:
m = subparsers.add_parser("monitor", help="Open a serial monitor")
m.add_argument("-p", "--port", required=True, help="Serial port (e.g., COM5, /dev/ttyUSB0)")
m.add_argument("-b", "--baud", type=int, default=1000000, help="Baud rate")
m.add_argument("--ts", action="store_true", help="Show timestamps on received lines")
m.add_argument("--save", help="Append output to a file")
m.add_argument("--reset", action="store_true", help="Toggle DTR/RTS on open")
m.add_argument("--crlf", action="store_true", help="Use CRLF as TX line ending in line mode (default LF)")
m.add_argument("--raw", action="store_true", help="Send keystrokes immediately (raw byte mode)")
m.add_argument("--no-echo", action="store_true", help="Do not locally echo typed input")
m.add_argument("--rtscts", action="store_true", help="Enable RTS/CTS hardware flow control")
m.add_argument("--xonxoff", action="store_true", help="Enable XON/XOFF software flow control")
m.add_argument("--dsrdtr", action="store_true", help="Enable DSR/DTR hardware flow control")
m.add_argument("--write-timeout", type=float, default=1.0, help="Write timeout in seconds")
m.add_argument("--dtr", type=int, choices=[0,1], help="Initial DTR level (0/1)")
m.add_argument("--rts", type=int, choices=[0,1], help="Initial RTS level (0/1)")
m.add_argument("--no-flush", action="store_true", help="Do not flush buffers on connect")
m.add_argument("--break-ms", type=int, default=0, help="Send BREAK for N milliseconds after opening")
m.set_defaults(func=cmd_monitor)

View file

@ -14,3 +14,8 @@ def cmd_ports(args) -> None:
if p.vid is not None and p.pid is not None:
vidpid = f" (VID:PID={p.vid:04x}:{p.pid:04x})"
print(f"{p.device}\t{p.description}{vidpid}")
def register(subparsers) -> None:
s = subparsers.add_parser("ports", help="List serial ports")
s.set_defaults(func=cmd_ports)

View file

@ -1 +1,2 @@
pyserial>=3.5
pyserial>=3.5
tomlkit>=0.13.3