From 85b1eb4363ba78ef67b6aba9f85691f3c19d693b Mon Sep 17 00:00:00 2001 From: Crazypsy92 Date: Tue, 24 Nov 2026 17:12:29 +0800 Subject: [PATCH] Add GUI-H1 functional experiment workbench --- README.md | 4 +- apps/rtos_inspector/main.c | 118 ++++++++ cmake/stage3.cmake | 2 + docs/gui_h1_architecture.md | 9 + docs/gui_h1_capabilities.md | 17 ++ docs/gui_h1_report.md | 21 ++ scripts/accept_gui_h1.py | 17 ++ scripts/stage8_1_install_renode.py | 3 + scripts/vel_dashboard.py | 183 +++++++++++- scripts/vel_gui_features.py | 105 +++++++ scripts/vel_gui_job.py | 139 ++++++++++ scripts/vel_gui_modbus.py | 167 +++++++++++ scripts/vel_gui_results.py | 57 ++++ scripts/vel_gui_workbench.py | 428 +++++++++++++++++++++++++++++ scripts/vel_inspector.py | 50 ++++ tests/gui/test_gui_h1.py | 201 ++++++++++++++ 16 files changed, 1514 insertions(+), 7 deletions(-) create mode 100644 apps/rtos_inspector/main.c create mode 100644 docs/gui_h1_architecture.md create mode 100644 docs/gui_h1_capabilities.md create mode 100644 docs/gui_h1_report.md create mode 100644 scripts/accept_gui_h1.py create mode 100644 scripts/vel_gui_features.py create mode 100644 scripts/vel_gui_job.py create mode 100644 scripts/vel_gui_modbus.py create mode 100644 scripts/vel_gui_results.py create mode 100644 scripts/vel_gui_workbench.py create mode 100644 scripts/vel_inspector.py create mode 100644 tests/gui/test_gui_h1.py diff --git a/README.md b/README.md index c44452c..d48bd83 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,9 @@ python3 scripts/vel.py gateway --mode all python3 scripts/vel.py reliability --mode quick ``` -打开 WSLg 图形窗口可执行 python3 scripts/vel.py dashboard。控制台分为内核、外设、RTOS 和日志页,读取实际仿真输出,并显示采样时间。可启动 Cortex-M3、Zephyr 内核、FreeRTOS、外设和网关验收。停止按钮只停止该窗口启动的任务。 +图形实验入口是 python3 scripts/vel.py dashboard(WSLg + Tkinter)。左侧选择功能;Modbus 默认是 RTU 控制 GPIO。启动会话后,可读 DO、DI 和寄存器,单独设置 DO,再由 FC01 与从站位图确认。CAN 提供 Loopback 测试;未恢复的 micro-ROS 环境显示不可执行。日志页能看本次运行、原始 RTU 字节和从站日志。运行 python3 scripts/vel.py dashboard --advanced 查看寄存器,或加 --live 启动实时 FreeRTOS 监控。 + +验收入口为 python3 scripts/accept_gui_h1.py。更多信息见 [功能范围](docs/gui_h1_capabilities.md) 和 [验收报告](docs/gui_h1_report.md)。没有 WSLg 时可加 --headless 执行注册表和作业生命周期检查。 网关在启动时会显示当前步骤及日志位置。如果此前终端用 Ctrl+Z 挂起了进程,回到原终端运行 jobs -l 和 fg,恢复运行,或恢复后按 Ctrl+C 停止。新版入口收到 Ctrl+Z 时会取消运行并释放工作区锁。 diff --git a/apps/rtos_inspector/main.c b/apps/rtos_inspector/main.c new file mode 100644 index 0000000..6d9c6d5 --- /dev/null +++ b/apps/rtos_inspector/main.c @@ -0,0 +1,118 @@ +#include "vel_runtime.h" +#include "queue.h" +#include "uart.h" + +#define MMIO(address) (*(volatile uint32_t *)(uintptr_t)(address)) +#define UART0 0x40004000UL +#define TIMER0 0x40000000UL +#define MAX_TASKS 8U + +static QueueHandle_t samples; +static TaskHandle_t producer_handle; +static uint32_t produced, consumed, commands; +static TaskStatus_t tasks[MAX_TASKS]; + +static void producer(void *arg) +{ + (void)arg; + for (;;) { + uint32_t next = produced + 1U; + if (xQueueSend(samples, &next, 0) == pdPASS) { + produced = next; + } + vTaskDelay(pdMS_TO_TICKS(140)); + } +} + +static void consumer(void *arg) +{ + (void)arg; + for (;;) { + uint32_t sample; + if (xQueueReceive(samples, &sample, portMAX_DELAY) == pdPASS) { + consumed = sample; + } + vTaskDelay(pdMS_TO_TICKS(240)); + } +} + +static void field(const char *name, uint32_t value) +{ + uart_putc(' '); + uart_puts(name); + uart_putc('='); + uart_u32(value); +} + +static void inspector(void *arg) +{ + (void)arg; + for (;;) { + /* Separate read and write paths for the UART. Reading DATA clears RXFULL. */ + if ((MMIO(UART0 + 4U) & 2U) != 0U) { + uint32_t command = MMIO(UART0); + if (command == 'p') { + vTaskSuspend(producer_handle); + ++commands; + } else if (command == 'r') { + vTaskResume(producer_handle); + ++commands; + } + } + + const UBaseType_t count = uxTaskGetSystemState(tasks, MAX_TASKS, NULL); + REQUIRE(count > 0U); + uart_puts("VEL_BEGIN"); + field("tick", (uint32_t)xTaskGetTickCount()); + field("switches", g_switches); + field("heap", (uint32_t)xPortGetFreeHeapSize()); + field("heap_min", (uint32_t)xPortGetMinimumEverFreeHeapSize()); + field("queue", (uint32_t)uxQueueMessagesWaiting(samples)); + field("produced", produced); + field("consumed", consumed); + field("commands", commands); + field("cpuid", MMIO(0xE000ED00UL)); + field("icsr", MMIO(0xE000ED04UL)); + field("vtor", MMIO(0xE000ED08UL)); + field("systick_load", MMIO(0xE000E014UL)); + field("systick_value", MMIO(0xE000E018UL)); + field("nvic_enabled", MMIO(0xE000E100UL)); + field("nvic_pending", MMIO(0xE000E200UL)); + field("uart_ctrl", MMIO(UART0 + 8U)); + field("uart_state", MMIO(UART0 + 4U)); + field("uart_div", MMIO(UART0 + 0x10U)); + field("timer_ctrl", MMIO(TIMER0)); + field("timer_value", MMIO(TIMER0 + 4U)); + field("timer_reload", MMIO(TIMER0 + 8U)); + field("tasks", (uint32_t)count); + uart_putc('\n'); + for (UBaseType_t i = 0; i < count; ++i) { + const TaskStatus_t *task = &tasks[i]; + uart_puts("VEL_TASK "); + uart_puts(task->pcTaskName); + field("id", (uint32_t)task->xTaskNumber); + field("state", (uint32_t)task->eCurrentState); + field("priority", (uint32_t)task->uxCurrentPriority); + field("stack_words", (uint32_t)task->usStackHighWaterMark); + uart_putc('\n'); + } + uart_puts("VEL_END\n"); + vTaskDelay(pdMS_TO_TICKS(350)); + } +} + +int main(void) +{ + REQUIRE(uart_init()); + MMIO(UART0 + 8U) = 3U; /* TX and RX. */ + MMIO(TIMER0 + 8U) = 25000000U; + MMIO(TIMER0) = 1U; /* Free-running APB Timer 0, no IRQ. */ + samples = xQueueCreate(4, sizeof(uint32_t)); + REQUIRE(samples != NULL); + REQUIRE(xTaskCreate(producer, "Producer", 384, NULL, 1, &producer_handle) == pdPASS); + REQUIRE(xTaskCreate(consumer, "Consumer", 384, NULL, 2, NULL) == pdPASS); + REQUIRE(xTaskCreate(inspector, "Inspector", 512, NULL, 3, NULL) == pdPASS); + vTaskStartScheduler(); + REQUIRE(0); + return 1; +} diff --git a/cmake/stage3.cmake b/cmake/stage3.cmake index bbc7a34..3cf7a42 100644 --- a/cmake/stage3.cmake +++ b/cmake/stage3.cmake @@ -55,3 +55,5 @@ set_tests_properties(arm_memory rtos_vendor PROPERTIES TIMEOUT 15) set_tests_properties(rtos_scheduler rtos_gdb rtos_vendor PROPERTIES LABELS "Stage3_1") set_tests_properties(arm_fatfs arm_fatfs_gdb PROPERTIES LABELS "Stage3_2") set_tests_properties(logger_0 logger_1 logger_2 logger_3 logger_4 logger_5 logger_6 logger_gdb arm_memory PROPERTIES LABELS "Stage3_3") + +vel_arm_firmware(rtos_inspector apps/rtos_inspector/main.c) diff --git a/docs/gui_h1_architecture.md b/docs/gui_h1_architecture.md new file mode 100644 index 0000000..e0b4738 --- /dev/null +++ b/docs/gui_h1_architecture.md @@ -0,0 +1,9 @@ +# GUI-H1 架构 + +默认 dashboard 使用 Tkinter 工作台。--advanced 和 --live 保留原来的寄存器与实时 FreeRTOS 监控。界面以 after 轮询本次会话日志,依赖检查在工作线程完成。注册表定义模式与固定参数,执行前再次校验,用户选择不会拼成 shell 命令。 + +vel_gui_job 持有功能锁,给实验提供独立工作区和证据目录,并保存命令、时刻、会话状态和退出码。它先温和停止所拥有的进程组,再按时限清理由 Linux subreaper 收养的子进程,包括旧测试另建会话的进程。关闭主窗口会等清理完成。高级监控可独立启动;从工作台打开时随主窗口清理。 + +Modbus 主站与 Tk 界面分进程。主站构建现有 Stage 8.2 从站,使用从站实际创建的 PTY,经 pymodbus 发出 FC01/02/03/04/05。读回的 FC01 状态与 IR7 以及 HR3 位图比对后才显示确认。DI 控件单独通过从站 UART0 既有仿真刺激接口改变虚拟输入,再使用 RTU FC02 与 IR6 确认。在 图形界面没有本地 GPIO 镜像。115 秒仿真会话到达上限后自动清理,也可手动停止。 + +每次交互保存 console.log、build.log、slave.log、rtu-wire.jsonl、slave-exit.json 和 result.json。LIVE 仅用于当前会话;历史记录显示时间与会话 ID,未产生数据时显示 N/A。CAN 等测试统计来自其原验收 JSON。 diff --git a/docs/gui_h1_capabilities.md b/docs/gui_h1_capabilities.md new file mode 100644 index 0000000..d4f365c --- /dev/null +++ b/docs/gui_h1_capabilities.md @@ -0,0 +1,17 @@ +# GUI-H1 功能与边界 + +| 功能 | 后端 | GUI 操作 | +| --- | --- | --- | +| Cortex-M3 | QEMU | 运行已构建的固件并检查 UART、SysTick、异常 | +| FreeRTOS | QEMU | CTest 调度、FatFs 和调试。高级窗口另有实时任务监控 | +| Zephyr 内核 | QEMU | 运行已构建的内核样例,显示实际任务和定时器计数 | +| GPIO / EXTI | Renode | 运行现有模拟 GPIO 和外部中断验收 | +| CAN | native_sim | 仅回环测试,显示发送、接收与一致性验证结果 | +| Modbus RTU | native_sim / PTY | 独立会话,单路 DO 控制与回读;DI 仿真刺激;寄存器读取;协议及故障测试 | +| Modbus TCP Gateway | native_sim | 快速故障检查或完整网关验收 | +| FatFs | Host | CTest 块设备及 FatFs 测试 | +| ROS 2 | Host | 已安装发行版的真实话题和服务检查 | +| micro-ROS / 完整历史链 | QEMU / XRCE / 多后端 | UNAVAILABLE,依赖 Lyrical 及未恢复的构建锁 | +| 物理硬件、RS485 电气特性 | — | NOT TESTED | + +GUI 不执行完整历史回归。Modbus 为独立模拟从站,操作不触及真实硬件。CAN 页暂无自定义发送 API。缺少 WSLg 时,仍可运行 CLI 验收和 GUI-H1 的 headless 检查。 diff --git a/docs/gui_h1_report.md b/docs/gui_h1_report.md new file mode 100644 index 0000000..2c6a7b3 --- /dev/null +++ b/docs/gui_h1_report.md @@ -0,0 +1,21 @@ +# GUI-H1 验收 · 2026-11-24 + +基线 4fa470ac3df4b8459fca2dc8eccb13aad70c7ef9。环境为 Bridge-Ubuntu-24.04、WSLg/Tkinter、Zephyr 4.4.2 native_sim、pymodbus 3.11.4。验收显示实际本机行为。Hardware、物理 RS485 和 Ethernet 为 NOT TESTED。 + +| 检查 | 结果 | +| --- | --- | +| python3 scripts/accept_gui_h1.py | 7/7,通过注册表、参数、进程生命周期和真实 WSLg 窗口 | +| python3 scripts/accept_gui_h1.py --headless | 6/6(DISPLAY 和 WAYLAND_DISPLAY 为空) | +| 工作台关闭 | 实际等待 RTU 进程退出。独立验证高级窗口实时 QEMU 随主窗口退出 | +| 旧界面入口 | dashboard --self-test 通过,得到 Cortex-M3 UART 结果 | +| RTU GPIO | DO_0 由 FC05 置 1 后由 FC01 与 IR7 确认为 1,再置 0 并回读为 0。FC02 和 IR6 读回 DI 位图 0101。FC03 与 FC04 均返回 8 个寄存器 | +| 独立注册入口 | CAN、Renode GPIO/EXTI、Host FatFs、Zephyr 内核、ROS 2 依次运行,退出码均为 0 | +| Stage 8.3 Gateway | 7 组通过。6 项运行检查及独立 TCP/RTU 状态比对 | +| Stage 8.2 RTU fault | PASS | +| Stage 8.2 RTU protocol | **FAIL**。1000 笔旧测试出现一次无应答后停止,复跑仍出现于不同请求。延长等待及增加请求间距的诊断尝试也未消除,未保留对旧测试的改动。没有自动重试写入 | +| Stage 0–7 历史全量 133 项 | NOT RUN,现有 Lyrical / micro-ROS 构建依赖未恢复 | +| Stage 8.3.1 独立压力和耐久 | NOT RUN,本轮范围为 GUI-H1 | + +本轮 GUI 验收的原始文件位于 build/workspaces/gui-h1/runs/rtu-odkbvc2f/。rtu-wire.jsonl 包含请求与响应;两条 FC05 命令 PDU 分别以 01050000ff00 和 010500000000 开头。console.log 保存 DO、DI、HR3、IR6、IR7 的前后读回。slave.log 包含实际 GPIO 统计和 INPUT bits=5。result.json 的 CANCELLED 是关闭窗口的预期生命周期结果,与会话中已确认的写入回读分别记录。slave-exit.json 保存从站退出结果。 + +测试索引:build/gui-h1-delivery.log(WSLg),build/gui-h1-final-tests.log(headless 和旧界面),build/gui-entry-urg4iqzr/(独立入口),build/gui-h1-regression/regression-vn4n77vi/(Gateway 和 RTU fault)。RTU protocol 复现日志保存在 build/gui-h1-regression/baseline-final/protocol.log;对应请求/响应在共用回归工作区的 modbus_stage8_2_ws/runs/master-*/wire.json。大日志与构建留在本机 build 目录。 diff --git a/scripts/accept_gui_h1.py b/scripts/accept_gui_h1.py new file mode 100644 index 0000000..fa3564d --- /dev/null +++ b/scripts/accept_gui_h1.py @@ -0,0 +1,17 @@ +"""Use --headless for the CLI subset, or run the real window acceptance.""" +import argparse +import os +import subprocess +import sys + +from vel_env import ROOT, tool_environment + +parser = argparse.ArgumentParser() +parser.add_argument("--headless", action="store_true") +args = parser.parse_args() +command = [sys.executable, ROOT / "tests/gui/test_gui_h1.py"] +if args.headless: + command.extend(["Registry", "Lifecycle"]) +elif not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")): + parser.error("WSLg display unavailable. Use --headless for CLI-only verification.") +raise SystemExit(subprocess.run(command, cwd=ROOT, env=tool_environment(), timeout=210).returncode) diff --git a/scripts/stage8_1_install_renode.py b/scripts/stage8_1_install_renode.py index dcbfc34..93585d8 100644 --- a/scripts/stage8_1_install_renode.py +++ b/scripts/stage8_1_install_renode.py @@ -6,6 +6,9 @@ version,url=pin['version'],pin['url'] archive=WS/('renode-'+version+'.tar.gz');target=WS/'tools/renode'/version WS.mkdir(parents=True,exist_ok=True) +if not archive.exists() and (cached := os.environ.get("VEL_GUI_RENODE_CACHE")): + import shutil + shutil.copyfile(cached,archive) if not archive.exists(): part=archive.with_suffix('.partial');subprocess.run(['curl','-fL','--connect-timeout','15','--max-time','180','--retry','2',url,'-o',str(part)],check=True,timeout=220);part.replace(archive) sha=hashlib.sha256(archive.read_bytes()).hexdigest() diff --git a/scripts/vel_dashboard.py b/scripts/vel_dashboard.py index 2a13ea0..5378dc5 100644 --- a/scripts/vel_dashboard.py +++ b/scripts/vel_dashboard.py @@ -16,6 +16,7 @@ from vel_env import ROOT, tool_environment, work from vel_jobs import lock_status +from vel_inspector import snapshot BG = "#101926" PANEL = "#182538" @@ -124,6 +125,28 @@ def read_sample(name): ) +# Register names follow the MPS2 AN385 models in QEMU 8.2.2. +PERIPHERALS = ( + ("UART0", "0x40004000", "实时采样 / 命令串口", + (("CTRL", "uart_ctrl"), ("STATE", "uart_state"), ("BAUDDIV", "uart_div"))), + ("UART1–4", "0x40005000、0x40006000、0x40007000、0x40009000", "已建模,未采样", ()), + ("APB Timer 0", "0x40000000", "实时采样", + (("CTRL", "timer_ctrl"), ("VALUE", "timer_value"), ("RELOAD", "timer_reload"))), + ("APB Timer 1", "0x40001000", "已建模,未采样", ()), + ("双定时器", "0x40002000", "已建模,未采样", ()), + ("Watchdog", "0x40008000", "已建模,未采样", ()), + ("SPI / PL022", "0x40020000、0x40021000、0x40026000、0x40027000", "已建模,未采样", ()), + ("I²C", "0x40022000、0x40023000、0x40029000、0x4002A000", "已建模,未采样", ()), + ("GPIO 0–3", "0x40010000–0x40013000", "AN385 为占位;虚拟 GPIO 另见历史测试", ()), + ("外接 ADC 接口", "0x40025000", "仅 PL022 控制器,未接 ADC 模型", ()), + ("DMA / I²S", "—", "无可用采样;I²S 为占位", ()), +) +CORE = (("SCB", "CPUID", "cpuid"), ("SCB", "ICSR", "icsr"), ("SCB", "VTOR", "vtor"), + ("SysTick", "LOAD", "systick_load"), ("SysTick", "VAL", "systick_value"), + ("NVIC", "ISER0", "nvic_enabled"), ("NVIC", "ISPR0", "nvic_pending")) +TASK_STATES = {0: "运行", 1: "就绪", 2: "阻塞", 3: "挂起", 4: "删除"} + + class Dashboard: def __init__(self, window): self.window = window @@ -136,6 +159,8 @@ def __init__(self, window): self.stop_at = None self.closing = False self.last_log = None + self.inspector_log = None + self.command_pending = None self.sample_paths = {} self.buttons = [] self.status = tk.StringVar(value="就绪 · 可查看已有采样,或启动一次新测试") @@ -173,9 +198,9 @@ def render(self): style="Muted.TLabel").pack(anchor="w", pady=(4, 12)) bar = ttk.Frame(frame) bar.pack(fill="x", pady=(0, 10)) - for label, action in [("运行 Cortex-M3", "arm"), ("运行 Zephyr 内核", "zephyr"), - ("运行 FreeRTOS", "freertos"), ("运行外设测试", "sensor"), - ("运行网关验收", "gateway")]: + for label, action in [("启动实时监控", "inspector"), ("Cortex-M3 测试", "arm"), + ("Zephyr 测试", "zephyr"), ("FreeRTOS 测试", "freertos"), + ("外设测试", "sensor"), ("网关验收", "gateway")]: button = ttk.Button(bar, text=label, command=lambda name=action: self.start(name)) button.pack(side="left", padx=(0, 5)) self.buttons.append(button) @@ -186,9 +211,10 @@ def render(self): self.tabs = ttk.Notebook(frame) self.tabs.pack(fill="both", expand=True) self.tables = {} + self.render_inspector() for title, sources in VIEWS: view = ttk.Frame(self.tabs, padding=12) - self.tabs.add(view, text=title) + self.tabs.add(view, text=title + " · 历史") ttk.Label(view, text="以下为模拟器输出的最近样本。空值表示该样本未提供此项。", style="Muted.TLabel").pack(anchor="w", pady=(0, 8)) table = ttk.Treeview(view, columns=("module", "name", "value"), show="headings") @@ -220,6 +246,126 @@ def render(self): self.log_box.pack(side="left", fill="both", expand=True) scroll.pack(side="right", fill="y") + def grid_table(self, parent, columns, height=9): + table = ttk.Treeview(parent, columns=[key for key, _, _ in columns], + show="headings", height=height) + for key, title, width in columns: + table.heading(key, text=title) + table.column(key, width=width, anchor="w") + return table + + def render_inspector(self): + core = ttk.Frame(self.tabs, padding=12) + peripherals = ttk.Frame(self.tabs, padding=12) + tasks = ttk.Frame(self.tabs, padding=12) + self.tabs.add(core, text="内核寄存器") + self.tabs.add(peripherals, text="片上外设") + self.tabs.add(tasks, text="RTOS 任务") + self.live_text = tk.StringVar(value="等待实时监控 · QEMU MPS2 AN385") + for view in (core, peripherals, tasks): + ttk.Label(view, textvariable=self.live_text, style="Muted.TLabel").pack(anchor="w", pady=(0, 8)) + self.core_table = self.grid_table(core, (("block", "模块", 150), + ("register", "寄存器", 150), ("value", "值", 210))) + self.core_table.pack(fill="both", expand=True) + for block, label, key in CORE: + self.core_table.insert("", "end", iid=key, values=(block, label, "—")) + self.peripheral_table = self.grid_table(peripherals, (("device", "片上模块", 150), + ("address", "基地址", 400), + ("support", "本目标支持状态", 320)), 11) + self.peripheral_table.pack(fill="both", expand=True) + for name, address, support, _ in PERIPHERALS: + self.peripheral_table.insert("", "end", iid=name, values=(name, address, support)) + self.register_text = tk.StringVar(value="选择外设查看寄存器与当前值") + ttk.Label(peripherals, textvariable=self.register_text, style="Status.TLabel").pack(anchor="w", pady=10) + self.peripheral_table.selection_set("UART0") + self.peripheral_table.bind("<>", lambda _: self.show_peripheral()) + self.live_values = {} + bar = ttk.Frame(tasks) + bar.pack(fill="x", pady=(0, 8)) + self.task_summary = tk.StringVar(value="等待 FreeRTOS 快照") + ttk.Label(bar, textvariable=self.task_summary).pack(side="left") + self.pause_worker = ttk.Button(bar, text="挂起 Producer", command=lambda: self.send_worker(b"p")) + self.resume_worker = ttk.Button(bar, text="恢复 Producer", command=lambda: self.send_worker(b"r")) + for button in (self.resume_worker, self.pause_worker): + button.pack(side="right", padx=3) + button.configure(state="disabled") + self.task_table = self.grid_table(tasks, (("id", "ID", 70), ("task", "任务", 180), + ("state", "调度状态", 120), ("priority", "优先级", 90), + ("stack", "最小栈余量(字)", 180)), 8) + self.task_table.pack(fill="both", expand=True) + ttk.Label(tasks, text="操作仅作用于实时演示固件的 Producer;任务状态由 FreeRTOS 返回。", + style="Muted.TLabel").pack(anchor="w", pady=8) + + def show_peripheral(self): + selected = self.peripheral_table.selection() + if not selected: + return + name, _, support, registers = next(item for item in PERIPHERALS if item[0] == selected[0]) + values = [f"{label} 0x{self.live_values[key]:08X}" if key in self.live_values else f"{label} —" + for label, key in registers] + self.register_text.set(f"{name} " + (" | ".join(values) if values else support)) + + def send_worker(self, command): + if not self.job or self.job_name != "inspector" or self.job.poll() is not None: + return + if not self.live_values or self.command_pending: + return + try: + self.job.stdin.write(command) + self.job.stdin.flush() + self.command_pending = (self.live_values.get("commands", 0), time.monotonic() + 3) + except OSError: + self.status.set("命令发送失败,实时监控已结束。") + + def refresh_inspector(self): + live = bool(self.job and self.job_name == "inspector" and not self.stop_at) + values, tasks = snapshot(tail(self.inspector_log)) if self.inspector_log else ({}, []) + stamp = None + if values and self.inspector_log: + try: + stamp = self.inspector_log.stat().st_mtime + except OSError: + pass + fresh = bool(live and stamp and time.time() - stamp < 2) + if stamp: + when = datetime.fromtimestamp(stamp).strftime("%H:%M:%S") + self.live_text.set(f"QEMU MPS2 AN385 · {'实时采样' if fresh else '最近快照'} · {when}") + elif live: + self.live_text.set("QEMU MPS2 AN385 · 等待构建或首个采样") + self.live_values = values + for _, _, key in CORE: + self.core_table.set(key, "value", f"0x{values[key]:08X}" if key in values else "—") + self.show_peripheral() + if values: + self.task_summary.set(f"Tick {values['tick']} · 切换 {values.get('switches', '—')} · " + f"队列 {values.get('queue', '—')}/4 · 空闲堆 {values.get('heap', '—')} B") + current = set() + producer_state = None + for name, task in sorted(tasks, key=lambda item: item[1]["id"]): + ident = str(task["id"]) + current.add(ident) + if name == "Producer": + producer_state = task["state"] + row = (ident, name, TASK_STATES.get(task["state"], "未知"), task["priority"], task["stack_words"]) + if self.task_table.exists(ident): + self.task_table.item(ident, values=row) + else: + self.task_table.insert("", "end", iid=ident, values=row) + for ident in set(self.task_table.get_children()) - current: + self.task_table.delete(ident) + if self.command_pending: + before, until = self.command_pending + if values.get("commands", 0) > before: + self.status.set("实时监控运行中 · 已收到固件确认") + self.command_pending = None + elif time.monotonic() > until or not live: + self.command_pending = None + if live: + self.status.set("实时监控运行中 · 等待固件确认超时") + ready = fresh and not self.command_pending and producer_state is not None + self.pause_worker.configure(state="normal" if ready and producer_state != 3 else "disabled") + self.resume_worker.configure(state="normal" if ready and producer_state == 3 else "disabled") + def start(self, action): if self.job is not None: return @@ -234,7 +380,9 @@ def start(self, action): "zephyr":"build/zephyr/kernel/zephyr/zephyr.elf", "sensor":"build/zephyr/sensor/zephyr/zephyr.elf"}.get(action, "build")) command = [sys.executable, ROOT / "scripts/vel.py", action] - if action == "gateway": + if action == "inspector": + command = [sys.executable, ROOT / "scripts/vel_inspector.py"] + elif action == "gateway": busy, owner = lock_status(work("gateway_stage8_3_ws") / "accept.lock") if busy: self.status.set("网关已有任务,请在原终端检查 jobs -l 或等待结束。") @@ -255,11 +403,16 @@ def start(self, action): self.status.set(f"固件还未构建。请先在终端运行 python3 scripts/vel.py {target}。") return self.log = path + if action == "inspector": + self.inspector_log = path + self.command_pending = None + self.tabs.select(2) self.log_choice.set("本次任务") self.job_name = action try: with path.open("w") as output: self.job = subprocess.Popen(command, cwd=ROOT, env=env, stdout=output, + stdin=subprocess.PIPE if action == "inspector" else None, stderr=subprocess.STDOUT, start_new_session=True) except OSError as error: self.status.set(str(error)) @@ -273,7 +426,13 @@ def start(self, action): def cancel(self): if self.job and self.job.poll() is None and self.stop_at is None: self.status.set("正在停止并清理本次任务…") - self.job.terminate() + try: + if self.job_name == "inspector": + os.killpg(self.job.pid, signal.SIGTERM) + else: + self.job.terminate() + except ProcessLookupError: + pass self.stop_at = time.monotonic() + 18 self.stop_button.configure(state="disabled") @@ -295,6 +454,8 @@ def refresh(self): elif rc is not None: result = "已停止" if self.stop_at else ("通过" if rc == 0 else f"失败 · 退出码 {rc}") self.status.set(f"{self.job_name} · {result} · 日志见「日志」页") + if self.job.stdin: + self.job.stdin.close() self.job = None self.stop_button.configure(state="disabled") for button in self.buttons: @@ -302,6 +463,7 @@ def refresh(self): if self.closing and self.job is None: self.window.destroy() return + self.refresh_inspector() busy, owner = lock_status(work("gateway_stage8_3_ws") / "accept.lock") self.lock_text.set(f"网关工作区 · {'运行中,PID '+str(owner.get('pid', '未知')) if busy else '空闲'}") for table, sources in self.tables.items(): @@ -339,13 +501,22 @@ def refresh(self): def main(): parser = argparse.ArgumentParser() + parser.add_argument("--advanced", action="store_true", help="open the register and RTOS monitor") + parser.add_argument("--live", action="store_true", help="start the live firmware on launch") parser.add_argument("--self-test", action="store_true", help="initialize and exercise the WSLg window") args = parser.parse_args() try: root = tk.Tk() except tk.TclError as error: raise SystemExit(f"无法打开窗口,请确认当前 WSL 已启用 WSLg。{error}") + if not (args.live or args.advanced or args.self_test): + from vel_gui_workbench import Workbench + Workbench(root, advanced=lambda window: Dashboard(window)) + root.mainloop() + return 0 app = Dashboard(root) + if args.live and not args.self_test: + root.after_idle(lambda: app.start("inspector")) if args.self_test: app.start("arm") deadline = time.monotonic() + 20 diff --git a/scripts/vel_gui_features.py b/scripts/vel_gui_features.py new file mode 100644 index 0000000..134b7b1 --- /dev/null +++ b/scripts/vel_gui_features.py @@ -0,0 +1,105 @@ +"""Fixed allowlist for the GUI. No user text enters a shell or a command path.""" +from dataclasses import dataclass +import subprocess +import sys + +from vel_env import ROOT, ros_setup, tool, tool_environment, work, zephyr_base + + +@dataclass(frozen=True) +class Feature: + id: str + title: str + category: str + backend: str + description: str + modes: dict + dependencies: tuple = () + evidence: str = "退出码与原始日志" + unavailable: str = "" + + +FEATURES = ( + Feature("arm", "Cortex-M3", "MCU / RTOS", "QEMU", "检查 UART、SysTick 和异常入口。", + {"单项实验": ("run_qemu.py",)}, ("qemu-system-arm", "arm ELF")), + Feature("freertos", "FreeRTOS", "MCU / RTOS", "QEMU", "构建并运行调度、FatFs 和调试测试。", + {"单项实验": ("vel.py", "freertos")}, ("arm-none-eabi-gcc", "cmake", "ninja", "qemu-system-arm", "gdb-multiarch")), + Feature("zephyr", "Zephyr 内核", "MCU / RTOS", "QEMU", "检查调度、定时器、工作队列和栈。", + {"单项实验": ("stage4_case.py", "kernel")}, ("qemu-system-arm", "Zephyr ELF")), + Feature("gpio", "GPIO / EXTI", "GPIO / EXTI", "Renode", "运行 STM32F103 模拟 GPIO、外部中断和 UART 检查。", + {"单项实验": ("accept_stage8_1.py", "--backend", "renode")}, ("arm-none-eabi-gcc", "gdb-multiarch", "Renode cache")), + Feature("can", "CAN Loopback", "CAN", "Zephyr native_sim", "测试模式:回环发送、接收与帧一致性验证。包含 GPIO 和 UART 检查。", + {"单项实验": ("accept_stage8_1.py", "--backend", "native_sim")}, ("Zephyr",)), + Feature("rtu", "Modbus RTU · 控制 GPIO", "Modbus", "Zephyr native_sim / PTY", + "读取 DO、DI 和寄存器。用 FC05 控制单路 DO,并用 FC01 和 GPIO 位图复核。", + {"交互会话": ("vel_gui_modbus.py",), + "快速测试": ("accept_stage8_2.py", "--mode", "fault"), + "协议与压力": ("accept_stage8_2.py", "--mode", "protocol")}, + ("Zephyr", "Modbus Python"), "FC01 / FC02 / FC03 / FC04 / FC05 与 PTY 字节记录"), + Feature("gateway", "Modbus TCP Gateway", "Modbus", "Zephyr native_sim / TCP", + "现有网关测试,包含实验所选范围的从站和网关构建。", + {"快速测试": ("accept_stage8_3.py", "--mode", "fault"), + "完整网关验收(约 2 分钟)": ("accept_stage8_3.py", "--mode", "all")}, + ("Zephyr", "Modbus Python")), + Feature("fatfs", "FatFs 虚拟存储", "FatFs", "Host / CTest", "运行主机及 FatFs 测试,无需挂载实体磁盘。", + {"单项实验": ("vel.py", "host")}, ("cmake", "ninja", "gcc")), + Feature("ros", "ROS 2", "ROS 2 / micro-ROS", "Host ROS 2", "运行已安装 ROS 2 的话题与服务示例。", + {"单项实验": ("stage5_ros_basic.py",)}, ("ROS 2 demos",)), + Feature("micro", "micro-ROS", "ROS 2 / micro-ROS", "QEMU / XRCE", + "原 Stage 6/7 需要匹配的 Lyrical 环境和依赖锁。", {}, + unavailable="当前入口需要恢复并核验原依赖,未启用。"), + Feature("reliability", "网关可靠性", "自动化验收", "native_sim", "运行同 TID、延迟 RTU、TCP 字节流与恢复。", + {"快速测试(约 2 分钟)": ("accept_stage8_3_1.py", "--mode", "quick")}, + ("Zephyr", "Modbus Python")), + Feature("history", "Stage 0–7 历史回归", "自动化验收", "多后端", + "完整历史回归需有原依赖与基线。", {}, unavailable="本机 micro-ROS 依赖未恢复。"), +) + +BY_ID = {feature.id: feature for feature in FEATURES} +CATEGORIES = ("系统概览", "MCU / RTOS", "GPIO / EXTI", "CAN", "Modbus", "FatFs", + "ROS 2 / micro-ROS", "自动化验收", "日志与高级信息") + + +def capabilities(dependencies=None): + env = tool_environment() + def probe(command): + try: + return subprocess.run(command, env=env, timeout=7, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL).returncode == 0 + except (OSError, subprocess.TimeoutExpired): + return False + arm = ROOT / "build/arm/cortex_m3_demo.elf" + zephyr = ROOT / "build/zephyr/kernel/zephyr/zephyr.elf" + ros = False + try: + if dependencies is not None and "ROS 2 demos" not in dependencies: + raise SystemExit + setup = ros_setup() + ros = probe(["bash", "-c", 'source "$1" && ros2 pkg prefix demo_nodes_cpp && ros2 pkg prefix demo_nodes_py', + "gui-ros", setup]) + except SystemExit: + pass + commands = {name: tool(name) != name for name in + ("qemu-system-arm", "arm-none-eabi-gcc", "cmake", "ninja", "gdb-multiarch", "gcc")} + return {**commands, "arm ELF": arm.is_file(), "Zephyr ELF": zephyr.is_file(), + "Zephyr": (zephyr_base() / "VERSION").is_file() and tool("dtc") != "dtc" + and commands["cmake"] and commands["ninja"] + and probe([sys.executable, "-c", "import west, yaml, pykwalify, elftools"]), + "Modbus Python": probe([sys.executable, "-c", "import pymodbus, serial"]), + "ROS 2 demos": ros, + "Renode cache": (work("simulation_stage8_1_ws") / "renode-1.17.0.tar.gz").is_file()} + + +def invocation(feature, mode, folder, available): + item = BY_ID.get(feature) + if item is None or not isinstance(mode, str) or mode not in item.modes: + raise ValueError("Unknown feature or mode.") + if missing := [dep for dep in item.dependencies if not available.get(dep)]: + raise ValueError("Missing dependencies: " + ", ".join(missing)) + script, *args = item.modes[mode] + path = ROOT / "scripts" / script + if not path.is_file(): + raise ValueError(f"Missing entrypoint: {script}") + if script == "vel_gui_modbus.py": + args.append(str(folder)) + return [sys.executable, str(path), *args] diff --git a/scripts/vel_gui_job.py b/scripts/vel_gui_job.py new file mode 100644 index 0000000..c977eb5 --- /dev/null +++ b/scripts/vel_gui_job.py @@ -0,0 +1,139 @@ +"""Linux supervisor for one GUI job, including legacy nested process groups.""" +import argparse +import ctypes +import json +import os +from pathlib import Path +import signal +import subprocess +import time + +from vel_env import ROOT, tool_environment, work +from vel_gui_features import BY_ID, capabilities, invocation +from vel_jobs import BusyWorkspace, workspace_lock + +EVIDENCE = ("VEL_STAGE1_EVIDENCE", "VEL_STAGE3_EVIDENCE", "VEL_STAGE4_EVIDENCE", + "VEL_STAGE5_EVIDENCE", "VEL_STAGE8_1_EVIDENCE", "VEL_STAGE8_2_EVIDENCE", + "VEL_STAGE8_3_EVIDENCE", "VEL_STAGE8_3_1_EVIDENCE") + + +def children(pid): + try: + return [int(item) for item in Path(f"/proc/{pid}/task/{pid}/children").read_text().split()] + except (FileNotFoundError, ProcessLookupError): + return [] + + +def send(pid, sig): + try: + descriptor = os.pidfd_open(pid) + except ProcessLookupError: + return + try: + signal.pidfd_send_signal(descriptor, sig) + except ProcessLookupError: + pass + finally: + os.close(descriptor) + + +def clean_children(): + # Orphans from helpers using start_new_session reparent to this subreaper. + deadline = time.monotonic() + 6 + while owned := children(os.getpid()): + sig = signal.SIGTERM if time.monotonic() < deadline - 3 else signal.SIGKILL + for pid in owned: + send(pid, sig) + try: + while os.waitpid(-1, os.WNOHANG)[0]: + pass + except ChildProcessError: + return + if time.monotonic() >= deadline: + raise RuntimeError("Owned process cleanup exceeded deadline") + time.sleep(.05) + + +def run(args, resolve=invocation): + result = {"id": args.feature, "mode": args.mode, "started": time.time(), "status": "FAIL"} + cancelled = False + def request_stop(*_): + nonlocal cancelled + cancelled = True + + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGTSTP): + signal.signal(sig, request_stop) + try: + if ctypes.CDLL(None, use_errno=True).prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER + raise OSError(ctypes.get_errno(), "Cannot enable owned process cleanup") + argv = resolve(args.feature, args.mode, args.folder, capabilities(BY_ID[args.feature].dependencies)) + result["command"] = argv + env = tool_environment() + env["PYTHONUNBUFFERED"] = "1" + # Legacy shared work directories become private to this job. + env["VEL_WORK_ROOT"] = str(args.folder / "work") + for key in EVIDENCE: + env[key] = str(args.folder / key[4:].lower()) + if args.feature == "gpio": + env["VEL_GUI_RENODE_CACHE"] = str(work("simulation_stage8_1_ws") / "renode-1.17.0.tar.gz") + lockdir = work("gui-h1/locks") + lockdir.mkdir(parents=True, exist_ok=True) + resource = {"arm": "arm", "zephyr": "zephyr", "fatfs": "host"}.get(args.feature, args.feature) + with workspace_lock(lockdir / (resource + ".lock")): + if cancelled: + result.update(status="CANCELLED", exit=130) + return 130 + proc = subprocess.Popen(argv, cwd=ROOT, env=env, start_new_session=True) + result["pid"] = proc.pid + deadline = time.monotonic() + args.timeout + try: + while proc.poll() is None and not cancelled and time.monotonic() < deadline: + time.sleep(.08) + if proc.poll() is None: + timed_out = not cancelled + result.update(status="TIMEOUT" if timed_out else "CANCELLED", + exit=124 if timed_out else 130) + elif cancelled: + result.update(status="CANCELLED", exit=130) + else: + outcome = "COMPLETED" if args.mode == "交互会话" else "PASS" + result.update(status=outcome if proc.returncode == 0 else "FAIL", exit=proc.returncode) + finally: + if proc.poll() is None: + try: + os.killpg(proc.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + proc.wait(4) + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.wait(3) + clean_children() + result["child_exit"] = proc.returncode + return result["exit"] + except (ValueError, BusyWorkspace, OSError, RuntimeError) as error: + result.update(status="UNAVAILABLE" if isinstance(error, ValueError) else + "BUSY" if isinstance(error, BusyWorkspace) else "FAIL", + exit=75 if isinstance(error, BusyWorkspace) else 2, reason=str(error)) + print(str(error), flush=True) + return result["exit"] + finally: + result["finished"] = time.time() + (args.folder / "result.json").write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("feature", choices=BY_ID) + parser.add_argument("mode") + parser.add_argument("folder", type=Path) + parser.add_argument("--timeout", type=float, choices=range(1, 901), default=480) + return run(parser.parse_args()) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/vel_gui_modbus.py b/scripts/vel_gui_modbus.py new file mode 100644 index 0000000..07b9dd8 --- /dev/null +++ b/scripts/vel_gui_modbus.py @@ -0,0 +1,167 @@ +"""Independent interactive RTU master. JSON commands in, readback events out.""" +import argparse +import json +import os +from pathlib import Path +import re +import select +import subprocess +import sys +import time +import tty + +from pymodbus.client import ModbusSerialClient + +from vel_env import ROOT, native_build +from vel_jobs import install_cancel_handlers + +APP = ROOT / "zephyr/apps/modbus_rtu_slave" + + +def event(kind, **fields): + print(json.dumps({"event": kind, "time": time.time(), **fields}), flush=True) + + +def validate(request): + if not isinstance(request, dict): + raise ValueError("Expected an operation object.") + op = request.get("op") + if op == "read" and set(request) == {"op"}: + return op + if (op == "write" and set(request) == {"op", "index", "value"} + and type(request["index"]) is int and 0 <= request["index"] < 8 + and type(request["value"]) is bool): + return op + if (op == "input" and set(request) == {"op", "mask"} + and type(request["mask"]) is int and 0 <= request["mask"] < 16): + return op + raise ValueError("Unsupported or invalid GPIO operation.") + + +def wait_for_slave(process, path): + deadline = time.monotonic() + 12 + while time.monotonic() < deadline: + log = path.read_text(errors="replace") + if "MODBUS_INIT rc=0" in log: + paths = re.findall(r"/dev/pts/\d+", log) + if len(paths) >= 2: + return paths[:2] + if process.poll() is not None: + raise RuntimeError(f"Slave exited with {process.returncode}: {path}") + time.sleep(.05) + raise TimeoutError(f"Slave startup timed out: {path}") + + +def commands(process): + pending = b"" + while process.poll() is None: + if not select.select([sys.stdin], [], [], .25)[0]: + continue + data = os.read(sys.stdin.fileno(), 4096) + if not data: + return + pending += data + while b"\n" in pending: + line, pending = pending.split(b"\n", 1) + yield line + if len(pending) > 4096: + raise ValueError("Command exceeds input limit.") + + +def session(folder): + # The interactive slave never shares an executable or a PTY with CLI acceptance. + build = folder / "slave-build" + with (folder / "build.log").open("w") as log: + native_build(APP, build, log=log) + slave_log = folder / "slave.log" + argv = [build / "zephyr/zephyr.exe", "-rt", "-stop_at=115"] + event("step", phase="slave", command=list(map(str, argv))) + with slave_log.open("w") as log, (folder / "rtu-wire.jsonl").open("w") as wire: + process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) + client = None + control = None + try: + ctl, serial_port = wait_for_slave(process, slave_log) + control = os.open(ctl, os.O_RDWR | os.O_NOCTTY) + tty.setraw(control) + + def trace(sending, data): + wire.write(json.dumps({"time": time.time(), "direction": "tx" if sending else "rx", + "hex": data.hex()}) + "\n") + wire.flush() + return data + + client = ModbusSerialClient(serial_port, baudrate=115200, parity="N", + timeout=.6, retries=0, trace_packet=trace) + if not client.connect(): + raise RuntimeError("Cannot open RTU slave PTY.") + + def call(method, *args, **kwargs): + # Native PTY turnaround is scheduled on simulator ticks. + time.sleep(.02) + result = getattr(client, method)(*args, device_id=1, **kwargs) + if result.isError(): + raise RuntimeError(f"{method}: {result}") + return result + + def readback(): + coils = call("read_coils", 0, count=8).bits[:8] + inputs = call("read_discrete_inputs", 0, count=4).bits[:4] + holding = call("read_holding_registers", 0, count=8).registers + registers = call("read_input_registers", 0, count=8).registers + do_mask = sum(1 << i for i, state in enumerate(coils) if state) + if registers[7] != do_mask or holding[3] != do_mask: + raise RuntimeError("FC01 and the slave GPIO output bitmap disagree.") + return dict(coils=coils, inputs=inputs, holding=holding, registers=registers) + + event("ready", **readback()) + for line in commands(process): + try: + req = json.loads(line) + op = validate(req) + if op == "write": + call("write_coil", req["index"], req["value"]) + elif op == "input": + offset = slave_log.stat().st_size + os.write(control, bytes([65 + req["mask"]])) + until = time.monotonic() + 1 + with slave_log.open() as monitor: + monitor.seek(offset) + expected = f"INPUT bits={req['mask']}" + while not any(line.strip() == expected for line in monitor): + if time.monotonic() >= until: + raise RuntimeError("Slave did not acknowledge DI stimulus.") + time.sleep(.02) + data = readback() + if op == "write" and data["coils"][req["index"]] != req["value"]: + raise RuntimeError("FC01 readback did not confirm FC05.") + if op == "input" and data["registers"][6] != req["mask"]: + raise RuntimeError("FC02/IR6 did not confirm the input stimulus.") + event("result", request=req, **data) + except (ValueError, OSError, RuntimeError) as error: + event("operation_error", reason=str(error)) + finally: + if client: + client.close() + if control is not None: + os.close(control) + if process.poll() is None: + process.terminate() + try: + process.wait(3) + except subprocess.TimeoutExpired: + process.kill() + process.wait(3) + (folder / "slave-exit.json").write_text(json.dumps({"pid": process.pid, "exit": process.returncode})) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("folder", type=Path) + args = parser.parse_args() + install_cancel_handlers() + try: + session(args.folder) + except Exception as error: + event("session_error", reason=str(error)) + sys.exit(1) diff --git a/scripts/vel_gui_results.py b/scripts/vel_gui_results.py new file mode 100644 index 0000000..962ab5a --- /dev/null +++ b/scripts/vel_gui_results.py @@ -0,0 +1,57 @@ +"""Summarize specific measured fields. A job's supervisor supplies its outcome.""" +import json +import re + + +def json_report(path): + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + return {} + + +def output_summary(feature, folder): + if feature in ("gpio", "can"): + backend = "renode" if feature == "gpio" else "native_sim" + result = json_report(folder / "stage8_1_evidence" / backend / "acceptance.json") + keys = (("中断边沿", "exti_edges"), ("UART 帧", "uart_frames")) if feature == "gpio" else ( + ("CAN 发送", "can_sent"), ("CAN 接收", "can_received"), + ("GPIO 翻转", "gpio_toggles"), ("输入边沿", "input_edges")) + if result.get("status") != "PASS": + return "N/A · 缺少完成后的测量" + return " · ".join(f"{title} {result.get(key, 'N/A')}" for title, key in keys) + if feature == "gateway": + r = folder / "stage8_3_evidence" + groups = json_report(r/"tests_all.json") + if not groups: + groups = json_report(r/"tests_fault.json") + cross = json_report(r/"rtu/consistency.json") + return f"网关测试组 {groups.get('tests', 'N/A')} · 独立状态比对 {cross.get('status', 'N/A')}" + if feature == "reliability": + files = sorted((folder/"work/gateway_stage8_3_1_ws").glob("accept-*/acceptance.json")) + steps = json_report(files[-1]).get("steps", {}) if files else {} + return " · ".join(f"{name} exit={data.get('exit', 'N/A')}" for name, data in steps.items()) or "N/A" + path = folder / "console.log" + if not path.is_file(): + return "N/A" + text = path.read_text(errors="replace") + if feature in ("freertos", "fatfs"): + match = re.search(r"(\d+)% tests passed, (\d+) tests failed out of (\d+)", text) + if match: + return f"CTest {int(match[3])-int(match[2])}/{match[3]}" + if feature == "arm": + values = re.findall(r"\[TICK\] (?:first|final)=(\d+)", text) + if len(values) == 2: + return f"SysTick {values[0]} → {values[1]}" + if feature == "zephyr": + log = folder / "stage4_evidence/stage4_1/kernel.log" + stats = dict(re.findall(r"\[STAT\] (\w+)=(\d+)", log.read_text())) if log.is_file() else {} + if stats: + return f"任务 A/B {stats.get('worker_a', 'N/A')}/{stats.get('worker_b', 'N/A')} · 定时器 {stats.get('timer', 'N/A')}" + if feature == "ros": + result = json_report(folder / "stage5_evidence/stage5_0/runtime_gate.json") + if result: + return f"消息 {result.get('listener_received', 'N/A')} · 服务结果 {result.get('service_sum', 'N/A')}" + return "详情见日志" + + diff --git a/scripts/vel_gui_workbench.py b/scripts/vel_gui_workbench.py new file mode 100644 index 0000000..dbdc6aa --- /dev/null +++ b/scripts/vel_gui_workbench.py @@ -0,0 +1,428 @@ +"""Tk workbench for the allowlisted embedded experiments.""" +from datetime import datetime +import json +import queue +import signal +import subprocess +import sys +import tempfile +import threading +import time +import tkinter as tk +from tkinter import ttk + +from vel_env import ROOT, tool_environment, work +from vel_gui_features import BY_ID, CATEGORIES, FEATURES, capabilities, invocation +from vel_gui_results import output_summary + +STATES = {"PASS": "通过", "COMPLETED": "会话结束", "FAIL": "失败", "CANCELLED": "已取消", "TIMEOUT": "超时", + "BUSY": "工作区占用", "UNAVAILABLE": "依赖不可用"} + + +def report(path): + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + return {} + + +class Workbench: + def __init__(self, window, advanced=None): + self.window = window + self.advanced = advanced + self.detail_window = None + self.detail_dashboard = None + self.last_error = None + self.window.title("VirtualEmbeddedLab · 仿真实验工作台") + self.window.geometry("1080x720") + self.window.minsize(900, 600) + self.window.protocol("WM_DELETE_WINDOW", self.close) + self.runs = work("gui-h1/runs") + self.runs.mkdir(parents=True, exist_ok=True) + self.feature = None + self.job = self.folder = self.running_feature = None + self.available = None + self.closing = False + self.live = False + self.pending = False + self.offset = 0 + self.partial = "" + self.inbox = queue.SimpleQueue() + self.category = tk.StringVar(value=CATEGORIES[0]) + self.mode = tk.StringVar() + self.choice = tk.StringVar() + self.status = tk.StringVar(value="正在检查后端依赖…") + self.history = tk.StringVar() + self.measurement = tk.StringVar() + self.history_folder = None + self.details = tk.StringVar() + self.state = tk.StringVar(value="未运行") + self.output = tk.StringVar(value="DO_0") + self.input_mask = tk.StringVar(value="0") + self.tail_key = None + self.log_source = tk.StringVar(value="console.log") + self.render() + self.select(CATEGORIES[0]) + threading.Thread(target=self.check_dependencies, daemon=True).start() + self.window.after(120, self.refresh) + + def check_dependencies(self): + try: + self.inbox.put(capabilities()) + except Exception as error: + self.inbox.put(error) + + def render(self): + self.window.configure(background="#132334") + banner = tk.Frame(self.window, bg="#132334", padx=18, pady=12) + banner.pack(fill="x") + tk.Label(banner, text="VirtualEmbeddedLab", bg="#132334", fg="white", + font=("Sans", 20, "bold")).pack(side="left") + tk.Label(banner, text="实验工作台", bg="#132334", fg="#80d9ca", + font=("Sans", 12)).pack(side="right") + body = ttk.Frame(self.window, padding=12) + body.pack(fill="both", expand=True) + nav = ttk.Frame(body, padding=(0, 0, 12, 0)) + nav.pack(side="left", fill="y") + for name in CATEGORIES: + ttk.Radiobutton(nav, text=name, variable=self.category, value=name, + command=lambda name=name: self.select(name)).pack(fill="x", pady=5) + self.right = ttk.Frame(body) + self.right.pack(side="right", fill="both", expand=True) + toolbar = ttk.Frame(self.right) + toolbar.pack(fill="x") + self.title = ttk.Label(toolbar, font=("Sans", 16, "bold")) + self.title.pack(side="left") + self.stop = ttk.Button(toolbar, text="停止当前任务", command=self.cancel, state="disabled") + self.stop.pack(side="right") + ttk.Label(self.right, textvariable=self.status, wraplength=650).pack(anchor="w", pady=5) + self.content = ttk.Frame(self.right) + self.content.pack(fill="both", expand=True) + + def select(self, category): + self.category.set(category) + for widget in self.content.winfo_children(): + widget.destroy() + self.feature = None + self.start_button = None + self.ops = [] + self.table = None + self.log_box = None + self.tail_key = None + self.title.configure(text=category) + if category == CATEGORIES[0]: + ttk.Label(self.content, text="选择实验,运行并查看本次结果。", font=("Sans", 13)).pack(anchor="w", pady=10) + self.overview = ttk.Label(self.content, text="正在检查可用后端…", wraplength=650) + self.overview.pack(anchor="w", pady=8) + for name in ("Modbus", "MCU / RTOS", "CAN", "FatFs"): + ttk.Button(self.content, text=name, command=lambda n=name: self.select(n)).pack(anchor="w", pady=4) + self.update_overview() + return + if category == CATEGORIES[-1]: + self.render_logs() + return + entries = [x for x in FEATURES if x.category == category] + self.choice.set(entries[0].title) + combo = ttk.Combobox(self.content, textvariable=self.choice, state="readonly", + values=[x.title for x in entries], width=43) + combo.pack(anchor="w", pady=(5, 8)) + combo.bind("<>", lambda _: self.render_feature( + next(x for x in entries if x.title == self.choice.get()))) + self.panel = ttk.Frame(self.content) + self.panel.pack(fill="both", expand=True) + self.render_feature(entries[0]) + + def update_overview(self): + if self.available is None or self.category.get() != CATEGORIES[0]: + return + backends = ("qemu-system-arm", "Zephyr", "Renode cache", "ROS 2 demos") + text = " · ".join(f"{n}: {'可用' if self.available.get(n) else 'UNAVAILABLE'}" for n in backends) + latest = next(iter(sorted(self.runs.glob("*/result.json"), key=lambda p: p.stat().st_mtime, + reverse=True)), None) + if latest: + data = report(latest) + name = BY_ID.get(data.get("id")) + text += f"\n最近实验:{name.title if name else '—'} · {data.get('status', 'N/A')}" + self.overview.configure(text=text + "\n物理硬件、RS485 电气特性:NOT TESTED") + + def render_feature(self, feature): + self.feature = feature + for widget in self.panel.winfo_children(): + widget.destroy() + self.ops = [] + self.table = None + ttk.Label(self.panel, text=feature.description, wraplength=650).pack(anchor="w") + ttk.Label(self.panel, text=f"后端:{feature.backend} · 结果:{feature.evidence}", + wraplength=650).pack(anchor="w", pady=4) + ttk.Label(self.panel, textvariable=self.details, wraplength=650).pack(anchor="w") + bar = ttk.Frame(self.panel) + bar.pack(fill="x", pady=7) + modes = tuple(feature.modes) + self.mode.set(modes[0] if modes else "不可执行") + mode = ttk.Combobox(bar, textvariable=self.mode, values=modes, state="readonly", width=33) + mode.pack(side="left") + self.start_button = ttk.Button(bar, text="启动实验", command=self.start) + self.start_button.pack(side="left", padx=7) + ttk.Label(bar, textvariable=self.state).pack(side="left", padx=5) + ttk.Label(self.panel, textvariable=self.history, wraplength=650).pack(anchor="w") + ttk.Label(self.panel, textvariable=self.measurement, wraplength=650).pack(anchor="w", pady=(0, 3)) + if feature.id == "rtu": + self.render_modbus(self.panel) + if self.live and self.running_feature == "rtu" and hasattr(self, "last_snapshot"): + self.present(self.last_snapshot) + self.update_controls() + + def render_modbus(self, parent): + row = ttk.Frame(parent) + row.pack(fill="x", pady=4) + ttk.Combobox(row, textvariable=self.output, values=[f"DO_{i}" for i in range(8)], + state="readonly", width=8).pack(side="left") + buttons = [ + ("置 1", lambda: self.write_output(True)), + ("置 0", lambda: self.write_output(False)), + ("读取状态", lambda: self.send({"op": "read"})), + ] + for label, callback in buttons: + widget = ttk.Button(row, text=label, command=callback) + widget.pack(side="left", padx=3) + self.ops.append(widget) + ttk.Combobox(row, textvariable=self.input_mask, values=list(range(16)), state="readonly", + width=4).pack(side="left", padx=(8, 3)) + widget = ttk.Button(row, text="注入 DI 位图", command=self.inject_input) + widget.pack(side="left") + self.ops.append(widget) + self.table = ttk.Treeview(parent, columns=("name", "value", "source"), show="headings", height=6) + for key, title, width in [("name", "功能", 135), ("value", "读回值", 255), ("source", "实际来源", 195)]: + self.table.heading(key, text=title) + self.table.column(key, width=width, anchor="w") + self.table.pack(fill="both", expand=True, pady=4) + for key, name, origin in [("coils", "DO_0 … DO_7", "FC01 · 从站 GPIO 输出"), + ("inputs", "DI_0 … DI_3", "FC02 · 从站 GPIO 输入"), + ("holding", "Holding 0–7", "FC03"), + ("registers", "Input 0–7", "FC04 · IR6/7 为 DI/DO 位图")]: + self.table.insert("", "end", iid=key, values=(name, "N/A", origin)) + ttk.Label(parent, text="交互会话使用独立从站。启动后约 115 秒后自动结束,或可手动停止。", + wraplength=640).pack(anchor="w") + + def render_logs(self): + bar = ttk.Frame(self.content) + bar.pack(fill="x", pady=6) + ttk.Button(bar, text="复制日志", command=self.copy_log).pack(side="left") + if self.history_folder and not self.job: + ttk.Button(bar, text="载入最近历史", command=self.load_history_log).pack(side="left", padx=4) + ttk.Combobox(bar, textvariable=self.log_source, state="readonly", width=18, + values=("console.log", "rtu-wire.jsonl", "slave.log", "build.log", "result.json")).pack(side="left", padx=5) + if self.advanced: + ttk.Button(bar, text="打开寄存器与实时 RTOS 监控", command=self.open_advanced).pack(side="left", padx=5) + self.log_path = ttk.Label(self.content, wraplength=650) + self.log_path.pack(anchor="w") + row = ttk.Frame(self.content) + row.pack(fill="both", expand=True) + self.log_box = tk.Text(row, wrap="word", font=("Monospace", 10), state="disabled") + y = ttk.Scrollbar(row, command=self.log_box.yview) + self.log_box.configure(yscrollcommand=y.set) + self.log_box.pack(side="left", fill="both", expand=True) + y.pack(side="right", fill="y") + + def open_advanced(self): + if self.detail_window and self.detail_window.winfo_exists(): + self.detail_window.lift() + return + self.detail_window = tk.Toplevel(self.window) + self.detail_dashboard = self.advanced(self.detail_window) + + def load_history_log(self): + if not self.job and self.history_folder: + self.folder = self.history_folder + self.tail_key = None + + def copy_log(self): + if self.folder: + self.window.clipboard_clear() + path = self.folder / self.log_source.get() + if path.is_file(): + self.window.clipboard_append(path.read_text(errors="replace")) + + def update_controls(self): + if not self.feature: + return + feature = self.feature + missing = [dep for dep in feature.dependencies if not (self.available or {}).get(dep)] + executable = self.available is not None and not missing and bool(feature.modes) + self.details.set("状态:正在探测" if self.available is None else + f"UNAVAILABLE · {feature.unavailable or '缺少 ' + ', '.join(missing)}" if not executable + else "可执行 · " + ("、".join(feature.dependencies) or "内置入口")) + self.start_button.configure(state="normal" if executable and not self.job else "disabled") + self.state.set("LIVE · 运行中" if self.job and self.running_feature == feature.id else "未运行 / 查看历史") + if self.live and self.running_feature == feature.id: + self.state.set("LIVE · 已连接") + for widget in self.ops: + widget.configure(state="normal" if self.live and not self.pending else "disabled") + if getattr(self, "history_id", None) != feature.id: + self.load_history(feature.id) + + def load_history(self, feature): + records = [] + for path in self.runs.glob("*/result.json"): + data = report(path) + if data.get("id") == feature: + records.append((data.get("finished", 0), data, path)) + if records: + stamp, data, path = max(records, key=lambda item: item[0]) + self.history_folder = path.parent + self.measurement.set("最近结果 · " + output_summary(feature, path.parent)) + self.history.set(f"HISTORY · {datetime.fromtimestamp(stamp):%m-%d %H:%M:%S} · " + f"{data['status']} · {path.parent.name}") + else: + self.history_folder = None + self.measurement.set("") + self.history.set("HISTORY · N/A") + self.history_id = feature + + def start(self): + if self.job or not self.feature: + return + try: + invocation(self.feature.id, self.mode.get(), self.runs, self.available or {}) + except ValueError as error: + self.status.set(str(error)) + return + self.folder = folder = type(self.runs)(tempfile.mkdtemp(prefix=self.feature.id + "-", dir=self.runs)) + self.offset = 0 + self.partial = "" + self.tail_key = None + self.live = self.pending = False + self.running_feature = self.feature.id + self.last_error = None + if self.table: + for key in self.table.get_children(): + self.table.set(key, "value", "N/A") + args = [sys.executable, ROOT / "scripts/vel_gui_job.py", self.feature.id, self.mode.get(), folder] + try: + with (folder / "console.log").open("w") as log: + self.job = subprocess.Popen(args, cwd=ROOT, env=tool_environment(), stdin=subprocess.PIPE, + stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + except OSError as error: + self.status.set(str(error)) + return + self.status.set(f"正在启动 {self.feature.title} · 会话 {folder.name}") + self.stop.configure(state="normal") + self.update_controls() + + def cancel(self): + if self.job and self.job.poll() is None: + self.job.send_signal(signal.SIGTERM) + self.status.set("正在停止并清理当前任务…") + self.stop.configure(state="disabled") + self.live = False + self.update_controls() + + def close(self): + self.closing = True + if self.detail_window and self.detail_window.winfo_exists(): + self.detail_dashboard.close() + if self.job: + self.cancel() + + def write_output(self, state): + choices = {f"DO_{index}": index for index in range(8)} + if self.output.get() in choices: + self.send({"op": "write", "index": choices[self.output.get()], "value": state}) + + def inject_input(self): + choices = {str(value): value for value in range(16)} + if self.input_mask.get() in choices: + self.send({"op": "input", "mask": choices[self.input_mask.get()]}) + + def send(self, data): + if not self.job or not self.live or self.pending: + return + try: + self.job.stdin.write((json.dumps(data) + "\n").encode()) + self.job.stdin.flush() + self.pending = True + self.status.set("等待真实 Modbus 回读…") + except OSError as error: + self.status.set(str(error)) + self.update_controls() + + def present(self, event): + for key in ("coils", "inputs", "holding", "registers"): + values = event[key] + self.table.set(key, "value", " ".join(str(int(v)) for v in values)) + + def events(self): + path = self.folder / "console.log" + with path.open("rb") as log: + log.seek(self.offset) + chunk = log.read(65536) + self.offset = log.tell() + text = self.partial + chunk.decode(errors="replace") + *lines, self.partial = text.split("\n") + for line in lines: + if not line.startswith('{"event"'): + continue + try: + event = json.loads(line) + except ValueError: + continue + kind = event.get("event") + if kind in ("ready", "result"): + self.live = True + if self.feature and self.feature.id == self.running_feature: + self.state.set("LIVE · 已连接") + self.last_snapshot = event + if self.table: + self.present(event) + self.status.set("LIVE · FC05 已由 FC01 和 GPIO 位图确认" if + event.get("request", {}).get("op") == "write" else + "LIVE · 已读取实际 DO / DI / 寄存器") + elif kind in ("operation_error", "session_error"): + self.last_error = f"{kind} · {event.get('reason', 'N/A')}" + self.status.set(self.last_error) + if kind in ("ready", "result", "operation_error", "session_error"): + self.pending = False + + def refresh(self): + if not self.inbox.empty(): + value = self.inbox.get() + self.available = value if isinstance(value, dict) else {} + self.status.set("就绪" if isinstance(value, dict) else str(value)) + self.update_overview() + if self.job: + self.events() + rc = self.job.poll() + if rc is not None: + data = report(self.folder / "result.json") + status = data.get("status", "FAIL") + self.status.set(f"{STATES.get(status, status)} · 退出码 {rc} · " + f"{data.get('reason') or self.last_error or self.folder.name} · 详见日志") + self.job.stdin.close() + self.job = None + self.live = self.pending = False + if self.table: + for key in self.table.get_children(): + self.table.set(key, "value", "N/A(会话结束)") + self.history_id = None + self.stop.configure(state="disabled") + if self.log_box and self.folder: + p = self.folder / self.log_source.get() + size = p.stat().st_size if p.is_file() else 0 + if self.tail_key != (p, size): + content = "N/A · 本次没有该日志" + if p.is_file(): + with p.open("rb") as raw: + raw.seek(max(0, size - 28000)) + content = raw.read(28000).decode(errors="replace") + self.log_box.configure(state="normal") + self.log_box.delete("1.0", "end") + self.log_box.insert("1.0", content) + self.log_box.configure(state="disabled") + self.log_box.see("end") + self.log_path.configure(text=str(p)) + self.tail_key = (p, size) + if self.closing and not self.job and not (self.detail_window and self.detail_window.winfo_exists()): + self.window.destroy() + return + self.update_controls() + self.window.after(180, self.refresh) diff --git a/scripts/vel_inspector.py b/scripts/vel_inspector.py new file mode 100644 index 0000000..734ff1b --- /dev/null +++ b/scripts/vel_inspector.py @@ -0,0 +1,50 @@ +"""Build and run the dedicated live dashboard firmware on MPS2 AN385.""" +import os +import re +import subprocess +import sys + +from run_qemu import command +from vel_env import ROOT, tool_environment + +FIELDS = re.compile(r" ([a-z0-9_]+)=(\d+)") + + +def snapshot(log): + """Return the most recent complete snapshot and its task table.""" + # The file can be tailed midway through a record, including its last line. + frames = list(re.finditer(r"^VEL_BEGIN([^\n]*)\n((?:VEL_TASK [^\n]*\n)+)VEL_END\n", + log, flags=re.MULTILINE)) + for frame in reversed(frames): + values = {k: int(v) for k, v in FIELDS.findall(frame[1])} + tasks = [] + for row in frame[2].splitlines(): + _, name, rest = row.split(" ", 2) + fields = {k: int(v) for k, v in FIELDS.findall(" " + rest)} + if not {"id", "state", "priority", "stack_words"} <= fields.keys(): + break + tasks.append((name, fields)) + else: + if len(tasks) == values.get("tasks") and "tick" in values: + return values, tasks + return {}, [] + + +def main(): + env = tool_environment() + build = ROOT / "build/dashboard-inspector" + subprocess.run(["cmake", "-S", ROOT, "-B", build, "-G", "Ninja", + "-DCMAKE_TOOLCHAIN_FILE=" + str(ROOT / "cmake/arm-none-eabi.cmake"), + "-DCMAKE_BUILD_TYPE=Debug", "-DVEL_FREERTOS=ON"], + env=env, check=True, timeout=180) + subprocess.run(["cmake", "--build", build, "--target", "rtos_inspector", "--parallel", "4"], + env=env, check=True, timeout=180) + args = command(build / "rtos_inspector.elf") + ["-nic", "none"] + os.execvpe(args[0], args, env) + + +if __name__ == "__main__": + try: + main() + except (OSError, subprocess.SubprocessError) as error: + sys.exit(str(error)) diff --git a/tests/gui/test_gui_h1.py b/tests/gui/test_gui_h1.py new file mode 100644 index 0000000..d713494 --- /dev/null +++ b/tests/gui/test_gui_h1.py @@ -0,0 +1,201 @@ +"""Repeatable GUI-H1 acceptance against the real WSLg window and RTU slave.""" +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts")) +from vel_env import tool_environment, work +from vel_gui_features import BY_ID, CATEGORIES, FEATURES, capabilities, invocation +from vel_jobs import workspace_lock + +ENV = tool_environment() + + +class Registry(unittest.TestCase): + def test_whitelist_and_dependencies(self): + flags = {s: True for f in FEATURES for s in f.dependencies} + self.assertEqual(len(BY_ID), len(FEATURES)) + for f in FEATURES: + self.assertIn(f.category, CATEGORIES) + self.assertTrue(f.modes or f.unavailable) + for mode in f.modes: + cmd = invocation(f.id, mode, ROOT, flags) + self.assertTrue(Path(cmd[1]).is_file()) + self.assertEqual(cmd[0], sys.executable) + with self.assertRaises(ValueError): + invocation(f.id, mode + "; arbitrary", ROOT, flags) + if f.dependencies: + with self.assertRaises(ValueError): + invocation(f.id, mode, ROOT, {}) + self.assertFalse(BY_ID["micro"].modes) + self.assertFalse(BY_ID["history"].modes) + + def test_invalid_modbus_parameters(self): + for command in ({"op":"write","index":8,"value":True}, + {"op":"write","index":"0; echo bad","value":True}, + {"op":"write","index":True,"value":True}, + {"op":"input","mask":16}, {"op":"read","extra":1}): + code = ("import json,sys; from vel_gui_modbus import validate; " + "validate(json.loads(sys.argv[1]))") + result = subprocess.run([sys.executable, "-c", code, json.dumps(command)], + cwd=ROOT / "scripts", env=ENV, capture_output=True, timeout=8) + self.assertIn(b"ValueError: Unsupported or invalid", result.stderr) + + +class Lifecycle(unittest.TestCase): + def job(self, folder, timeout=7, mode="单项实验", feature="arm"): + return [sys.executable, ROOT / "scripts/vel_gui_job.py", feature, mode, + folder, "--timeout", str(timeout)] + + def test_exit_success_and_rejected_mode(self): + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) + ok = subprocess.run(self.job(folder), cwd=ROOT, env=ENV, capture_output=True, timeout=20) + self.assertEqual(ok.returncode, 0, ok.stderr) + self.assertEqual(json.loads((folder/"result.json").read_text())["status"], "PASS") + failed = subprocess.run(self.job(folder, mode="invalid"), cwd=ROOT, env=ENV, + capture_output=True, timeout=20) + self.assertEqual(failed.returncode, 2) + self.assertEqual(json.loads((folder/"result.json").read_text())["status"], "UNAVAILABLE") + + def test_failed_job_reaps_separate_session(self): + # Run the real supervisor with an injected test-only resolver. The + # production CLI cannot select arbitrary commands. + code = r""" +from argparse import Namespace +from pathlib import Path +import subprocess,sys +from vel_gui_job import run +def fixture(*_): + worker = "import subprocess,sys; p=subprocess.Popen(['sleep','60'],start_new_session=True); print(p.pid,flush=True); sys.exit(11)" + return [sys.executable, "-c", worker] +sys.exit(run(Namespace(feature="arm",mode="single",folder=Path(sys.argv[1]),timeout=5),resolve=fixture)) +""" + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) + execution = subprocess.run([sys.executable, "-c", code, folder], cwd=ROOT/"scripts", + env=ENV, capture_output=True, timeout=20, text=True) + self.assertEqual(execution.returncode, 11, execution.stderr) + data = json.loads((folder/"result.json").read_text()) + self.assertEqual(data["status"], "FAIL") + self.assertFalse(Path("/proc", execution.stdout.splitlines()[0]).exists()) + + def test_lock_conflict(self): + lock = work("gui-h1/locks") / "arm.lock" + lock.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as directory, workspace_lock(lock): + folder = Path(directory) + busy = subprocess.run(self.job(folder), cwd=ROOT, env=ENV, capture_output=True, timeout=20) + self.assertEqual(busy.returncode, 75, busy.stderr) + self.assertEqual(json.loads((folder/"result.json").read_text())["status"], "BUSY") + + def test_timeout_without_killing_unrelated_process(self): + alive = subprocess.Popen(["sleep", "45"], start_new_session=True) + try: + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) + timed = subprocess.run(self.job(folder, 1, "交互会话", "rtu"), + stdin=subprocess.PIPE, cwd=ROOT, env=ENV, + capture_output=True, timeout=23) + self.assertEqual(timed.returncode, 124, timed.stderr) + result = json.loads((folder/"result.json").read_text()) + self.assertEqual(result["status"], "TIMEOUT") + self.assertFalse(Path("/proc", str(result["pid"])).exists()) + self.assertIsNone(alive.poll()) + finally: + alive.terminate() + alive.wait(5) + + +class Graphical(unittest.TestCase): + def test_real_wslg_and_rtu_gpio(self): + import tkinter as tk + from vel_gui_workbench import Workbench + + root = tk.Tk() + root.geometry("900x600") + window = Workbench(root) + start = time.monotonic() + phase = 0 + failure = [] + def check(): + nonlocal phase + try: + self.assertLess(time.monotonic()-start, 155, window.status.get()) + if phase == 0 and window.available is not None: + for category in CATEGORIES: + window.select(category) + root.update_idletasks() + window.select("Modbus") + self.assertEqual(window.feature.id, "rtu") + self.assertEqual(window.table.set("coils", "value"), "N/A") + self.assertIn("HISTORY", window.history.get()) + self.assertEqual(window.mode.get(), "交互会话") + self.assertEqual(str(window.start_button["state"]), "normal") + window.start_button.invoke() + owned = window.job + window.start() + self.assertIs(window.job, owned) + phase = 1 + elif phase == 1 and window.live: + self.assertEqual(window.last_snapshot["coils"][0], False) + self.assertIn("LIVE", window.state.get()) + window.ops[0].invoke() + phase = 2 + elif phase == 2 and window.live and not window.pending: + self.assertEqual(window.last_snapshot["coils"][0], True) + self.assertEqual(window.last_snapshot["registers"][7], 1) + self.assertTrue(window.table.set("coils","value").startswith("1")) + window.ops[1].invoke() + phase = 3 + elif phase == 3 and window.live and not window.pending: + self.assertEqual(window.last_snapshot["coils"][0], False) + self.assertEqual(window.last_snapshot["registers"][7], 0) + window.input_mask.set("5") + window.ops[3].invoke() + phase = 4 + elif phase == 4 and window.live and not window.pending: + self.assertEqual(window.last_snapshot["inputs"], [True,False,True,False]) + self.assertEqual(window.last_snapshot["registers"][6], 5) + window.select(CATEGORIES[-1]) + window.log_source.set("rtu-wire.jsonl") + phase = 5 + elif phase == 5: + self.assertIn('"direction"', window.log_box.get("1.0","end")) + print("WSLg session", window.folder, flush=True) + window.close() + phase = 6 + return + except Exception as error: + failure.append(error) + window.close() + return + root.after(160,check) + root.after(180,check) + root.mainloop() + if failure: + raise failure[0] + self.assertEqual(phase,6) + result=json.loads((window.folder/"result.json").read_text()) + self.assertEqual(result["status"],"CANCELLED") + slave=json.loads((window.folder/"slave-exit.json").read_text()) + self.assertFalse(Path("/proc",str(slave["pid"])).exists()) + frames=[json.loads(line) for line in (window.folder/"rtu-wire.jsonl").read_text().splitlines()] + sent=[x["hex"][:12] for x in frames if x["direction"]=="tx"] + for request in ("01050000ff00","010500000000","010100000008","010200000004", + "010300000008","010400000008"): + self.assertIn(request,sent) + self.assertIn("INPUT bits=5",(window.folder/"slave.log").read_text()) + self.assertTrue(any(x["direction"]=="rx" for x in frames)) + self.assertFalse(Path("/proc",str(result["pid"])).exists()) + + +if __name__ == "__main__": + unittest.main(verbosity=2)