diff --git a/AVALONIA.md b/AVALONIA.md index 04e69df..77f25cd 100644 --- a/AVALONIA.md +++ b/AVALONIA.md @@ -1,7 +1,7 @@ # SopHelper 统一 Avalonia 跨平台版 入口为 `SopHelper.Avalonia.slnx`。Windows、Linux 都编译 `src/SopHelper.Avalonia`,不存在 Windows/Linux 两份视图或 ViewModel。 -现有 WPF `src/SopHelper.App` 保留作为迁移参考,未修改其源码。此前 `SopHelper.Linux` 简化验证版已停止作为部署入口。 +原 WPF 仓库已完整归档到 `../archive/SopHelper-WPF-20261108/`。旧 Linux 简化版已删除;当前仓库是唯一活动版本。 ## 与原程序的对应关系 @@ -13,7 +13,7 @@ | ROI 图像画框、坐标微调、相机取图 | Avalonia `RegionCanvas`,仍保存原图像素坐标 | | 零件标注、复核、SAM2、导出、YOLO 训练 | `Training`,保留原项目格式与 worker 协议 | | 相机预览、录像、退出清理 | `Training/CameraWindow`,保留相机互斥与关闭等待流程 | -| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 直接链接原 `SopHelper.Engine` 源文件 | +| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 | 界面框架相关 API(绘图、图像缓冲、文件选择、UI 调度、窗口关闭)统一由 Avalonia 实现。 ViewModel 不按操作系统分叉。UVC 的 MSMF/DSHOW 与 V4L2、Python 可执行文件路径和原生 SDK 库名, diff --git a/LINUX.md b/LINUX.md index f70d848..28ae3f0 100644 --- a/LINUX.md +++ b/LINUX.md @@ -1,12 +1,12 @@ # SopHelper Linux 部署 当前入口是统一的 **Avalonia 跨平台版**,详见 [AVALONIA.md](AVALONIA.md)。 -Windows 和 Linux 都编译 `src/SopHelper.Avalonia`;之前的 `SopHelper.Linux` 简化验证版不再作为部署入口。 +Windows 和 Linux 都编译 `src/SopHelper.Avalonia`;旧 Linux 简化验证版已删除。 ## 本地生成 Linux 包 ```powershell -dotnet publish src/SopHelper.Avalonia -c Release -r linux-x64 --self-contained true -o artifacts/avalonia/linux-x64 +dotnet publish src/SopHelper.Avalonia -c Release -r linux-x64 -p:NativePlatform=Linux --self-contained true -o artifacts/avalonia/linux-x64 ``` 在目标机的图形会话中执行 `./SopHelper.Avalonia`。训练功能需要为 Linux 单独安装 Python 运行时: diff --git a/README.md b/README.md index a980fb3..4a3bc52 100644 --- a/README.md +++ b/README.md @@ -1,211 +1,63 @@ -# SopHelper — 单相机 SOP 辅助 +# SopHelper.Avalonia -工位上接一个 UVC 或海康工业相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、 -超时报违规、留日志和快照。侧栏的「零件标注与训练」集成 PartTrainer 的采集、标注与模型训练流程。 +Windows / Linux 共用一套 Avalonia 桌面程序,保留 SOP 作业辅助、配方编辑、相机采集、YOLO 与双手关键点检测,以及零件标注和训练流程。 -引擎逻辑移植自 [VisionInspectionSystem](https://github.com/TheDoorIsUnlocked/VisionInspectionSystem)(MIT)。 +本目录是唯一活动仓库。原 WPF 仓库完整归档至 `../archive/SopHelper-WPF-20261108/`;旧 Linux 简化版已从活动代码中删除。 +Git 提交历史保留。当前代码、构建和测试不依赖归档目录。 -## 结构 +## 目录 -``` -SopHelper.Engine net8.0 纯类库,零 UI 依赖(可单测、可被别的项目引用) - Camera/ UVC(MSMF / DSHOW)及海康 MVS(GigE / USB)连续采集,单相机 - Inference/ YOLOv8 ONNX(自带 letterbox + DFL 解码 + NMS) - MediaPipe 手部两阶段(palm 192 → 方形裁剪 → landmark 224) - Pipeline/ 采集 → 推理 → 结果帧,支持抽帧 - Sop/ 配方加载 + 条件判定 + 违规 + 状态机 - -SopHelper.App net8.0-windows,Prism.DryIoc - 纯 WPF 样式,无 HandyControl / SkiaSharp.Views.WPF +```text +SopHelper.Avalonia.slnx +src/ + SopHelper.Avalonia/ 统一桌面界面、ViewModel、平台适配 + SopHelper.CrossPlatform.Engine/ 独立共享引擎:相机、推理、SOP、录像、训练数据 +configs/sop/ YAML 配方 +models/、yolo_models/ 模型 +libs/ Windows/Linux 海康绑定及可选 CUDA 库 +tools/ worker、运行环境、发布和部署脚本 +tests/ Avalonia、引擎和硬件回归检查 +python/ 本地 Python 运行环境(不入 Git) +workspace/ 设置、录像和工作数据(不入 Git) +artifacts/ 构建和测试输出(不入 Git) ``` -依赖包括 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime.Gpu、YamlDotNet 和海康 MVS SDK —— 没有 -GPL/AGPL 组件(YOLO 那段是自己写的,就是为了不引 GPL-3.0 的 YoloDotNet)。 - -## 跑起来 - -```bash -dotnet build SopHelper.slnx -``` - -1. 把模型丢进 `models/` 和 `yolo_models/`。构建时自动拷到输出目录,模型文件本身不入 git。 - 当前用的三份(获取渠道与许可证): - - | 模型 | 来源 | 许可证 | - |---|---|---| - | `palm_detection_full_Nx3x192x192_post.onnx` | PINTO0309/hand_landmark release 1.0.0 | Apache-2.0 | - | `hand_landmark_sparse_Nx3x224x224.onnx` | 同上 | Apache-2.0 | - | `yolo11n.onnx` | dme-compunet/YoloSharp 仓内 | **AGPL-3.0**(Ultralytics 血统),仅测试用,生产前换掉 | -2. 接相机。 -3. 界面上:刷新相机 → 选配方 → 应用 → 开始/停止。 - -没有模型也能起:缺哪个就在日志里报哪条警告,只有手部类和计时类条件能工作。 - -运行时,检测到的手会直接标在视频画面上:21 个关键点与骨架连线,不显示手部外框或文字标签。 -标记与 ROI 共用原图坐标,随预览一起缩放;未检测到手或停止采集时清除。 -需要 `models/` 中的 palm 与 landmark 两份模型,缺失时日志会提示。 -手掌检测与手部关键点确认的默认置信度门槛均为 40%(界面上的置信度滑块用于 YOLO 目标检测)。 -默认支持同帧显示两只手。针对 palm 导出中内置的单手 NMS 限制,加载时仅在内存中 -适配候选输出数量,原始模型文件不变;相邻手部去重使用原始手掌框。 - -双手回归检查(提供一段同时包含左右手的视频,从项目根目录运行): - -```bash -dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4 -``` - -### GPU 推理 - -使用 ONNX Runtime GPU 1.23.0,手掌、手部关键点与 YOLO 默认优先使用 NVIDIA CUDA, -不可用时自动回退 CPU。加载配方后,日志会显示手部与 YOLO 的实际推理后端,以及 GPU 回退原因。 -图像裁剪、预处理及画面绘制仍在 CPU 上执行。 - -现场需安装 NVIDIA 驱动、兼容的 CUDA 12.x 运行库(本机为 CUDA 12.6),并确保 CUDA `bin` -在进程 PATH 中;还需要 cuDNN 9。可从项目目录执行以下脚本,从 NVIDIA 官方下载 cuDNN, -校验 SHA256 后将 DLL 及许可证放入 `libs/cuda/`: +## 构建和运行 ```powershell -pwsh -NoProfile -File tools/Install-GpuRuntime.ps1 -dotnet build SopHelper.slnx +dotnet build SopHelper.Avalonia.slnx -c Release +dotnet run --project src/SopHelper.Avalonia +pwsh -File tools/Publish-Avalonia.ps1 ``` -`libs/cuda/` 不入 Git,构建/发布时自动携带其中的 DLL 和许可证。换机器部署时也需提供 CUDA 12.x -运行库。脚本不修改系统安装和 PATH。兼容要求见 [ONNX Runtime CUDA 文档](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html)。 +发布结果:`artifacts/avalonia/win-x64/SopHelper.Avalonia.exe` 和 +`artifacts/avalonia/linux-x64/SopHelper.Avalonia`。 +两个平台使用同一套视图、ViewModel 和业务代码,仅供应商 SDK 绑定及原生运行库不同。 -强制验证 GPU(若回退 CPU 则测试失败);对比 CPU 可将 `--require-gpu` 换成 `--cpu`: +Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部署见 [LINUX.md](LINUX.md)。 +发布脚本会携带 Windows 的仓库 Python 运行时,Linux 需建立对应平台环境。 -```bash -dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4 --require-gpu -``` +## 操作流程 -### 海康相机取视频 +1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。 +2. 配方编辑器保留步骤、区域、全局设置、检测模型四个标签页;区域坐标使用原图像素。 +3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。 +4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。 -参考 `plcsharp` 的 `MvCameraControl` 接法,支持海康机器人 GigE / USB 工业相机。 -`libs/MvCameraControl.Net.dll` 随项目提供,构建和发布会自动复制;现场需安装 -**MVS 4.5 或以上的 x64 运行时**(与 SDK 兼容),使用 x64 进程运行。 -原生运行时通常位于 `C:\Program Files (x86)\Common Files\MVS\Runtime\Win64_x64`。 +模型文件:`palm_detection_full_Nx3x192x192_post.onnx`、`hand_landmark_sparse_Nx3x224x224.onnx`; +目标检测模型由配方选择。测试用 `yolo11n.onnx` 和训练依赖沿用其上游许可。 -1. 先在 MVS 中确认能发现相机并正常取图,然后关闭 MVS 对该设备的连接。 -2. GigE 相机与网卡配置在可互通的网段;USB 相机安装 MVS USB 驱动。 -3. SOP 页点击「刷新」,选择 `海康 型号 / 序列号`,选择配方后点击「开始/停止」。 - 视频进入现有预览、ROI、推理和 SOP 判定流程。 -4. 停止后可切换相机,再次开始会重新连接;运行及连接过程中禁止切换设备。 - -采集会设置连续模式并关闭触发;GigE 尝试优化包大小。输出统一为 BGR 三通道, -灰度、Bayer、RGB、YUV 等格式转换后再交给管线。SDK 缓冲在复制后立即归还。 -未安装 MVS 时日志提示原因,UVC 仍可使用。此功能针对工业相机,不包含安防摄像头 RTSP。 - -应用退出统一释放相机,再释放推理管线,不依赖页面的 `Destroy()`。 -退出时等待尚未完成的设备操作及采集线程,归还缓冲、关闭设备并反初始化 MVS。 - -退出回归检查(不创建窗口,执行正式 WPF 退出链路): - -```bash -dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -# 连接现场海康、收到视频帧后直接退出,并在同一进程中验证设备可重新打开 -dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware -``` - -## 零件标注与训练 - -侧栏「零件标注与训练」包含以下工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。 - -首次使用 Python 功能,在 SopHelper 根目录执行: +## 验证 ```powershell -powershell -ExecutionPolicy Bypass -File tools/Setup-Python.ps1 -Sam2 -# CPU 环境附加 -Cpu +dotnet run --project tests/Avalonia.Smoke -c Release +dotnet run --project tests/HandednessSmoke -c Release +dotnet run --project tests/Training.Smoke -c Release -- python/python.exe +dotnet run --project tests/YoloModelSmoke -c Release -- models/yolo11n.onnx +# 现场相机检查会实际打开设备;先关闭其他程序对相机的连接。 +dotnet run --project tests/Mvs.Smoke -c Release -- --hardware ``` -程序固定使用可执行文件同目录的 `python/python.exe`,不读取系统 PATH 或设置文件中的 Python 路径,界面不提供路径设置。安装脚本将完整运行时及依赖放在仓库 `python/`,构建和发布会携带该目录。相机预览和录像不需要 Python。设置保存在 `workspace/settings.json`,录像默认保存在 `workspace/recordings`;API Key 不保存到配置或日志。原 PartTrainer 的 `project.json` 可直接打开,项目中原有的绝对视频、权重路径需要仍然有效。集成后的源码、Python worker 和安装脚本均在本仓库内,构建与发布无需 PartTrainer 目录。 - -相机录像窗口以模态打开;SOP 正在运行或操作相机时会提示先停止,避免两个流程同时占用设备。关闭采集窗口会结束并封装录像。关闭主窗口时会取消后台 Python 任务、等待进程退出并释放相机;即使已切回 SOP 页面也会清理。 - -标注目前支持单目标、单类别矩形框。导出只包含已复核正样本和明确标记的无目标帧,按时间划分训练与验证并保留间隔。单段视频的指标用于验证流程,实际效果需使用独立现场视频评估。 - -训练后点击「导出最新模型为 ONNX」,在 SOP 配方编辑器「检测模型」选择导出的 ONNX;类别表可留空以读取模型元数据,也可提供对应类别表。导出采用固定尺寸、opset 17、无内置 NMS。原 PartTrainer 项目保留,可继续独立运行。 - -Python 依赖中的 Ultralytics 使用 AGPL-3.0 / 商业许可;SAM2 使用其上游许可。部署时需遵守所选依赖与模型的许可。 - -集成回归检查: - -```powershell -dotnet run --project tests/Training.Smoke -dotnet run --project tests/Training.UiSmoke -dotnet run --project tests/Training.CameraSmoke -dotnet run --project tests/Training.ShellSmoke -python/python.exe -X utf8 -m unittest discover -s tests -p test_worker.py -v -``` - -## 配方 - -`configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。 - -支持的方法(就是参考项目现有配方里真正被用过的那些): - -| method | 需要模型 | 依赖 | -|---|---|---| -| `time_elapsed` | 否 | 计时 | -| `hand_in_region` | 否 | MediaPipe | -| `hand_move` | 否 | MediaPipe(起点证据来自上一帧的轨迹) | -| `object_present` | 是 | YOLO | -| `object_in_zone` | 是 | YOLO | -| `hand_near_object` | 是 | YOLO + MediaPipe | -| `person_present` | 是 | YOLO(COCO 的 person) | - -步骤里写了没实现的方法,**加载配方时就会报出来**——否则现场表现是"这一步永远不推进", -极难定位。 - -违规:`timeout` / `object_removed`,同类 3 秒冷却。 - -### 配方编辑器 - -SOP 页配方行的「编辑 / 新建」。表单式,四个 tab:步骤 / 区域 / 全局设置 / 检测模型, -字段与 YAML 一一对应;method、区域名、hand、违规类型都是下拉选——就是为了不让 -"照抄别人的 YAML 拼错一个字母"这种事发生(下拉候选就是 `ConditionMethod` 那几项)。 -区域改键名会同步更新所有引用它的步骤;删区域会清掉引用。 - -“检测模型”页选择普通 YOLO 的 ONNX 文件和对应类别表;类别表留空时可从模型的 `names` 元数据读取。 -加载时会检查类别数量和输出格式,加载失败会在 SOP 日志提示,切换到缺失模型也会释放旧模型。 -该页的“相机曝光(μs)”随配方保存到 `sop.settings.exposure_time_us`,例如 10000 表示 10 毫秒。 -海康相机在区域取图与 SOP 启动前关闭自动曝光并应用该值;留空保留设备设置。UVC 暂不支持微秒曝光设置,请留空。 -程序启动时自动扫描相机并恢复上次成功使用的设备,主窗口默认最大化。 - -区域页支持图像画框标定: - -1. 停止运行,在 SOP 页选好相机,打开「编辑 / 新建」→「区域」。 -2. 已有预览画面会作为背景带入;也可点「从相机取图」获取新的一帧,或「打开图片」载入原图。 - 取图完成后自动关闭相机,不启动 SOP 判定。 -3. 左侧选中区域(没有则点「加区域」),在图上按住左键拖动画框,松开后更新 X1/Y1/X2/Y2。 - 支持反方向拖动;超出图像边界会截取到边界;Esc 取消本次绘制。 -4. 重画可直接替换所选区域;下方数字可微调,并同步更新图上的框。点击「保存」写入配方。 - -图像保持原比例显示,坐标保存为原图像素,不包含预览留白。打开的图片应与现场相机分辨率一致。 - -区域编辑回归检查(可加 `--hardware` 使用现场海康取图): - -```bash -dotnet run --project tests/RegionEditorSmoke/RegionEditorSmoke.csproj -``` - -两条要注意的: - -- **保存是重写整个文件,注释会丢**(YamlDotNet 不保留注释)。`demo.yaml` 顶上那些说明 - 注释,编辑器保存一次就没了——那些话是给编辑器的字段说的,不是给自己的。 -- **运行中不能编辑**,和「应用」一致,得先停止。保存成功后界面会重扫 `configs/sop`、 - 选中刚存的配方并立即重新应用,区域覆盖层跟着更新。新建时文件名可填,之后不可改 - (SOP 页是按文件名选配方的)。 - -## 判定语义(踩过的坑) - -- **稳定帧门控**:按 `(步骤Id, 条件序号)` 累计连续命中帧数,达标才放行,未命中立即清零。 - `time_elapsed` / `hand_move` 豁免(自带时序或瞬时语义)。 -- **Start / Reset 必须清空跨帧状态**,否则第二轮会"秒过",防抖形同虚设。 -- **区域坐标是绝对像素**,必须在真机画面上标定,别照抄别人的 YAML。 - -## 已知限制 - -- 单相机。多相机需求请先改 `ICameraService` 的契约再说。 -- YOLO 和 MediaPipe 的解析是照搬参考项目逻辑重写的,本机没有 onnx 文件, - **只过了编译,没跑过真实推理**。第一次接上模型时先拿一段已知动作的视频验一遍。 -- 快照只存帧(`snaps/`),不叠加 ROI 和检测框。 +运行 `--check-runtime` 可检查发布包的模型和 SOP 引擎。 +Avalonia 验证使用假相机,覆盖导航、原始配方字段保持、标注保存、相机缓冲显示和画框坐标。 +详细架构与平台验证记录见 [AVALONIA.md](AVALONIA.md),研发方向见 [研发计划.md](研发计划.md)。 diff --git a/SopHelper.Linux.slnx b/SopHelper.Linux.slnx deleted file mode 100644 index ac2b058..0000000 --- a/SopHelper.Linux.slnx +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/SopHelper.slnx b/SopHelper.slnx deleted file mode 100644 index 93846e4..0000000 --- a/SopHelper.slnx +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/SopHelper.App/App.xaml b/src/SopHelper.App/App.xaml deleted file mode 100644 index 82e167e..0000000 --- a/src/SopHelper.App/App.xaml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - diff --git a/src/SopHelper.App/App.xaml.cs b/src/SopHelper.App/App.xaml.cs deleted file mode 100644 index d8e63bb..0000000 --- a/src/SopHelper.App/App.xaml.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System.IO; -using System.Reflection; -using System.Windows; -using System.Windows.Threading; -using Prism.Ioc; -using Prism.Mvvm; -using SopHelper.Core.Prism; -using SopHelper.Engine.Camera; -using SopHelper.Engine.Pipeline; -using SopHelper.Engine.Sop; -using SopHelper.Models; -using SopHelper.VVMs.RecipeEditor; -using SopHelper.VVMs.SopPage; -using SopHelper.VVMs.MainWindow; - -namespace SopHelper; - -/// -/// 应用程序入口,负责初始化 Prism 框架和注册组件(启动链照搬 plcsharp) -/// -public partial class App -{ - private ICameraService? _camera; - private DetectionPipeline? _pipeline; - private Engine.Training.WorkerClient? _trainingWorker; - - /// - /// 注册应用程序所需的类型和服务 - /// - protected override void RegisterTypes(IContainerRegistry containerRegistry) - { - RegisterEvents(); // 捕获全局异常 - - // 注册带 [Model] 特性的类,单例 - foreach (var model in from t in Assembly.GetExecutingAssembly().GetTypes() - where t.GetCustomAttribute() is not null - select t) - { - _ = containerRegistry.RegisterSingleton(model); - } - - // 注册带 [NavigationPage] 特性的 View 到导航 - foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes() - where t.GetCustomAttribute() is not null - select t) - { - containerRegistry.RegisterForNavigation(view, view.Name); - } - - _ = containerRegistry.RegisterSingleton(); - - // 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集, - // 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。 - // 共享硬件和推理由应用持有;页面销毁和容器回收不能代替应用退出清理。 - _camera = new CameraService(); - _pipeline = new DetectionPipeline(_camera); - containerRegistry.RegisterInstance(_camera); - containerRegistry.RegisterInstance(_pipeline); - _ = containerRegistry.RegisterSingleton(); - - // ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册 - _ = containerRegistry.RegisterSingleton(); - _trainingWorker = new Engine.Training.WorkerClient(); - containerRegistry.RegisterInstance(_trainingWorker); - containerRegistry.RegisterSingleton(); - - // 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出) - containerRegistry.RegisterDialog("RecipeEditorDialog"); - } - - /// - /// 创建Shell - /// - protected override Window CreateShell() - { - var navigate = Container.Resolve(); - - // 反射收集导航页 - foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes() - where t.GetCustomAttribute() is not null - orderby t.GetCustomAttribute()!.Index - select t) - { - var page = view.GetCustomAttribute()!; - - var item = Container.Resolve(); - item.ViewName = page.ViewName; - item.DisplayName = page.DisplayName; - navigate.Pages.Add(item); - } - - var window = Container.Resolve(); - - // 默认页:区域要等窗口加载后才注册,CreateShell 里立刻 RequestNavigate 会静默失败 - //(实测启动后内容区是空的),必须等 Loaded;走 SelectedIndex 让侧栏同步高亮。 - window.Loaded += (_, _) => - { - if (navigate.Pages.Count > 0) navigate.SelectedIndex = 0; - }; - - return window; - } - - protected override void OnExit(ExitEventArgs e) - { - try - { - _trainingWorker?.Dispose(); - // Dispose 等待采集线程退出、归还缓冲并关闭设备,然后才能释放推理模型。 - try { _camera?.Dispose(); } - catch (Exception ex) { Log(ex, "Exit.Camera"); } - try { _pipeline?.Dispose(); } - catch (Exception ex) { Log(ex, "Exit.Pipeline"); } - } - finally - { - base.OnExit(e); - } - } - - /// - /// 自动寻找ViewModel并绑定到View,要求ViewModel命名为View的全名加上ViewModel,比如MainWindow的ViewModel命名为MainWindowViewModel - /// - protected override void ConfigureViewModelLocator() - { - base.ConfigureViewModelLocator(); - - ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) => - { - var viewName = viewType.FullName; - var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName; - var viewModelName = $"{viewName}ViewModel, {viewAssemblyName}"; - return Type.GetType(viewModelName); - }); - } - - /// - /// 捕获全局异常 - /// - private static void RegisterEvents() - { - AppDomain.CurrentDomain.UnhandledException += (_, e) => - Log(e.ExceptionObject as Exception, "AppDomain"); - - Current.DispatcherUnhandledException += (_, e) => - { - Log(e.Exception, "Dispatcher"); - e.Handled = true; // 上位机不能因一次异常退出 - }; - } - - private static void Log(Exception? ex, string from) - { - if (ex is null) return; - var line = $"[{DateTime.Now:HH:mm:ss.fff}] [{from}] {ex.Message}"; - Console.WriteLine(line); - try - { - Directory.CreateDirectory("logs"); - File.AppendAllText(Path.Combine("logs", "error.log"), line + Environment.NewLine); - } - catch - { - // 日志失败不影响主流程 - } - } -} diff --git a/src/SopHelper.App/Assets/BellwetherLogo.xaml b/src/SopHelper.App/Assets/BellwetherLogo.xaml deleted file mode 100644 index d7dfec9..0000000 --- a/src/SopHelper.App/Assets/BellwetherLogo.xaml +++ /dev/null @@ -1,167 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/SopHelper.App/Core/Prism/CoreAttribute.cs b/src/SopHelper.App/Core/Prism/CoreAttribute.cs deleted file mode 100644 index 29ab00c..0000000 --- a/src/SopHelper.App/Core/Prism/CoreAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace SopHelper.Core.Prism; - -/// -/// 标志此特性的类会被注册为单例(照搬 plcsharp 约定) -/// -[AttributeUsage(AttributeTargets.Class)] -public class ModelAttribute : Attribute -{ -} - -/// -/// 标志此特性的 View 会被注册到导航列表 -/// -[AttributeUsage(AttributeTargets.Class)] -public class NavigationPageAttribute : Attribute -{ - /// - /// 视图名称(导航用) - /// - public string ViewName { get; set; } = ""; - - /// - /// Display名称 - /// - public string DisplayName { get; set; } = ""; - - /// - /// 排序序号 - /// - public int Index { get; set; } -} - -/// -/// 标志此特性的类会被注册为弹出窗口 -/// -[AttributeUsage(AttributeTargets.Class)] -public class DialogAttribute : Attribute -{ -} diff --git a/src/SopHelper.App/Core/Prism/MessageEvent.cs b/src/SopHelper.App/Core/Prism/MessageEvent.cs deleted file mode 100644 index b0b9370..0000000 --- a/src/SopHelper.App/Core/Prism/MessageEvent.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Prism.Events; - -namespace SopHelper.Core.Prism; - -/// -/// 全局消息事件(照搬 plcsharp:模块间解耦都走事件聚合器) -/// -public class MessageEvent : PubSubEvent -{ -} - -/// -/// 消息内容 -/// -public struct Message -{ - /// - /// 消息目标 - /// - public string Target { get; set; } - - /// - /// 消息 - /// - public string Content { get; set; } - - /// - /// 消息类型 1 记录 2 弹出 3 弹出并记录 - /// - public ShowType Type { get; set; } - - /// - /// 级别 - /// - public MsgLevel Level { get; set; } -} - -/// -/// 显示方式 -/// -public enum ShowType -{ - /// 仅记录日志 - Log = 1, - - /// 仅提示 - Show = 2, - - /// 提示并记录 - Both = 3, -} - -/// -/// 消息级别 -/// -public enum MsgLevel -{ - Info, - Warn, - Error, -} diff --git a/src/SopHelper.App/Core/Prism/ModelBase.cs b/src/SopHelper.App/Core/Prism/ModelBase.cs deleted file mode 100644 index 1562226..0000000 --- a/src/SopHelper.App/Core/Prism/ModelBase.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Prism.Events; -using Prism.Ioc; -using Prism.Mvvm; - -namespace SopHelper.Core.Prism; - -/// -/// 模型Base -/// -public class ModelBase : BindableBase -{ - /// - /// 事件聚合器 - /// - protected readonly IEventAggregator _eventAggregator; - - /// - /// DI 容器 - /// - protected readonly IContainerExtension _container; - - /// - /// 模型Base - /// - public ModelBase(IContainerExtension container, IEventAggregator ea) - { - _container = container; - _eventAggregator = ea; - - _eventAggregator.GetEvent().Subscribe(OnMessage, ThreadOption.PublisherThread, true); - - AppDomain.CurrentDomain.ProcessExit += OnExit; - } - - /// - /// 收到消息(子类覆写做本模块的落库/统计) - /// - protected virtual void OnMessage(Message message) - { - } - - /// - /// 进程退出(子类覆写做释放) - /// - protected virtual void OnExit(object? sender, EventArgs e) - { - } -} diff --git a/src/SopHelper.App/Core/Prism/NavigateItem.cs b/src/SopHelper.App/Core/Prism/NavigateItem.cs deleted file mode 100644 index 4af4c70..0000000 --- a/src/SopHelper.App/Core/Prism/NavigateItem.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Prism.Mvvm; - -namespace SopHelper.Core.Prism; - -/// -/// Navigate项 -/// -public class NavigateItem : BindableBase -{ - private string _viewName = ""; - - /// - /// 视图名称 - /// - public string ViewName - { - get { return _viewName; } - set { SetProperty(ref _viewName, value); } - } - - private string _displayName = ""; - - /// - /// Display名称 - /// - public string DisplayName - { - get { return _displayName; } - set { SetProperty(ref _displayName, value); } - } -} diff --git a/src/SopHelper.App/Core/Prism/ViewModelBase.cs b/src/SopHelper.App/Core/Prism/ViewModelBase.cs deleted file mode 100644 index 40777ed..0000000 --- a/src/SopHelper.App/Core/Prism/ViewModelBase.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Prism.Mvvm; -using Prism.Navigation; - -namespace SopHelper.Core.Prism; - -/// -/// 视图模型Base -/// -public abstract class ViewModelBase : BindableBase, IDestructible -{ - /// - /// Destroy - /// - public virtual void Destroy() - { - } -} diff --git a/src/SopHelper.App/Models/NavigationModel.cs b/src/SopHelper.App/Models/NavigationModel.cs deleted file mode 100644 index 06027e9..0000000 --- a/src/SopHelper.App/Models/NavigationModel.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.ObjectModel; -using Prism.Events; -using Prism.Ioc; -using Prism.Navigation.Regions; -using SopHelper.Core.Prism; - -namespace SopHelper.Models; - -/// -/// Navigate模型 -/// -[Model] -public class NavigationModel : ModelBase -{ - private readonly IRegionManager _regionManager; - - /// - /// Navigate模型 - /// - public NavigationModel(IContainerExtension container, IEventAggregator ea, IRegionManager regionManager) - : base(container, ea) - { - _regionManager = regionManager; - } - - private ObservableCollection _pages = []; - - /// - /// 导航页列表(shell 侧栏绑定) - /// - public ObservableCollection Pages - { - get { return _pages; } - set { SetProperty(ref _pages, value); } - } - - private NavigateItem? _target; - - /// - /// 当前页 - /// - public NavigateItem? Target - { - get { return _target; } - set { SetProperty(ref _target, value); } - } - - private int _selectedIndex = -1; - - /// - /// 侧栏选中索引 - /// - public int SelectedIndex - { - get { return _selectedIndex; } - set - { - if (!SetProperty(ref _selectedIndex, value)) return; - if (value >= 0 && value < Pages.Count) Navigate(Pages[value].ViewName); - } - } - - /// - /// 导航到指定页 - /// - public void Navigate(string viewName) - { - if (string.IsNullOrEmpty(viewName)) return; - - Target = Pages.FirstOrDefault(n => n.ViewName == viewName); - if (Target is null) return; - - _regionManager.RequestNavigate(ContentRegion, viewName); - } - - /// - /// 内容区名(shell 与导航的唯一约定) - /// - public const string ContentRegion = "ContentRegion"; -} diff --git a/src/SopHelper.App/SopHelper.App.csproj b/src/SopHelper.App/SopHelper.App.csproj deleted file mode 100644 index f18c1b7..0000000 --- a/src/SopHelper.App/SopHelper.App.csproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - WinExe - net8.0-windows - true - latest - enable - enable - x64 - AnyCPU;x64 - true - SopHelper - SopHelper - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/SopHelper.App/Themes/Styles.xaml b/src/SopHelper.App/Themes/Styles.xaml deleted file mode 100644 index 11b291f..0000000 --- a/src/SopHelper.App/Themes/Styles.xaml +++ /dev/null @@ -1,332 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/SopHelper.App/Training/AnnotationCanvas.cs b/src/SopHelper.App/Training/AnnotationCanvas.cs deleted file mode 100644 index 2a1f54a..0000000 --- a/src/SopHelper.App/Training/AnnotationCanvas.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Windows; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; - -namespace SopHelper.Training; - -/// Aspect-fit preview with original-image coordinates, including letterbox offsets. -public sealed class AnnotationCanvas : FrameworkElement -{ - public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(nameof(Source), typeof(BitmapSource), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); - public static readonly DependencyProperty BoxProperty = DependencyProperty.Register(nameof(Box), typeof(double[]), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); - public BitmapSource? Source { get => (BitmapSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); } - public double[]? Box { get => (double[]?)GetValue(BoxProperty); set => SetValue(BoxProperty, value); } - public event Action? BoxDrawn; - private Point? _start; - private Point _end; - public AnnotationCanvas() { ClipToBounds = true; Cursor = Cursors.Cross; Focusable = true; } - private Rect ImageRect - { - get - { - if (Source == null) return Rect.Empty; - var scale = Math.Min(ActualWidth / Source.PixelWidth, ActualHeight / Source.PixelHeight); - var w = Source.PixelWidth * scale; var h = Source.PixelHeight * scale; - return new Rect((ActualWidth - w) / 2, (ActualHeight - h) / 2, w, h); - } - } - protected override void OnRender(DrawingContext dc) - { - dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize)); - var image = ImageRect; - if (Source == null || image.IsEmpty) return; - dc.DrawImage(Source, image); - var pen = new Pen(new SolidColorBrush(Color.FromRgb(0, 220, 220)), 2); - if (Box is { Length: 4 } b) - { - var scale = image.Width / Source.PixelWidth; - dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30, 0, 220, 220)), pen, - new Rect(image.X + b[0]*scale, image.Y + b[1]*scale, (b[2]-b[0])*scale, (b[3]-b[1])*scale)); - } - if (_start is { } start) dc.DrawRectangle(null, new Pen(Brushes.Yellow, 2), new Rect(start, _end)); - } - protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) - { - if (!IsEnabled || Source == null || !ImageRect.Contains(e.GetPosition(this))) return; - Focus(); _start = _end = e.GetPosition(this); CaptureMouse(); InvalidateVisual(); e.Handled = true; - } - protected override void OnMouseMove(MouseEventArgs e) - { - if (_start == null) return; - var p = e.GetPosition(this); var image = ImageRect; - _end = new Point(Math.Clamp(p.X, image.Left, image.Right), Math.Clamp(p.Y, image.Top, image.Bottom)); - InvalidateVisual(); - } - protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) - { - if (_start is not { } start || Source == null) return; - var rectangle = new Rect(start, _end); var image = ImageRect; - _start = null; ReleaseMouseCapture(); InvalidateVisual(); - if (rectangle.Width < 3 || rectangle.Height < 3 || image.Width <= 0) return; - var scale = Source.PixelWidth / image.Width; - BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale, (rectangle.Top-image.Top)*scale, - Math.Min(Source.PixelWidth, (rectangle.Right-image.Left)*scale), Math.Min(Source.PixelHeight, (rectangle.Bottom-image.Top)*scale)]); - } - protected override void OnLostMouseCapture(MouseEventArgs e) { _start = null; InvalidateVisual(); base.OnLostMouseCapture(e); } -} diff --git a/src/SopHelper.App/Training/CameraViewModel.cs b/src/SopHelper.App/Training/CameraViewModel.cs deleted file mode 100644 index 6866ac5..0000000 --- a/src/SopHelper.App/Training/CameraViewModel.cs +++ /dev/null @@ -1,288 +0,0 @@ -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.IO; -using System.Text.Json; -using System.Windows; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Threading; -using Microsoft.Win32; -using OpenCvSharp; -using SopHelper.Engine.Camera; -using Prism.Commands; -using Prism.Mvvm; - -namespace SopHelper.Training; - -public sealed class CameraViewModel : BindableBase -{ - private readonly ICameraService _camera; - private readonly VideoRecorder _recorder = new(); - private readonly object _frames = new(); - private readonly Dispatcher _dispatcher; - private readonly DispatcherTimer _timer; - private readonly string _settingsPath; - private readonly Stopwatch _previewClock = Stopwatch.StartNew(); - private Mat? _latest; - private int _previewPending; - private int _generation; - private long _lastFrameTick; - private volatile bool _closing; - private bool _busy, _previewing, _recording; - private string _status = "刷新设备列表,选择相机后开启预览"; - private string _directory; - private string _lastRecording = ""; - private string _recordingInfo = "未录像"; - private CameraInfo? _selected; - private BitmapSource? _preview; - private Task _operation = Task.CompletedTask; - private Task? _shutdown; - private readonly List _commands = []; - - public ObservableCollection Cameras { get; } = []; - public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } } - public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); } - public string Status { get => _status; private set => SetProperty(ref _status, value); } - public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } } - public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } } - public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } } - public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing; - public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing; - public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览"; - public string RecordButtonText => IsRecording ? "停止录像" : "开始录像"; - public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); } - public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); } - public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } } - public double RecordingFps { get; set; } = 30; - public DelegateCommand RefreshCommand { get; } - public DelegateCommand PreviewCommand { get; } - public DelegateCommand RecordCommand { get; } - public DelegateCommand BrowseCommand { get; } - public DelegateCommand RevealCommand { get; } - - public CameraViewModel(ICameraService camera, string root) - { - _camera = camera; _dispatcher = Application.Current.Dispatcher; - _directory = Path.Combine(root, "workspace", "recordings"); - _settingsPath = Path.Combine(root, "workspace", "camera-settings.json"); - try - { - if (File.Exists(_settingsPath)) - { - using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath)); - SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory; - } - } - catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; } - RefreshCommand = Command(RefreshAsync, () => CanChooseCamera); - PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null)); - RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame))); - BrowseCommand = Command(() => - { - var picker = new OpenFolderDialog { Title = "选择录像保存目录" }; - if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory; - if (picker.ShowDialog() == true) { SaveDirectory = picker.FolderName; SaveSettings(); } - return Task.CompletedTask; - }, () => CanChangeDirectory); - RevealCommand = Command(() => - { - if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording)) - { - var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true }; - info.ArgumentList.Add("/select," + LastRecording); Process.Start(info); - } - else - { - Directory.CreateDirectory(SaveDirectory); - var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true }; - info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info); - } - return Task.CompletedTask; - }, () => !IsBusy && !_closing); - _camera.FrameArrived += OnFrame; - _camera.ConnectionChanged += OnConnection; - _camera.Error += OnError; - _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher); - _timer.Start(); - } - - private DelegateCommand Command(Func action, Func canExecute) - { - var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute); - _commands.Add(command); return command; - } - private async Task PerformAsync(Func action) - { - if (IsBusy || _closing) return; - IsBusy = true; - try { await action(); } - catch (Exception e) { Status = e.Message; } - finally { IsBusy = false; } - } - private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); } - private void StateChanged() - { - RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory)); - RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands(); - } - private async Task RefreshAsync() - { - Status = "正在枚举 UVC / 海康相机…"; - var devices = await _camera.EnumerateAsync(); - if (_closing) return; - Cameras.Clear(); foreach (var device in devices) Cameras.Add(device); - SelectedCamera = Cameras.FirstOrDefault(); - Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机"; - } - private async Task TogglePreviewAsync() - { - if (IsPreviewing) - { - StopRecording(); - await Task.Run(_camera.Disconnect); - ClearPreview(); IsPreviewing = false; Status = "相机已关闭"; - return; - } - var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机"); - Status = "正在连接 " + selected.Name; - if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用"); - if (_closing) return; - if (!await _camera.StartAsync()) - { - await Task.Run(_camera.Disconnect); - throw new IOException("相机已连接,但采集启动失败"); - } - IsPreviewing = true; Status = "相机预览中,可开始录像"; - } - private Task ToggleRecordingAsync() - { - if (IsRecording) { StopRecording(); return Task.CompletedTask; } - if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录"); - var directory = Path.GetFullPath(SaveDirectory.Trim()); - SaveDirectory = directory; SaveSettings(); - lock (_frames) - { - if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览"); - if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像"); - LastRecording = _recorder.Start(directory, _latest, RecordingFps); - } - IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick(); - return Task.CompletedTask; - } - private void StopRecording() - { - RecordingResult? result; - lock (_frames) result = _recorder.Stop(); - IsRecording = false; - if (result != null) - { - LastRecording = result.Path; - RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧"; - Status = "录像已保存,可在主窗口导入视频继续标注"; - } - } - private void OnFrame(CameraFrame frame) - { - if (_closing) return; - BitmapSource? preview = null; - string? recordingError = null; - var generation = Volatile.Read(ref _generation); - lock (_frames) - { - if (_closing) return; - Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp()); - if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest); - try { _recorder.Write(frame.Bgr); } - catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; } - if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0) - { - try - { - var stride = checked((int)frame.Bgr.Step()); - preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24, - null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride); - preview.Freeze(); _previewClock.Restart(); - } - catch { Interlocked.Exchange(ref _previewPending, 0); throw; } - } - } - if (recordingError != null) - { - var error = recordingError; - Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; }); - } - if (preview != null) - { - var bitmap = preview; - Post(() => - { - try - { - if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); } - } - finally { Interlocked.Exchange(ref _previewPending, 0); } - }); - } - } - private void OnConnection(bool connected) - { - if (!connected) Post(() => - { - if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection. - StopRecording(); IsPreviewing = false; ClearPreview(); - }); - } - private void OnError(string message) => Post(() => Status = message); - private void Post(Action action) - { - if (!_closing && !_dispatcher.HasShutdownStarted) - _dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background); - } - private void Tick() - { - if (_closing) return; - if (IsRecording) - { - if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2) - { - StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接"; - } - else if (!_recorder.IsRecording) IsRecording = false; - else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps"; - } - if (IsPreviewing && !_camera.IsGrabbing && !IsBusy) - { - StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接"; - } - } - private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 && - Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2; - private void ClearPreview() - { - Interlocked.Increment(ref _generation); - lock (_frames) { _latest?.Dispose(); _latest = null; } - Preview = null; - } - private void SaveSettings() - { - Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!); - File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory })); - } - public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync(); - private async Task ShutdownCoreAsync() - { - _closing = true; _timer.Stop(); StateChanged(); - await _operation; - try { await Task.Run(_camera.Dispose); } - finally - { - try { StopRecording(); } - finally - { - ClearPreview(); - _camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError; - IsPreviewing = false; - } - } - } -} diff --git a/src/SopHelper.App/Training/CameraWindow.xaml b/src/SopHelper.App/Training/CameraWindow.xaml deleted file mode 100644 index 7764281..0000000 --- a/src/SopHelper.App/Training/CameraWindow.xaml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - -