-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflash.py
More file actions
95 lines (79 loc) · 2.71 KB
/
flash.py
File metadata and controls
95 lines (79 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""根目录 stcgal 烧录包装入口。"""
from __future__ import annotations
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
SUPPORTED_PROTOCOLS = (
"auto",
"stc89",
"stc89a",
"stc12a",
"stc12b",
"stc12",
"stc15a",
"stc15",
"stc8",
"stc8d",
"stc8g",
"usb15",
)
def build_parser() -> argparse.ArgumentParser:
"""构建命令行参数解析器。"""
parser = argparse.ArgumentParser(description="Flash an STC MCU with stcgal.")
parser.add_argument("--port", required=True, help="Serial port, for example COM3.")
parser.add_argument(
"--protocol",
default="auto",
choices=SUPPORTED_PROTOCOLS,
help="Explicit stcgal protocol. Use auto to let stcgal decide.",
)
parser.add_argument("--baud", type=int, default=115200, help="Programming baud rate.")
parser.add_argument("--handshake", type=int, default=2400, help="Handshake baud rate.")
parser.add_argument("--firmware", required=True, help="Firmware path (.ihx/.hex/.bin).")
parser.add_argument("--dry-run", action="store_true", help="Print the stcgal command without executing it.")
return parser
def find_stcgal_command(allow_missing: bool = False) -> list[str]:
"""定位 stcgal 命令或模块入口。"""
executable = shutil.which("stcgal")
if executable:
return [executable]
try:
import stcgal # type: ignore # noqa: F401
except ImportError as exc:
if allow_missing:
return ["stcgal"]
raise SystemExit("stcgal is not installed. Run `pip install -r requirements.txt`.") from exc
return [sys.executable, "-m", "stcgal.frontend"]
def build_stcgal_command(args: argparse.Namespace, allow_missing_tool: bool = False) -> list[str]:
"""把包装参数转换为 stcgal 参数。"""
firmware = Path(args.firmware).resolve()
if not firmware.exists():
raise SystemExit(f"Firmware not found: {firmware}")
command = find_stcgal_command(allow_missing=allow_missing_tool)
if args.protocol != "auto":
command.extend(["-P", args.protocol])
command.extend(
[
"-p",
args.port,
"-b",
str(args.baud),
"-l",
str(args.handshake),
str(firmware),
]
)
return command
def main(argv: list[str] | None = None) -> int:
"""执行烧录包装流程。"""
parser = build_parser()
args = parser.parse_args(argv)
command = build_stcgal_command(args, allow_missing_tool=args.dry_run)
if args.dry_run:
print(" ".join(command))
return 0
return subprocess.call(command)
if __name__ == "__main__":
raise SystemExit(main())