diff --git a/Hardware-Vue/.env.example b/Hardware-Vue/.env.example new file mode 100644 index 0000000..277f952 --- /dev/null +++ b/Hardware-Vue/.env.example @@ -0,0 +1,6 @@ +# 前端构建产物会请求同源的 /api 与 /cameraHub。 +# 如果前后端分离部署,可在这里改成后端绝对地址,例如 http://192.168.1.10:5062 +# VITE_API_BASE= + +# 开发期 Vite 代理的上游地址(vite.config.ts 读取) +# VITE_BACKEND_URL=http://localhost:5062 diff --git a/Hardware-Vue/.gitignore b/Hardware-Vue/.gitignore new file mode 100644 index 0000000..0e41f4a --- /dev/null +++ b/Hardware-Vue/.gitignore @@ -0,0 +1,9 @@ +node_modules +dist +dist-ssr +*.local +.env +.env.*.local +.vite +.DS_Store +*.log diff --git a/Hardware-Vue/.idea/.gitignore b/Hardware-Vue/.idea/.gitignore new file mode 100644 index 0000000..b6b1ecf --- /dev/null +++ b/Hardware-Vue/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 已忽略包含查询文件的默认文件夹 +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ diff --git a/Hardware-Vue/.idea/Hardware-Vue.iml b/Hardware-Vue/.idea/Hardware-Vue.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/Hardware-Vue/.idea/Hardware-Vue.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/Hardware-Vue/.idea/misc.xml b/Hardware-Vue/.idea/misc.xml new file mode 100644 index 0000000..6f29fee --- /dev/null +++ b/Hardware-Vue/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Hardware-Vue/.idea/modules.xml b/Hardware-Vue/.idea/modules.xml new file mode 100644 index 0000000..b4459d9 --- /dev/null +++ b/Hardware-Vue/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Hardware-Vue/README.md b/Hardware-Vue/README.md new file mode 100644 index 0000000..43cc8ca --- /dev/null +++ b/Hardware-Vue/README.md @@ -0,0 +1,175 @@ +# Hardware-Vue + +LIBS Lab 激光诱导击穿光谱元素分析系统的 Vue 3 前端,依据 `Image` 文件夹中的 1~5 号设计图重新实现。 + +## 流程 + +``` +首页 1.png + ├─ 元素检测 ──→ 放置待测样品 2.png ──开始检测──→ 轮廓识别与点位规划 3.png + │ │ 15s + │ ↓ + │ 光谱采集与分析 4.png + │ │ 10s + │ ↓ + └────────────── 60s 自动关闭 / 关闭按钮 ──────── 检测完成 5.png +``` + +- 首页其余三个模块点击后弹出「研发中」提示框。 +- 3、4、5 页面除计时进度与返回逻辑外,业务数据均为静态展示。 + +## 界面预览 + +| 首页 | 放置待测样品 | +| --- | --- | +| ![首页](docs/preview-home.png) | ![放置待测样品](docs/preview-sample.png) | + +| 轮廓识别与点位规划 | 光谱采集与分析 | +| --- | --- | +| ![点位规划](docs/preview-scan.png) | ![光谱采集](docs/preview-spectrum.png) | + +| 检测完成 | 研发中提示 | +| --- | --- | +| ![检测完成](docs/preview-result.png) | ![研发中提示](docs/preview-modal.png) | + +## 页面与交互 + +| 页面 | 路由 | 交互 | +| --- | --- | --- | +| 首页 | `/` | 左上角展示 `logo.png`;右侧播放 `Principle.mp4`;点击「元素检测」进入 `/sample`,其余三个模块弹出研发中提示 | +| 放置待测样品 | `/sample` | 左侧相机实时画面;「返回」回首页;「开始检测」进入 `/scan`;「预览对焦」暂时弹出提示 | +| 轮廓识别与点位规划 | `/scan` | 进度条 15s 后自动进入 `/spectrum`;「中止流程」与右上角关闭回首页 | +| 光谱采集与分析 | `/spectrum` | 进度条 10s 后自动进入 `/result`;「中止流程」回首页 | +| 检测完成 | `/result` | 60s 倒计时结束自动回首页;「关闭」立即回首页;「导出报告」暂时弹出提示 | +| 兼容路由 | `/pay` | 重定向到 `/sample` | + +设计稿按 **1920 × 1080** 制作,使用 `transform: scale()` 整体等比缩放适配不同分辨率;1920×1080 与 1366×768 均已验证。 + +## 技术栈 + +| 用途 | 选型 | +| --- | --- | +| 框架 | Vue 3 + TypeScript(` + + diff --git a/Hardware-Vue/package.json b/Hardware-Vue/package.json new file mode 100644 index 0000000..921ec99 --- /dev/null +++ b/Hardware-Vue/package.json @@ -0,0 +1,24 @@ +{ + "name": "hardware-vue", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview", + "type-check": "vue-tsc --noEmit" + }, + "dependencies": { + "@microsoft/signalr": "^8.0.7", + "vue": "^3.5.13", + "vue-router": "^4.5.0" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "@vitejs/plugin-vue": "^5.2.1", + "typescript": "~5.7.3", + "vite": "^6.0.7", + "vue-tsc": "^2.2.0" + } +} diff --git a/Hardware-Vue/pnpm-lock.yaml b/Hardware-Vue/pnpm-lock.yaml new file mode 100644 index 0000000..d86b930 --- /dev/null +++ b/Hardware-Vue/pnpm-lock.yaml @@ -0,0 +1,1161 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@microsoft/signalr': + specifier: ^8.0.7 + version: 8.0.29 + vue: + specifier: ^3.5.13 + version: 3.5.44(typescript@5.7.3) + vue-router: + specifier: ^4.5.0 + version: 4.6.4(vue@3.5.44(typescript@5.7.3)) + devDependencies: + '@types/node': + specifier: ^22.10.5 + version: 22.20.5 + '@vitejs/plugin-vue': + specifier: ^5.2.1 + version: 5.2.4(vite@6.4.5(@types/node@22.20.5))(vue@3.5.44(typescript@5.7.3)) + typescript: + specifier: ~5.7.3 + version: 5.7.3 + vite: + specifier: ^6.0.7 + version: 6.4.5(@types/node@22.20.5) + vue-tsc: + specifier: ^2.2.0 + version: 2.2.12(typescript@5.7.3) + +packages: + + '@babel/helper-string-parser@7.29.11': + resolution: {integrity: sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.12': + resolution: {integrity: sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/types@7.29.11': + resolution: {integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==} + engines: {node: '>=6.9.0'} + + '@esbuild/aix-ppc64@0.25.12': + resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.25.12': + resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.25.12': + resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.25.12': + resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.25.12': + resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.25.12': + resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.25.12': + resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.25.12': + resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.25.12': + resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.25.12': + resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.25.12': + resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.25.12': + resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.25.12': + resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.25.12': + resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.25.12': + resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.25.12': + resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.25.12': + resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.25.12': + resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.25.12': + resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.25.12': + resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.25.12': + resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.25.12': + resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.25.12': + resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.25.12': + resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.25.12': + resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.25.12': + resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@microsoft/signalr@8.0.29': + resolution: {integrity: sha512-yzszFiTAuRxHm3qxNaSan3YzN8dffLqQcc3ZNJD2tn9eInCBBi7u2xCJ6AVNXjw19RDoBc+NPWfYN43K1HcjdA==} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-android-arm-eabi@4.67.4': + resolution: {integrity: sha512-/v/pUAPOcwp+r1Hjjdg0cBV1TE89CzGKrKh2FgkIQw2QBcIMmVPOCSfuOZStCn4Xh/98HXfo/ht6ztcssctPNg==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.67.4': + resolution: {integrity: sha512-6tmmB/P52Vt167FXXEw5auiEUgTtZz7aqUgWHqYXToIUE0HFDY6fTdAyeekjjsNk6O/8dtpSKtClxSj1mMneKQ==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-android-x64@4.67.4': + resolution: {integrity: sha512-8Z9Q4RmotVmuL4llOvqX814JNiOK1oqoBv+glG5KbpRfUiypqzz2/fxIzK4Pq129l4dT5a8Gszmpc0/XPYoFuQ==} + cpu: [x64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.67.4': + resolution: {integrity: sha512-pnq6hssxTtwuRAl6Kdi/+IDY+b1IhkUetjhUkdLAAJCssjfqtL2Oqy/FXJVJFtAWOu1oRlArIvf0Yk1O92x2HQ==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.67.4': + resolution: {integrity: sha512-BeIrGZvHMVdJg/N+ohZfFywG/gF41684YhDj2wBvouj7m9ziP1tZDUNwzXRiDY+3WIKngaC4hiUBqVtBPGP5og==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.67.4': + resolution: {integrity: sha512-fRFX/oqNg/g780DKoS8RIfYcZD59Ru5O/bSeK1N7gQljBFrTxJY/q5EX4eMs5SrJf32VgVBVVYCdfPpzAwPPnQ==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.67.4': + resolution: {integrity: sha512-bSrBRopG1q+0RuOsW0NtYTtIODlvNA3T3ebx5WnQVdSxWIoXFmj+rZdHUHdSLgFdZ5M6VGmekYE7r4RMGQXjfg==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.67.4': + resolution: {integrity: sha512-L8IvdrJVtl65g1ozwDSyjGPG+FmibhCdFUwmqTItJLw0S3+Oj4QzFs7rfgTUiK7rsPjkCLdG1/GApFxoynXFJQ==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.67.4': + resolution: {integrity: sha512-h7PcoQOzC31jshNpQ48J0akB9tsghjkSjSl5AZ6XsVGTxVsln7t7C4SQyw62tNVSaz2SeHgk4VT2ELbL17BSHQ==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.67.4': + resolution: {integrity: sha512-KSPuOBNHoOl7AsVjeY1KZci8+0up0U4TFAHU5IzBYN8P+Z6cB9DZq28+JQycZW7f6WLLa/tSzhV7Rdy95bVi+g==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.67.4': + resolution: {integrity: sha512-0E/mKmVk1PlQeQYygIwQm0jlwjANTzGSiNBMPrFx+rdFGFj/2Axh4p6XwcrystQIqXZVudTaGsdbDpzYgJ4wSA==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.67.4': + resolution: {integrity: sha512-Fvw7dOSc2Sa9UOipRZVI0zOgdLCzsjVyD/6JuHXzUHTXFu7mMgmeX/0/bCVBIut1dz+nWz3pV4WpS/Qg0XVnxw==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.67.4': + resolution: {integrity: sha512-jzxbVHaE7V3F+P0wEK7UydQtvv7Twfdtx58jI5/3VRx1jJxyrn+qFwfXmqjVFxPhBl+zjaRs+ZJMFJw7vdHaQA==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.67.4': + resolution: {integrity: sha512-fhtrzp9p4GjEJVaigaap9g6X9nP6xgJtKiLLXSDgpE18HXufA5aqfltGn+KAqMtVZReJZfOrXm//y5YSA9BWbA==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.67.4': + resolution: {integrity: sha512-uynaF7IUHwAckV0S+yC1f5esy9gB+aqCBsPH5BOck32TYdCuAn2lVG5tvUcFnEsrviGEmRZxE1NHSOieUPYJEg==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.67.4': + resolution: {integrity: sha512-uaqRFdfb8eIa2bVHN/FE3ndCvR0zV2xv0AwjCfxrqSu6l6fp/54VhjfhslKlf2RIik9L1jwlt4E56PeVX6tQtQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.67.4': + resolution: {integrity: sha512-JZRow7kmxUDEASnxHuVG5itTm+nTXi9BQUABcVUnUEngC+OPwMrpx1uJ9hIA/v+IcAEBL52ktCSPXk5OJn9Jqg==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.67.4': + resolution: {integrity: sha512-rdrh4e+Lq9fCNKoDPaCqeHXbQCe7yl77Ukl45tlSClwYdZ1gpFGZz1XLJdYtY++FRlfL5aHvb6/0n3GDW/Nxsw==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.67.4': + resolution: {integrity: sha512-wL7MS4r0fYcxluF3ne2plofHZiB/LsqNCnyaUlyiKpAJLb6agPSFz7DEFCfkonWAZXMrLwCmC08b2ZEnEdJkog==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.67.4': + resolution: {integrity: sha512-4H0XHfd2VufGjX7NjUyeue78sD0bRIoKSGjGqO+F5nSvL6jN48NAU7esdmtFEYxZXwObLtt3MJ/kHS0jASMW3g==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.67.4': + resolution: {integrity: sha512-osRHQbE55pZpCLetpMsFmhkapyZnAUH73qRKMh+npi3boUom6u6hdaTTPSxlInXxwJHsn9r2uDhdz0V7Yoxx2A==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.67.4': + resolution: {integrity: sha512-95+exYEyOwrZePsE0czi4q7X5lxKPa21+lmyAZlwbYENITQ0Unk4HAQAFp/p+KhXBHBx9mUABXRYjOC5A1wY3Q==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.67.4': + resolution: {integrity: sha512-FOXOcKhNQpO4Po+Ynan6IbtM67SrXZbgpRJWVYwz53CT5veI7sVzDwVBmWS65N5Imv+wK3SVhIPAl+C5DXXNCg==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.67.4': + resolution: {integrity: sha512-cklKh0gJOkAZQcWziQa3hrjxZKN+PCHZ7SPTyGJDAiBVr05ZXlEjGFCG7zFJMaVibxsmzAe1FimN4u/HBns9+Q==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.67.4': + resolution: {integrity: sha512-AegwxJPc9bvUp8fQtlsUHkFMOMkGylWU7glyL+YD4vwG+QaYoGXYLSsQoeTD7kvoLZrVlMWNVhTg1dedY5C1VQ==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.67.4': + resolution: {integrity: sha512-RJZnrwTWj7Iq2ooBwoGbDdC65tDwYawneGcAfFMJqVUrRZMcskka6nTkBpXR/47G7kzn3EW2qupExnaBy11vwg==} + cpu: [x64] + os: [win32] + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@vitejs/plugin-vue@5.2.4': + resolution: {integrity: sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==} + engines: {node: ^18.0.0 || >=20.0.0} + peerDependencies: + vite: ^5.0.0 || ^6.0.0 + vue: ^3.2.25 + + '@volar/language-core@2.4.15': + resolution: {integrity: sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA==} + + '@volar/source-map@2.4.15': + resolution: {integrity: sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg==} + + '@volar/typescript@2.4.15': + resolution: {integrity: sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@vue/compiler-core@3.5.44': + resolution: {integrity: sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ==} + + '@vue/compiler-dom@3.5.44': + resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==} + + '@vue/compiler-sfc@3.5.44': + resolution: {integrity: sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw==} + + '@vue/compiler-ssr@3.5.44': + resolution: {integrity: sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA==} + + '@vue/compiler-vue2@2.7.16': + resolution: {integrity: sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A==} + + '@vue/devtools-api@6.6.4': + resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==} + + '@vue/language-core@2.2.12': + resolution: {integrity: sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@vue/reactivity@3.5.44': + resolution: {integrity: sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw==} + + '@vue/runtime-core@3.5.44': + resolution: {integrity: sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ==} + + '@vue/runtime-dom@3.5.44': + resolution: {integrity: sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg==} + + '@vue/server-renderer@3.5.44': + resolution: {integrity: sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ==} + + '@vue/shared@3.5.44': + resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==} + + abort-controller@3.0.0: + resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} + engines: {node: '>=6.5'} + + alien-signals@1.0.13: + resolution: {integrity: sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg==} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + brace-expansion@2.1.7: + resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + de-indent@1.0.2: + resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + esbuild@0.25.12: + resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@2.0.2: + resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + + event-target-shim@5.0.1: + resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} + engines: {node: '>=6'} + + eventsource@2.0.2: + resolution: {integrity: sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fetch-cookie@2.2.0: + resolution: {integrity: sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + he@1.2.0: + resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} + hasBin: true + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + minimatch@9.0.9: + resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + engines: {node: '>=16 || 14 >=14.17'} + + muggle-string@0.4.1: + resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + node-fetch@2.7.0: + resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} + engines: {node: 4.x || >=6.0.0} + peerDependencies: + encoding: ^0.1.0 + peerDependenciesMeta: + encoding: + optional: true + + path-browserify@1.0.1: + resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + psl@1.15.0: + resolution: {integrity: sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + querystringify@2.2.0: + resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} + + requires-port@1.0.0: + resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} + + rollup@4.67.4: + resolution: {integrity: sha512-Lsv3oKcz5jgOQJej/p7nfwbVEdAbDT+z6OPf/SCdI+nF+q2ENp0pTKT35ZwXAmH8g45mfrIiJeEyAqKYSYoL9Q==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + set-cookie-parser@2.7.3: + resolution: {integrity: sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tough-cookie@4.1.4: + resolution: {integrity: sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==} + engines: {node: '>=6'} + + tr46@0.0.3: + resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} + + typescript@5.7.3: + resolution: {integrity: sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + universalify@0.2.0: + resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==} + engines: {node: '>= 4.0.0'} + + url-parse@1.5.10: + resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==} + + vite@6.4.5: + resolution: {integrity: sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + jiti: '>=1.21.0' + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vscode-uri@3.2.0: + resolution: {integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==} + + vue-router@4.6.4: + resolution: {integrity: sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==} + peerDependencies: + vue: ^3.5.0 + + vue-tsc@2.2.12: + resolution: {integrity: sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw==} + hasBin: true + peerDependencies: + typescript: '>=5.0.0' + + vue@3.5.44: + resolution: {integrity: sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + webidl-conversions@3.0.1: + resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} + + whatwg-url@5.0.0: + resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + + ws@7.5.13: + resolution: {integrity: sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==} + engines: {node: '>=8.3.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ^5.0.2 + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + +snapshots: + + '@babel/helper-string-parser@7.29.11': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/parser@7.29.12': + dependencies: + '@babel/types': 7.29.11 + + '@babel/types@7.29.11': + dependencies: + '@babel/helper-string-parser': 7.29.11 + '@babel/helper-validator-identifier': 7.29.7 + + '@esbuild/aix-ppc64@0.25.12': + optional: true + + '@esbuild/android-arm64@0.25.12': + optional: true + + '@esbuild/android-arm@0.25.12': + optional: true + + '@esbuild/android-x64@0.25.12': + optional: true + + '@esbuild/darwin-arm64@0.25.12': + optional: true + + '@esbuild/darwin-x64@0.25.12': + optional: true + + '@esbuild/freebsd-arm64@0.25.12': + optional: true + + '@esbuild/freebsd-x64@0.25.12': + optional: true + + '@esbuild/linux-arm64@0.25.12': + optional: true + + '@esbuild/linux-arm@0.25.12': + optional: true + + '@esbuild/linux-ia32@0.25.12': + optional: true + + '@esbuild/linux-loong64@0.25.12': + optional: true + + '@esbuild/linux-mips64el@0.25.12': + optional: true + + '@esbuild/linux-ppc64@0.25.12': + optional: true + + '@esbuild/linux-riscv64@0.25.12': + optional: true + + '@esbuild/linux-s390x@0.25.12': + optional: true + + '@esbuild/linux-x64@0.25.12': + optional: true + + '@esbuild/netbsd-arm64@0.25.12': + optional: true + + '@esbuild/netbsd-x64@0.25.12': + optional: true + + '@esbuild/openbsd-arm64@0.25.12': + optional: true + + '@esbuild/openbsd-x64@0.25.12': + optional: true + + '@esbuild/openharmony-arm64@0.25.12': + optional: true + + '@esbuild/sunos-x64@0.25.12': + optional: true + + '@esbuild/win32-arm64@0.25.12': + optional: true + + '@esbuild/win32-ia32@0.25.12': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@microsoft/signalr@8.0.29': + dependencies: + abort-controller: 3.0.0 + eventsource: 2.0.2 + fetch-cookie: 2.2.0 + node-fetch: 2.7.0 + ws: 7.5.13 + transitivePeerDependencies: + - bufferutil + - encoding + - utf-8-validate + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@rollup/rollup-android-arm-eabi@4.67.4': + optional: true + + '@rollup/rollup-android-arm64@4.67.4': + optional: true + + '@rollup/rollup-android-x64@4.67.4': + optional: true + + '@rollup/rollup-darwin-arm64@4.67.4': + optional: true + + '@rollup/rollup-darwin-x64@4.67.4': + optional: true + + '@rollup/rollup-freebsd-arm64@4.67.4': + optional: true + + '@rollup/rollup-freebsd-x64@4.67.4': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.67.4': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.67.4': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.67.4': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.67.4': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.67.4': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.67.4': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.67.4': + optional: true + + '@rollup/rollup-linux-x64-musl@4.67.4': + optional: true + + '@rollup/rollup-openbsd-x64@4.67.4': + optional: true + + '@rollup/rollup-openharmony-arm64@4.67.4': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.67.4': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.67.4': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.67.4': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.67.4': + optional: true + + '@types/estree@1.0.10': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 6.21.0 + + '@vitejs/plugin-vue@5.2.4(vite@6.4.5(@types/node@22.20.5))(vue@3.5.44(typescript@5.7.3))': + dependencies: + vite: 6.4.5(@types/node@22.20.5) + vue: 3.5.44(typescript@5.7.3) + + '@volar/language-core@2.4.15': + dependencies: + '@volar/source-map': 2.4.15 + + '@volar/source-map@2.4.15': {} + + '@volar/typescript@2.4.15(typescript@5.7.3)': + dependencies: + '@volar/language-core': 2.4.15 + path-browserify: 1.0.1 + vscode-uri: 3.2.0 + optionalDependencies: + typescript: 5.7.3 + + '@vue/compiler-core@3.5.44': + dependencies: + '@babel/parser': 7.29.12 + '@vue/shared': 3.5.44 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.2.2 + + '@vue/compiler-dom@3.5.44': + dependencies: + '@vue/compiler-core': 3.5.44 + '@vue/shared': 3.5.44 + + '@vue/compiler-sfc@3.5.44': + dependencies: + '@babel/parser': 7.29.12 + '@vue/compiler-core': 3.5.44 + '@vue/compiler-dom': 3.5.44 + '@vue/compiler-ssr': 3.5.44 + '@vue/shared': 3.5.44 + estree-walker: 2.0.2 + magic-string: 0.30.21 + postcss: 8.5.32 + source-map-js: 1.2.2 + + '@vue/compiler-ssr@3.5.44': + dependencies: + '@vue/compiler-dom': 3.5.44 + '@vue/shared': 3.5.44 + + '@vue/compiler-vue2@2.7.16': + dependencies: + de-indent: 1.0.2 + he: 1.2.0 + + '@vue/devtools-api@6.6.4': {} + + '@vue/language-core@2.2.12(typescript@5.7.3)': + dependencies: + '@volar/language-core': 2.4.15 + '@vue/compiler-dom': 3.5.44 + '@vue/compiler-vue2': 2.7.16 + '@vue/shared': 3.5.44 + alien-signals: 1.0.13 + minimatch: 9.0.9 + muggle-string: 0.4.1 + path-browserify: 1.0.1 + optionalDependencies: + typescript: 5.7.3 + + '@vue/reactivity@3.5.44': + dependencies: + '@vue/shared': 3.5.44 + + '@vue/runtime-core@3.5.44': + dependencies: + '@vue/reactivity': 3.5.44 + '@vue/shared': 3.5.44 + + '@vue/runtime-dom@3.5.44': + dependencies: + '@vue/reactivity': 3.5.44 + '@vue/runtime-core': 3.5.44 + '@vue/shared': 3.5.44 + csstype: 3.2.3 + + '@vue/server-renderer@3.5.44': + dependencies: + '@vue/compiler-ssr': 3.5.44 + '@vue/runtime-dom': 3.5.44 + '@vue/shared': 3.5.44 + + '@vue/shared@3.5.44': {} + + abort-controller@3.0.0: + dependencies: + event-target-shim: 5.0.1 + + alien-signals@1.0.13: {} + + balanced-match@1.0.2: {} + + brace-expansion@2.1.7: + dependencies: + balanced-match: 1.0.2 + + csstype@3.2.3: {} + + de-indent@1.0.2: {} + + entities@7.0.1: {} + + esbuild@0.25.12: + optionalDependencies: + '@esbuild/aix-ppc64': 0.25.12 + '@esbuild/android-arm': 0.25.12 + '@esbuild/android-arm64': 0.25.12 + '@esbuild/android-x64': 0.25.12 + '@esbuild/darwin-arm64': 0.25.12 + '@esbuild/darwin-x64': 0.25.12 + '@esbuild/freebsd-arm64': 0.25.12 + '@esbuild/freebsd-x64': 0.25.12 + '@esbuild/linux-arm': 0.25.12 + '@esbuild/linux-arm64': 0.25.12 + '@esbuild/linux-ia32': 0.25.12 + '@esbuild/linux-loong64': 0.25.12 + '@esbuild/linux-mips64el': 0.25.12 + '@esbuild/linux-ppc64': 0.25.12 + '@esbuild/linux-riscv64': 0.25.12 + '@esbuild/linux-s390x': 0.25.12 + '@esbuild/linux-x64': 0.25.12 + '@esbuild/netbsd-arm64': 0.25.12 + '@esbuild/netbsd-x64': 0.25.12 + '@esbuild/openbsd-arm64': 0.25.12 + '@esbuild/openbsd-x64': 0.25.12 + '@esbuild/openharmony-arm64': 0.25.12 + '@esbuild/sunos-x64': 0.25.12 + '@esbuild/win32-arm64': 0.25.12 + '@esbuild/win32-ia32': 0.25.12 + '@esbuild/win32-x64': 0.25.12 + + estree-walker@2.0.2: {} + + event-target-shim@5.0.1: {} + + eventsource@2.0.2: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fetch-cookie@2.2.0: + dependencies: + set-cookie-parser: 2.7.3 + tough-cookie: 4.1.4 + + fsevents@2.3.3: + optional: true + + he@1.2.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + minimatch@9.0.9: + dependencies: + brace-expansion: 2.1.7 + + muggle-string@0.4.1: {} + + nanoid@3.3.20: {} + + node-fetch@2.7.0: + dependencies: + whatwg-url: 5.0.0 + + path-browserify@1.0.1: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + psl@1.15.0: + dependencies: + punycode: 2.3.1 + + punycode@2.3.1: {} + + querystringify@2.2.0: {} + + requires-port@1.0.0: {} + + rollup@4.67.4: + dependencies: + '@types/estree': 1.0.10 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.67.4 + '@rollup/rollup-android-arm64': 4.67.4 + '@rollup/rollup-android-x64': 4.67.4 + '@rollup/rollup-darwin-arm64': 4.67.4 + '@rollup/rollup-darwin-x64': 4.67.4 + '@rollup/rollup-freebsd-arm64': 4.67.4 + '@rollup/rollup-freebsd-x64': 4.67.4 + '@rollup/rollup-linux-arm-gnueabihf': 4.67.4 + '@rollup/rollup-linux-arm-musleabihf': 4.67.4 + '@rollup/rollup-linux-arm64-gnu': 4.67.4 + '@rollup/rollup-linux-arm64-musl': 4.67.4 + '@rollup/rollup-linux-loong64-gnu': 4.67.4 + '@rollup/rollup-linux-loong64-musl': 4.67.4 + '@rollup/rollup-linux-ppc64-gnu': 4.67.4 + '@rollup/rollup-linux-ppc64-musl': 4.67.4 + '@rollup/rollup-linux-riscv64-gnu': 4.67.4 + '@rollup/rollup-linux-riscv64-musl': 4.67.4 + '@rollup/rollup-linux-s390x-gnu': 4.67.4 + '@rollup/rollup-linux-x64-gnu': 4.67.4 + '@rollup/rollup-linux-x64-musl': 4.67.4 + '@rollup/rollup-openbsd-x64': 4.67.4 + '@rollup/rollup-openharmony-arm64': 4.67.4 + '@rollup/rollup-win32-arm64-msvc': 4.67.4 + '@rollup/rollup-win32-ia32-msvc': 4.67.4 + '@rollup/rollup-win32-x64-gnu': 4.67.4 + '@rollup/rollup-win32-x64-msvc': 4.67.4 + fsevents: 2.3.3 + + set-cookie-parser@2.7.3: {} + + source-map-js@1.2.2: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tough-cookie@4.1.4: + dependencies: + psl: 1.15.0 + punycode: 2.3.1 + universalify: 0.2.0 + url-parse: 1.5.10 + + tr46@0.0.3: {} + + typescript@5.7.3: {} + + undici-types@6.21.0: {} + + universalify@0.2.0: {} + + url-parse@1.5.10: + dependencies: + querystringify: 2.2.0 + requires-port: 1.0.0 + + vite@6.4.5(@types/node@22.20.5): + dependencies: + esbuild: 0.25.12 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + postcss: 8.5.32 + rollup: 4.67.4 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 22.20.5 + fsevents: 2.3.3 + + vscode-uri@3.2.0: {} + + vue-router@4.6.4(vue@3.5.44(typescript@5.7.3)): + dependencies: + '@vue/devtools-api': 6.6.4 + vue: 3.5.44(typescript@5.7.3) + + vue-tsc@2.2.12(typescript@5.7.3): + dependencies: + '@volar/typescript': 2.4.15(typescript@5.7.3) + '@vue/language-core': 2.2.12(typescript@5.7.3) + typescript: 5.7.3 + + vue@3.5.44(typescript@5.7.3): + dependencies: + '@vue/compiler-dom': 3.5.44 + '@vue/compiler-sfc': 3.5.44 + '@vue/runtime-dom': 3.5.44 + '@vue/server-renderer': 3.5.44 + '@vue/shared': 3.5.44 + optionalDependencies: + typescript: 5.7.3 + + webidl-conversions@3.0.1: {} + + whatwg-url@5.0.0: + dependencies: + tr46: 0.0.3 + webidl-conversions: 3.0.1 + + ws@7.5.13: {} diff --git a/Hardware-Vue/pnpm-workspace.yaml b/Hardware-Vue/pnpm-workspace.yaml new file mode 100644 index 0000000..f2754f0 --- /dev/null +++ b/Hardware-Vue/pnpm-workspace.yaml @@ -0,0 +1,4 @@ +nodeLinker: hoisted +verifyDepsBeforeRun: false +allowBuilds: + esbuild: true diff --git a/Hardware-Vue/public/media/Principle.mp4 b/Hardware-Vue/public/media/Principle.mp4 new file mode 100644 index 0000000..04d9801 Binary files /dev/null and b/Hardware-Vue/public/media/Principle.mp4 differ diff --git a/Hardware-Vue/public/media/Principle_old.mp4 b/Hardware-Vue/public/media/Principle_old.mp4 new file mode 100644 index 0000000..cb79499 Binary files /dev/null and b/Hardware-Vue/public/media/Principle_old.mp4 differ diff --git a/Hardware-Vue/src/App.vue b/Hardware-Vue/src/App.vue new file mode 100644 index 0000000..257df4c --- /dev/null +++ b/Hardware-Vue/src/App.vue @@ -0,0 +1,14 @@ + + + diff --git a/Hardware-Vue/src/api/camera.ts b/Hardware-Vue/src/api/camera.ts new file mode 100644 index 0000000..a343e52 --- /dev/null +++ b/Hardware-Vue/src/api/camera.ts @@ -0,0 +1,78 @@ +/** + * USB 相机接口封装。 + * 后端实现见 HardwareWeb/Controllers/CameraController.cs: + * GET /api/camera/status -> { connected: boolean } + * POST /api/camera/connect -> { connected: boolean } + * POST /api/camera/disconnect -> { connected: boolean } + */ + +export interface CameraStatus { + connected: boolean +} + +const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '') +const REQUEST_TIMEOUT = 5000 + +export class CameraApiError extends Error { + readonly status: number + + constructor(message: string, status = 0) { + super(message) + this.name = 'CameraApiError' + this.status = status + } +} + +async function request(path: string, init?: RequestInit): Promise { + const controller = new AbortController() + const timer = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT) + + try { + const response = await fetch(`${API_BASE}${path}`, { + ...init, + cache: 'no-store', + signal: controller.signal, + headers: { + Accept: 'application/json', + ...(init?.headers ?? {}), + }, + }) + + if (!response.ok) { + let detail = `HTTP ${response.status}` + try { + const body = (await response.json()) as { message?: string; error?: string } + detail = body.message ?? body.error ?? detail + } catch { + // 响应不是 JSON 时保留状态码信息 + } + throw new CameraApiError(detail, response.status) + } + + return (await response.json()) as T + } catch (error) { + if (error instanceof CameraApiError) throw error + if (error instanceof DOMException && error.name === 'AbortError') { + throw new CameraApiError('相机服务响应超时') + } + throw new CameraApiError(error instanceof Error ? error.message : '无法连接相机服务') + } finally { + window.clearTimeout(timer) + } +} + +export function getCameraStatus(): Promise { + return request('/api/camera/status') +} + +export function connectCamera(): Promise { + return request('/api/camera/connect', { method: 'POST' }) +} + +export function disconnectCamera(): Promise { + return request('/api/camera/disconnect', { method: 'POST' }) +} + +export function getCameraHubUrl(): string { + return `${API_BASE}/cameraHub` +} diff --git a/Hardware-Vue/src/assets/camera-placeholder.webp b/Hardware-Vue/src/assets/camera-placeholder.webp new file mode 100644 index 0000000..af77e93 Binary files /dev/null and b/Hardware-Vue/src/assets/camera-placeholder.webp differ diff --git a/Hardware-Vue/src/assets/logo.png b/Hardware-Vue/src/assets/logo.png new file mode 100644 index 0000000..e713369 Binary files /dev/null and b/Hardware-Vue/src/assets/logo.png differ diff --git a/Hardware-Vue/src/assets/report-qr.png b/Hardware-Vue/src/assets/report-qr.png new file mode 100644 index 0000000..463e7b3 Binary files /dev/null and b/Hardware-Vue/src/assets/report-qr.png differ diff --git a/Hardware-Vue/src/components/AppStage.vue b/Hardware-Vue/src/components/AppStage.vue new file mode 100644 index 0000000..08c6eb3 --- /dev/null +++ b/Hardware-Vue/src/components/AppStage.vue @@ -0,0 +1,36 @@ + + + + + diff --git a/Hardware-Vue/src/components/CameraPreview.vue b/Hardware-Vue/src/components/CameraPreview.vue new file mode 100644 index 0000000..398ec71 --- /dev/null +++ b/Hardware-Vue/src/components/CameraPreview.vue @@ -0,0 +1,294 @@ + + + + + diff --git a/Hardware-Vue/src/components/GuideIcon.vue b/Hardware-Vue/src/components/GuideIcon.vue new file mode 100644 index 0000000..aeaafd9 --- /dev/null +++ b/Hardware-Vue/src/components/GuideIcon.vue @@ -0,0 +1,55 @@ + + + + + diff --git a/Hardware-Vue/src/components/MiniSpectrum.vue b/Hardware-Vue/src/components/MiniSpectrum.vue new file mode 100644 index 0000000..8709625 --- /dev/null +++ b/Hardware-Vue/src/components/MiniSpectrum.vue @@ -0,0 +1,94 @@ + + + + + diff --git a/Hardware-Vue/src/components/ModuleButton.vue b/Hardware-Vue/src/components/ModuleButton.vue new file mode 100644 index 0000000..d06840e --- /dev/null +++ b/Hardware-Vue/src/components/ModuleButton.vue @@ -0,0 +1,132 @@ + + + + + diff --git a/Hardware-Vue/src/components/ModuleIcon.vue b/Hardware-Vue/src/components/ModuleIcon.vue new file mode 100644 index 0000000..5765ce8 --- /dev/null +++ b/Hardware-Vue/src/components/ModuleIcon.vue @@ -0,0 +1,81 @@ + + + + + diff --git a/Hardware-Vue/src/components/PageHeader.vue b/Hardware-Vue/src/components/PageHeader.vue new file mode 100644 index 0000000..a528ee8 --- /dev/null +++ b/Hardware-Vue/src/components/PageHeader.vue @@ -0,0 +1,86 @@ + + + + + diff --git a/Hardware-Vue/src/components/PrinciplePlayer.vue b/Hardware-Vue/src/components/PrinciplePlayer.vue new file mode 100644 index 0000000..3245c6b --- /dev/null +++ b/Hardware-Vue/src/components/PrinciplePlayer.vue @@ -0,0 +1,385 @@ + + + + + diff --git a/Hardware-Vue/src/components/ProgressStrip.vue b/Hardware-Vue/src/components/ProgressStrip.vue new file mode 100644 index 0000000..9fb2738 --- /dev/null +++ b/Hardware-Vue/src/components/ProgressStrip.vue @@ -0,0 +1,92 @@ + + + + + diff --git a/Hardware-Vue/src/components/ScanVisual.vue b/Hardware-Vue/src/components/ScanVisual.vue new file mode 100644 index 0000000..e7d3eed --- /dev/null +++ b/Hardware-Vue/src/components/ScanVisual.vue @@ -0,0 +1,350 @@ + + + + + diff --git a/Hardware-Vue/src/components/SpectrumChart.vue b/Hardware-Vue/src/components/SpectrumChart.vue new file mode 100644 index 0000000..2b04946 --- /dev/null +++ b/Hardware-Vue/src/components/SpectrumChart.vue @@ -0,0 +1,300 @@ + + + + + diff --git a/Hardware-Vue/src/components/StatusFooter.vue b/Hardware-Vue/src/components/StatusFooter.vue new file mode 100644 index 0000000..af60267 --- /dev/null +++ b/Hardware-Vue/src/components/StatusFooter.vue @@ -0,0 +1,74 @@ + + + + + diff --git a/Hardware-Vue/src/components/ToastHost.vue b/Hardware-Vue/src/components/ToastHost.vue new file mode 100644 index 0000000..19d4963 --- /dev/null +++ b/Hardware-Vue/src/components/ToastHost.vue @@ -0,0 +1,68 @@ + + + + + diff --git a/Hardware-Vue/src/components/UnderDevelopmentModal.vue b/Hardware-Vue/src/components/UnderDevelopmentModal.vue new file mode 100644 index 0000000..b62cf06 --- /dev/null +++ b/Hardware-Vue/src/components/UnderDevelopmentModal.vue @@ -0,0 +1,168 @@ + + + + + diff --git a/Hardware-Vue/src/composables/useCameraStatus.ts b/Hardware-Vue/src/composables/useCameraStatus.ts new file mode 100644 index 0000000..42b3538 --- /dev/null +++ b/Hardware-Vue/src/composables/useCameraStatus.ts @@ -0,0 +1,75 @@ +import { computed, onBeforeUnmount, onMounted, ref } from 'vue' +import { getCameraStatus } from '@/api/camera' + +export type CameraConnectionState = 'checking' | 'connected' | 'disconnected' | 'offline' + +/** + * 轮询 /api/camera/status,供首页与支付页共用。 + * 后端不可达时返回 offline,界面展示为“相机服务离线”,不会阻塞页面。 + */ +export function useCameraStatus(pollInterval = 5000, autoStart = true) { + const state = ref('checking') + const connected = ref(null) + const lastChecked = ref(null) + const errorMessage = ref('') + + let timer: number | undefined + let inFlight = false + + async function refresh() { + if (inFlight) return + inFlight = true + try { + const { connected: isConnected } = await getCameraStatus() + connected.value = isConnected + state.value = isConnected ? 'connected' : 'disconnected' + errorMessage.value = '' + } catch (error) { + connected.value = null + state.value = 'offline' + errorMessage.value = error instanceof Error ? error.message : '无法连接相机服务' + } finally { + inFlight = false + lastChecked.value = new Date() + } + } + + function startPolling() { + stopPolling() + timer = window.setInterval(refresh, pollInterval) + } + + function stopPolling() { + if (timer !== undefined) { + window.clearInterval(timer) + timer = undefined + } + } + + function onVisibilityChange() { + if (document.visibilityState === 'visible') void refresh() + } + + onMounted(() => { + if (!autoStart) return + void refresh() + startPolling() + document.addEventListener('visibilitychange', onVisibilityChange) + }) + + onBeforeUnmount(() => { + stopPolling() + document.removeEventListener('visibilitychange', onVisibilityChange) + }) + + return { + state, + connected, + lastChecked, + errorMessage, + isConnected: computed(() => state.value === 'connected'), + refresh, + startPolling, + stopPolling, + } +} diff --git a/Hardware-Vue/src/composables/useCameraStream.ts b/Hardware-Vue/src/composables/useCameraStream.ts new file mode 100644 index 0000000..ca4344a --- /dev/null +++ b/Hardware-Vue/src/composables/useCameraStream.ts @@ -0,0 +1,150 @@ +import { computed, onBeforeUnmount, ref } from 'vue' +import { + HubConnectionBuilder, + HubConnectionState, + LogLevel, + type HubConnection, +} from '@microsoft/signalr' +import { getCameraHubUrl } from '@/api/camera' + +interface CameraFramePayload { + frameIndex: number + timestamp: string + imageBase64: string + /** 后端根据实际采集格式给出:image/jpeg、image/png 或 image/bmp */ + mimeType?: string + width?: number + height?: number + capturedAt?: string +} + +interface CameraStatusPayload { + isConnected: boolean + message?: string + deviceName?: string | null + framesReceived?: number + lastFrameAt?: string | null +} + +export type StreamState = 'idle' | 'connecting' | 'connected' | 'offline' + +/** 摄像头 MJPG 帧,base64 直出为 JPEG */ +const FRAME_MIME = 'image/jpeg' +/** 限制前端刷新率,避免高帧率推流时占用过多主线程 */ +const MIN_FRAME_INTERVAL = 70 + +/** + * 通过 SignalR(/cameraHub)接收相机实时帧。 + * 事件契约见 HardwareWeb/Services/CameraBroadcastService.cs: + * CameraFrame -> { frameIndex, timestamp, imageBase64 } + * CameraStatus -> { isConnected, message } + */ +export function useCameraStream() { + const state = ref('idle') + const frameUrl = ref(null) + const frameIndex = ref(0) + const errorMessage = ref('') + const hasFrame = ref(false) + + let connection: HubConnection | null = null + let lastFrameAt = 0 + let stoppedByUser = false + + const isLive = computed(() => state.value === 'connected' && hasFrame.value) + + function handleFrame(payload: CameraFramePayload) { + if (!payload?.imageBase64) return + const now = performance.now() + if (now - lastFrameAt < MIN_FRAME_INTERVAL) return + lastFrameAt = now + const mime = + payload.mimeType ?? + (payload.imageBase64.startsWith('iVBOR') + ? 'image/png' + : payload.imageBase64.startsWith('Qk') + ? 'image/bmp' + : FRAME_MIME) + frameUrl.value = `data:${mime};base64,${payload.imageBase64}` + frameIndex.value = payload.frameIndex + hasFrame.value = true + state.value = 'connected' + } + + function handleStatus(payload: CameraStatusPayload) { + if (payload.isConnected) { + state.value = 'connected' + errorMessage.value = '' + } else { + hasFrame.value = false + frameUrl.value = null + state.value = 'offline' + } + } + + async function connect() { + if (connection && connection.state !== HubConnectionState.Disconnected) return + stoppedByUser = false + state.value = 'connecting' + errorMessage.value = '' + + const hub = new HubConnectionBuilder() + .withUrl(getCameraHubUrl(), { withCredentials: false }) + .withAutomaticReconnect({ + nextRetryDelayInMilliseconds: (context) => + Math.min(1000 * 2 ** context.previousRetryCount, 10000), + }) + .configureLogging(LogLevel.Warning) + .build() + + hub.on('CameraFrame', handleFrame) + hub.on('CameraStatus', handleStatus) + hub.onreconnecting(() => { + state.value = 'connecting' + }) + hub.onreconnected(() => { + state.value = 'connected' + }) + hub.onclose(() => { + if (stoppedByUser) return + state.value = 'offline' + hasFrame.value = false + }) + + connection = hub + + try { + await hub.start() + state.value = 'connected' + } catch (error) { + state.value = 'offline' + errorMessage.value = error instanceof Error ? error.message : '实时画面连接失败' + connection = null + await hub.stop().catch(() => undefined) + } + } + + async function disconnect() { + stoppedByUser = true + hasFrame.value = false + frameUrl.value = null + const hub = connection + connection = null + state.value = 'idle' + if (hub) await hub.stop().catch(() => undefined) + } + + onBeforeUnmount(() => { + void disconnect() + }) + + return { + state, + frameUrl, + frameIndex, + errorMessage, + hasFrame, + isLive, + connect, + disconnect, + } +} diff --git a/Hardware-Vue/src/composables/useCountdown.ts b/Hardware-Vue/src/composables/useCountdown.ts new file mode 100644 index 0000000..8830638 --- /dev/null +++ b/Hardware-Vue/src/composables/useCountdown.ts @@ -0,0 +1,31 @@ +import { onBeforeUnmount, onMounted, ref } from 'vue' + +/** 秒级倒计时,归零时只触发一次回调。 */ +export function useCountdown(seconds: number, onComplete: () => void) { + const remaining = ref(seconds) + + let timer: number | undefined + let finished = false + + onMounted(() => { + timer = window.setInterval(() => { + remaining.value = Math.max(0, remaining.value - 1) + + if (remaining.value === 0 && !finished) { + finished = true + window.clearInterval(timer) + timer = undefined + onComplete() + } + }, 1000) + }) + + onBeforeUnmount(() => { + if (timer !== undefined) { + window.clearInterval(timer) + timer = undefined + } + }) + + return { remaining } +} diff --git a/Hardware-Vue/src/composables/useStageScale.ts b/Hardware-Vue/src/composables/useStageScale.ts new file mode 100644 index 0000000..26c1b53 --- /dev/null +++ b/Hardware-Vue/src/composables/useStageScale.ts @@ -0,0 +1,27 @@ +import { onBeforeUnmount, onMounted, ref } from 'vue' + +/** + * 设计稿为 1920 × 1080 的一体机大屏。 + * 用 transform 整体缩放,可以在任意分辨率下保持设计比例与布局,不会出现错位。 + */ +export function useStageScale(width = 1920, height = 1080) { + const scale = ref(1) + + const update = () => { + const next = Math.min(window.innerWidth / width, window.innerHeight / height) + scale.value = Math.max(0.2, Math.round(next * 10000) / 10000) + } + + onMounted(() => { + update() + window.addEventListener('resize', update, { passive: true }) + window.addEventListener('orientationchange', update) + }) + + onBeforeUnmount(() => { + window.removeEventListener('resize', update) + window.removeEventListener('orientationchange', update) + }) + + return { scale, update } +} diff --git a/Hardware-Vue/src/composables/useTimedProgress.ts b/Hardware-Vue/src/composables/useTimedProgress.ts new file mode 100644 index 0000000..523674b --- /dev/null +++ b/Hardware-Vue/src/composables/useTimedProgress.ts @@ -0,0 +1,48 @@ +import { onBeforeUnmount, onMounted, ref } from 'vue' + +/** + * 平滑推进 0 → 100 的进度值,到达 100% 时只触发一次回调。 + * 组件卸载(用户中止流程)时会自动取消,不会误跳转。 + */ +export function useTimedProgress(durationMs: number, onComplete: () => void) { + const progress = ref(0) + + let frame = 0 + let startedAt = 0 + let finished = false + + const tick = (now: number) => { + if (!startedAt) startedAt = now + const elapsed = now - startedAt + progress.value = Math.min(100, (elapsed / durationMs) * 100) + + if (progress.value >= 100) { + if (!finished) { + finished = true + onComplete() + } + return + } + + frame = window.requestAnimationFrame(tick) + } + + onMounted(() => { + if (durationMs <= 0) { + progress.value = 100 + if (!finished) { + finished = true + onComplete() + } + return + } + + frame = window.requestAnimationFrame(tick) + }) + + onBeforeUnmount(() => { + window.cancelAnimationFrame(frame) + }) + + return { progress } +} diff --git a/Hardware-Vue/src/composables/useToast.ts b/Hardware-Vue/src/composables/useToast.ts new file mode 100644 index 0000000..17f7d6f --- /dev/null +++ b/Hardware-Vue/src/composables/useToast.ts @@ -0,0 +1,26 @@ +import { readonly, ref } from 'vue' + +const message = ref('') +const visible = ref(false) +let timer: number | undefined + +export function showToast(text: string, duration = 2400) { + message.value = text + visible.value = true + + if (timer !== undefined) { + window.clearTimeout(timer) + } + + timer = window.setTimeout(() => { + visible.value = false + timer = undefined + }, duration) +} + +export function useToast() { + return { + message: readonly(message), + visible: readonly(visible), + } +} diff --git a/Hardware-Vue/src/env.d.ts b/Hardware-Vue/src/env.d.ts new file mode 100644 index 0000000..b1477f5 --- /dev/null +++ b/Hardware-Vue/src/env.d.ts @@ -0,0 +1,16 @@ +/// + +interface ImportMetaEnv { + readonly VITE_API_BASE?: string + readonly VITE_HUB_URL?: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent, Record, unknown> + export default component +} diff --git a/Hardware-Vue/src/main.ts b/Hardware-Vue/src/main.ts new file mode 100644 index 0000000..42b27be --- /dev/null +++ b/Hardware-Vue/src/main.ts @@ -0,0 +1,6 @@ +import { createApp } from 'vue' +import App from './App.vue' +import router from './router' +import './styles/main.css' + +createApp(App).use(router).mount('#app') diff --git a/Hardware-Vue/src/router/index.ts b/Hardware-Vue/src/router/index.ts new file mode 100644 index 0000000..5199ae8 --- /dev/null +++ b/Hardware-Vue/src/router/index.ts @@ -0,0 +1,52 @@ +import { createRouter, createWebHistory } from 'vue-router' +import HomeView from '@/views/HomeView.vue' + +const router = createRouter({ + history: createWebHistory(import.meta.env.BASE_URL), + routes: [ + { + path: '/', + name: 'home', + component: HomeView, + meta: { title: '激光诱导击穿光谱 元素分析系统' }, + }, + { + path: '/sample', + name: 'sample', + component: () => import('@/views/SampleSetupView.vue'), + meta: { title: '放置待测样品' }, + }, + { + path: '/scan', + name: 'scan', + component: () => import('@/views/ScanPlanView.vue'), + meta: { title: '样品轮廓识别与激光点位规划' }, + }, + { + path: '/spectrum', + name: 'spectrum', + component: () => import('@/views/SpectrumView.vue'), + meta: { title: '光谱数据采集与分析' }, + }, + { + path: '/result', + name: 'result', + component: () => import('@/views/ResultView.vue'), + meta: { title: '检测完成' }, + }, + { + path: '/pay', + redirect: { name: 'sample' }, + }, + { + path: '/:pathMatch(.*)*', + redirect: { name: 'home' }, + }, + ], +}) + +router.afterEach((to) => { + document.title = (to.meta.title as string | undefined) ?? 'LIBS Lab' +}) + +export default router diff --git a/Hardware-Vue/src/styles/main.css b/Hardware-Vue/src/styles/main.css new file mode 100644 index 0000000..f5ae3b4 --- /dev/null +++ b/Hardware-Vue/src/styles/main.css @@ -0,0 +1,190 @@ +:root { + --bg: #f0f2f5; + --bg-deep: #e4e8ee; + --surface: #ffffff; + --surface-soft: #f7f8fa; + --ink: #1c2735; + --ink-soft: #3f4c5e; + --muted: #7c8797; + --muted-light: #a5afbc; + --line: #e2e7ee; + --line-strong: #cfd8e4; + + --blue: #2f6fd0; + --blue-dark: #245bb5; + --blue-soft: #eaf2ff; + --teal: #2ab7ac; + --teal-dark: #1a9b91; + --green: #78bd3f; + --green-dark: #5aa02b; + --orange: #f5b51f; + --orange-dark: #e09a06; + --orange-soft: #fff3d5; + --red: #e15b55; + + --radius-lg: 20px; + --radius-md: 14px; + --radius-sm: 9px; + --shadow-card: 0 10px 30px rgba(33, 53, 84, 0.08); + --shadow-card-strong: 0 18px 48px rgba(33, 53, 84, 0.12); + + --font: "HarmonyOS Sans SC", "PingFang SC", "Microsoft YaHei", + "Noto Sans SC", sans-serif; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body, +#app { + width: 100%; + height: 100%; + margin: 0; +} + +html { + background: #e5e9ee; +} + +body { + overflow: hidden; + color: var(--ink); + font-family: var(--font); + font-size: 16px; + line-height: 1.5; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: optimizeLegibility; + user-select: none; + -webkit-tap-highlight-color: transparent; +} + +button { + margin: 0; + padding: 0; + border: 0; + color: inherit; + font: inherit; + background: none; + cursor: pointer; +} + +button:focus-visible { + outline: 3px solid rgba(47, 111, 208, 0.4); + outline-offset: 3px; +} + +img, +video, +svg { + display: block; + max-width: 100%; +} + +h1, +h2, +h3, +p { + margin: 0; +} + +ul, +ol { + margin: 0; + padding: 0; + list-style: none; +} + +/* Shared header actions */ +.header-button { + display: inline-flex; + align-items: center; + justify-content: center; + height: 64px; + border-radius: 10px; + font-size: 26px; + font-weight: 600; + letter-spacing: 3px; + transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; +} + +.header-button:hover { + transform: translateY(-1px); +} + +.header-button--outline { + width: 132px; + border: 2px solid var(--blue); + color: var(--blue); + background: #fff; +} + +.header-button--outline:hover { + background: var(--blue-soft); +} + +.header-button--warn { + width: 300px; + height: 68px; + color: #fff; + background: linear-gradient(180deg, #ffc82f 0%, #f0ac0b 100%); + box-shadow: + 0 10px 22px rgba(240, 172, 11, 0.28), + inset 0 1px 0 rgba(255, 255, 255, 0.55); + text-shadow: 0 1px 2px rgba(160, 100, 0, 0.26); +} + +.header-button--warn:hover { + box-shadow: + 0 14px 28px rgba(240, 172, 11, 0.36), + inset 0 1px 0 rgba(255, 255, 255, 0.55); +} + +.icon-close { + display: grid; + place-items: center; + width: 52px; + height: 52px; + border-radius: 50%; + color: #9aa5b3; + transition: color 0.2s ease, background 0.2s ease; +} + +.icon-close:hover { + color: #4c5a6b; + background: #f0f3f7; +} + +.icon-close svg { + width: 26px; + height: 26px; +} + +.page-enter-active, +.page-leave-active { + transition: opacity 0.32s ease, transform 0.32s ease; +} + +.page-enter-from { + opacity: 0; + transform: translateY(10px); +} + +.page-leave-to { + opacity: 0; + transform: translateY(-6px); +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + } +} diff --git a/Hardware-Vue/src/views/HomeView.vue b/Hardware-Vue/src/views/HomeView.vue new file mode 100644 index 0000000..fefe8df --- /dev/null +++ b/Hardware-Vue/src/views/HomeView.vue @@ -0,0 +1,174 @@ + + + + + diff --git a/Hardware-Vue/src/views/ResultView.vue b/Hardware-Vue/src/views/ResultView.vue new file mode 100644 index 0000000..94ab44e --- /dev/null +++ b/Hardware-Vue/src/views/ResultView.vue @@ -0,0 +1,290 @@ + + + + + diff --git a/Hardware-Vue/src/views/SampleSetupView.vue b/Hardware-Vue/src/views/SampleSetupView.vue new file mode 100644 index 0000000..57c35eb --- /dev/null +++ b/Hardware-Vue/src/views/SampleSetupView.vue @@ -0,0 +1,228 @@ + + + + + diff --git a/Hardware-Vue/src/views/ScanPlanView.vue b/Hardware-Vue/src/views/ScanPlanView.vue new file mode 100644 index 0000000..4300636 --- /dev/null +++ b/Hardware-Vue/src/views/ScanPlanView.vue @@ -0,0 +1,178 @@ + + + + + diff --git a/Hardware-Vue/src/views/SpectrumView.vue b/Hardware-Vue/src/views/SpectrumView.vue new file mode 100644 index 0000000..21af052 --- /dev/null +++ b/Hardware-Vue/src/views/SpectrumView.vue @@ -0,0 +1,222 @@ + + + + + diff --git a/Hardware-Vue/tsconfig.json b/Hardware-Vue/tsconfig.json new file mode 100644 index 0000000..36f452f --- /dev/null +++ b/Hardware-Vue/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "jsx": "preserve", + "resolveJsonModule": true, + "isolatedModules": true, + "esModuleInterop": true, + "skipLibCheck": true, + "noEmit": true, + "useDefineForClassFields": true, + "types": ["vite/client", "node"], + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + } + }, + "include": [ + "src/**/*.ts", + "src/**/*.d.ts", + "src/**/*.vue", + "vite.config.ts" + ] +} diff --git a/Hardware-Vue/vite.config.ts b/Hardware-Vue/vite.config.ts new file mode 100644 index 0000000..2e75af3 --- /dev/null +++ b/Hardware-Vue/vite.config.ts @@ -0,0 +1,45 @@ +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +// 开发期将相机接口与 SignalR 统一代理到 HardwareWeb,避免跨域配置。 +const backend = process.env.VITE_BACKEND_URL ?? 'http://localhost:5062' + +const proxy = { + '/api': { + target: backend, + changeOrigin: true, + }, + '/cameraHub': { + target: backend, + changeOrigin: true, + ws: true, + }, +} + +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, + server: { + host: '127.0.0.1', + port: 5173, + watch: { + // 文档截图等静态资源无需触发 HMR,避免 Windows 文件占用导致 watcher 崩溃。 + ignored: ['**/docs/**'], + }, + proxy, + }, + preview: { + host: '127.0.0.1', + port: 4173, + proxy, + }, + build: { + outDir: 'dist', + sourcemap: false, + }, +}) diff --git a/HardwareControl.Core/HardwareControl.Core.csproj b/HardwareControl.Core/HardwareControl.Core.csproj new file mode 100644 index 0000000..570cb63 --- /dev/null +++ b/HardwareControl.Core/HardwareControl.Core.csproj @@ -0,0 +1,38 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + dll\aris\ArisSharp.dll + + + + + + + aris.dll + PreserveNewest + PreserveNewest + + + libusb-1.0.dll + PreserveNewest + PreserveNewest + + + + diff --git a/HardwareControl.Core/HardwareException.cs b/HardwareControl.Core/HardwareException.cs new file mode 100644 index 0000000..4ce9302 --- /dev/null +++ b/HardwareControl.Core/HardwareException.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace HardwareControl.Core +{ + public enum HardwareErrorKind + { + NotConnected, + ConnectFailed, + CommunicationFailed, + Timeout, + Unknown, + InvalidArgument, + InvalidState, + NotSupported + } + + public class HardwareException : Exception + { + public HardwareErrorKind Kind { get; } + + public HardwareException(HardwareErrorKind kind, string message, Exception? inner = null) : base(message, inner) + { + Kind = kind; + } + } +} diff --git a/HardwareControl.Core/HardwareService/IArisSpectrometerService.cs b/HardwareControl.Core/HardwareService/IArisSpectrometerService.cs new file mode 100644 index 0000000..0db7a57 --- /dev/null +++ b/HardwareControl.Core/HardwareService/IArisSpectrometerService.cs @@ -0,0 +1,68 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareControl.Core.HardwareServiceImpl.HardwareService +{ + /// + /// aris 光谱仪服务。 + /// 单台使用 AcquireFrame 同步单帧;多台使用 StartMeasurement 一次性武装, + /// 收齐回调后按波长拼接。所有操作在内部串行化,单帧/多台采集互斥。 + /// + public interface IArisSpectrometerService : IAsyncDisposable + { + /// 是否已经成功连接(不保证设备此刻仍在线)。 + bool IsConnected { get; } + + /// 连接时发现并初始化的设备数量。 + int DeviceCount { get; } + + /// 当前选中的设备;未连接时为 null。 + SpectrometerDeviceInfo? SelectedDevice { get; } + + /// 选中设备的像素数;未连接时为 null。 + int? PixelCount { get; } + + /// 连接时缓存的设备列表;未连接时为空。 + IReadOnlyList Devices { get; } + + /// 本次连接累计成功采集的帧数。 + long FramesAcquired { get; } + + /// 最近一次成功采集的完成时间;尚未采集时为 null。 + DateTimeOffset? LastAcquireAt { get; } + + Task ConnectAsync(CancellationToken ct = default); + + Task DisconnectAsync(CancellationToken ct = default); + + /// + /// 同步采一帧。内部串行化所有原生调用,因此并发调用会排队, + /// 只影响排队阶段,已开始的曝光无法取消。 + /// + Task AcquireFrameAsync( + SpectrumAcquisitionRequest? request = null, + CancellationToken ct = default); + + /// + /// 多台光谱仪同步采集一帧:StartMeasurement 一次武装所有设备, + /// 收齐每台设备的回调后按波长自动拼接(重合区间各去一半)。 + /// 由第三台设备触发激光的场景使用 Software 触发模式; + /// 有外部 AD/TTL 触发源时使用 FreeRunEdge/External。 + /// 部分设备超时会返回已收到的帧,并通过 MissingSerials 标记缺失设备。 + /// + Task AcquireSynchronizedAsync( + SynchronizedSpectrumRequest? request = null, + CancellationToken ct = default); + + /// 查询设备运行时状态(一次 USB 往返)。 + Task GetDeviceStatusAsync( + int? deviceIndex = null, + CancellationToken ct = default); + + /// 读取波长数组(用于单独绘制坐标轴)。 + Task GetWavelengthsAsync( + int? deviceIndex = null, + CancellationToken ct = default); + + event EventHandler? StatusChanged; + } +} diff --git a/HardwareControl.Core/HardwareService/IUsbCameraService.cs b/HardwareControl.Core/HardwareService/IUsbCameraService.cs new file mode 100644 index 0000000..a0dd454 --- /dev/null +++ b/HardwareControl.Core/HardwareService/IUsbCameraService.cs @@ -0,0 +1,27 @@ +using HardwareControl.Core.UsbCamera; + +namespace HardwareControl.Core.HardwareServiceImpl.HardwareService +{ + public interface IUsbCameraService : IAsyncDisposable + { + bool IsConnected { get; } + + /// 最近一次成功打开的设备名称。 + string? DeviceName { get; } + + /// 当前(或最近一次)采集格式;未打开过设备时为 null。 + CameraFrameFormat? FrameFormat { get; } + + /// 最近一帧的到达时间(UTC);尚未收到帧时为 null。 + DateTimeOffset? LastFrameAt { get; } + + /// 本次连接累计收到的帧数。 + long FramesReceived { get; } + + Task ConnectAsync(CancellationToken ct = default); + Task DisconnectAsync(CancellationToken ct = default); + + event EventHandler? StatusChanged; + event EventHandler? FrameArrived; + } +} diff --git a/HardwareControl.Core/HardwareServiceImpl/ArisSpectrometerService.cs b/HardwareControl.Core/HardwareServiceImpl/ArisSpectrometerService.cs new file mode 100644 index 0000000..562c493 --- /dev/null +++ b/HardwareControl.Core/HardwareServiceImpl/ArisSpectrometerService.cs @@ -0,0 +1,921 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Aris; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.Spectrometer; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ArisSpectrumFrame = Aris.SpectrumFrame; +using SpectrumFrame = HardwareControl.Core.Spectrometer.SpectrumFrame; + +namespace HardwareControl.Core.HardwareServiceImpl +{ + /// + /// aris 光谱仪服务实现。 + /// + /// 线程模型: + /// * 所有原生调用(连接、单帧采集、多台同步采集、状态、波长)都由 串行化, + /// 因为 / aris.dll 内部虽然也加锁,但采集是长事务, + /// 在业务层排队更容易控制超时与日志; + /// * 原生调用是同步阻塞的,因此放到线程池执行,避免占用 ASP.NET Core 请求线程; + /// * 单台使用同步 AcquireFrame;多台使用 StartMeasurement 一次武装, + /// 回调只做拷贝/入队,收齐后调用 StopMeasurement 并拼接。 + /// 单帧与多台测量在 SDK 层互斥(测量中调用单帧会返回 InvalidState)。 + /// + public sealed class ArisSpectrometerService : IArisSpectrometerService + { + private readonly ArisSpectrometerOptions _options; + private readonly ILogger _logger; + + // 串行化全部原生调用 + private readonly SemaphoreSlim _gate = new(1, 1); + + private ArisSpectrometer? _spectrometer; + private volatile SpectrometerDeviceInfo[] _devices = Array.Empty(); + private volatile SpectrometerDeviceInfo? _selectedDevice; + private volatile bool _connected; + private bool _disposed; + + private long _framesAcquired; + private long _lastAcquireAtTicks; + + public ArisSpectrometerService( + IOptions options, + ILogger logger) + { + _options = options.Value; + _logger = logger; + } + + public bool IsConnected => _connected; + + public int DeviceCount => _devices.Length; + + public SpectrometerDeviceInfo? SelectedDevice => _selectedDevice; + + public int? PixelCount => _selectedDevice?.PixelCount; + + public IReadOnlyList Devices => _devices; + + public long FramesAcquired => Interlocked.Read(ref _framesAcquired); + + public DateTimeOffset? LastAcquireAt + { + get + { + var ticks = Interlocked.Read(ref _lastAcquireAtTicks); + return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero); + } + } + + public event EventHandler? StatusChanged; + + // ---------- 连接 ---------- + + public async Task ConnectAsync(CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + if (_connected) + { + return; + } + + await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + private void ConnectCore() + { + EnsureProcessIs64Bit(); + + try + { + EnsureSpectrometer(); + var spectrometer = _spectrometer!; + + _logger.LogInformation("正在连接 aris 光谱仪..."); + spectrometer.Connect(); + + var count = spectrometer.DeviceCount; + if (count <= 0) + { + throw new HardwareException( + HardwareErrorKind.ConnectFailed, + "aris 光谱仪连接成功但设备数量为 0"); + } + + var devices = new SpectrometerDeviceInfo[count]; + for (var i = 0; i < count; i++) + { + devices[i] = MapDevice(i, spectrometer.GetDeviceInfo(i)); + } + + var selected = SelectDevice(devices); + + // 触发模式只应在连接后设置一次;设备要求全部 Idle。 + if (_options.TriggerMode is { } triggerMode) + { + spectrometer.SetTriggerMode(triggerMode); + } + + if (_options.Gain is { } gain) + { + spectrometer.SetGain(selected.Index, gain); + } + + _devices = devices; + _selectedDevice = selected; + _connected = true; + + // 帧数按“本次连接”统计,与相机服务保持一致。 + Interlocked.Exchange(ref _framesAcquired, 0); + Interlocked.Exchange(ref _lastAcquireAtTicks, 0); + + var message = count == 1 + ? $"光谱仪已连接:{selected.SerialNumber}({selected.PixelCount} 像素)" + : $"光谱仪已连接:共 {count} 台,当前使用 {selected.SerialNumber}({selected.PixelCount} 像素)"; + + _logger.LogInformation( + "aris 光谱仪已连接:{DeviceCount} 台,选中索引 {Index},序列号 {SerialNumber},像素数 {PixelCount},固件 {Firmware}", + count, + selected.Index, + selected.SerialNumber, + selected.PixelCount, + selected.FirmwareVersion); + + StatusChanged?.Invoke(this, new SpectrometerStatusChangedEventArgs(true, message)); + } + catch (ArisException ex) + { + // 连接流程可能已经打开了 USB 设备(例如设置触发模式时才失败), + // 立即销毁上下文,避免留下半连接状态导致下一次连接报 not idle。 + DisposeSpectrometerCore(); + _logger.LogError( + ex, + "连接 aris 光谱仪失败,状态码 {Status}", + ex.Status); + + throw MapArisException(ex, "连接光谱仪", connecting: true); + } + catch (HardwareException) + { + DisposeSpectrometerCore(); + throw; + } + catch (Exception ex) when (ex is DllNotFoundException + or BadImageFormatException + or EntryPointNotFoundException) + { + DisposeSpectrometerCore(); + _logger.LogError(ex, "加载 aris 原生库失败"); + throw new HardwareException( + HardwareErrorKind.ConnectFailed, + BuildNativeLoadFailureMessage(ex), + ex); + } + catch (Exception ex) + { + DisposeSpectrometerCore(); + _logger.LogError(ex, "连接 aris 光谱仪时发生未预期异常"); + throw new HardwareException( + HardwareErrorKind.ConnectFailed, + "连接光谱仪失败", + ex); + } + } + + private static void EnsureProcessIs64Bit() + { + if (!Environment.Is64BitProcess) + { + throw new HardwareException( + HardwareErrorKind.ConnectFailed, + "aris.dll 仅提供 x64 版本,请使用 64 位进程运行" + + "(PlatformTarget=x64 或 64 位宿主)"); + } + } + + private void EnsureSpectrometer() + { + if (_spectrometer is not null) + { + return; + } + + // SetLogEnabled 也会加载 aris.dll,因此必须放在异常映射覆盖的范围内。 + ArisSpectrometer.SetLogEnabled(_options.SdkLogEnabled); + _spectrometer = new ArisSpectrometer(); + } + + private SpectrometerDeviceInfo SelectDevice(SpectrometerDeviceInfo[] devices) + { + if (!string.IsNullOrWhiteSpace(_options.PreferredSerialNumber)) + { + var matched = devices.FirstOrDefault(device => string.Equals( + device.SerialNumber, + _options.PreferredSerialNumber, + StringComparison.OrdinalIgnoreCase)); + + if (matched is not null) + { + return matched; + } + + _logger.LogWarning( + "未找到序列号为 {SerialNumber} 的光谱仪,回退到配置的设备索引 {DeviceIndex}", + _options.PreferredSerialNumber, + _options.DeviceIndex); + } + + if (_options.DeviceIndex < 0 || _options.DeviceIndex >= devices.Length) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + $"配置的 DeviceIndex={_options.DeviceIndex} 超出已连接设备数量 {devices.Length}"); + } + + return devices[_options.DeviceIndex]; + } + + // ---------- 断开 ---------- + + public async Task DisconnectAsync(CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (_disposed) + { + return; + } + + var wasConnected = _connected; + await Task.Run(DisposeSpectrometerCore, CancellationToken.None) + .ConfigureAwait(false); + + if (wasConnected) + { + _logger.LogInformation("aris 光谱仪已断开"); + StatusChanged?.Invoke( + this, + new SpectrometerStatusChangedEventArgs(false, "光谱仪已断开")); + } + } + finally + { + _gate.Release(); + } + } + + /// 停止测量、断开并销毁上下文;异常只记日志,保证状态一定归零。 + private void DisposeSpectrometerCore() + { + var spectrometer = _spectrometer; + _spectrometer = null; + _connected = false; + _devices = Array.Empty(); + _selectedDevice = null; + + if (spectrometer is null) + { + return; + } + + try + { + // ArisSpectrometer.Dispose 内部会先 stop 再 disconnect,然后销毁上下文。 + spectrometer.Dispose(); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "释放 aris 光谱仪上下文时发生异常"); + } + } + + // ---------- 单帧采集 ---------- + + public async Task AcquireFrameAsync( + SpectrumAcquisitionRequest? request = null, + CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + var spectrometer = _spectrometer; + if (!_connected || spectrometer is null) + { + throw new HardwareException( + HardwareErrorKind.NotConnected, + "光谱仪尚未连接,请先调用连接接口"); + } + + var parameters = Normalize(request); + ct.ThrowIfCancellationRequested(); + + _logger.LogDebug( + "开始单帧采集:设备 {DeviceIndex},曝光 {ExposureUs}us,平均 {Averaging},延迟 {DelayUs}us,超时 {TimeoutMs}ms", + parameters.DeviceIndex, + parameters.ExposureUs, + parameters.Averaging, + parameters.DelayUs, + parameters.TimeoutMs); + + var startedAt = Stopwatch.GetTimestamp(); + + ArisSpectrumFrame native; + try + { + native = await Task.Run( + () => spectrometer.AcquireFrame( + parameters.DeviceIndex, + parameters.ExposureUs, + parameters.Averaging, + parameters.DelayUs, + parameters.TimeoutMs), + CancellationToken.None) + .ConfigureAwait(false); + } + catch (ArisException ex) + { + _logger.LogWarning( + ex, + "单帧采集失败,状态码 {Status}", + ex.Status); + throw MapArisException(ex, "采集光谱"); + } + + var acquiredAt = DateTimeOffset.Now; + var elapsed = Stopwatch.GetElapsedTime(startedAt); + var frame = MapFrame(native, parameters.DeviceIndex, acquiredAt, elapsed); + + Interlocked.Increment(ref _framesAcquired); + Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks); + + _logger.LogDebug( + "单帧采集完成:设备 {DeviceIndex},{PixelCount} 像素,耗时 {ElapsedMs:F0}ms,温度 {Temperature:F2}℃", + frame.DeviceIndex, + frame.Info.PixelCount, + elapsed.TotalMilliseconds, + frame.Info.SensorTemperature); + + return frame; + } + finally + { + _gate.Release(); + } + } + + // ---------- 多台同步采集 ---------- + + public async Task AcquireSynchronizedAsync( + SynchronizedSpectrumRequest? request = null, + CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + var spectrometer = RequireConnected(); + var parameters = NormalizeSynchronized(request); + ct.ThrowIfCancellationRequested(); + + return await Task.Run( + () => AcquireSynchronizedCore(spectrometer, parameters), + CancellationToken.None) + .ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + private SynchronizedSpectrumResult AcquireSynchronizedCore( + ArisSpectrometer spectrometer, + (int ExposureUs, int Averaging, int DelayUs, int WaitTimeoutMs) parameters) + { + var devices = _devices; + var expected = devices.Length; + if (expected == 0) + { + throw new HardwareException( + HardwareErrorKind.NotConnected, + "没有可采集的光谱仪,请先调用连接接口"); + } + + var bySerial = new Dictionary( + StringComparer.OrdinalIgnoreCase); + foreach (var device in devices) + { + if (!bySerial.TryAdd(device.SerialNumber, device)) + { + _logger.LogWarning( + "重复的光谱仪序列号 {SerialNumber},只保留第一台", + device.SerialNumber); + } + } + + var frames = new ConcurrentDictionary( + StringComparer.OrdinalIgnoreCase); + var errors = new ConcurrentDictionary( + StringComparer.OrdinalIgnoreCase); + var accounted = new ConcurrentDictionary( + StringComparer.OrdinalIgnoreCase); + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + EventHandler onSpectrum = (_, e) => + { + // 回调在 aris 测量线程上:只做拷贝/入队,不调用任何阻塞接口。 + var serial = e.SerialNumber.Trim(); + if (!bySerial.ContainsKey(serial)) + { + return; + } + + frames.TryAdd( + serial, + new CapturedSpectrum(e.Wavelengths, e.Spectrum, DateTimeOffset.Now)); + accounted.TryAdd(serial, 0); + + if (accounted.Count >= expected) + { + completion.TrySetResult(true); + } + }; + + EventHandler onError = (_, e) => + { + var serial = e.SerialNumber.Trim(); + if (!bySerial.ContainsKey(serial)) + { + return; + } + + errors[serial] = e.Message; + accounted.TryAdd(serial, 0); + + if (accounted.Count >= expected) + { + completion.TrySetResult(true); + } + }; + + var startedAt = Stopwatch.GetTimestamp(); + var startElapsed = TimeSpan.Zero; + var waitElapsed = TimeSpan.Zero; + + spectrometer.SpectrumReceived += onSpectrum; + spectrometer.ErrorOccurred += onError; + try + { + _logger.LogInformation( + "开始多台光谱仪同步采集:{DeviceCount} 台,曝光 {ExposureUs}us,平均 {Averaging},延迟 {DelayUs}us", + expected, + parameters.ExposureUs, + parameters.Averaging, + parameters.DelayUs); + + // 一次武装所有空闲设备;measureCount=1 表示每台只采一帧。 + spectrometer.StartMeasurement( + parameters.ExposureUs, + parameters.Averaging, + parameters.DelayUs, + measureCount: 1); + + startElapsed = Stopwatch.GetElapsedTime(startedAt); + + var waitStarted = Stopwatch.GetTimestamp(); + completion.Task.Wait(parameters.WaitTimeoutMs); + waitElapsed = Stopwatch.GetElapsedTime(waitStarted); + } + catch (ArisException ex) + { + _logger.LogError( + ex, + "多台光谱仪同步采集失败,状态码 {Status}", + ex.Status); + throw MapArisException(ex, "同步采集多台光谱仪"); + } + finally + { + // StopMeasurement 会置停止标志并 join 全部测量线程,必须在回调线程之外调用。 + try + { + spectrometer.StopMeasurement(); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "停止多台光谱仪测量时发生异常"); + } + + spectrometer.SpectrumReceived -= onSpectrum; + spectrometer.ErrorOccurred -= onError; + } + + var acquiredAt = DateTimeOffset.Now; + var received = new List(frames.Count); + foreach (var pair in frames.OrderBy( + pair => pair.Key, StringComparer.OrdinalIgnoreCase)) + { + if (!bySerial.TryGetValue(pair.Key, out var device)) + { + continue; + } + + var captured = pair.Value; + if (captured.Wavelengths.Length == 0 + || captured.Wavelengths.Length != captured.Spectrum.Length) + { + errors[pair.Key] = "波长与光谱长度不一致或为空"; + continue; + } + + received.Add(new SynchronizedSpectrumFrame( + device.Index, + device.SerialNumber, + captured.Wavelengths, + captured.Spectrum, + captured.ReceivedAt)); + } + + var receivedSerials = new HashSet( + received.Select(frame => frame.SerialNumber), + StringComparer.OrdinalIgnoreCase); + + var missing = devices + .Where(device => !receivedSerials.Contains(device.SerialNumber)) + .Select(device => device.SerialNumber) + .ToArray(); + + var errorList = errors + .OrderBy(pair => pair.Key, StringComparer.OrdinalIgnoreCase) + .Select(pair => new SpectrumDeviceError(pair.Key, pair.Value)) + .ToArray(); + + if (received.Count == 0) + { + var detail = errorList.Length == 0 + ? "等待超时,未收到任何设备的光谱帧" + : "未收到任何设备的光谱帧:" + string.Join( + ";", + errorList.Select(error => $"{error.SerialNumber}: {error.Message}")); + + throw new HardwareException(HardwareErrorKind.Timeout, detail); + } + + MergedSpectrum merged; + try + { + merged = SpectrumMerger.Merge(received); + } + catch (Exception ex) + { + _logger.LogError(ex, "拼接多台光谱仪数据失败"); + throw new HardwareException( + HardwareErrorKind.CommunicationFailed, + "拼接光谱数据失败", + ex); + } + + if (merged.PixelCount == 0) + { + throw new HardwareException( + HardwareErrorKind.CommunicationFailed, + "拼接光谱为空,请检查设备返回的波长数据"); + } + + Interlocked.Add(ref _framesAcquired, received.Count); + Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks); + + _logger.LogInformation( + "多台光谱仪同步采集完成:收到 {ReceivedCount}/{ExpectedCount} 台,拼接后 {PixelCount} 点,等待 {WaitMs:F0}ms", + received.Count, + expected, + merged.PixelCount, + waitElapsed.TotalMilliseconds); + + return new SynchronizedSpectrumResult( + received, + merged, + missing, + errorList, + expected, + acquiredAt, + startElapsed, + waitElapsed); + } + + private (int ExposureUs, int Averaging, int DelayUs, int WaitTimeoutMs) + NormalizeSynchronized(SynchronizedSpectrumRequest? request) + { + var defaultExposureUs = _options.SynchronizedExposureUs > 0 + ? _options.SynchronizedExposureUs + : _options.ExposureUs; + + var exposureUs = request?.ExposureUs ?? defaultExposureUs; + if (exposureUs <= 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "曝光时间 ExposureUs 必须大于 0 微秒"); + } + + var averaging = request?.Averaging ?? _options.Averaging; + if (averaging < 1) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "平均次数 Averaging 必须大于等于 1"); + } + + var delayUs = request?.DelayUs ?? _options.DelayUs; + if (delayUs < 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "触发延迟 DelayUs 不能小于 0"); + } + + var waitTimeoutMs = request?.WaitTimeoutMs + ?? _options.SynchronizedWaitTimeoutMs; + if (waitTimeoutMs <= 0) + { + waitTimeoutMs = _options.SynchronizedWaitTimeoutMs > 0 + ? _options.SynchronizedWaitTimeoutMs + : 8000; + } + + return (exposureUs, averaging, delayUs, waitTimeoutMs); + } + + private (int DeviceIndex, int ExposureUs, int Averaging, int DelayUs, int TimeoutMs) + Normalize(SpectrumAcquisitionRequest? request) + { + var exposureUs = request?.ExposureUs ?? _options.ExposureUs; + if (exposureUs <= 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "曝光时间 ExposureUs 必须大于 0 微秒"); + } + + var averaging = request?.Averaging ?? _options.Averaging; + if (averaging < 1) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "平均次数 Averaging 必须大于等于 1"); + } + + var delayUs = request?.DelayUs ?? _options.DelayUs; + if (delayUs < 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "触发延迟 DelayUs 不能小于 0"); + } + + var timeoutMs = request?.TimeoutMs ?? _options.TimeoutMs; + if (timeoutMs < 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + "超时 TimeoutMs 不能小于 0"); + } + + var deviceIndex = ResolveDeviceIndex(request?.DeviceIndex); + + return (deviceIndex, exposureUs, averaging, delayUs, timeoutMs); + } + + private int ResolveDeviceIndex(int? deviceIndex) + { + var index = deviceIndex ?? _selectedDevice?.Index ?? _options.DeviceIndex; + if (index < 0 || index >= _devices.Length) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + $"设备索引 {index} 超出范围,已连接设备数量 {_devices.Length}"); + } + + return index; + } + + // ---------- 查询 ---------- + + public async Task GetDeviceStatusAsync( + int? deviceIndex = null, + CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + var spectrometer = RequireConnected(); + + var index = ResolveDeviceIndex(deviceIndex); + try + { + var status = await Task.Run( + () => spectrometer.GetDeviceStatus(index), + CancellationToken.None) + .ConfigureAwait(false); + + return new SpectrometerDeviceStatus( + index, + status.State.ToString(), + status.AvailableSpectra); + } + catch (ArisException ex) + { + throw MapArisException(ex, "查询设备状态"); + } + } + finally + { + _gate.Release(); + } + } + + public async Task GetWavelengthsAsync( + int? deviceIndex = null, + CancellationToken ct = default) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + var spectrometer = RequireConnected(); + + var index = ResolveDeviceIndex(deviceIndex); + try + { + return await Task.Run( + () => spectrometer.GetWavelengths(index), + CancellationToken.None) + .ConfigureAwait(false); + } + catch (ArisException ex) + { + throw MapArisException(ex, "读取波长"); + } + } + finally + { + _gate.Release(); + } + } + + private ArisSpectrometer RequireConnected() + { + var spectrometer = _spectrometer; + if (!_connected || spectrometer is null) + { + throw new HardwareException( + HardwareErrorKind.NotConnected, + "光谱仪尚未连接,请先调用连接接口"); + } + + return spectrometer; + } + + // ---------- 映射 ---------- + + private static SpectrometerDeviceInfo MapDevice(int index, DeviceInfo info) => + new( + index, + info.SerialNumber, + info.PixelCount, + info.StartPixel, + info.EndPixel, + info.FirmwareVersion.ToString()); + + private static SpectrumFrame MapFrame( + ArisSpectrumFrame native, + int deviceIndex, + DateTimeOffset acquiredAt, + TimeSpan elapsed) + { + var info = native.Info; + + return new SpectrumFrame( + deviceIndex, + native.SerialNumber, + native.Wavelengths, + native.Spectrum, + new SpectrumFrameInfo( + info.ExposureTimeUs, + info.Averaging, + info.DeviceTime10Us, + info.DeviceDateDays, + info.PixelCount, + info.DataFormat, + info.LoadLevel, + info.SensorTemperature, + info.DarkAvg, + info.ReadoutNoise, + info.AppliedProcessing, + info.ErrorFlags, + info.IntensityUnit, + info.DarkSubtracted), + acquiredAt, + elapsed); + } + + private sealed record CapturedSpectrum( + float[] Wavelengths, + float[] Spectrum, + DateTimeOffset ReceivedAt); + + private static HardwareException MapArisException( + ArisException ex, + string operation, + bool connecting = false) + { + var kind = ex.Status switch + { + ArisStatus.NoDevice => connecting + ? HardwareErrorKind.ConnectFailed + : HardwareErrorKind.NotConnected, + ArisStatus.NotConnected => HardwareErrorKind.NotConnected, + ArisStatus.Timeout => HardwareErrorKind.Timeout, + ArisStatus.InvalidArgument => HardwareErrorKind.InvalidArgument, + ArisStatus.InvalidState => HardwareErrorKind.InvalidState, + ArisStatus.NotSupported => HardwareErrorKind.NotSupported, + ArisStatus.DeviceError or ArisStatus.Communication => + HardwareErrorKind.CommunicationFailed, + ArisStatus.BufferTooSmall or ArisStatus.Internal => + HardwareErrorKind.Unknown, + _ => HardwareErrorKind.Unknown, + }; + + var hint = ex.Status switch + { + ArisStatus.NoDevice => + "。请检查光谱仪 USB 连接以及 354F:0101 的 WinUSB/libusb 驱动", + ArisStatus.Timeout => + "。请检查触发模式与曝光时间,或确认设备是否响应", + ArisStatus.InvalidState => + "。设备可能仍在上一轮测量中,请稍后重试或重新连接", + ArisStatus.Communication or ArisStatus.DeviceError => + "。请检查 USB 供电与线缆", + ArisStatus.NotSupported => + "。设备/固件不支持该配置(例如数据格式不是 0)", + _ => string.Empty, + }; + + return new HardwareException(kind, $"{operation}失败:{ex.Message}{hint}", ex); + } + + private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch + { + DllNotFoundException => + "加载 aris.dll 失败:请确认 aris.dll 与 libusb-1.0.dll 已复制到程序输出目录" + + $"(当前目录:{AppContext.BaseDirectory})", + BadImageFormatException => + "加载 aris.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行", + EntryPointNotFoundException => + "加载 aris.dll 失败:DLL 版本与 ArisSharp.dll 不匹配,请使用配套版本", + _ => "加载 aris 原生库失败", + }; + + // ---------- 释放 ---------- + + private void ThrowIfDisposed() + { + ObjectDisposedException.ThrowIf(_disposed, this); + } + + public async ValueTask DisposeAsync() + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + if (_disposed) + { + return; + } + + _disposed = true; + DisposeSpectrometerCore(); + } + finally + { + _gate.Release(); + _gate.Dispose(); + } + + GC.SuppressFinalize(this); + } + } +} diff --git a/HardwareControl.Core/HardwareServiceImpl/UsbCameraService.cs b/HardwareControl.Core/HardwareServiceImpl/UsbCameraService.cs new file mode 100644 index 0000000..f76a851 --- /dev/null +++ b/HardwareControl.Core/HardwareServiceImpl/UsbCameraService.cs @@ -0,0 +1,427 @@ +using FlashCap; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.UsbCamera; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace HardwareControl.Core.HardwareServiceImpl +{ + public class UsbCameraService : IUsbCameraService + { + private readonly UsbCameraOptions _options; + private readonly ILogger _logger; + + // 串行化所有对 FlashCap 设备对象的访问 + private readonly SemaphoreSlim _gate = new(1, 1); + + private CaptureDevice? _device; + private CancellationTokenSource? _reconnectCts; + private volatile bool _connected; + + private volatile CameraFrameFormat? _frameFormat; + private volatile string? _deviceName; + private long _lastFrameAtTicks; + private long _framesReceived; + private long _connectedAtTicks; + + public bool IsConnected => _connected; + + public string? DeviceName => _deviceName; + + public CameraFrameFormat? FrameFormat => _frameFormat; + + public DateTimeOffset? LastFrameAt + { + get + { + var ticks = Interlocked.Read(ref _lastFrameAtTicks); + return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero); + } + } + + public long FramesReceived => Interlocked.Read(ref _framesReceived); + + public event EventHandler? StatusChanged; + public event EventHandler? FrameArrived; + + public UsbCameraService( + IOptions options, + ILogger logger) + { + _options = options.Value; + _logger = logger; + } + + // ---------- 连接 ---------- + + public async Task ConnectAsync(CancellationToken ct = default) + { + await _gate.WaitAsync(ct); + try + { + if (_connected) return; + await ConnectCoreAsync(ct); + } + finally + { + _gate.Release(); + } + } + + private async Task ConnectCoreAsync(CancellationToken ct) + { + try + { + var devices = new CaptureDevices(); + var descriptors = devices.EnumerateDescriptors().ToList(); + + if (descriptors.Count == 0) + throw new HardwareException( + HardwareErrorKind.ConnectFailed, "没有枚举到任何相机设备"); + + var descriptor = SelectDescriptor(descriptors); + var characteristics = SelectCharacteristics(descriptor); + var format = CameraFrameFormat.From(characteristics); + + _logger.LogInformation( + "尝试打开相机:{Device},格式:{Format}({Width}x{Height},{Fps:F1}fps,{Mime})", + descriptor, characteristics, + format.Width, format.Height, format.FramesPerSecond, format.MimeType); + + Interlocked.Exchange(ref _framesReceived, 0); + Interlocked.Exchange(ref _lastFrameAtTicks, 0); + _frameFormat = format; + _deviceName = descriptor.Name; + + // 注意:OpenAsync 的回调在 FlashCap 内部线程执行, + // 回调内不能阻塞太久,否则会丢帧。 + _device = await descriptor.OpenAsync( + characteristics, + async bufferScope => + { + try + { + if (!_connected) + { + // 已断开或正在重连,丢弃旧设备回调中的帧 + return; + } + + // ExtractImage() 可能返回 FlashCap 内部复用的缓冲区, + // 而帧会进入 Channel 异步发送,必须用 CopyImage() 取得独立副本。 + byte[] image = bufferScope.Buffer.CopyImage(); + long frameIndex = bufferScope.Buffer.FrameIndex; + var timestamp = bufferScope.Buffer.Timestamp; + var capturedAt = DateTimeOffset.Now; + + Interlocked.Increment(ref _framesReceived); + Interlocked.Exchange(ref _lastFrameAtTicks, capturedAt.UtcTicks); + + FrameArrived?.Invoke( + this, + new FrameArrivedEventArgs( + image, frameIndex, timestamp, capturedAt, format)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "抓帧回调中发生异常"); + } + }); + + await _device.StartAsync(); + + Interlocked.Exchange( + ref _connectedAtTicks, DateTimeOffset.UtcNow.UtcTicks); + _connected = true; + _logger.LogInformation("相机已连接并开始采集"); + StatusChanged?.Invoke(this, new(true, "相机已连接")); + + // 启动后台监控(用于检测断线与画面超时) + EnsureReconnectWatcher(); + } + catch (HardwareException) + { + _connected = false; + _frameFormat = null; + _deviceName = null; + _device?.Dispose(); + _device = null; + throw; + } + catch (Exception ex) + { + _connected = false; + _frameFormat = null; + _deviceName = null; + _device?.Dispose(); + _device = null; + + _logger.LogError(ex, "连接相机失败"); + throw new HardwareException( + HardwareErrorKind.ConnectFailed, "连接相机失败", ex); + } + } + + private CaptureDeviceDescriptor SelectDescriptor( + List descriptors) + { + if (!string.IsNullOrWhiteSpace(_options.DeviceNameKeyword)) + { + var matched = descriptors.FirstOrDefault( + d => d.Name.Contains( + _options.DeviceNameKeyword, StringComparison.OrdinalIgnoreCase)); + + if (matched != null) return matched; + + _logger.LogWarning( + "未找到名称包含 {Keyword} 的设备,回退到第一个设备", + _options.DeviceNameKeyword); + } + + return descriptors[0]; + } + + private VideoCharacteristics SelectCharacteristics( + CaptureDeviceDescriptor descriptor) + { + var all = descriptor.Characteristics; + + if (!string.IsNullOrWhiteSpace(_options.PreferredFormatKeyword)) + { + var matched = all.FirstOrDefault( + c => c.ToString().Contains( + _options.PreferredFormatKeyword, StringComparison.OrdinalIgnoreCase)); + + if (matched != null) return matched; + + _logger.LogWarning( + "未找到格式包含 {Keyword} 的配置,回退到第一个格式", + _options.PreferredFormatKeyword); + } + + return all[0]; + } + + // ---------- 断开 ---------- + + public async Task DisconnectAsync(CancellationToken ct = default) + { + await _gate.WaitAsync(ct); + try + { + await DisconnectCoreAsync(); + } + finally + { + _gate.Release(); + } + } + + private async Task DisconnectCoreAsync() + { + CancelReconnectWatcher(); + await StopDeviceAsync(); + + if (_connected) + { + _connected = false; + Interlocked.Exchange(ref _connectedAtTicks, 0); + StatusChanged?.Invoke(this, new(false, "相机已断开")); + } + } + + // ---------- 重连监控 ---------- + + /// + /// 保证只有一个重连监控循环。重连成功时 ConnectCoreAsync 会调用它, + /// 若当前循环仍在运行则不会重复创建。 + /// + private void EnsureReconnectWatcher() + { + var existing = _reconnectCts; + if (existing is { IsCancellationRequested: false }) + { + return; + } + + existing?.Dispose(); + _reconnectCts = new CancellationTokenSource(); + var token = _reconnectCts.Token; + _ = Task.Run(() => ReconnectLoopAsync(token)); + } + + private void CancelReconnectWatcher() + { + var cts = _reconnectCts; + _reconnectCts = null; + if (cts is null) + { + return; + } + + try + { + cts.Cancel(); + } + catch (ObjectDisposedException) + { + // 已释放,忽略 + } + + cts.Dispose(); + } + + private async Task ReconnectLoopAsync(CancellationToken ct) + { + var baseDelay = Math.Max(250, _options.ReconnectBaseDelayMs); + var maxDelay = Math.Max(baseDelay, _options.ReconnectMaxDelayMs); + var delay = baseDelay; + + while (!ct.IsCancellationRequested) + { + try + { + await Task.Delay(delay, ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + + if (ct.IsCancellationRequested) + { + break; + } + + if (_connected) + { + if (!HasFrameTimedOut()) + { + continue; + } + + _logger.LogWarning( + "超过 {Timeout}ms 未收到相机帧,标记断线并重连", + _options.FrameTimeoutMs); + + try + { + await MarkDisconnectedAsync("相机画面超时,正在重连...", ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + } + + _logger.LogInformation("检测到断线,尝试重连..."); + StatusChanged?.Invoke(this, new(false, "正在重连...")); + + try + { + await _gate.WaitAsync(ct); + try + { + if (_connected) + { + continue; + } + + await ConnectCoreAsync(ct); + delay = baseDelay; + } + finally + { + _gate.Release(); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "重连失败,{Delay}ms 后重试", delay); + delay = Math.Min(delay * 2, maxDelay); + } + } + } + + /// 检查当前连接是否长时间没有新帧。 + private bool HasFrameTimedOut() + { + var timeoutMs = _options.FrameTimeoutMs; + if (timeoutMs <= 0) + { + return false; + } + + var referenceTicks = Interlocked.Read(ref _lastFrameAtTicks); + if (referenceTicks == 0) + { + referenceTicks = Interlocked.Read(ref _connectedAtTicks); + } + + if (referenceTicks == 0) + { + return false; + } + + var reference = new DateTimeOffset(referenceTicks, TimeSpan.Zero); + return DateTimeOffset.UtcNow - reference > + TimeSpan.FromMilliseconds(timeoutMs); + } + + /// 画面超时时由监控循环调用:停止旧设备并通知前端。 + private async Task MarkDisconnectedAsync(string message, CancellationToken ct) + { + await _gate.WaitAsync(ct); + try + { + if (!_connected) + { + return; + } + + _connected = false; + Interlocked.Exchange(ref _connectedAtTicks, 0); + await StopDeviceAsync(); + StatusChanged?.Invoke(this, new(false, message)); + } + finally + { + _gate.Release(); + } + } + + private async Task StopDeviceAsync() + { + var device = _device; + _device = null; + if (device is null) + { + return; + } + + try + { + await device.StopAsync(); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "停止采集时发生异常"); + } + + device.Dispose(); + } + + // ---------- 释放 ---------- + + public async ValueTask DisposeAsync() + { + await DisconnectAsync(); + _gate.Dispose(); + } + + } +} diff --git a/HardwareControl.Core/Spectrometer/ArisSpectrometerOptions.cs b/HardwareControl.Core/Spectrometer/ArisSpectrometerOptions.cs new file mode 100644 index 0000000..5fa34cd --- /dev/null +++ b/HardwareControl.Core/Spectrometer/ArisSpectrometerOptions.cs @@ -0,0 +1,70 @@ +using Aris; + +namespace HardwareControl.Core.Spectrometer +{ + /// + /// aris 光谱仪配置,对应 appsettings.json 的 "ArisSpectrometer" 节。 + /// 所有属性都有默认值,配置文件可只写需要覆盖的项。 + /// + public sealed class ArisSpectrometerOptions + { + public const string SectionName = "ArisSpectrometer"; + + /// + /// 默认使用的设备索引(0 起)。多台设备时由 优先。 + /// + public int DeviceIndex { get; set; } + + /// + /// 优先匹配的序列号;非空且能匹配到设备时覆盖 。 + /// + public string? PreferredSerialNumber { get; set; } + + /// 单帧采集默认曝光时间,单位微秒,必须大于 0。 + public int ExposureUs { get; set; } = 1000; + + /// 单帧采集默认平均次数,必须大于等于 1。 + public int Averaging { get; set; } = 1; + + /// 单帧采集默认触发延迟,单位微秒,必须大于等于 0。 + public int DelayUs { get; set; } + + /// + /// 单帧采集默认超时,单位毫秒;小于等于 0 时由 SDK 按 + /// max(3000, 曝光/1000 + 2000) 计算。 + /// + public int TimeoutMs { get; set; } + + /// + /// 多台同步采集的默认曝光时间,单位微秒。 + /// SDK 逐台武装设备,第三台通常比前两台晚约 0.6 秒启动; + /// 曝光窗口必须覆盖这段武装时间,否则前两台会在第三台触发激光前结束。 + /// 默认 1 秒,可按现场时序下调,但建议不低于 0.7 秒。 + /// + public int SynchronizedExposureUs { get; set; } = 1_000_000; + + /// + /// 多台同步采集时,StartMeasurement 返回后等待所有设备回调的默认最长时间(毫秒)。 + /// + public int SynchronizedWaitTimeoutMs { get; set; } = 8000; + + /// + /// 连接成功后设置的触发模式;为 null 时保持设备当前配置。 + /// 手册要求触发模式只在连接后设置一次。 + /// 默认 :纯自由运行。 + /// 由第三台设备触发激光、其余设备自由收光的场景使用 Software; + /// 有外部 AD/TTL 触发源时改为 FreeRunEdge 或 External。 + /// + public TriggerMode? TriggerMode { get; set; } = Aris.TriggerMode.Software; + + /// + /// 连接成功后设置的增益(0=低增益,1=高增益);为 null 时保持设备当前配置。 + /// + public int? Gain { get; set; } + + /// + /// 是否打开 aris.dll 内部的诊断日志(默认关闭,避免刷屏)。 + /// + public bool SdkLogEnabled { get; set; } + } +} diff --git a/HardwareControl.Core/Spectrometer/MergedSpectrum.cs b/HardwareControl.Core/Spectrometer/MergedSpectrum.cs new file mode 100644 index 0000000..704b822 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/MergedSpectrum.cs @@ -0,0 +1,18 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 多台光谱仪按波长拼接后的结果。 + /// 拼接直接使用各设备原始采样点,不做插值;重合波长区间的处理规则见 + /// 。 + /// + /// 拼接后的波长数组,按升序排列。 + /// 拼接后的强度数组,与波长等长。 + /// 每一段数据的来源设备,用于分段绘图。 + public sealed record MergedSpectrum( + float[] Wavelengths, + float[] Spectrum, + IReadOnlyList Segments) + { + public int PixelCount => Wavelengths.Length; + } +} diff --git a/HardwareControl.Core/Spectrometer/MergedSpectrumSegment.cs b/HardwareControl.Core/Spectrometer/MergedSpectrumSegment.cs new file mode 100644 index 0000000..cfc289e --- /dev/null +++ b/HardwareControl.Core/Spectrometer/MergedSpectrumSegment.cs @@ -0,0 +1,18 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 拼接后光谱中的一段,表示这一段采样点来自哪台设备。 + /// 前端应按 Segments 分段绘制;相邻段波长不连续时应断开连线,避免把光谱间隙画成直线。 + /// + /// 来源设备索引。 + /// 来源设备序列号。 + /// 该段第一个点的波长。 + /// 该段最后一个点的波长。 + /// 该段的采样点数。 + public sealed record MergedSpectrumSegment( + int DeviceIndex, + string SerialNumber, + float WavelengthStart, + float WavelengthEnd, + int PointCount); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrometerDeviceInfo.cs b/HardwareControl.Core/Spectrometer/SpectrometerDeviceInfo.cs new file mode 100644 index 0000000..9e95307 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrometerDeviceInfo.cs @@ -0,0 +1,25 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 光谱仪静态信息(连接时读取一次)。 + /// + /// 设备索引(0 起),调用单帧采集时使用。 + /// 设备序列号。 + /// 光谱像素数,即波长与强度数组的长度。 + /// + /// 协议 0x2009 的原始值(手册语义为 FirstOffsetPixel), + /// 不是光谱起始像素,请勿用于切片。 + /// + /// + /// 协议 0x200A 的原始值(手册语义为 NumOffsetPixels), + /// 不是光谱结束像素,请勿用于切片。 + /// + /// 固件版本,形如 4.1.7.0。 + public sealed record SpectrometerDeviceInfo( + int Index, + string SerialNumber, + int PixelCount, + int StartPixel, + int EndPixel, + string FirmwareVersion); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrometerDeviceStatus.cs b/HardwareControl.Core/Spectrometer/SpectrometerDeviceStatus.cs new file mode 100644 index 0000000..4d3b7df --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrometerDeviceStatus.cs @@ -0,0 +1,13 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 光谱仪运行时状态(每次查询都会走一次 USB 往返)。 + /// + /// 设备索引。 + /// 设备状态名,如 Idle、TakingSpectrum。 + /// 设备缓冲中可读的帧数。 + public sealed record SpectrometerDeviceStatus( + int DeviceIndex, + string State, + int AvailableSpectra); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrometerStatusChangedEventArgs.cs b/HardwareControl.Core/Spectrometer/SpectrometerStatusChangedEventArgs.cs new file mode 100644 index 0000000..ccffb41 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrometerStatusChangedEventArgs.cs @@ -0,0 +1,18 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 光谱仪连接状态变化事件参数。 + /// + public class SpectrometerStatusChangedEventArgs : EventArgs + { + public bool IsConnected { get; } + + public string Message { get; } + + public SpectrometerStatusChangedEventArgs(bool isConnected, string message) + { + IsConnected = isConnected; + Message = message; + } + } +} diff --git a/HardwareControl.Core/Spectrometer/SpectrumAcquisitionRequest.cs b/HardwareControl.Core/Spectrometer/SpectrumAcquisitionRequest.cs new file mode 100644 index 0000000..6099bbb --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrumAcquisitionRequest.cs @@ -0,0 +1,24 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 单帧同步采集参数。为 null 的字段使用 + /// 中的默认值。 + /// + public sealed record SpectrumAcquisitionRequest + { + /// 设备索引;为 null 时使用连接时选中的设备。 + public int? DeviceIndex { get; init; } + + /// 曝光时间,单位微秒,必须大于 0。 + public int? ExposureUs { get; init; } + + /// 平均次数,必须大于等于 1。 + public int? Averaging { get; init; } + + /// 触发延迟,单位微秒,必须大于等于 0。 + public int? DelayUs { get; init; } + + /// 超时,单位毫秒;小于等于 0 时由 SDK 计算。 + public int? TimeoutMs { get; init; } + } +} diff --git a/HardwareControl.Core/Spectrometer/SpectrumDeviceError.cs b/HardwareControl.Core/Spectrometer/SpectrumDeviceError.cs new file mode 100644 index 0000000..6ae8135 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrumDeviceError.cs @@ -0,0 +1,5 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// 测量过程中 SDK 上报的单台设备错误。 + public sealed record SpectrumDeviceError(string SerialNumber, string Message); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrumFrame.cs b/HardwareControl.Core/Spectrometer/SpectrumFrame.cs new file mode 100644 index 0000000..ebdf0f4 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrumFrame.cs @@ -0,0 +1,21 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 一帧同步采集的光谱。数组已从原生内存复制到托管内存,调用方可以安全留存。 + /// + /// 实际采集的设备索引。 + /// 设备序列号。 + /// 波长数组,长度等于 的长度。 + /// 强度数组。 + /// 报文头元数据。 + /// 采集完成的主机本地时间。 + /// 从调用原生采集到返回所耗时间。 + public sealed record SpectrumFrame( + int DeviceIndex, + string SerialNumber, + float[] Wavelengths, + float[] Spectrum, + SpectrumFrameInfo Info, + DateTimeOffset AcquiredAt, + TimeSpan Elapsed); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrumFrameInfo.cs b/HardwareControl.Core/Spectrometer/SpectrumFrameInfo.cs new file mode 100644 index 0000000..36ccb1e --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrumFrameInfo.cs @@ -0,0 +1,35 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 光谱帧头元数据(来自设备返回的 64 字节报文头)。 + /// + /// 实际曝光时间,单位微秒。 + /// 实际平均次数。 + /// 设备时间戳:当日 0 点起的 0.1ms 计数。 + /// 设备日期戳:1970-01-01 起的天数。 + /// 本帧像素数。 + /// 设备数据格式;当前 SDK 只支持 0。 + /// 负载率,接近 1.0 表示接近饱和。 + /// 传感器温度,单位摄氏度。 + /// 暗电平平均值。 + /// 读出噪声。 + /// 已应用的处理标志(原始 16 位)。 + /// 非 0 表示该帧处理出错(报文头高 4 位)。 + /// 强度单位(低 4 位)。 + /// 是否已扣除暗背景。 + public sealed record SpectrumFrameInfo( + int ExposureTimeUs, + int Averaging, + uint DeviceTime10Us, + uint DeviceDateDays, + int PixelCount, + int DataFormat, + float LoadLevel, + float SensorTemperature, + float DarkAvg, + float ReadoutNoise, + ushort AppliedProcessing, + ushort ErrorFlags, + ushort IntensityUnit, + bool DarkSubtracted); +} diff --git a/HardwareControl.Core/Spectrometer/SpectrumMerger.cs b/HardwareControl.Core/Spectrometer/SpectrumMerger.cs new file mode 100644 index 0000000..25d2238 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SpectrumMerger.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 多台光谱仪的波长拼接。 + /// + /// 规则: + /// * 任意两台设备的波长区间重合时,以重合区间的中点切分: + /// 低波长设备保留重合区间的下半段,高波长设备保留上半段, + /// 即“重合部分各去一半”; + /// * 三台及以上同时重合时,按两两中点划分区间,再按两两胜出次数决定该区间归属; + /// * 单台设备被其他设备覆盖时,允许该设备贡献多段不连续区间; + /// * 直接使用各设备原始采样点,不做插值;输出按波长升序排列。 + /// + public static class SpectrumMerger + { + private const double Epsilon = 1e-6; + + public static MergedSpectrum Merge(IReadOnlyList frames) + { + ArgumentNullException.ThrowIfNull(frames); + + if (frames.Count == 0) + { + return Empty(); + } + + var normalized = frames + .Select(Normalize) + .Where(frame => frame is not null) + .Cast() + .OrderBy(frame => frame.Start) + .ThenBy(frame => frame.DeviceIndex) + .ToList(); + + if (normalized.Count == 0) + { + return Empty(); + } + + // 所有设备起止点 + 每两台设备重合区间的中点,把波长轴切成若干基本区间。 + var boundaries = new List(normalized.Count * 4); + foreach (var frame in normalized) + { + boundaries.Add(frame.Start); + boundaries.Add(frame.End); + } + + var pairMidpoints = new Dictionary<(int Lower, int Higher), double>(); + for (var i = 0; i < normalized.Count; i++) + { + for (var j = i + 1; j < normalized.Count; j++) + { + var overlapStart = Math.Max(normalized[i].Start, normalized[j].Start); + var overlapEnd = Math.Min(normalized[i].End, normalized[j].End); + + if (overlapEnd - overlapStart <= Epsilon) + { + continue; + } + + var midpoint = (overlapStart + overlapEnd) / 2.0; + pairMidpoints[(i, j)] = midpoint; + boundaries.Add(midpoint); + } + } + + boundaries.Sort(); + var uniqueBoundaries = new List(boundaries.Count); + foreach (var boundary in boundaries) + { + if (uniqueBoundaries.Count == 0 + || boundary - uniqueBoundaries[^1] > Epsilon) + { + uniqueBoundaries.Add(boundary); + } + } + + if (uniqueBoundaries.Count < 2) + { + return MergeSinglePoint(normalized); + } + + var mergedWavelengths = new List(normalized.Sum(frame => frame.Wavelengths.Length)); + var mergedSpectrum = new List(mergedWavelengths.Capacity); + var owners = new List(mergedWavelengths.Capacity); + + for (var index = 0; index < uniqueBoundaries.Count - 1; index++) + { + var intervalStart = uniqueBoundaries[index]; + var intervalEnd = uniqueBoundaries[index + 1]; + if (intervalEnd - intervalStart <= Epsilon) + { + continue; + } + + var probe = (intervalStart + intervalEnd) / 2.0; + var covering = new List(normalized.Count); + for (var i = 0; i < normalized.Count; i++) + { + var frame = normalized[i]; + if (frame.Start <= probe + Epsilon && frame.End >= probe - Epsilon) + { + covering.Add(i); + } + } + + if (covering.Count == 0) + { + // 设备之间的波长空隙:保留空隙,由前端按 Segments 断开绘制。 + continue; + } + + var winner = ChooseWinner(covering, normalized, pairMidpoints, probe); + var source = normalized[winner]; + var first = LowerBound(source.Wavelengths, intervalStart - Epsilon); + var last = UpperBound(source.Wavelengths, intervalEnd + Epsilon); + + for (var point = first; point < last; point++) + { + var wavelength = source.Wavelengths[point]; + if (!float.IsFinite(wavelength)) + { + continue; + } + + // 基本区间在边界处会重叠取点,这里按波长去重。 + if (mergedWavelengths.Count > 0 + && wavelength <= mergedWavelengths[^1] + Epsilon) + { + continue; + } + + mergedWavelengths.Add(wavelength); + mergedSpectrum.Add(source.Spectrum[point]); + owners.Add(winner); + } + } + + if (mergedWavelengths.Count == 0) + { + return Empty(); + } + + return new MergedSpectrum( + mergedWavelengths.ToArray(), + mergedSpectrum.ToArray(), + BuildSegments(owners, mergedWavelengths, normalized)); + } + + private static int ChooseWinner( + List covering, + List frames, + Dictionary<(int Lower, int Higher), double> pairMidpoints, + double probe) + { + if (covering.Count == 1) + { + return covering[0]; + } + + if (covering.Count == 2) + { + return ChoosePairWinner( + covering[0], covering[1], frames, pairMidpoints, probe); + } + + // 三台以上同时覆盖:每对设备按其中点规则投一票,票多者获得该区间。 + var wins = covering.ToDictionary(index => index, _ => 0); + for (var x = 0; x < covering.Count; x++) + { + for (var y = x + 1; y < covering.Count; y++) + { + var i = covering[x]; + var j = covering[y]; + var key = i < j ? (i, j) : (j, i); + + if (!pairMidpoints.TryGetValue(key, out var midpoint)) + { + continue; + } + + var winner = ChoosePairWinner(i, j, frames, pairMidpoints, probe); + wins[winner]++; + } + } + + // 平票时优先保留起始波长更高(更靠长波侧)的设备,再按设备索引稳定排序。 + return covering + .OrderByDescending(index => wins[index]) + .ThenByDescending(index => frames[index].Start) + .ThenBy(index => frames[index].DeviceIndex) + .First(); + } + + private static int ChoosePairWinner( + int i, + int j, + List frames, + Dictionary<(int Lower, int Higher), double> pairMidpoints, + double probe) + { + var first = frames[i]; + var second = frames[j]; + + // 起始波长更小的设备是“低波长设备”;完全相同时按设备索引决定。 + var iIsLower = first.Start < second.Start + || (Math.Abs(first.Start - second.Start) <= Epsilon + && first.DeviceIndex < second.DeviceIndex); + + var lower = iIsLower ? i : j; + var higher = iIsLower ? j : i; + + var key = i < j ? (i, j) : (j, i); + if (!pairMidpoints.TryGetValue(key, out var midpoint)) + { + return lower; + } + + return probe < midpoint ? lower : higher; + } + + private static IReadOnlyList BuildSegments( + List owners, + List wavelengths, + List frames) + { + var segments = new List(); + var segmentStart = 0; + + for (var i = 1; i <= owners.Count; i++) + { + if (i < owners.Count && owners[i] == owners[segmentStart]) + { + continue; + } + + var source = frames[owners[segmentStart]]; + segments.Add(new MergedSpectrumSegment( + source.DeviceIndex, + source.SerialNumber, + wavelengths[segmentStart], + wavelengths[i - 1], + i - segmentStart)); + + segmentStart = i; + } + + return segments; + } + + private static MergedSpectrum MergeSinglePoint(List frames) + { + var source = frames[0]; + return new MergedSpectrum( + source.Wavelengths, + source.Spectrum, + new[] + { + new MergedSpectrumSegment( + source.DeviceIndex, + source.SerialNumber, + source.Wavelengths[0], + source.Wavelengths[^1], + source.Wavelengths.Length), + }); + } + + private static NormalizedFrame? Normalize(SynchronizedSpectrumFrame frame) + { + var count = frame.Wavelengths.Length; + if (count == 0 || frame.Spectrum.Length != count) + { + return null; + } + + var points = new List<(float Wavelength, float Intensity)>(count); + for (var i = 0; i < count; i++) + { + var wavelength = frame.Wavelengths[i]; + if (float.IsFinite(wavelength)) + { + points.Add((wavelength, frame.Spectrum[i])); + } + } + + if (points.Count == 0) + { + return null; + } + + // 正常情况下 SDK 返回的波长已升序;这里排序同时兼容降序/乱序数据。 + points.Sort((left, right) => left.Wavelength.CompareTo(right.Wavelength)); + + var wavelengths = new float[points.Count]; + var spectrum = new float[points.Count]; + for (var i = 0; i < points.Count; i++) + { + wavelengths[i] = points[i].Wavelength; + spectrum[i] = points[i].Intensity; + } + + return new NormalizedFrame( + frame.DeviceIndex, + frame.SerialNumber, + wavelengths, + spectrum, + wavelengths[0], + wavelengths[^1]); + } + + private static int LowerBound(float[] values, double target) + { + var low = 0; + var high = values.Length; + while (low < high) + { + var middle = low + ((high - low) / 2); + if (values[middle] < target) + { + low = middle + 1; + } + else + { + high = middle; + } + } + + return low; + } + + private static int UpperBound(float[] values, double target) + { + var low = 0; + var high = values.Length; + while (low < high) + { + var middle = low + ((high - low) / 2); + if (values[middle] <= target) + { + low = middle + 1; + } + else + { + high = middle; + } + } + + return low; + } + + private static MergedSpectrum Empty() => new( + Array.Empty(), + Array.Empty(), + Array.Empty()); + + private sealed record NormalizedFrame( + int DeviceIndex, + string SerialNumber, + float[] Wavelengths, + float[] Spectrum, + double Start, + double End); + } +} diff --git a/HardwareControl.Core/Spectrometer/SynchronizedSpectrumFrame.cs b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumFrame.cs new file mode 100644 index 0000000..eb3518a --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumFrame.cs @@ -0,0 +1,22 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 多台同步采集时,某一台设备返回的一帧光谱。 + /// 流式回调不携带报文头,因此这里没有温度/负载率等元数据; + /// 需要这些字段请使用单帧 AcquireFrame 接口。 + /// + /// 设备索引(0 起)。 + /// 设备序列号。 + /// 波长数组。 + /// 强度数组,与波长等长。 + /// 回调在本机收到该帧的时间。 + public sealed record SynchronizedSpectrumFrame( + int DeviceIndex, + string SerialNumber, + float[] Wavelengths, + float[] Spectrum, + DateTimeOffset ReceivedAt) + { + public int PixelCount => Wavelengths.Length; + } +} diff --git a/HardwareControl.Core/Spectrometer/SynchronizedSpectrumRequest.cs b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumRequest.cs new file mode 100644 index 0000000..e14091f --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumRequest.cs @@ -0,0 +1,27 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 多台光谱仪同步采集参数。一次调用会采集所有已连接设备各一帧。 + /// 为 null 的字段使用 中的默认值。 + /// + public sealed record SynchronizedSpectrumRequest + { + /// + /// 曝光时间,单位微秒,必须大于 0。 + /// 为 null 时使用配置中的 。 + /// + public int? ExposureUs { get; init; } + + /// 平均次数,必须大于等于 1。 + public int? Averaging { get; init; } + + /// 触发延迟,单位微秒,必须大于等于 0。 + public int? DelayUs { get; init; } + + /// + /// StartMeasurement 返回后,等待所有设备回调的最长时间(毫秒)。 + /// 小于等于 0 时使用配置中的 。 + /// + public int? WaitTimeoutMs { get; init; } + } +} diff --git a/HardwareControl.Core/Spectrometer/SynchronizedSpectrumResult.cs b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumResult.cs new file mode 100644 index 0000000..15cb247 --- /dev/null +++ b/HardwareControl.Core/Spectrometer/SynchronizedSpectrumResult.cs @@ -0,0 +1,29 @@ +namespace HardwareControl.Core.Spectrometer +{ + /// + /// 多台光谱仪同步采集的结果:每台设备一帧原始光谱,外加按波长拼接后的完整光谱。 + /// + /// 实际收到的设备帧,按序列号排序。 + /// 拼接后的光谱。 + /// 超时未收到帧的序列号。 + /// 测量过程中 SDK 上报的设备错误。 + /// 本次期望采集的设备数。 + /// 采集完成的主机本地时间。 + /// StartMeasurement 武装设备所耗时间。 + /// 等待设备回调所耗时间。 + public sealed record SynchronizedSpectrumResult( + IReadOnlyList Frames, + MergedSpectrum Merged, + IReadOnlyList MissingSerials, + IReadOnlyList Errors, + int ExpectedDeviceCount, + DateTimeOffset AcquiredAt, + TimeSpan StartElapsed, + TimeSpan WaitElapsed) + { + /// 所有设备都返回了帧(允许存在已收到帧的设备的告警)。 + public bool IsComplete => MissingSerials.Count == 0; + + public int ReceivedDeviceCount => Frames.Count; + } +} diff --git a/HardwareControl.Core/UsbCamera/CameraFrameFormat.cs b/HardwareControl.Core/UsbCamera/CameraFrameFormat.cs new file mode 100644 index 0000000..0bd4c73 --- /dev/null +++ b/HardwareControl.Core/UsbCamera/CameraFrameFormat.cs @@ -0,0 +1,34 @@ +using FlashCap; + +namespace HardwareControl.Core.UsbCamera +{ + /// + /// 当前采集格式。前端用它选择正确的 data URL MIME, + /// MJPG/PNG 帧可直接显示,YUV 等格式由 FlashCap 转码为 BMP。 + /// + public sealed record CameraFrameFormat( + int Width, + int Height, + string PixelFormat, + double FramesPerSecond, + string MimeType) + { + public bool IsCompressed => MimeType is "image/jpeg" or "image/png"; + + public static string ResolveMimeType(PixelFormats pixelFormat) => + pixelFormat switch + { + PixelFormats.JPEG => "image/jpeg", + PixelFormats.PNG => "image/png", + _ => "image/bmp", + }; + + public static CameraFrameFormat From(VideoCharacteristics characteristics) => + new( + characteristics.Width, + characteristics.Height, + characteristics.PixelFormat.ToString(), + (double)characteristics.FramesPerSecond, + ResolveMimeType(characteristics.PixelFormat)); + } +} diff --git a/HardwareControl.Core/UsbCamera/FrameArrivedEventArgs.cs b/HardwareControl.Core/UsbCamera/FrameArrivedEventArgs.cs new file mode 100644 index 0000000..54e73be --- /dev/null +++ b/HardwareControl.Core/UsbCamera/FrameArrivedEventArgs.cs @@ -0,0 +1,38 @@ +namespace HardwareControl.Core.UsbCamera +{ + /// + /// 一帧图像。ImageData 由 CopyImage() 生成, + /// 调用方可以安全地在回调返回后继续持有、排队或异步发送。 + /// + public class FrameArrivedEventArgs : EventArgs + { + public byte[] ImageData { get; } + public long FrameIndex { get; } + public TimeSpan Timestamp { get; } + public DateTimeOffset CapturedAt { get; } + + /// 采集格式与 MIME 类型,随帧一起传递。 + public CameraFrameFormat Format { get; } + + public string MimeType => Format.MimeType; + public int Width => Format.Width; + public int Height => Format.Height; + + public FrameArrivedEventArgs( + byte[] imageData, + long frameIndex, + TimeSpan timestamp, + DateTimeOffset capturedAt, + CameraFrameFormat format) + { + ArgumentNullException.ThrowIfNull(imageData); + ArgumentNullException.ThrowIfNull(format); + + ImageData = imageData; + FrameIndex = frameIndex; + Timestamp = timestamp; + CapturedAt = capturedAt; + Format = format; + } + } +} diff --git a/HardwareControl.Core/UsbCamera/UsbCameraOptions.cs b/HardwareControl.Core/UsbCamera/UsbCameraOptions.cs new file mode 100644 index 0000000..75ce10a --- /dev/null +++ b/HardwareControl.Core/UsbCamera/UsbCameraOptions.cs @@ -0,0 +1,24 @@ +namespace HardwareControl.Core.UsbCamera +{ + /// + /// Usb相机操作类 + /// + public class UsbCameraOptions + { + // 设备名称关键词,null 表示取第一个设备 + public string? DeviceNameKeyword { get; set; } + + // 优先使用的格式关键词,例如 "MJPG" 或 "640x480" + // 为 null 时取该设备的第一个格式 + public string? PreferredFormatKeyword { get; set; } + + // 重连基础间隔,单位毫秒 + public int ReconnectBaseDelayMs { get; set; } = 1000; + + // 重连最大间隔,单位毫秒 + public int ReconnectMaxDelayMs { get; set; } = 10_000; + + // 抓帧超时,单位毫秒 + public int FrameTimeoutMs { get; set; } = 5000; + } +} diff --git a/HardwareControl.Core/UsbCamera/UsbCameraStatusChangedEventArgs.cs b/HardwareControl.Core/UsbCamera/UsbCameraStatusChangedEventArgs.cs new file mode 100644 index 0000000..c0963ca --- /dev/null +++ b/HardwareControl.Core/UsbCamera/UsbCameraStatusChangedEventArgs.cs @@ -0,0 +1,14 @@ +namespace HardwareControl.Core.UsbCamera +{ + public class UsbCameraStatusChangedEventArgs : EventArgs + { + public bool IsConnected { get; } + public string Message { get; } + + public UsbCameraStatusChangedEventArgs(bool isConnected, string message) + { + IsConnected = isConnected; + Message = message; + } + } +} diff --git a/HardwareControl.Core/dll/aris/ArisSharp.dll b/HardwareControl.Core/dll/aris/ArisSharp.dll new file mode 100644 index 0000000..db96ad8 Binary files /dev/null and b/HardwareControl.Core/dll/aris/ArisSharp.dll differ diff --git a/HardwareControl.Core/dll/aris/aris.dll b/HardwareControl.Core/dll/aris/aris.dll new file mode 100644 index 0000000..8ad37c9 Binary files /dev/null and b/HardwareControl.Core/dll/aris/aris.dll differ diff --git a/HardwareControl.Core/dll/aris/libusb-1.0.dll b/HardwareControl.Core/dll/aris/libusb-1.0.dll new file mode 100644 index 0000000..76a674d Binary files /dev/null and b/HardwareControl.Core/dll/aris/libusb-1.0.dll differ diff --git a/HardwareProbe/HardwareProbe.csproj b/HardwareProbe/HardwareProbe.csproj new file mode 100644 index 0000000..5a5aa42 --- /dev/null +++ b/HardwareProbe/HardwareProbe.csproj @@ -0,0 +1,19 @@ + + + + Exe + net8.0 + enable + enable + AnyCPU;x64 + + + + + + + + + + + diff --git a/HardwareProbe/Program.cs b/HardwareProbe/Program.cs new file mode 100644 index 0000000..654f72d --- /dev/null +++ b/HardwareProbe/Program.cs @@ -0,0 +1,59 @@ +// See https://aka.ms/new-console-template for more information + +using HardwareControl.Core.HardwareServiceImpl; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.UsbCamera; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +var host = Host.CreateDefaultBuilder(args) + .ConfigureServices(services => + { + services.Configure(opt => + { + opt.DeviceNameKeyword = null; // 取第一个相机 + opt.PreferredFormatKeyword = "MJPG"; // 找不到就回退第一个 + opt.ReconnectBaseDelayMs = 1000; + opt.ReconnectMaxDelayMs = 10_000; + }); + + services.AddSingleton(); + services.AddLogging(b => b.AddConsole()); + }) + .Build(); + +var service = host.Services.GetRequiredService(); + +service.StatusChanged += (_, e) => + Console.WriteLine($"[状态] 已连接={e.IsConnected},{e.Message}"); + +var frameCount = 0; +service.FrameArrived += async (_, e) => +{ + frameCount++; + Console.WriteLine( + $"收到帧 #{e.FrameIndex},{e.Width}x{e.Height} {e.Format.PixelFormat} {e.MimeType}," + + $"大小 {e.ImageData.Length} 字节," + + $"相对时间 {e.Timestamp:mm\\:ss\\.fff},绝对时间 {e.CapturedAt:HH:mm:ss.fff}"); + + if (frameCount <= 5) + { + var extension = e.MimeType switch + { + "image/png" => "png", + "image/bmp" => "bmp", + _ => "jpg", + }; + var path = Path.Combine( + AppContext.BaseDirectory, $"frame_{frameCount}.{extension}"); + await File.WriteAllBytesAsync(path, e.ImageData); + Console.WriteLine($"已保存:{path}"); + } +}; + +await service.ConnectAsync(); +Console.WriteLine("已连接。按回车断开并退出。"); +Console.ReadLine(); + +await service.DisconnectAsync(); \ No newline at end of file diff --git a/HardwareWeb/Controllers/CameraController.cs b/HardwareWeb/Controllers/CameraController.cs new file mode 100644 index 0000000..42e6bf1 --- /dev/null +++ b/HardwareWeb/Controllers/CameraController.cs @@ -0,0 +1,56 @@ +using HardwareControl.Core; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using Microsoft.AspNetCore.Mvc; + +namespace HardwareWeb.Controllers +{ + [ApiController] + [Route("api/camera")] + public class CameraController : ControllerBase + { + private readonly IUsbCameraService _cameraService; + + public CameraController(IUsbCameraService cameraService) + { + _cameraService = cameraService; + } + + [HttpPost("connect")] + public async Task Connect(CancellationToken ct) + { + try + { + await _cameraService.ConnectAsync(ct); + return Ok(new { connected = _cameraService.IsConnected }); + } + catch (HardwareException ex) + { + return StatusCode(500, new + { + error = ex.Kind.ToString(), + message = ex.Message + }); + } + } + + [HttpPost("disconnect")] + public async Task Disconnect(CancellationToken ct) + { + await _cameraService.DisconnectAsync(ct); + return Ok(new { connected = _cameraService.IsConnected }); + } + + [HttpGet("status")] + public IActionResult GetStatus() + { + return Ok(new + { + connected = _cameraService.IsConnected, + deviceName = _cameraService.DeviceName, + format = _cameraService.FrameFormat, + framesReceived = _cameraService.FramesReceived, + lastFrameAt = _cameraService.LastFrameAt + }); + } + } +} diff --git a/HardwareWeb/Controllers/SpectrometerController.cs b/HardwareWeb/Controllers/SpectrometerController.cs new file mode 100644 index 0000000..dcb4e04 --- /dev/null +++ b/HardwareWeb/Controllers/SpectrometerController.cs @@ -0,0 +1,189 @@ +using HardwareControl.Core; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.Spectrometer; +using HardwareWeb.Models; +using Microsoft.AspNetCore.Mvc; + +namespace HardwareWeb.Controllers +{ + /// + /// aris 光谱仪 Web 接口。 + /// + /// 采集方式为同步单帧(SDK 的 AcquireFrame):POST /acquire 会阻塞到一帧采集完成, + /// 通常几十毫秒到数秒(取决于曝光时间),前端应设置足够的请求超时。 + /// 所有光谱仪操作在服务层串行执行,并发请求会排队。 + /// + [ApiController] + [Route("api/spectrometer")] + public class SpectrometerController : ControllerBase + { + private readonly IArisSpectrometerService _spectrometer; + private readonly ILogger _logger; + + public SpectrometerController( + IArisSpectrometerService spectrometer, + ILogger logger) + { + _spectrometer = spectrometer; + _logger = logger; + } + + /// 连接光谱仪并读取设备列表。重复调用是幂等的。 + [HttpPost("connect")] + [ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)] + public async Task Connect(CancellationToken ct) + { + try + { + await _spectrometer.ConnectAsync(ct); + return Ok(SpectrometerStatusPayload.From(_spectrometer)); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + /// 断开光谱仪,释放原生上下文。 + [HttpPost("disconnect")] + [ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)] + public async Task Disconnect(CancellationToken ct) + { + try + { + await _spectrometer.DisconnectAsync(ct); + return Ok(SpectrometerStatusPayload.From(_spectrometer)); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + /// 读取当前连接状态、设备列表和累计采集帧数,不访问硬件。 + [HttpGet("status")] + [ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)] + public IActionResult GetStatus() => + Ok(SpectrometerStatusPayload.From(_spectrometer)); + + /// 读取波长数组,用于单独绘制光谱坐标轴。 + [HttpGet("wavelengths")] + [ProducesResponseType(typeof(WavelengthsPayload), StatusCodes.Status200OK)] + public async Task GetWavelengths( + [FromQuery] int? deviceIndex, + CancellationToken ct) + { + try + { + var wavelengths = await _spectrometer.GetWavelengthsAsync(deviceIndex, ct); + var index = deviceIndex ?? _spectrometer.SelectedDevice?.Index ?? 0; + + return Ok(new WavelengthsPayload(index, wavelengths.Length, wavelengths)); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + /// 查询设备运行时状态(一次 USB 往返)。 + [HttpGet("devices/{deviceIndex:int}/status")] + [ProducesResponseType(typeof(SpectrometerDeviceStatusPayload), StatusCodes.Status200OK)] + public async Task GetDeviceStatus( + int deviceIndex, + CancellationToken ct) + { + try + { + var status = await _spectrometer.GetDeviceStatusAsync(deviceIndex, ct); + return Ok(SpectrometerDeviceStatusPayload.From(status)); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + /// + /// 同步采集一帧光谱。请求体可省略,此时使用 appsettings.json 中的默认参数。 + /// + [HttpPost("acquire")] + [ProducesResponseType(typeof(SpectrumFramePayload), StatusCodes.Status200OK)] + public async Task Acquire( + [FromBody] SpectrumAcquisitionRequest? request, + CancellationToken ct) + { + try + { + var frame = await _spectrometer.AcquireFrameAsync(request, ct); + return Ok(SpectrumFramePayload.From(frame)); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + /// + /// 多台光谱仪同步采集一帧:一次武装所有已连接设备,收齐后按波长自动拼接。 + /// 部分设备超时会返回已收到的数据,IsComplete=false。 + /// + [HttpPost("acquire-synchronized")] + [ProducesResponseType(typeof(SynchronizedSpectrumPayload), StatusCodes.Status200OK)] + public async Task AcquireSynchronized( + [FromBody] SynchronizedSpectrumRequest? request, + CancellationToken ct) + { + try + { + var result = await _spectrometer.AcquireSynchronizedAsync(request, ct); + return Ok(SynchronizedSpectrumPayload.From(result)); + //return Ok(null); + } + catch (HardwareException ex) + { + return HardwareError(ex); + } + } + + private IActionResult HardwareError(HardwareException ex) + { + var statusCode = ex.Kind switch + { + HardwareErrorKind.InvalidArgument => StatusCodes.Status400BadRequest, + HardwareErrorKind.NotConnected => StatusCodes.Status409Conflict, + HardwareErrorKind.InvalidState => StatusCodes.Status409Conflict, + HardwareErrorKind.Timeout => StatusCodes.Status504GatewayTimeout, + HardwareErrorKind.ConnectFailed => StatusCodes.Status503ServiceUnavailable, + HardwareErrorKind.CommunicationFailed => StatusCodes.Status503ServiceUnavailable, + HardwareErrorKind.NotSupported => StatusCodes.Status501NotImplemented, + _ => StatusCodes.Status500InternalServerError, + }; + + if (statusCode >= 500) + { + _logger.LogError( + ex, + "光谱仪接口失败:{Kind},{Message}", + ex.Kind, + ex.Message); + } + else + { + _logger.LogWarning( + "光谱仪接口失败:{Kind},{Message}", + ex.Kind, + ex.Message); + } + + return new ObjectResult(new + { + error = ex.Kind.ToString(), + message = ex.Message + }) + { + StatusCode = statusCode + }; + } + } +} diff --git a/HardwareWeb/Controllers/WeatherForecastController.cs b/HardwareWeb/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..275cf6e --- /dev/null +++ b/HardwareWeb/Controllers/WeatherForecastController.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Mvc; + +namespace HardwareWeb.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git a/HardwareWeb/HardwareWeb.csproj b/HardwareWeb/HardwareWeb.csproj new file mode 100644 index 0000000..c5c1298 --- /dev/null +++ b/HardwareWeb/HardwareWeb.csproj @@ -0,0 +1,29 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + ..\HardwareControl.Core\dll\aris\ArisSharp.dll + true + + + + diff --git a/HardwareWeb/HardwareWeb.http b/HardwareWeb/HardwareWeb.http new file mode 100644 index 0000000..82db618 --- /dev/null +++ b/HardwareWeb/HardwareWeb.http @@ -0,0 +1,74 @@ +@HardwareWeb_HostAddress = http://localhost:5062 + +GET {{HardwareWeb_HostAddress}}/weatherforecast/ +Accept: application/json + +### + +### 光谱仪:连接(枚举并初始化所有 aris 设备) +POST {{HardwareWeb_HostAddress}}/api/spectrometer/connect +Accept: application/json + +### + +### 光谱仪:状态(不访问硬件) +GET {{HardwareWeb_HostAddress}}/api/spectrometer/status +Accept: application/json + +### + +### 光谱仪:同步采集一帧,使用 appsettings 默认参数 +POST {{HardwareWeb_HostAddress}}/api/spectrometer/acquire +Content-Type: application/json +Accept: application/json + +{} + +### + +### 光谱仪:同步采集一帧,指定参数 +POST {{HardwareWeb_HostAddress}}/api/spectrometer/acquire +Content-Type: application/json +Accept: application/json + +{ + "deviceIndex": 0, + "exposureUs": 1000, + "averaging": 1, + "delayUs": 0, + "timeoutMs": 5000 +} + +### + +### 光谱仪:多台同步采集一帧并自动拼接 +POST {{HardwareWeb_HostAddress}}/api/spectrometer/acquire-synchronized +Content-Type: application/json +Accept: application/json + +{ + "exposureUs": 1000000, + "averaging": 1, + "delayUs": 0, + "waitTimeoutMs": 8000 +} + +### + +### 光谱仪:波长轴 +GET {{HardwareWeb_HostAddress}}/api/spectrometer/wavelengths?deviceIndex=0 +Accept: application/json + +### + +### 光谱仪:设备运行时状态 +GET {{HardwareWeb_HostAddress}}/api/spectrometer/devices/0/status +Accept: application/json + +### + +### 光谱仪:断开 +POST {{HardwareWeb_HostAddress}}/api/spectrometer/disconnect +Accept: application/json + +### diff --git a/HardwareWeb/Hubs/CameraHub.cs b/HardwareWeb/Hubs/CameraHub.cs new file mode 100644 index 0000000..14ecf7a --- /dev/null +++ b/HardwareWeb/Hubs/CameraHub.cs @@ -0,0 +1,109 @@ +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareWeb.Models; +using HardwareWeb.Services; +using Microsoft.AspNetCore.SignalR; + +namespace HardwareWeb.Hubs +{ + /// + /// 相机实时通道: + /// - 连接后自动加入画面组,并立即收到一次 CameraStatus; + /// - 前端可调用 SubscribeFrames / UnsubscribeFrames 暂停或恢复画面; + /// - GetStatus 用于页面刷新或断线重连后的状态对齐。 + /// + public class CameraHub : Hub + { + public const string FrameGroup = "camera-frames"; + + private readonly IUsbCameraService _cameraService; + private readonly CameraViewerRegistry _viewers; + private readonly ILogger _logger; + + public CameraHub( + IUsbCameraService cameraService, + CameraViewerRegistry viewers, + ILogger logger) + { + _cameraService = cameraService; + _viewers = viewers; + _logger = logger; + } + + public override async Task OnConnectedAsync() + { + await base.OnConnectedAsync(); + + await JoinFrameGroupAsync(Context.ConnectionId, Context.ConnectionAborted); + await SendStatusAsync(Clients.Caller, Context.ConnectionAborted); + + _logger.LogInformation( + "SignalR 客户端已连接:{ConnectionId},当前画面观看者 {Count}", + Context.ConnectionId, _viewers.Count); + } + + public override async Task OnDisconnectedAsync(Exception? exception) + { + _viewers.Remove(Context.ConnectionId); + + await base.OnDisconnectedAsync(exception); + + _logger.LogInformation( + "SignalR 客户端已断开:{ConnectionId},当前画面观看者 {Count}", + Context.ConnectionId, _viewers.Count); + } + + /// 读取当前相机状态,不改变订阅。 + public CameraStatusPayload GetStatus() => + CameraStatusPayload.From(_cameraService); + + /// 恢复画面推送。连接时默认已订阅,可重复调用。 + public async Task SubscribeFrames() + { + await JoinFrameGroupAsync(Context.ConnectionId, Context.ConnectionAborted); + return CameraStatusPayload.From(_cameraService); + } + + /// 停止接收画面,但仍可接收 CameraStatus。 + public async Task UnsubscribeFrames() + { + await Groups.RemoveFromGroupAsync( + Context.ConnectionId, FrameGroup, Context.ConnectionAborted); + _viewers.Remove(Context.ConnectionId); + + _logger.LogInformation( + "客户端暂停画面:{ConnectionId},当前画面观看者 {Count}", + Context.ConnectionId, _viewers.Count); + } + + private async Task JoinFrameGroupAsync( + string connectionId, CancellationToken ct) + { + try + { + await Groups.AddToGroupAsync(connectionId, FrameGroup, ct); + _viewers.Add(connectionId); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning( + ex, "加入相机画面组失败:{ConnectionId}", connectionId); + } + } + + private async Task SendStatusAsync(IClientProxy client, CancellationToken ct) + { + try + { + await client.SendAsync( + "CameraStatus", + CameraStatusPayload.From(_cameraService), + ct); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning( + ex, "发送相机初始状态失败:{ConnectionId}", Context.ConnectionId); + } + } + } +} diff --git a/HardwareWeb/Models/CameraFramePayload.cs b/HardwareWeb/Models/CameraFramePayload.cs new file mode 100644 index 0000000..52d4b9f --- /dev/null +++ b/HardwareWeb/Models/CameraFramePayload.cs @@ -0,0 +1,15 @@ +namespace HardwareWeb.Models +{ + /// + /// SignalR "CameraFrame" 事件负载。图像以 base64 发送, + /// MimeType 指明 JPEG / PNG / BMP,前端据此生成 data URL。 + /// + public sealed record CameraFramePayload( + long FrameIndex, + TimeSpan Timestamp, + DateTimeOffset CapturedAt, + int Width, + int Height, + string MimeType, + string ImageBase64); +} diff --git a/HardwareWeb/Models/CameraStatusPayload.cs b/HardwareWeb/Models/CameraStatusPayload.cs new file mode 100644 index 0000000..c014ebe --- /dev/null +++ b/HardwareWeb/Models/CameraStatusPayload.cs @@ -0,0 +1,33 @@ +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.UsbCamera; + +namespace HardwareWeb.Models +{ + /// + /// SignalR "CameraStatus" 事件负载。 + /// 前端只依赖 IsConnected / Message,其余字段用于诊断和扩展。 + /// + public sealed record CameraStatusPayload( + bool IsConnected, + string Message, + string? DeviceName, + CameraFrameFormat? Format, + long FramesReceived, + DateTimeOffset? LastFrameAt, + DateTimeOffset UpdatedAt) + { + public static CameraStatusPayload From( + IUsbCameraService camera, string? message = null) + { + var isConnected = camera.IsConnected; + return new CameraStatusPayload( + isConnected, + message ?? (isConnected ? "相机已连接" : "相机未连接"), + camera.DeviceName, + camera.FrameFormat, + camera.FramesReceived, + camera.LastFrameAt, + DateTimeOffset.Now); + } + } +} diff --git a/HardwareWeb/Models/MergedSpectrumPayload.cs b/HardwareWeb/Models/MergedSpectrumPayload.cs new file mode 100644 index 0000000..415ac61 --- /dev/null +++ b/HardwareWeb/Models/MergedSpectrumPayload.cs @@ -0,0 +1,22 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 拼接后的完整光谱。直接拼接原始采样点,不做插值; + /// 前端应按 Segments 分段绘制,段与段之间波长不连续时断开连线。 + /// + public sealed record MergedSpectrumPayload( + int PixelCount, + float[] Wavelengths, + float[] Spectrum, + IReadOnlyList Segments) + { + public static MergedSpectrumPayload From(MergedSpectrum merged) => + new( + merged.PixelCount, + merged.Wavelengths, + merged.Spectrum, + merged.Segments.Select(MergedSpectrumSegmentPayload.From).ToArray()); + } +} diff --git a/HardwareWeb/Models/MergedSpectrumSegmentPayload.cs b/HardwareWeb/Models/MergedSpectrumSegmentPayload.cs new file mode 100644 index 0000000..6ceaa72 --- /dev/null +++ b/HardwareWeb/Models/MergedSpectrumSegmentPayload.cs @@ -0,0 +1,21 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// 拼接光谱中的一段及其来源设备。 + public sealed record MergedSpectrumSegmentPayload( + int DeviceIndex, + string SerialNumber, + float WavelengthStart, + float WavelengthEnd, + int PointCount) + { + public static MergedSpectrumSegmentPayload From(MergedSpectrumSegment segment) => + new( + segment.DeviceIndex, + segment.SerialNumber, + segment.WavelengthStart, + segment.WavelengthEnd, + segment.PointCount); + } +} diff --git a/HardwareWeb/Models/SpectrometerDevicePayload.cs b/HardwareWeb/Models/SpectrometerDevicePayload.cs new file mode 100644 index 0000000..ebfcb67 --- /dev/null +++ b/HardwareWeb/Models/SpectrometerDevicePayload.cs @@ -0,0 +1,26 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 光谱仪静态设备信息。 + /// StartPixel / EndPixel 是协议原始值,不是光谱切片起止像素。 + /// + public sealed record SpectrometerDevicePayload( + int Index, + string SerialNumber, + int PixelCount, + int StartPixel, + int EndPixel, + string FirmwareVersion) + { + public static SpectrometerDevicePayload From(SpectrometerDeviceInfo device) => + new( + device.Index, + device.SerialNumber, + device.PixelCount, + device.StartPixel, + device.EndPixel, + device.FirmwareVersion); + } +} diff --git a/HardwareWeb/Models/SpectrometerDeviceStatusPayload.cs b/HardwareWeb/Models/SpectrometerDeviceStatusPayload.cs new file mode 100644 index 0000000..4d1dc81 --- /dev/null +++ b/HardwareWeb/Models/SpectrometerDeviceStatusPayload.cs @@ -0,0 +1,14 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// 光谱仪运行时状态(一次 USB 往返)。 + public sealed record SpectrometerDeviceStatusPayload( + int DeviceIndex, + string State, + int AvailableSpectra) + { + public static SpectrometerDeviceStatusPayload From(SpectrometerDeviceStatus status) => + new(status.DeviceIndex, status.State, status.AvailableSpectra); + } +} diff --git a/HardwareWeb/Models/SpectrometerStatusPayload.cs b/HardwareWeb/Models/SpectrometerStatusPayload.cs new file mode 100644 index 0000000..74698c9 --- /dev/null +++ b/HardwareWeb/Models/SpectrometerStatusPayload.cs @@ -0,0 +1,50 @@ +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 光谱仪状态负载。 + /// 前端可只依赖 IsConnected / Message,其余字段用于诊断。 + /// + public sealed record SpectrometerStatusPayload( + bool IsConnected, + string Message, + int DeviceCount, + SpectrometerDevicePayload? SelectedDevice, + IReadOnlyList Devices, + long FramesAcquired, + DateTimeOffset? LastAcquireAt, + DateTimeOffset UpdatedAt) + { + public static SpectrometerStatusPayload From( + IArisSpectrometerService service, + string? message = null) + { + var isConnected = service.IsConnected; + var devices = service.Devices + .Select(SpectrometerDevicePayload.From) + .ToArray(); + + var selected = service.SelectedDevice is { } device + ? SpectrometerDevicePayload.From(device) + : null; + + var defaultMessage = isConnected + ? selected is null + ? "光谱仪已连接" + : $"光谱仪已连接:{selected.SerialNumber}" + : "光谱仪未连接"; + + return new SpectrometerStatusPayload( + isConnected, + message ?? defaultMessage, + service.DeviceCount, + selected, + devices, + service.FramesAcquired, + service.LastAcquireAt, + DateTimeOffset.Now); + } + } +} diff --git a/HardwareWeb/Models/SpectrumDeviceErrorPayload.cs b/HardwareWeb/Models/SpectrumDeviceErrorPayload.cs new file mode 100644 index 0000000..ba4720f --- /dev/null +++ b/HardwareWeb/Models/SpectrumDeviceErrorPayload.cs @@ -0,0 +1,11 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// 测量过程中 SDK 上报的单台设备错误。 + public sealed record SpectrumDeviceErrorPayload(string SerialNumber, string Message) + { + public static SpectrumDeviceErrorPayload From(SpectrumDeviceError error) => + new(error.SerialNumber, error.Message); + } +} diff --git a/HardwareWeb/Models/SpectrumFrameInfoPayload.cs b/HardwareWeb/Models/SpectrumFrameInfoPayload.cs new file mode 100644 index 0000000..0ad889e --- /dev/null +++ b/HardwareWeb/Models/SpectrumFrameInfoPayload.cs @@ -0,0 +1,41 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 光谱帧头元数据,字段含义见 aris C API 手册的 aris_frame_info。 + /// + public sealed record SpectrumFrameInfoPayload( + int ExposureTimeUs, + int Averaging, + uint DeviceTime10Us, + uint DeviceDateDays, + int PixelCount, + int DataFormat, + float LoadLevel, + float SensorTemperature, + float DarkAvg, + float ReadoutNoise, + ushort AppliedProcessing, + ushort ErrorFlags, + ushort IntensityUnit, + bool DarkSubtracted) + { + public static SpectrumFrameInfoPayload From(SpectrumFrameInfo info) => + new( + info.ExposureTimeUs, + info.Averaging, + info.DeviceTime10Us, + info.DeviceDateDays, + info.PixelCount, + info.DataFormat, + info.LoadLevel, + info.SensorTemperature, + info.DarkAvg, + info.ReadoutNoise, + info.AppliedProcessing, + info.ErrorFlags, + info.IntensityUnit, + info.DarkSubtracted); + } +} diff --git a/HardwareWeb/Models/SpectrumFramePayload.cs b/HardwareWeb/Models/SpectrumFramePayload.cs new file mode 100644 index 0000000..866ce84 --- /dev/null +++ b/HardwareWeb/Models/SpectrumFramePayload.cs @@ -0,0 +1,30 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 单帧光谱负载。Wavelengths 与 Spectrum 等长,长度见 PixelCount。 + /// 前端通常把 Wavelengths 作为 x 轴、Spectrum 作为 y 轴绘制曲线。 + /// + public sealed record SpectrumFramePayload( + int DeviceIndex, + string SerialNumber, + int PixelCount, + float[] Wavelengths, + float[] Spectrum, + SpectrumFrameInfoPayload Info, + DateTimeOffset AcquiredAt, + double ElapsedMs) + { + public static SpectrumFramePayload From(SpectrumFrame frame) => + new( + frame.DeviceIndex, + frame.SerialNumber, + frame.Info.PixelCount, + frame.Wavelengths, + frame.Spectrum, + SpectrumFrameInfoPayload.From(frame.Info), + frame.AcquiredAt, + Math.Round(frame.Elapsed.TotalMilliseconds, 1)); + } +} diff --git a/HardwareWeb/Models/SynchronizedSpectrumFramePayload.cs b/HardwareWeb/Models/SynchronizedSpectrumFramePayload.cs new file mode 100644 index 0000000..46c06ec --- /dev/null +++ b/HardwareWeb/Models/SynchronizedSpectrumFramePayload.cs @@ -0,0 +1,25 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 多台同步采集时某一台设备的原始帧。流式回调不带帧头元数据。 + /// + public sealed record SynchronizedSpectrumFramePayload( + int DeviceIndex, + string SerialNumber, + int PixelCount, + float[] Wavelengths, + float[] Spectrum, + DateTimeOffset ReceivedAt) + { + public static SynchronizedSpectrumFramePayload From(SynchronizedSpectrumFrame frame) => + new( + frame.DeviceIndex, + frame.SerialNumber, + frame.PixelCount, + frame.Wavelengths, + frame.Spectrum, + frame.ReceivedAt); + } +} diff --git a/HardwareWeb/Models/SynchronizedSpectrumPayload.cs b/HardwareWeb/Models/SynchronizedSpectrumPayload.cs new file mode 100644 index 0000000..aeb9819 --- /dev/null +++ b/HardwareWeb/Models/SynchronizedSpectrumPayload.cs @@ -0,0 +1,34 @@ +using HardwareControl.Core.Spectrometer; + +namespace HardwareWeb.Models +{ + /// + /// 多台光谱仪同步采集结果。 + /// IsComplete=false 表示有设备超时未返回,Frames/Merged 是已收到设备的部分结果。 + /// + public sealed record SynchronizedSpectrumPayload( + bool IsComplete, + int ExpectedDeviceCount, + int ReceivedDeviceCount, + IReadOnlyList Frames, + MergedSpectrumPayload Merged, + IReadOnlyList MissingSerials, + IReadOnlyList Errors, + DateTimeOffset AcquiredAt, + double StartElapsedMs, + double WaitElapsedMs) + { + public static SynchronizedSpectrumPayload From(SynchronizedSpectrumResult result) => + new( + result.IsComplete, + result.ExpectedDeviceCount, + result.ReceivedDeviceCount, + result.Frames.Select(SynchronizedSpectrumFramePayload.From).ToArray(), + MergedSpectrumPayload.From(result.Merged), + result.MissingSerials, + result.Errors.Select(SpectrumDeviceErrorPayload.From).ToArray(), + result.AcquiredAt, + Math.Round(result.StartElapsed.TotalMilliseconds, 1), + Math.Round(result.WaitElapsed.TotalMilliseconds, 1)); + } +} diff --git a/HardwareWeb/Models/WavelengthsPayload.cs b/HardwareWeb/Models/WavelengthsPayload.cs new file mode 100644 index 0000000..4b47739 --- /dev/null +++ b/HardwareWeb/Models/WavelengthsPayload.cs @@ -0,0 +1,8 @@ +namespace HardwareWeb.Models +{ + /// 波长数组负载,用于单独绘制光谱坐标轴。 + public sealed record WavelengthsPayload( + int DeviceIndex, + int PixelCount, + float[] Wavelengths); +} diff --git a/HardwareWeb/Program.cs b/HardwareWeb/Program.cs new file mode 100644 index 0000000..8372dcd --- /dev/null +++ b/HardwareWeb/Program.cs @@ -0,0 +1,61 @@ +using HardwareControl.Core.HardwareServiceImpl; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.Spectrometer; +using HardwareControl.Core.UsbCamera; +using HardwareWeb.Hubs; +using HardwareWeb.Services; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +// 1. 相机配置从 appsettings.json 的 "UsbCamera" 节读取 +builder.Services.Configure( + builder.Configuration.GetSection("UsbCamera")); + +// 2. 注册相机服务为单例——整个进程只允许一个实例持有 CaptureDevice +builder.Services.AddSingleton(); + +// 3. 光谱仪配置从 appsettings.json 的 "ArisSpectrometer" 节读取。 +// 光谱仪服务同样必须是单例:aris 上下文和 USB 设备不能被多个实例同时持有。 +builder.Services.Configure( + builder.Configuration.GetSection(ArisSpectrometerOptions.SectionName)); +builder.Services.AddSingleton(); + +// 4. 相机推流参数(帧率、观看者 gating、帧大小上限) +builder.Services.Configure( + builder.Configuration.GetSection(CameraStreamOptions.SectionName)); +builder.Services.AddSingleton(); + +// 5. SignalR +builder.Services.AddSignalR(options => +{ + options.EnableDetailedErrors = builder.Environment.IsDevelopment(); +}); + +// 6. 后台桥接服务:消费硬件事件,通过 IHubContext 推送给客户端 +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); + + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseAuthorization(); + +app.MapControllers(); + +// 前端通过 /cameraHub 接收 CameraFrame / CameraStatus 实时消息 +app.MapHub("/cameraHub"); + +app.Run(); diff --git a/HardwareWeb/Properties/launchSettings.json b/HardwareWeb/Properties/launchSettings.json new file mode 100644 index 0000000..f374618 --- /dev/null +++ b/HardwareWeb/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:29203", + "sslPort": 0 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5062", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/HardwareWeb/SPECTROMETER_API.md b/HardwareWeb/SPECTROMETER_API.md new file mode 100644 index 0000000..2076947 --- /dev/null +++ b/HardwareWeb/SPECTROMETER_API.md @@ -0,0 +1,272 @@ +# aris 光谱仪 Web 接口 + +所有接口以 `/api/spectrometer` 为前缀,返回 JSON(camelCase), +实现见 `Controllers/SpectrometerController.cs`,硬件封装见 +`HardwareControl.Core/HardwareServiceImpl/ArisSpectrometerService.cs`。 + +## 调用顺序 + +1. `POST /api/spectrometer/connect` +2. 按需调用 `GET /api/spectrometer/status`、`POST /api/spectrometer/acquire`(单台) + 或 `POST /api/spectrometer/acquire-synchronized`(多台同步采集并拼接) +3. 结束时 `POST /api/spectrometer/disconnect` + +## 触发模式 + +`appsettings.json` 的 `ArisSpectrometer:TriggerMode` 决定连接后写入设备的触发模式: + +| 值 | 适用场景 | +|---|---| +| `Software`(本工程默认) | 纯自由运行;本工程由 670 启动采集时触发激光,使用此模式 | +| `FreeRunEdge` | 自由运行 + 外触发输入使能;需要外部 AD/TTL 触发沿时使用 | +| `External` | 仅响应外部硬触发,没有触发源时不会出帧 | + +本工程的实际接线是 **670 触发激光器**,所以不要用 `FreeRunEdge`: +实测 `FreeRunEdge` 下 670 会停在 `WaitingForTrigger`,不产新帧, +只能读到一小时前的旧帧;改成 `Software` 后 670 会自由运行并产生新帧。 + +### 同步采集的曝光时间 + +SDK 的 `StartMeasurement` 是**逐台武装**的:646、664 先启动,670 约晚 **0.6 秒** +才启动并触发激光。因此同步采集的曝光窗口必须覆盖这段时间: + +- `appsettings.json` 的 `SynchronizedExposureUs` 默认 **1,000,000 µs(1 秒)**; +- 前两台在 1 秒曝光内仍处于曝光状态,670 启动触发激光时能收到光; +- 如果把 `exposureUs` 设成 2000 µs(2 ms),前两台会在约 70 ms 就结束, + 670 还没启动,激光自然收不到; +- 现场可按实际武装时间下调,但建议不低于 **0.7 秒**。 + +修改配置后需要重启 `HardwareWeb` 并重新调用 `connect` 才会写入设备。 + +## 接口 + +### POST /api/spectrometer/connect + +枚举并连接所有 aris 光谱仪,读取设备信息,并按配置设置触发模式。 +无设备时返回 `503`,`error = "ConnectFailed"`。 + +响应体: + +```json +{ + "isConnected": true, + "message": "光谱仪已连接:SN...", + "deviceCount": 1, + "selectedDevice": { + "index": 0, + "serialNumber": "SN...", + "pixelCount": 3648, + "startPixel": 0, + "endPixel": 15, + "firmwareVersion": "4.3.7.0" + }, + "devices": [ + { + "index": 0, + "serialNumber": "SN...", + "pixelCount": 3648, + "startPixel": 0, + "endPixel": 15, + "firmwareVersion": "4.3.7.0" + } + ], + "framesAcquired": 0, + "lastAcquireAt": null, + "updatedAt": "2026-11-09T09:39:01+08:00" +} +``` + +> `startPixel` / `endPixel` 是协议 0x2009/0x200A 的原始值, +> 不是光谱起止像素,不能用于切片。 + +### POST /api/spectrometer/disconnect + +停止测量、断开 USB 并销毁 aris 上下文。响应体同 `connect`(此时未连接)。 + +### GET /api/spectrometer/status + +不访问硬件,直接返回缓存的连接状态、设备列表和计数。响应体同 `connect`。 + +### POST /api/spectrometer/acquire + +同步采集一帧。请求体可省略或传 `{}`,此时使用 `appsettings.json` +`ArisSpectrometer` 节的默认参数。 + +```json +{ + "deviceIndex": 0, + "exposureUs": 1000, + "averaging": 1, + "delayUs": 0, + "timeoutMs": 5000 +} +``` + +| 字段 | 说明 | +|---|---| +| `deviceIndex` | 设备索引,缺省用连接时选中的设备 | +| `exposureUs` | 曝光时间(微秒),必须 > 0 | +| `averaging` | 平均次数,必须 ≥ 1 | +| `delayUs` | 触发延迟(微秒),必须 ≥ 0 | +| `timeoutMs` | 超时(毫秒),≤ 0 时由 SDK 按 `max(3000, 曝光/1000 + 2000)` 计算 | + +响应体: + +```json +{ + "deviceIndex": 0, + "serialNumber": "SN...", + "pixelCount": 3648, + "wavelengths": [340.0, 340.2, 340.4], + "spectrum": [1234.5, 1240.1, 1238.7], + "info": { + "exposureTimeUs": 1000, + "averaging": 1, + "deviceTime10Us": 0, + "deviceDateDays": 0, + "pixelCount": 3648, + "dataFormat": 0, + "loadLevel": 0.42, + "sensorTemperature": 28.5, + "darkAvg": 100.2, + "readoutNoise": 3.1, + "appliedProcessing": 0, + "errorFlags": 0, + "intensityUnit": 0, + "darkSubtracted": false + }, + "acquiredAt": "2026-11-09T09:39:01+08:00", + "elapsedMs": 1032.4 +} +``` + +`wavelengths` 与 `spectrum` 等长,前端把前者当 x 轴、后者当 y 轴即可。 +上面的数组为截断示例,实际长度为 `pixelCount`(本机设备为 3648)。 + +### POST /api/spectrometer/acquire-synchronized + +多台光谱仪同时收光:一次 `StartMeasurement` 武装所有已连接设备,每台采一帧, +收齐后按波长自动拼接。请求体可省略: + +```json +{ + "exposureUs": 1000000, + "averaging": 1, + "delayUs": 0, + "waitTimeoutMs": 8000 +} +``` + +| 字段 | 说明 | +|---|---| +| `exposureUs` | 曝光时间(微秒),必须 > 0;缺省用 `SynchronizedExposureUs`(默认 1,000,000) | +| `averaging` | 平均次数,必须 ≥ 1 | +| `delayUs` | 触发延迟(微秒),必须 ≥ 0 | +| `waitTimeoutMs` | `StartMeasurement` 返回后等待所有设备回调的最长时间(毫秒);≤ 0 用配置 `SynchronizedWaitTimeoutMs` | + +本工程使用 `ArisSpectrometer:TriggerMode = Software`(默认): +670 启动采集时触发激光,646/664 在 1 秒曝光窗口内收光。 +`FreeRunEdge` / `External` 只在有外部 AD/TTL 触发源时使用; +`FreeRunEdge` 下 670 会等待外触发,可能只返回旧帧。触发模式只在 `connect` 时写入一次。 + +响应体(数组仅示意,实际长度见 `pixelCount`): + +```json +{ + "isComplete": true, + "expectedDeviceCount": 3, + "receivedDeviceCount": 3, + "frames": [ + { + "deviceIndex": 0, + "serialNumber": "646", + "pixelCount": 3648, + "wavelengths": [189.45, 189.50, 189.55], + "spectrum": [12.3, 12.5, 12.4], + "receivedAt": "2026-11-09T10:55:03+08:00" + } + ], + "merged": { + "pixelCount": 10000, + "wavelengths": [189.45, 189.50, 189.55], + "spectrum": [12.3, 12.5, 12.4], + "segments": [ + { + "deviceIndex": 0, + "serialNumber": "646", + "wavelengthStart": 189.45, + "wavelengthEnd": 279.2, + "pointCount": 1824 + } + ] + }, + "missingSerials": [], + "errors": [], + "acquiredAt": "2026-11-09T10:55:03+08:00", + "startElapsedMs": 3120.5, + "waitElapsedMs": 78.2 +} +``` + +拼接规则: + +1. 设备按起始波长升序排列。 +2. 两台设备波长区间重合时,取重合区间的中点切分: + 低波长设备保留下半段,高波长设备保留上半段,即“重合部分各去一半”。 +3. 三台及以上同时重合时,按两两中点划分子区间,再按两两胜出次数决定归属; + 平票时优先保留起始波长更高的设备。 +4. 一台设备被另一台完全覆盖时,它仍可贡献中间一段;`segments` 会为同一台设备 + 生成多段。 +5. 直接拼接各设备原始采样点,**不做插值**;`segments` 用于前端分段绘制, + 相邻段波长不连续时应断开连线。 + +部分设备超时不会让整个请求失败:接口仍返回 `200`,`isComplete=false`, +`missingSerials` 列出缺失设备,`frames`/`merged` 是已收到设备的结果。 +一台都没收到时返回 `504 Timeout`。 + +> 流式回调不携带帧头,因此这里的 `frames` 没有温度、负载率等元数据; +> 需要这些字段请使用单帧 `POST /acquire`。 + +### GET /api/spectrometer/wavelengths?deviceIndex=0 + +只取波长数组,避免每次重绘都保存整帧: + +```json +{ "deviceIndex": 0, "pixelCount": 3648, "wavelengths": [340.0, 340.2, 340.4] } +``` + +数组为截断示例。 + +### GET /api/spectrometer/devices/{deviceIndex}/status + +查询设备运行时状态,每次调用有一次 USB 往返: + +```json +{ "deviceIndex": 0, "state": "Idle", "availableSpectra": 0 } +``` + +## 错误响应 + +```json +{ "error": "NotConnected", "message": "光谱仪尚未连接,请先调用连接接口" } +``` + +| HTTP | error | 说明 | +|---|---|---| +| 400 | `InvalidArgument` | 参数越界(曝光 ≤ 0、索引超范围等) | +| 409 | `NotConnected` / `InvalidState` | 未连接,或设备状态不允许采集 | +| 501 | `NotSupported` | 设备/固件不支持(如 DataFormat ≠ 0) | +| 503 | `ConnectFailed` / `CommunicationFailed` | 未发现设备、DLL 加载失败或 USB 通信失败 | +| 504 | `Timeout` | 等光谱超时 | + +## 前端注意事项 + +- `POST /acquire` 是同步阻塞调用,耗时约等于 `曝光 × 平均 + 准备时间`, + 前端请求超时应大于 `timeoutMs`(建议 10s 以上)。 +- `POST /acquire-synchronized` 会先逐台武装设备(670 约比前两台晚 0.6s), + 再等待一次 1 秒左右的曝光窗口和 `waitTimeoutMs`;前端请求超时应大于 + 这段时间之和(建议 20s 以上)。 +- 服务层串行化所有光谱仪调用,多个前端同时采集会排队,不会并发干扰设备。 +- 同一个页面不要同时发起多个采集请求,否则后一个会等待前一个完成。 +- 进程必须是 x64;`aris.dll` 与 `libusb-1.0.dll` 由 `HardwareControl.Core` + 自动复制到输出目录。 diff --git a/HardwareWeb/Services/CameraBroadcastChannel.cs b/HardwareWeb/Services/CameraBroadcastChannel.cs new file mode 100644 index 0000000..f18e12e --- /dev/null +++ b/HardwareWeb/Services/CameraBroadcastChannel.cs @@ -0,0 +1,44 @@ +using System.Threading.Channels; +using HardwareControl.Core.UsbCamera; + +namespace HardwareWeb.Services +{ + public abstract record CameraBroadcastMessage; + + public record FrameMessage( + byte[] ImageData, + long FrameIndex, + TimeSpan Timestamp, + DateTimeOffset CapturedAt, + CameraFrameFormat Format) + : CameraBroadcastMessage; + + public record StatusMessage(bool IsConnected, string Message) + : CameraBroadcastMessage; + + public class CameraBroadcastChannel + { + private readonly Channel _channel; + + public CameraBroadcastChannel() + { + // 只保留较新的帧:消费速度低于采集速度时丢弃旧帧, + // 而不是把几十帧大图堆在内存里。 + _channel = Channel.CreateBounded( + new BoundedChannelOptions(16) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + SingleWriter = false, + AllowSynchronousContinuations = false, + }); + } + + public bool TryWrite(CameraBroadcastMessage message) + => _channel.Writer.TryWrite(message); + + public IAsyncEnumerable ReadAllAsync( + CancellationToken ct) + => _channel.Reader.ReadAllAsync(ct); + } +} diff --git a/HardwareWeb/Services/CameraBroadcastService.cs b/HardwareWeb/Services/CameraBroadcastService.cs new file mode 100644 index 0000000..14ec341 --- /dev/null +++ b/HardwareWeb/Services/CameraBroadcastService.cs @@ -0,0 +1,191 @@ +using System.Diagnostics; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.UsbCamera; +using HardwareWeb.Hubs; +using HardwareWeb.Models; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Options; + +namespace HardwareWeb.Services +{ + /// + /// 消费相机事件并通过 SignalR 推送: + /// - CameraStatus 广播给所有已连接客户端; + /// - CameraFrame 只发送给加入相机画面组的客户端; + /// - 按配置帧率抽帧,没有观看者时不生成 base64,降低带宽和 CPU。 + /// + public class CameraBroadcastService : BackgroundService + { + private readonly IUsbCameraService _cameraService; + private readonly CameraBroadcastChannel _channel; + private readonly IHubContext _hubContext; + private readonly CameraViewerRegistry _viewers; + private readonly CameraStreamOptions _options; + private readonly ILogger _logger; + + private long _lastFrameSentTimestamp; + private bool _firstFrameLogged; + + public CameraBroadcastService( + IUsbCameraService cameraService, + CameraBroadcastChannel channel, + IHubContext hubContext, + CameraViewerRegistry viewers, + IOptions options, + ILogger logger) + { + _cameraService = cameraService; + _channel = channel; + _hubContext = hubContext; + _viewers = viewers; + _options = options.Value; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _cameraService.StatusChanged += OnStatusChanged; + _cameraService.FrameArrived += OnFrameArrived; + + _logger.LogInformation( + "相机推流已启动:Enabled={Enabled},FPS={Fps},仅在有观看者时推流={OnlyViewers}", + _options.Enabled, + Math.Clamp(_options.FramesPerSecond, 1, 60), + _options.SendOnlyWhenViewers); + + try + { + await foreach (var message in _channel.ReadAllAsync(stoppingToken)) + { + try + { + switch (message) + { + case StatusMessage status: + await BroadcastStatusAsync(status, stoppingToken); + break; + + case FrameMessage frame: + await BroadcastFrameAsync(frame, stoppingToken); + break; + } + } + catch (OperationCanceledException) + when (stoppingToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "推送消息到 SignalR 失败"); + } + } + } + catch (OperationCanceledException) + when (stoppingToken.IsCancellationRequested) + { + // 正常停机 + } + finally + { + _cameraService.StatusChanged -= OnStatusChanged; + _cameraService.FrameArrived -= OnFrameArrived; + } + } + + private async Task BroadcastStatusAsync( + StatusMessage status, CancellationToken ct) + { + var payload = CameraStatusPayload.From(_cameraService, status.Message) with + { + IsConnected = status.IsConnected, + }; + await _hubContext.Clients.All.SendAsync("CameraStatus", payload, ct); + + _logger.LogInformation( + "相机状态推送:{Connected},{Message}", + payload.IsConnected, payload.Message); + } + + private async Task BroadcastFrameAsync( + FrameMessage frame, CancellationToken ct) + { + if (!_options.Enabled) + { + return; + } + + if (_options.SendOnlyWhenViewers && !_viewers.HasViewers) + { + // 没有观看者时重置节流时间,第一个观看者接入后可立即收到画面。 + _lastFrameSentTimestamp = 0; + return; + } + + var maxFrameBytes = _options.MaxFrameBytes; + if (maxFrameBytes > 0 && frame.ImageData.Length > maxFrameBytes) + { + _logger.LogWarning( + "丢弃超大相机帧:{Size} 字节,上限 {Limit} 字节", + frame.ImageData.Length, maxFrameBytes); + return; + } + + var maxAgeMs = _options.MaxFrameAgeMs; + if (maxAgeMs > 0 && + DateTimeOffset.UtcNow - frame.CapturedAt.ToUniversalTime() > + TimeSpan.FromMilliseconds(maxAgeMs)) + { + return; + } + + var fps = Math.Clamp(_options.FramesPerSecond, 1, 60); + var minIntervalTicks = Stopwatch.Frequency / (double)fps; + var now = Stopwatch.GetTimestamp(); + + if (_lastFrameSentTimestamp != 0 && + now - _lastFrameSentTimestamp < minIntervalTicks) + { + return; + } + + _lastFrameSentTimestamp = now; + + var payload = new CameraFramePayload( + frame.FrameIndex, + frame.Timestamp, + frame.CapturedAt, + frame.Format.Width, + frame.Format.Height, + frame.Format.MimeType, + Convert.ToBase64String(frame.ImageData)); + + await _hubContext.Clients + .Group(CameraHub.FrameGroup) + .SendAsync("CameraFrame", payload, ct); + + if (!_firstFrameLogged) + { + _firstFrameLogged = true; + _logger.LogInformation( + "开始推送相机画面:{Width}x{Height},{Mime},原始 {Size} 字节,限帧 {Fps}fps", + frame.Format.Width, frame.Format.Height, frame.Format.MimeType, + frame.ImageData.Length, fps); + } + } + + private void OnStatusChanged( + object? sender, UsbCameraStatusChangedEventArgs e) + { + _channel.TryWrite(new StatusMessage(e.IsConnected, e.Message)); + } + + private void OnFrameArrived(object? sender, FrameArrivedEventArgs e) + { + // 关键:这里运行在 FlashCap 的采集线程上。 + // ImageData 已由 CopyImage() 复制,可安全地放入 Channel 异步发送。 + _channel.TryWrite(new FrameMessage( + e.ImageData, e.FrameIndex, e.Timestamp, e.CapturedAt, e.Format)); + } + } +} diff --git a/HardwareWeb/Services/CameraStreamOptions.cs b/HardwareWeb/Services/CameraStreamOptions.cs new file mode 100644 index 0000000..774d26d --- /dev/null +++ b/HardwareWeb/Services/CameraStreamOptions.cs @@ -0,0 +1,25 @@ +namespace HardwareWeb.Services +{ + /// + /// 相机推流参数,对应 appsettings.json 的 "CameraStream" 节。 + /// + public sealed class CameraStreamOptions + { + public const string SectionName = "CameraStream"; + + /// 是否向前端推送视频帧。 + public bool Enabled { get; set; } = true; + + /// 推流帧率上限。相机本身 30fps 时默认降到 15fps,降低带宽与 CPU。 + public int FramesPerSecond { get; set; } = 15; + + /// 没有 SignalR 观看者时不生成 base64,也不推送。 + public bool SendOnlyWhenViewers { get; set; } = true; + + /// 超过该时长的旧帧直接丢弃,避免重连后显示过期画面;0 表示不限制。 + public int MaxFrameAgeMs { get; set; } = 1500; + + /// 单帧字节数上限,超过则丢弃并记录告警。 + public int MaxFrameBytes { get; set; } = 8 * 1024 * 1024; + } +} diff --git a/HardwareWeb/Services/CameraViewerRegistry.cs b/HardwareWeb/Services/CameraViewerRegistry.cs new file mode 100644 index 0000000..da41205 --- /dev/null +++ b/HardwareWeb/Services/CameraViewerRegistry.cs @@ -0,0 +1,23 @@ +using System.Collections.Concurrent; + +namespace HardwareWeb.Services +{ + /// + /// 记录当前订阅视频帧的 SignalR 连接。 + /// 广播服务据此判断“是否有观看者”,没有观看者时不编码、不发送画面。 + /// + public sealed class CameraViewerRegistry + { + private readonly ConcurrentDictionary _viewers = + new(StringComparer.Ordinal); + + public int Count => _viewers.Count; + + public bool HasViewers => !_viewers.IsEmpty; + + public bool Add(string connectionId) => _viewers.TryAdd(connectionId, 0); + + public bool Remove(string connectionId) => + _viewers.TryRemove(connectionId, out _); + } +} diff --git a/HardwareWeb/WeatherForecast.cs b/HardwareWeb/WeatherForecast.cs new file mode 100644 index 0000000..95c614c --- /dev/null +++ b/HardwareWeb/WeatherForecast.cs @@ -0,0 +1,13 @@ +namespace HardwareWeb +{ + public class WeatherForecast + { + public DateOnly Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } + } +} diff --git a/HardwareWeb/appsettings.Development.json b/HardwareWeb/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/HardwareWeb/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/HardwareWeb/appsettings.json b/HardwareWeb/appsettings.json new file mode 100644 index 0000000..7326c98 --- /dev/null +++ b/HardwareWeb/appsettings.json @@ -0,0 +1,36 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "UsbCamera": { + "DeviceNameKeyword": null, + "PreferredFormatKeyword": "MJPG", + "ReconnectBaseDelayMs": 1000, + "ReconnectMaxDelayMs": 10000, + "FrameTimeoutMs": 5000 + }, + "ArisSpectrometer": { + "DeviceIndex": 0, + "PreferredSerialNumber": null, + "ExposureUs": 1000, + "Averaging": 1, + "DelayUs": 0, + "TimeoutMs": 0, + "SynchronizedExposureUs": 1000000, + "SynchronizedWaitTimeoutMs": 8000, + "TriggerMode": "Software", + "Gain": null, + "SdkLogEnabled": false + }, + "CameraStream": { + "Enabled": true, + "FramesPerSecond": 15, + "SendOnlyWhenViewers": true, + "MaxFrameAgeMs": 1500, + "MaxFrameBytes": 8388608 + } +} diff --git a/Image/.write-test b/Image/.write-test new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/Image/.write-test @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/Image/1.png b/Image/1.png new file mode 100644 index 0000000..d57b12b Binary files /dev/null and b/Image/1.png differ diff --git a/Image/2.png b/Image/2.png new file mode 100644 index 0000000..85be414 Binary files /dev/null and b/Image/2.png differ diff --git a/Image/3.png b/Image/3.png new file mode 100644 index 0000000..2e3b736 Binary files /dev/null and b/Image/3.png differ diff --git a/Image/4.png b/Image/4.png new file mode 100644 index 0000000..50a5b2e Binary files /dev/null and b/Image/4.png differ diff --git a/Image/5.png b/Image/5.png new file mode 100644 index 0000000..43e2e76 Binary files /dev/null and b/Image/5.png differ diff --git a/Image/Principle.mp4 b/Image/Principle.mp4 new file mode 100644 index 0000000..04d9801 Binary files /dev/null and b/Image/Principle.mp4 differ diff --git a/Image/Principle_old.mp4 b/Image/Principle_old.mp4 new file mode 100644 index 0000000..cb79499 Binary files /dev/null and b/Image/Principle_old.mp4 differ diff --git a/Image/logo.png b/Image/logo.png new file mode 100644 index 0000000..97d1d57 Binary files /dev/null and b/Image/logo.png differ diff --git a/SpectraElement.slnx b/SpectraElement.slnx new file mode 100644 index 0000000..ce64916 --- /dev/null +++ b/SpectraElement.slnx @@ -0,0 +1,8 @@ + + + + + + + +