添加项目文件。

This commit is contained in:
ldh
2026-11-13 09:51:38 +08:00
parent 35573a85eb
commit abb5d5d32f
123 changed files with 9453 additions and 0 deletions
+6
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
node_modules
dist
dist-ssr
*.local
.env
.env.*.local
.vite
.DS_Store
*.log
+10
View File
@@ -0,0 +1,10 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 已忽略包含查询文件的默认文件夹
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Hardware-Vue.iml" filepath="$PROJECT_DIR$/.idea/Hardware-Vue.iml" />
</modules>
</component>
</project>
+175
View File
@@ -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(`<script setup>`) |
| 构建 | Vite 6 |
| 路由 | Vue Router 4 |
| 实时画面 | `@microsoft/signalr` |
## 目录
```
src/
├─ api/camera.ts # 相机 REST 接口
├─ assets/
│ ├─ logo.png # 首页 Logo
│ ├─ camera-placeholder.webp # 无实时帧时的相机占位图
│ └─ report-qr.png # 检测完成页二维码
├─ components/
│ ├─ AppStage.vue # 1920×1080 等比缩放舞台
│ ├─ PageHeader.vue # 通用页头
│ ├─ StatusFooter.vue # 底部状态栏
│ ├─ ProgressStrip.vue # 流程进度条
│ ├─ ModuleButton.vue / ModuleIcon.vue
│ ├─ PrinciplePlayer.vue # 原理视频与自定义进度
│ ├─ CameraPreview.vue # 相机实时画面
│ ├─ GuideIcon.vue # 操作指引图标
│ ├─ ScanVisual.vue # 轮廓识别 SVG 动画
│ ├─ SpectrumChart.vue # 光谱图表
│ ├─ MiniSpectrum.vue # 结果页缩略光谱
│ ├─ UnderDevelopmentModal.vue # 研发中提示框
│ └─ ToastHost.vue # 轻提示
├─ composables/
│ ├─ useCameraStatus.ts # 轮询相机状态
│ ├─ useCameraStream.ts # 接收 SignalR 相机帧
│ ├─ useTimedProgress.ts # 15s / 10s 流程进度
│ ├─ useCountdown.ts # 结果页 60s 倒计时
│ ├─ useToast.ts
│ └─ useStageScale.ts
├─ views/
│ ├─ HomeView.vue
│ ├─ SampleSetupView.vue
│ ├─ ScanPlanView.vue
│ ├─ SpectrumView.vue
│ └─ ResultView.vue
└─ styles/main.css
public/media/Principle.mp4 # 首页原理演示视频
docs/ # 界面截图
```
## 相机实时画面
`/sample` 页面加载时:
1. 调用 `GET /api/camera/status` 获取相机状态;
2. 若状态为未连接,调用 `POST /api/camera/connect` 尝试拉起相机;
3. 连接 `/cameraHub`,收到 `CameraFrame` 后把 base64 帧写入 `<img>`;
4. 无实时帧时展示从 `2.png` 裁切的相机占位图,并在页头显示「实时画面 / 连接中 / 相机服务离线」。
SignalR 事件契约:
| 事件 / 方法 | 说明 |
| --- | --- |
| `CameraStatus` | `{ isConnected, message, deviceName, format, framesReceived, lastFrameAt, updatedAt }` |
| `CameraFrame` | `{ frameIndex, timestamp, capturedAt, width, height, mimeType, imageBase64 }` |
| `GetStatus()` | 主动拉取状态 |
| `SubscribeFrames()` / `UnsubscribeFrames()` | 暂停或恢复画面推送 |
后端默认通过 15 fps 抽帧,且没有观看者时不生成画面,详细实现见 `HardwareWeb/Services/CameraBroadcastService.cs`。前端会优先使用后端下发的 `mimeType`,兼容 JPEG / PNG / BMP。
## 本地运行
```bash
# 1. 启动后端(相机实时画面需要;仅看静态页面可跳过)
dotnet run --project ..\HardwareWeb
# 2. 安装依赖并启动前端
cd Hardware-Vue
pnpm install
pnpm dev
```
打开 `http://127.0.0.1:5173`。
`pnpm-workspace.yaml` 固定了 `nodeLinker: hoisted` 并允许 esbuild 安装脚本;如果 pnpm 提示构建脚本未授权,执行一次 `pnpm approve-builds --all` 后重新安装。
Vite 已配置代理(`pnpm dev` 与 `pnpm preview` 均生效):
- `/api` → `http://localhost:5062`
- `/cameraHub`(含 WebSocket)→ `http://localhost:5062`
可通过环境变量覆盖后端地址:
```bash
$env:VITE_BACKEND_URL = "http://192.168.1.10:5062"
pnpm dev
```
## 构建与部署
```bash
pnpm build # vue-tsc 类型检查 + 产物输出到 dist/
pnpm preview # http://127.0.0.1:4173,已带 API / SignalR 代理
```
Nginx 部署时需要把前端 History 路由回退到 `index.html`,并代理接口与 WebSocket:
```nginx
location / {
try_files $uri $uri/ /index.html;
}
location /cameraHub {
proxy_pass http://127.0.0.1:5062;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
```
## 当前静态占位说明
- 2/3/4/5 页面的采样参数、光谱峰值、检测结果均为静态展示,尚未接入真实检测流程。
- 3 页轮廓动画、4 页光谱曲线为前端 SVG 模拟,不是真实相机/光谱数据。
- 5 页二维码来自设计图 `5.png`,暂为静态占位内容;「导出报告」暂未实现。
- 首页原理视频为项目提供的 `Image/Principle.mp4`(实际时长约 15s),Logo 来自 `Image/logo.png`。
- 相机占位图从 `Image/2.png` 裁切;接入真实相机后自动替换为实时帧。
- 3/4 页进度条仅用于计时演示,分别 15s、10s 后自动跳转;5 页 60s 后自动回首页。
Binary file not shown.

After

Width:  |  Height:  |  Size: 1003 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 466 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 601 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 335 KiB

+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f4f5f7" />
<meta
name="description"
content="LIBS Lab 激光诱导击穿光谱元素分析系统 — 自助式元素检测平台"
/>
<link
rel="icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%23f4f6f9'/%3E%3Cpath d='M9 8h5v11h8v5H9V8Z' fill='%232f6fd0'/%3E%3Cpath d='M18 8h5v5h-5z' fill='%23f5b51f'/%3E%3C/svg%3E"
/>
<title>LIBS Lab | 激光诱导击穿光谱 元素分析系统</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+24
View File
@@ -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"
}
}
+1161
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
nodeLinker: hoisted
verifyDepsBeforeRun: false
allowBuilds:
esbuild: true
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { RouterView } from 'vue-router'
import ToastHost from '@/components/ToastHost.vue'
</script>
<template>
<RouterView v-slot="{ Component }">
<Transition name="page" mode="out-in">
<component :is="Component" />
</Transition>
</RouterView>
<ToastHost />
</template>
+78
View File
@@ -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<T>(path: string, init?: RequestInit): Promise<T> {
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<CameraStatus> {
return request<CameraStatus>('/api/camera/status')
}
export function connectCamera(): Promise<CameraStatus> {
return request<CameraStatus>('/api/camera/connect', { method: 'POST' })
}
export function disconnectCamera(): Promise<CameraStatus> {
return request<CameraStatus>('/api/camera/disconnect', { method: 'POST' })
}
export function getCameraHubUrl(): string {
return `${API_BASE}/cameraHub`
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { useStageScale } from '@/composables/useStageScale'
const { scale } = useStageScale()
</script>
<template>
<div class="app-viewport">
<div class="app-stage" :style="{ transform: `scale(${scale})` }">
<slot />
</div>
</div>
</template>
<style scoped>
.app-viewport {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
background:
radial-gradient(circle at 50% 12%, #f7f8fa 0%, #e6eaef 58%, #dfe4ea 100%);
}
.app-stage {
position: relative;
flex: none;
width: 1920px;
height: 1080px;
overflow: hidden;
background: var(--bg);
transform-origin: center center;
}
</style>
@@ -0,0 +1,294 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { connectCamera } from '@/api/camera'
import { useCameraStatus } from '@/composables/useCameraStatus'
import { useCameraStream } from '@/composables/useCameraStream'
import cameraPlaceholder from '@/assets/camera-placeholder.webp'
const { state: cameraState, refresh, startPolling } = useCameraStatus(5000, false)
const { state: streamState, frameUrl, isLive, connect } = useCameraStream()
const connectingCamera = ref(false)
const statusText = computed(() => {
if (isLive.value) return '实时画面'
if (
connectingCamera.value ||
streamState.value === 'connecting' ||
cameraState.value === 'checking'
) {
return '连接中'
}
if (cameraState.value === 'offline') return '相机服务离线'
if (cameraState.value === 'connected') return '等待画面'
return '预览画面'
})
const statusTone = computed<'on' | 'wait' | 'off'>(() => {
if (isLive.value) return 'on'
if (statusText.value === '连接中' || statusText.value === '等待画面') {
return 'wait'
}
return 'off'
})
onMounted(async () => {
await refresh()
const streamPromise = connect()
if (cameraState.value === 'disconnected') {
connectingCamera.value = true
try {
await connectCamera()
await refresh()
} catch {
// 没有相机或服务不可达时保留占位画面
} finally {
connectingCamera.value = false
}
}
startPolling()
await streamPromise
})
</script>
<template>
<section class="camera-card">
<header class="camera-card__header">
<h2>相机画面</h2>
<span class="camera-card__status" :class="`camera-card__status--${statusTone}`">
<i class="camera-card__dot"></i>
{{ statusText }}
</span>
</header>
<div class="camera-card__viewport">
<img
class="camera-card__image"
:src="frameUrl ?? cameraPlaceholder"
:alt="frameUrl ? '相机实时画面' : '相机预览画面'"
draggable="false"
/>
<template v-if="frameUrl">
<span class="crosshair crosshair--horizontal" aria-hidden="true"></span>
<span class="crosshair crosshair--vertical" aria-hidden="true"></span>
<div class="focus-box" aria-hidden="true">
<span class="focus-box__corner focus-box__corner--tl"></span>
<span class="focus-box__corner focus-box__corner--tr"></span>
<span class="focus-box__corner focus-box__corner--bl"></span>
<span class="focus-box__corner focus-box__corner--br"></span>
<span class="focus-box__tick focus-box__tick--left"></span>
<span class="focus-box__tick focus-box__tick--right"></span>
</div>
<span class="scan-line" aria-hidden="true"></span>
</template>
</div>
</section>
</template>
<style scoped>
.camera-card {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
border: 1px solid #d8e0e9;
border-radius: 18px;
background: #fff;
box-shadow: var(--shadow-card);
}
.camera-card__header {
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
height: 76px;
padding: 0 28px;
background: linear-gradient(180deg, #3d80e2 0%, #2f6fd0 100%);
}
.camera-card__header h2 {
color: #fff;
font-size: 30px;
font-weight: 600;
letter-spacing: 3px;
text-shadow: 0 1px 3px rgba(16, 49, 101, 0.22);
}
.camera-card__status {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 5px 12px;
border: 1px solid rgba(255, 255, 255, 0.24);
border-radius: 30px;
background: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.92);
font-size: 15px;
letter-spacing: 1px;
}
.camera-card__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #c9d4e4;
}
.camera-card__status--on .camera-card__dot {
background: #74f4c5;
box-shadow: 0 0 9px rgba(116, 244, 197, 0.9);
animation: live-dot 1.8s ease-in-out infinite;
}
.camera-card__status--wait .camera-card__dot {
background: #ffd86a;
box-shadow: 0 0 8px rgba(255, 216, 106, 0.8);
}
.camera-card__status--off .camera-card__dot {
background: #ff9a91;
box-shadow: 0 0 8px rgba(255, 154, 145, 0.7);
}
.camera-card__viewport {
position: relative;
flex: 1;
overflow: hidden;
background: #080d14;
}
.camera-card__image {
width: 100%;
height: 100%;
object-fit: cover;
}
.crosshair {
position: absolute;
z-index: 1;
background: rgba(255, 255, 255, 0.55);
box-shadow: 0 0 6px rgba(255, 255, 255, 0.22);
pointer-events: none;
}
.crosshair--horizontal {
top: 50%;
right: 0;
left: 0;
height: 1px;
}
.crosshair--vertical {
top: 0;
bottom: 0;
left: 50%;
width: 1px;
}
.focus-box {
position: absolute;
top: 37%;
left: 34%;
z-index: 2;
width: 32%;
height: 31%;
}
.focus-box__corner {
position: absolute;
width: 34px;
height: 34px;
border: 3px solid #74f1df;
filter: drop-shadow(0 0 5px rgba(116, 241, 223, 0.4));
}
.focus-box__corner--tl {
top: 0;
left: 0;
border-right: 0;
border-bottom: 0;
}
.focus-box__corner--tr {
top: 0;
right: 0;
border-bottom: 0;
border-left: 0;
}
.focus-box__corner--bl {
bottom: 0;
left: 0;
border-top: 0;
border-right: 0;
}
.focus-box__corner--br {
right: 0;
bottom: 0;
border-top: 0;
border-left: 0;
}
.focus-box__tick {
position: absolute;
top: 50%;
width: 4px;
height: 30px;
background: rgba(116, 241, 223, 0.8);
transform: translateY(-50%);
}
.focus-box__tick--left {
left: -2px;
}
.focus-box__tick--right {
right: -2px;
}
.scan-line {
position: absolute;
right: 4%;
left: 4%;
z-index: 1;
height: 2px;
background: linear-gradient(90deg, transparent, rgba(145, 255, 235, 0.45), transparent);
animation: scan-line 4.5s ease-in-out infinite;
}
@keyframes live-dot {
0%,
100% {
opacity: 0.4;
}
50% {
opacity: 1;
}
}
@keyframes scan-line {
0%,
100% {
top: 20%;
opacity: 0;
}
12% {
opacity: 0.7;
}
55% {
top: 76%;
opacity: 0.45;
}
88% {
opacity: 0;
}
}
</style>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
defineProps<{
name: 'door' | 'tray' | 'focus'
}>()
</script>
<template>
<svg
class="guide-icon"
viewBox="0 0 64 64"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<template v-if="name === 'door'">
<rect x="13" y="12" width="38" height="28" rx="3" stroke="currentColor" stroke-width="2.2" />
<path d="M19 18h26v16H19z" stroke="currentColor" stroke-width="1.8" />
<path d="M25 40v6h14v-6M20 52h24" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" />
<circle cx="41" cy="26" r="2.2" fill="currentColor" />
</template>
<template v-else-if="name === 'tray'">
<path
d="M16 31h32l-4 14H20l-4-14Z"
stroke="currentColor"
stroke-width="2.2"
stroke-linejoin="round"
/>
<path d="M20 31v-9h24v9M27 31v-5h10v5" stroke="currentColor" stroke-width="2" />
<path d="M31 14h8M36 10l5 4-5 4" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" />
<path d="M22 50h20" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" />
</template>
<template v-else>
<path
d="M18 25v-5a2 2 0 0 1 2-2h5M39 18h5a2 2 0 0 1 2 2v5M46 39v5a2 2 0 0 1-2 2h-5M25 46h-5a2 2 0 0 1-2-2v-5"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
/>
<circle cx="32" cy="32" r="7" stroke="currentColor" stroke-width="2" />
<path d="M32 27v10M27 32h10" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
<path d="M21 12h22" stroke="currentColor" stroke-width="2" stroke-linecap="round" opacity="0.8" />
</template>
</svg>
</template>
<style scoped>
.guide-icon {
width: 100%;
height: 100%;
color: #fff;
filter: drop-shadow(0 2px 3px rgba(0, 0, 0, 0.1));
}
</style>
@@ -0,0 +1,94 @@
<script setup lang="ts">
const bars = [
{ x: 96, height: 38 },
{ x: 116, height: 66 },
{ x: 136, height: 108 },
{ x: 156, height: 72 },
{ x: 176, height: 46 },
{ x: 220, height: 54 },
{ x: 244, height: 74 },
{ x: 286, height: 42 },
{ x: 320, height: 34 },
]
</script>
<template>
<div class="mini-spectrum">
<svg viewBox="0 0 360 150" preserveAspectRatio="none" aria-label="光谱缩略图">
<defs>
<linearGradient id="miniStroke" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#63ecff" />
<stop offset="0.55" stop-color="#a9b7ff" />
<stop offset="1" stop-color="#ff8bdc" />
</linearGradient>
<linearGradient id="miniFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#dff8ff" stop-opacity="0.35" />
<stop offset="1" stop-color="#7bd9ff" stop-opacity="0" />
</linearGradient>
</defs>
<rect width="360" height="150" fill="#2c67c4" />
<g stroke="rgba(255,255,255,0.26)" stroke-width="0.7">
<line x1="20" x2="350" y1="128" y2="128" />
<line x1="20" x2="20" y1="16" y2="128" />
<line x1="20" x2="350" y1="88" y2="88" stroke-dasharray="2 4" />
<line x1="20" x2="350" y1="48" y2="48" stroke-dasharray="2 4" />
</g>
<g fill="rgba(255,255,255,0.7)" font-size="8">
<text x="4" y="30">30</text>
<text x="4" y="70">20</text>
<text x="4" y="110">10</text>
<text x="12" y="144">0</text>
<text x="44" y="128">0</text>
<text x="96" y="128">100</text>
<text x="162" y="128">200</text>
<text x="228" y="128">300</text>
<text x="292" y="128">400</text>
</g>
<path
d="M22 120 L30 118 L38 121 L46 115 L54 119 L62 112 L70 118 L78 108 L86 114 L94 95 L100 102 L106 62 L112 97 L118 110 L124 92 L130 103 L136 50 L142 88 L148 106 L154 83 L160 110 L166 112 L172 92 L178 108 L184 102 L190 110 L196 93 L202 109 L208 98 L214 112 L220 76 L226 104 L232 112 L238 62 L244 90 L250 108 L256 98 L262 112 L268 92 L274 111 L280 105 L286 83 L292 110 L298 104 L304 114 L310 90 L316 110 L322 102 L328 112 L334 104 L340 112"
fill="none"
stroke="url(#miniStroke)"
stroke-width="1.7"
stroke-linejoin="round"
/>
<g fill="#ffb7e8">
<rect
v-for="bar in bars"
:key="bar.x"
:x="bar.x"
:y="128 - bar.height"
width="2.4"
:height="bar.height"
opacity="0.55"
/>
</g>
<path
d="M22 120 L100 102 L136 50 L168 112 L220 76 L238 62 L286 83 L340 112"
fill="none"
stroke="rgba(255,235,255,0.24)"
stroke-width="0.6"
/>
</svg>
</div>
</template>
<style scoped>
.mini-spectrum {
width: 360px;
height: 150px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 3px;
background: #2c67c4;
}
.mini-spectrum svg {
width: 100%;
height: 100%;
}
</style>
@@ -0,0 +1,132 @@
<script setup lang="ts">
import ModuleIcon from '@/components/ModuleIcon.vue'
withDefaults(
defineProps<{
title: string
tone: 'blue' | 'orange' | 'green' | 'teal'
icon: 'detect' | 'metal' | 'soil' | 'water'
}>(),
{},
)
defineEmits<{
click: []
}>()
</script>
<template>
<button
class="module-button"
:class="`module-button--${tone}`"
type="button"
@click="$emit('click')"
>
<span class="module-button__icon">
<ModuleIcon :name="icon" />
</span>
<span class="module-button__label">{{ title }}</span>
</button>
</template>
<style scoped>
.module-button {
position: relative;
display: block;
height: 252px;
overflow: hidden;
border-radius: 18px;
text-align: left;
box-shadow:
0 16px 30px var(--module-shadow),
inset 0 2px 0 rgba(255, 255, 255, 0.55),
inset 0 -10px 24px rgba(0, 0, 0, 0.08);
transition: transform 0.25s cubic-bezier(0.22, 1, 0.36, 1),
box-shadow 0.25s ease;
}
.module-button::before {
content: '';
position: absolute;
inset: 0;
background:
radial-gradient(ellipse 85% 65% at 18% 6%, rgba(255, 255, 255, 0.34) 0%, transparent 58%),
linear-gradient(180deg, rgba(255, 255, 255, 0.12), transparent 36%);
pointer-events: none;
}
.module-button::after {
content: '';
position: absolute;
right: 18px;
bottom: 14px;
left: 18px;
height: 1px;
background: rgba(255, 255, 255, 0.2);
opacity: 0.8;
}
.module-button:hover {
transform: translateY(-4px);
box-shadow:
0 22px 38px var(--module-shadow-strong),
inset 0 2px 0 rgba(255, 255, 255, 0.6),
inset 0 -10px 24px rgba(0, 0, 0, 0.08);
}
.module-button:active {
transform: translateY(-1px) scale(0.995);
}
.module-button--blue {
--module-shadow: rgba(47, 111, 208, 0.26);
--module-shadow-strong: rgba(47, 111, 208, 0.38);
background: linear-gradient(145deg, #4b8ae8 0%, #3778d9 48%, #2f6fd0 100%);
}
.module-button--orange {
--module-shadow: rgba(238, 166, 11, 0.28);
--module-shadow-strong: rgba(238, 166, 11, 0.4);
background: linear-gradient(145deg, #ffc845 0%, #f8b526 50%, #eea50b 100%);
}
.module-button--green {
--module-shadow: rgba(107, 171, 49, 0.28);
--module-shadow-strong: rgba(107, 171, 49, 0.4);
background: linear-gradient(145deg, #91d258 0%, #7cc242 50%, #67ad2f 100%);
}
.module-button--teal {
--module-shadow: rgba(38, 174, 163, 0.28);
--module-shadow-strong: rgba(38, 174, 163, 0.4);
background: linear-gradient(145deg, #46cec2 0%, #2fb8ac 50%, #22a99e 100%);
}
.module-button__icon {
position: absolute;
top: 24px;
left: 24px;
display: grid;
place-items: center;
width: 92px;
height: 92px;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.36);
border-radius: 16px;
background: rgba(255, 255, 255, 0.14);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.24);
}
.module-button__label {
position: absolute;
right: 18px;
bottom: 44px;
left: 18px;
color: #fff;
font-size: 31px;
font-weight: 600;
letter-spacing: 4px;
text-align: center;
text-shadow: 0 2px 5px rgba(33, 49, 79, 0.24);
}
</style>
@@ -0,0 +1,81 @@
<script setup lang="ts">
defineProps<{
name: 'detect' | 'metal' | 'soil' | 'water'
}>()
</script>
<template>
<svg
class="module-icon"
viewBox="0 0 64 64"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<template v-if="name === 'detect'">
<path
d="M14 26V17a3 3 0 0 1 3-3h9M38 14h9a3 3 0 0 1 3 3v9M50 38v9a3 3 0 0 1-3 3h-9M26 50h-9a3 3 0 0 1-3-3v-9"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
/>
<path
d="m32 21 2.7 6.3L41 30l-6.3 2.7L32 39l-2.7-6.3L23 30l6.3-2.7L32 21Z"
stroke="currentColor"
stroke-width="2"
stroke-linejoin="round"
/>
<circle cx="44.5" cy="20.5" r="2.4" fill="currentColor" />
</template>
<template v-else-if="name === 'metal'">
<path
d="M25 14h14v7l4.5 6.5V50a2 2 0 0 1-2 2h-19a2 2 0 0 1-2-2V27.5L25 21v-7Z"
stroke="currentColor"
stroke-width="2.2"
stroke-linejoin="round"
/>
<path d="M25 21h14M22.5 34h19" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
<path d="M30 28h4" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
</template>
<template v-else-if="name === 'soil'">
<rect
x="19"
y="12"
width="26"
height="40"
rx="3.5"
stroke="currentColor"
stroke-width="2.2"
/>
<path d="M32 21v15M24.5 28.5h15" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" />
<path d="M25 43h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
</template>
<template v-else>
<path
d="M22 23h20v25a2 2 0 0 1-2 2H24a2 2 0 0 1-2-2V23Z"
stroke="currentColor"
stroke-width="2.2"
stroke-linejoin="round"
/>
<path d="m23 23 5.5-9h7L41 23" stroke="currentColor" stroke-width="2.2" stroke-linejoin="round" />
<path
d="M32 30c3.2 4.1 5 6.4 5 9.1a5 5 0 0 1-10 0c0-2.7 1.8-5 5-9.1Z"
stroke="currentColor"
stroke-width="2"
stroke-linejoin="round"
/>
</template>
</svg>
</template>
<style scoped>
.module-icon {
width: 100%;
height: 100%;
color: #fff;
filter: drop-shadow(0 2px 3px rgba(0, 0, 0, 0.12));
}
</style>
@@ -0,0 +1,86 @@
<script setup lang="ts">
withDefaults(
defineProps<{
title: string
subtitle?: string
variant?: 'default' | 'process' | 'result'
}>(),
{ variant: 'default' },
)
</script>
<template>
<header class="page-header" :class="`page-header--${variant}`">
<div class="page-header__side">
<slot name="left" />
</div>
<div class="page-header__center">
<h1>{{ title }}</h1>
<p v-if="subtitle">{{ subtitle }}</p>
</div>
<div class="page-header__side page-header__side--right">
<slot name="right" />
</div>
</header>
</template>
<style scoped>
.page-header {
position: relative;
display: grid;
grid-template-columns: 340px 1fr 340px;
align-items: center;
height: 140px;
padding: 0 44px;
background: #fff;
box-shadow: 0 3px 14px rgba(28, 43, 66, 0.06);
z-index: 3;
}
.page-header--process {
height: 118px;
}
.page-header--result {
height: 118px;
}
.page-header__side {
display: flex;
align-items: center;
min-width: 0;
}
.page-header__side--right {
justify-content: flex-end;
}
.page-header__center {
text-align: center;
}
.page-header__center h1 {
font-size: 42px;
font-weight: 600;
letter-spacing: 3px;
color: #1f2937;
}
.page-header--process .page-header__center h1 {
font-size: 38px;
letter-spacing: 2px;
}
.page-header--result .page-header__center h1 {
font-size: 40px;
}
.page-header__center p {
margin-top: 10px;
font-size: 20px;
letter-spacing: 3px;
color: var(--muted);
}
</style>
@@ -0,0 +1,385 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
const slides = [
{ src: `${import.meta.env.BASE_URL}media/Principle.mp4`, label: '检测原理演示动画' },
{ src: `${import.meta.env.BASE_URL}media/Principle_old.mp4`, label: '检测原理演示动画(旧版)' },
]
const videoRefs = ref<(HTMLVideoElement | null)[]>([])
const activeIndex = ref(0)
const loaded = ref(slides.map(() => false))
const playing = ref(false)
const dragging = ref(false)
const dragOffset = ref(0)
const trackStyle = computed(() => ({
transform: `translate3d(calc(-${activeIndex.value * 100}% + ${dragOffset.value}px), 0, 0)`,
}))
let startX = 0
let startY = 0
let pointerId: number | null = null
let gestureActive = false
function setVideoRef(el: unknown, index: number) {
videoRefs.value[index] = el instanceof HTMLVideoElement ? el : null
}
function goTo(index: number) {
const total = slides.length
const next = ((index % total) + total) % total
if (next === activeIndex.value) return
const previous = videoRefs.value[activeIndex.value]
activeIndex.value = next
previous?.pause()
const video = videoRefs.value[next]
if (!video) return
video.currentTime = 0
void video.play().catch(() => {
playing.value = false
})
}
function togglePlay() {
const video = videoRefs.value[activeIndex.value]
if (!video) return
if (video.paused) {
void video.play().catch(() => undefined)
} else {
video.pause()
}
}
function onLoadedMetadata(index: number) {
loaded.value[index] = true
}
function onPlay(index: number) {
if (index === activeIndex.value) playing.value = true
}
function onPause(index: number) {
if (index === activeIndex.value) playing.value = false
}
function onPointerDown(event: PointerEvent) {
if (event.pointerType === 'mouse' && event.button !== 0) return
startX = event.clientX
startY = event.clientY
pointerId = event.pointerId
gestureActive = false
dragging.value = true
}
function onPointerMove(event: PointerEvent) {
if (!dragging.value || event.pointerId !== pointerId) return
const dx = event.clientX - startX
const dy = event.clientY - startY
if (!gestureActive) {
if (Math.abs(dx) < 10 && Math.abs(dy) < 10) return
if (Math.abs(dy) > Math.abs(dx)) {
endDrag(event)
return
}
gestureActive = true
try {
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
} catch {
// 指针已失效时忽略,不影响滑动判定
}
}
dragOffset.value = dx
}
function onPointerUp(event: PointerEvent) {
if (event.pointerId !== pointerId) return
const offset = dragOffset.value
const swiped = gestureActive && Math.abs(offset) > 60
endDrag(event)
if (swiped) goTo(activeIndex.value + (offset < 0 ? 1 : -1))
}
function endDrag(event: PointerEvent) {
dragging.value = false
dragOffset.value = 0
gestureActive = false
pointerId = null
const target = event.currentTarget as HTMLElement
if (target.hasPointerCapture?.(event.pointerId)) {
target.releasePointerCapture(event.pointerId)
}
}
onMounted(() => {
const video = videoRefs.value[activeIndex.value]
if (!video) return
video.muted = true
void video.play().catch(() => {
playing.value = false
})
})
</script>
<template>
<section
class="principle"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="endDrag"
>
<header class="principle__header">
<h2>检测原理演示区</h2>
<span class="principle__badge">
<span class="principle__dot"></span>
自动播放
</span>
</header>
<div class="principle__video">
<div class="principle__fallback" aria-hidden="true">
<svg viewBox="0 0 900 640" preserveAspectRatio="xMidYMid slice">
<defs>
<linearGradient id="principleSky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#2f6fd0" />
<stop offset="1" stop-color="#1d55ae" />
</linearGradient>
<linearGradient id="principleBeam" x1="0" y1="1" x2="1" y2="0">
<stop offset="0" stop-color="#60f2ff" stop-opacity="0.2" />
<stop offset="1" stop-color="#fff6b7" />
</linearGradient>
<radialGradient id="principleStar">
<stop offset="0" stop-color="#fff9cf" />
<stop offset="0.35" stop-color="#ffc46b" stop-opacity="0.8" />
<stop offset="1" stop-color="#ff9c4f" stop-opacity="0" />
</radialGradient>
</defs>
<rect width="900" height="640" fill="url(#principleSky)" />
<circle cx="690" cy="250" r="110" fill="url(#principleStar)" />
<path d="M250 450 C420 420 560 330 690 250" stroke="url(#principleBeam)" stroke-width="4" fill="none" />
<g opacity="0.8">
<rect x="280" y="300" width="3" height="90" fill="#71f2ff" />
<rect x="292" y="270" width="3" height="120" fill="#65baff" />
<rect x="304" y="320" width="3" height="70" fill="#bfffe7" />
<rect x="316" y="250" width="4" height="140" fill="#ffd166" />
<rect x="330" y="290" width="3" height="100" fill="#ff9f6b" />
<rect x="342" y="330" width="3" height="60" fill="#80e8ff" />
<rect x="354" y="310" width="3" height="80" fill="#e6a8ff" />
</g>
</svg>
</div>
<div
class="principle__slider"
:class="{ 'is-dragging': dragging }"
:style="trackStyle"
>
<div v-for="(slide, index) in slides" :key="slide.src" class="principle__slide">
<video
:ref="(el) => setVideoRef(el, index)"
class="principle__media"
:class="{ 'is-ready': loaded[index] }"
:src="slide.src"
muted
loop
playsinline
preload="metadata"
:aria-label="slide.label"
@loadedmetadata="onLoadedMetadata(index)"
@play="onPlay(index)"
@pause="onPause(index)"
@error="loaded[index] = false"
></video>
</div>
</div>
<button
v-if="!playing"
class="principle__play"
type="button"
aria-label="播放原理动画"
@click="togglePlay"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m9 6 9 6-9 6V6Z" fill="currentColor" />
</svg>
</button>
<span v-if="playing" class="principle__caption">原理动画播放中</span>
</div>
</section>
</template>
<style scoped>
.principle {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
padding: 24px 24px 18px;
overflow: hidden;
border-radius: 20px;
touch-action: none;
background:
radial-gradient(ellipse 80% 60% at 82% 8%, rgba(120, 174, 255, 0.35), transparent 62%),
linear-gradient(145deg, #3c7fdd 0%, #2f6fd0 48%, #2559ad 100%);
box-shadow:
0 18px 46px rgba(37, 89, 173, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.24);
}
.principle::before {
content: '';
position: absolute;
inset: 0;
background-image:
linear-gradient(rgba(255, 255, 255, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.05) 1px, transparent 1px);
background-size: 48px 48px;
mask-image: linear-gradient(180deg, #000, transparent 65%);
pointer-events: none;
}
.principle__header {
position: relative;
z-index: 1;
display: flex;
align-items: center;
justify-content: space-between;
height: 62px;
}
.principle__header h2 {
color: #fff;
font-size: 30px;
font-weight: 600;
letter-spacing: 3px;
text-shadow: 0 2px 5px rgba(18, 51, 103, 0.24);
}
.principle__badge {
display: inline-flex;
align-items: center;
gap: 9px;
padding: 6px 14px;
border: 1px solid rgba(255, 255, 255, 0.22);
border-radius: 30px;
background: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.86);
font-size: 15px;
letter-spacing: 1px;
}
.principle__dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #86f3cd;
box-shadow: 0 0 9px rgba(134, 243, 205, 0.9);
}
.principle__video {
position: relative;
flex: 1;
overflow: hidden;
border-radius: 14px;
background: #255bb3;
touch-action: none;
cursor: grab;
user-select: none;
}
.principle__video:active {
cursor: grabbing;
}
.principle__fallback,
.principle__media {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
.principle__fallback svg {
width: 100%;
height: 100%;
}
.principle__slider {
position: absolute;
inset: 0;
display: flex;
transition: transform 0.45s cubic-bezier(0.22, 1, 0.36, 1);
}
.principle__slider.is-dragging {
transition: none;
}
.principle__slide {
position: relative;
flex: 0 0 100%;
height: 100%;
}
.principle__media {
object-fit: cover;
opacity: 0;
transition: opacity 0.4s ease;
}
.principle__media.is-ready {
opacity: 1;
}
.principle__play {
position: absolute;
top: 50%;
left: 50%;
display: grid;
place-items: center;
width: 86px;
height: 86px;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 50%;
color: #fff;
background: rgba(15, 48, 104, 0.42);
box-shadow: 0 10px 30px rgba(8, 35, 79, 0.2);
backdrop-filter: blur(6px);
transform: translate(-50%, -50%);
transition: background 0.2s ease, transform 0.2s ease;
}
.principle__play:hover {
background: rgba(15, 48, 104, 0.58);
transform: translate(-50%, -50%) scale(1.05);
}
.principle__play svg {
width: 38px;
height: 38px;
margin-left: 4px;
}
.principle__caption {
position: absolute;
bottom: 26px;
left: 50%;
color: rgba(255, 255, 255, 0.92);
font-size: 22px;
letter-spacing: 4px;
text-shadow: 0 2px 8px rgba(7, 33, 78, 0.55);
transform: translateX(-50%);
white-space: nowrap;
}
</style>
@@ -0,0 +1,92 @@
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
progress: number
label: string
note?: string
}>()
const clamped = computed(() => Math.max(0, Math.min(100, props.progress)))
</script>
<template>
<div class="progress-strip">
<div
class="progress-strip__track"
role="progressbar"
:aria-valuenow="Math.round(clamped)"
aria-valuemin="0"
aria-valuemax="100"
:aria-label="label"
>
<div class="progress-strip__fill" :style="{ width: `${clamped}%` }"></div>
<span
class="progress-strip__label"
:class="{ 'progress-strip__label--on-fill': clamped > 52 }"
>
{{ label }}
</span>
</div>
<span v-if="note" class="progress-strip__note">{{ note }}</span>
</div>
</template>
<style scoped>
.progress-strip {
display: flex;
align-items: center;
gap: 26px;
width: 100%;
}
.progress-strip__track {
position: relative;
flex: 1;
height: 52px;
overflow: hidden;
border: 1px solid #b8cce3;
border-radius: 8px;
background: #dce8f5;
box-shadow: inset 0 2px 6px rgba(43, 75, 116, 0.08);
}
.progress-strip__fill {
position: absolute;
top: 0;
bottom: 0;
left: 0;
border-radius: 7px;
background:
linear-gradient(90deg, rgba(255, 255, 255, 0.16), transparent 22%),
linear-gradient(180deg, #4a89e2 0%, #2f6fd0 58%, #255db5 100%);
transition: width 0.12s linear;
}
.progress-strip__label {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: #245c9f;
font-size: 27px;
font-weight: 600;
letter-spacing: 3px;
transition: color 0.15s linear, text-shadow 0.15s linear;
}
.progress-strip__label--on-fill {
color: #fff;
text-shadow: 0 2px 5px rgba(17, 52, 100, 0.5);
}
.progress-strip__note {
flex: none;
min-width: 190px;
color: #334155;
font-size: 25px;
letter-spacing: 1px;
text-align: right;
}
</style>
+350
View File
@@ -0,0 +1,350 @@
<script setup lang="ts">
const points = [
{ x: 520, y: 250, label: '1', tone: '#57e6ff' },
{ x: 432, y: 302, label: 'P2', tone: '#91e34b' },
{ x: 658, y: 298, label: 'P3', tone: '#f7c94a' },
{ x: 718, y: 368, label: 'P4', tone: '#91e34b' },
{ x: 618, y: 478, label: 'P5', tone: '#91e34b' },
]
const markers = [
[410, 220],
[470, 170],
[560, 145],
[640, 160],
[700, 205],
[735, 260],
[748, 330],
[735, 405],
[700, 465],
[640, 515],
[560, 535],
[480, 520],
[410, 490],
[360, 450],
[330, 390],
[325, 325],
[350, 255],
[385, 200],
]
</script>
<template>
<section class="scan-visual">
<div class="scan-visual__bar" aria-hidden="true">
<span class="scan-visual__menu">
<span></span>
<span></span>
<span></span>
</span>
<span class="scan-visual__close">
<svg viewBox="0 0 24 24">
<path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
</span>
</div>
<div class="scan-visual__stage">
<svg viewBox="0 0 1000 600" preserveAspectRatio="xMidYMid meet" role="img" aria-label="样品轮廓识别与点位规划动画">
<defs>
<pattern id="scanDots" width="34" height="34" patternUnits="userSpaceOnUse">
<circle cx="2" cy="2" r="1" fill="rgba(255,255,255,0.13)" />
</pattern>
<linearGradient id="scanBand" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#9df9ff" stop-opacity="0" />
<stop offset="0.5" stop-color="#9df9ff" stop-opacity="0.2" />
<stop offset="1" stop-color="#9df9ff" stop-opacity="0" />
</linearGradient>
<linearGradient id="contourStroke" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#ffeda5" />
<stop offset="0.48" stop-color="#f9da7a" />
<stop offset="0.52" stop-color="#9ff6db" />
<stop offset="1" stop-color="#79e6c0" />
</linearGradient>
</defs>
<rect width="1000" height="600" fill="url(#scanDots)" />
<g stroke="rgba(255,255,255,0.22)" stroke-width="1">
<line x1="500" y1="24" x2="500" y2="96" />
<line x1="500" y1="504" x2="500" y2="576" />
<line x1="34" y1="300" x2="86" y2="300" />
<line x1="914" y1="300" x2="966" y2="300" />
</g>
<g fill="none" stroke="rgba(255,255,255,0.8)" stroke-width="1.4">
<circle cx="500" cy="60" r="7" />
<path d="M500 48v24M488 60h24" />
<circle cx="500" cy="540" r="6" />
<path d="M500 530v20M490 540h20" />
</g>
<path
d="M500 95
C548 80 596 101 623 131
C663 114 707 138 721 177
C764 193 789 228 781 266
C812 301 810 344 785 375
C800 417 775 456 740 472
C720 511 676 536 636 525
C601 555 551 559 515 535
C471 555 421 540 396 510
C346 505 316 465 323 425
C286 395 286 345 311 310
C301 265 331 225 371 215
C386 170 431 145 471 155
C483 121 491 101 500 95 Z"
fill="rgba(255,255,255,0.035)"
stroke="url(#contourStroke)"
stroke-width="2.4"
stroke-linejoin="round"
/>
<path
class="scan-visual__dash"
d="M500 95
C548 80 596 101 623 131
C663 114 707 138 721 177
C764 193 789 228 781 266
C812 301 810 344 785 375
C800 417 775 456 740 472
C720 511 676 536 636 525
C601 555 551 559 515 535
C471 555 421 540 396 510
C346 505 316 465 323 425
C286 395 286 345 311 310
C301 265 331 225 371 215
C386 170 431 145 471 155
C483 121 491 101 500 95 Z"
fill="none"
stroke="rgba(108,246,220,0.75)"
stroke-width="1.2"
stroke-dasharray="7 13"
stroke-linecap="round"
/>
<g>
<circle
v-for="(marker, index) in markers"
:key="`marker-${index}`"
:cx="marker[0]"
:cy="marker[1]"
r="2.2"
fill="rgba(255,255,255,0.72)"
/>
</g>
<g>
<g v-for="point in points" :key="point.label">
<circle
:cx="point.x"
:cy="point.y"
r="16"
fill="none"
:stroke="point.tone"
stroke-width="1.4"
opacity="0.75"
class="scan-visual__point-halo"
/>
<circle :cx="point.x" :cy="point.y" r="8" :fill="point.tone" stroke="#fff" stroke-width="1.6" />
<text
:x="point.x + 22"
:y="point.y + 12"
fill="#ffffff"
font-size="28"
font-weight="500"
letter-spacing="1"
>
{{ point.label }}
</text>
</g>
</g>
<text
x="500"
y="350"
fill="#ffffff"
font-size="34"
font-weight="500"
letter-spacing="3"
text-anchor="middle"
opacity="0.95"
>
样品图片识别动画
</text>
<text
x="500"
y="392"
fill="rgba(255,255,255,0.62)"
font-size="18"
letter-spacing="5"
text-anchor="middle"
>
激光点位规划中
</text>
<rect class="scan-visual__band" x="-180" y="0" width="180" height="600" fill="url(#scanBand)">
<animate attributeName="x" values="-180;1010" dur="5.2s" repeatCount="indefinite" />
</rect>
</svg>
<span class="scan-visual__corner scan-visual__corner--tl" aria-hidden="true"></span>
<span class="scan-visual__corner scan-visual__corner--tr" aria-hidden="true"></span>
<span class="scan-visual__corner scan-visual__corner--bl" aria-hidden="true"></span>
<span class="scan-visual__corner scan-visual__corner--br" aria-hidden="true"></span>
<span class="scan-visual__rail scan-visual__rail--left" aria-hidden="true"></span>
<span class="scan-visual__rail scan-visual__rail--right" aria-hidden="true"></span>
</div>
</section>
</template>
<style scoped>
.scan-visual {
display: flex;
flex-direction: column;
height: 100%;
padding: 10px 16px 16px;
overflow: hidden;
border: 1px solid #1e55a4;
border-radius: 18px;
background:
radial-gradient(ellipse 70% 50% at 50% 0%, rgba(120, 180, 255, 0.22), transparent 70%),
linear-gradient(150deg, #3b7edd 0%, #2f6fd0 46%, #2559ac 100%);
box-shadow:
0 18px 44px rgba(31, 77, 147, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.22);
}
.scan-visual__bar {
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
height: 52px;
padding: 0 8px;
color: rgba(255, 255, 255, 0.9);
}
.scan-visual__menu {
display: flex;
flex-direction: column;
gap: 5px;
}
.scan-visual__menu span {
width: 26px;
height: 2px;
border-radius: 2px;
background: currentColor;
}
.scan-visual__close {
display: grid;
place-items: center;
width: 34px;
height: 34px;
}
.scan-visual__close svg {
width: 24px;
height: 24px;
}
.scan-visual__stage {
position: relative;
flex: 1;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.58);
border-radius: 8px;
background: rgba(24, 72, 148, 0.16);
}
.scan-visual__stage svg {
width: 100%;
height: 100%;
}
.scan-visual__dash {
animation: contour-dash 6s linear infinite;
}
.scan-visual__point-halo {
animation: point-pulse 2.4s ease-in-out infinite;
transform-box: fill-box;
transform-origin: center;
}
.scan-visual__corner {
position: absolute;
z-index: 3;
width: 30px;
height: 30px;
border: 2px solid rgba(255, 255, 255, 0.9);
}
.scan-visual__corner--tl {
top: 8px;
left: 8px;
border-right: 0;
border-bottom: 0;
}
.scan-visual__corner--tr {
top: 8px;
right: 8px;
border-bottom: 0;
border-left: 0;
}
.scan-visual__corner--bl {
bottom: 8px;
left: 8px;
border-top: 0;
border-right: 0;
}
.scan-visual__corner--br {
right: 8px;
bottom: 8px;
border-top: 0;
border-left: 0;
}
.scan-visual__rail {
position: absolute;
top: 50%;
z-index: 3;
width: 5px;
height: 54px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.82);
transform: translateY(-50%);
}
.scan-visual__rail--left {
left: 10px;
}
.scan-visual__rail--right {
right: 10px;
}
@keyframes contour-dash {
to {
stroke-dashoffset: -200;
}
}
@keyframes point-pulse {
0%,
100% {
opacity: 0.35;
transform: scale(0.85);
}
50% {
opacity: 0.9;
transform: scale(1.18);
}
}
</style>
@@ -0,0 +1,300 @@
<script setup lang="ts">
import { computed } from 'vue'
const width = 1360
const height = 720
const pad = { left: 112, right: 44, top: 74, bottom: 88 }
const xMin = 380
const xMax = 700
const yMin = 0
const yMax = 36
const peaks = [
{ center: 421, amplitude: 4.4, width: 2.2 },
{ center: 438.4, amplitude: 26.5, width: 2.0 },
{ center: 447.5, amplitude: 10.5, width: 2.6 },
{ center: 468, amplitude: 5.5, width: 2.2 },
{ center: 492, amplitude: 13.5, width: 2.4 },
{ center: 505, amplitude: 7.2, width: 2.0 },
{ center: 510.6, amplitude: 23.5, width: 2.5 },
{ center: 518.4, amplitude: 30.5, width: 2.1 },
{ center: 540, amplitude: 10.5, width: 2.4 },
{ center: 557, amplitude: 7.4, width: 2.1 },
{ center: 574, amplitude: 4.6, width: 2.0 },
{ center: 590, amplitude: 13.4, width: 2.2 },
{ center: 606, amplitude: 6.2, width: 2.1 },
{ center: 614.5, amplitude: 26.5, width: 2.4 },
{ center: 634, amplitude: 6.8, width: 2.2 },
{ center: 653, amplitude: 12.2, width: 2.3 },
{ center: 672, amplitude: 8.4, width: 2.2 },
{ center: 686, amplitude: 10.8, width: 2.0 },
]
const labels = [
{ center: 438.4, element: 'Fe', wavelength: '438.4 nm', lift: 56, dx: 0 },
{ center: 510.6, element: 'Cu', wavelength: '510.6 nm', lift: 100, dx: -94 },
{ center: 518.4, element: 'Mg', wavelength: '518.4 nm', lift: 54, dx: 96 },
{ center: 614.5, element: 'Si', wavelength: '614.5 nm', lift: 58, dx: 0 },
]
const toX = (lambda: number) =>
pad.left + ((lambda - xMin) / (xMax - xMin)) * (width - pad.left - pad.right)
const toY = (intensity: number) =>
height - pad.bottom - ((intensity - yMin) / (yMax - yMin)) * (height - pad.top - pad.bottom)
function intensityAt(lambda: number, index: number) {
let value = 0.72
value += 0.34 * Math.sin(index * 0.37)
value += 0.22 * Math.sin(index * 1.19 + 1.2)
value += 0.14 * Math.cos(index * 2.23)
value += 0.08 * Math.sin(index * 3.7)
for (const peak of peaks) {
const distance = (lambda - peak.center) / peak.width
value += peak.amplitude * Math.exp(-0.5 * distance * distance)
}
return Math.max(0.2, value)
}
const curve = computed(() => {
const count = 620
const points: Array<{ x: number; y: number }> = []
for (let index = 0; index < count; index += 1) {
const ratio = index / (count - 1)
const lambda = xMin + ratio * (xMax - xMin)
points.push({ x: toX(lambda), y: toY(intensityAt(lambda, index)) })
}
return points
})
const linePath = computed(() =>
curve.value
.map((point, index) => `${index === 0 ? 'M' : 'L'}${point.x.toFixed(2)} ${point.y.toFixed(2)}`)
.join(' '),
)
const areaPath = computed(() => {
const bottom = height - pad.bottom
return `${linePath.value} L${toX(xMax).toFixed(2)} ${bottom} L${toX(xMin).toFixed(2)} ${bottom} Z`
})
const yTicks = [0, 10, 20, 30]
const xTicks = [400, 450, 500, 550, 600, 650]
const peakLabels = computed(() =>
labels.map((label) => {
const peak = peaks.find((item) => item.center === label.center)
const peakValue = peak ? peak.amplitude + 1.4 : 10
const x = toX(label.center)
const y = toY(peakValue)
const labelY = Math.max(pad.top + 22, y - label.lift)
return { ...label, x, y, labelX: x + label.dx, labelY }
}),
)
</script>
<template>
<div class="spectrum-chart">
<svg
class="spectrum-chart__svg"
:viewBox="`0 0 ${width} ${height}`"
preserveAspectRatio="xMidYMid meet"
role="img"
aria-label="光谱采集图表"
>
<defs>
<linearGradient id="spectrumStroke" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#6bf2ff" />
<stop offset="0.42" stop-color="#8fe3ff" />
<stop offset="0.72" stop-color="#b49cff" />
<stop offset="1" stop-color="#ff8ad8" />
</linearGradient>
<linearGradient id="spectrumArea" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#a7d5ff" stop-opacity="0.22" />
<stop offset="1" stop-color="#2f6fd0" stop-opacity="0" />
</linearGradient>
</defs>
<rect width="1360" height="720" fill="#2f6fd0" />
<rect width="1360" height="720" fill="url(#spectrumArea)" opacity="0.35" />
<g stroke="rgba(255,255,255,0.24)" stroke-width="1">
<line
v-for="tick in yTicks"
:key="`grid-y-${tick}`"
:x1="pad.left"
:x2="width - pad.right"
:y1="toY(tick)"
:y2="toY(tick)"
stroke-dasharray="3 5"
/>
<line
v-for="tick in xTicks"
:key="`grid-x-${tick}`"
:x1="toX(tick)"
:x2="toX(tick)"
:y1="pad.top"
:y2="height - pad.bottom"
opacity="0.55"
/>
</g>
<g fill="rgba(255,255,255,0.72)" font-size="21" text-anchor="end">
<text
v-for="tick in yTicks"
:key="`label-y-${tick}`"
:x="pad.left - 20"
:y="toY(tick) + 7"
>
{{ tick }}
</text>
</g>
<g fill="rgba(255,255,255,0.74)" font-size="19" text-anchor="middle">
<text
v-for="tick in xTicks"
:key="`label-x-${tick}`"
:x="toX(tick)"
:y="height - pad.bottom + 34"
>
{{ tick }}
</text>
</g>
<g stroke="rgba(255,255,255,0.8)" stroke-width="1.6">
<line :x1="pad.left" :x2="pad.left" :y1="pad.top" :y2="height - pad.bottom" />
<line
:x1="pad.left"
:x2="width - pad.right"
:y1="height - pad.bottom"
:y2="height - pad.bottom"
/>
</g>
<g fill="rgba(255,255,255,0.85)" font-size="22">
<text x="24" y="58">a.u.</text>
<text
x="34"
y="380"
text-anchor="middle"
:transform="`rotate(-90 34 380)`"
>
强 度
</text>
<text x="500" :y="height - 24" text-anchor="middle">波长 nm</text>
<text :x="width - 70" :y="height - 24" text-anchor="end">波长 nm</text>
</g>
<path :d="areaPath" fill="url(#spectrumArea)" />
<path
:d="linePath"
fill="none"
stroke="url(#spectrumStroke)"
stroke-width="2.6"
stroke-linejoin="round"
stroke-linecap="round"
filter="drop-shadow(0 0 5px rgba(146, 228, 255, 0.45))"
/>
<g v-for="label in peakLabels" :key="label.element">
<line
:x1="label.labelX"
:x2="label.x"
:y1="label.labelY + 33"
:y2="label.y - 8"
stroke="rgba(255,255,255,0.62)"
stroke-width="1.3"
stroke-dasharray="3 4"
/>
<circle :cx="label.x" :cy="label.y - 8" r="3.4" fill="#ffffff" opacity="0.92" />
<text
:x="label.labelX"
:y="label.labelY"
fill="#ffffff"
font-size="34"
font-weight="500"
text-anchor="middle"
>
{{ label.element }}
</text>
<text
:x="label.labelX"
:y="label.labelY + 33"
fill="#ffffff"
font-size="24"
text-anchor="middle"
>
{{ label.wavelength }}
</text>
</g>
</svg>
<div class="spectrum-chart__status">
<span class="spectrum-chart__pulse"></span>
光谱采集进行中
</div>
</div>
</template>
<style scoped>
.spectrum-chart {
position: relative;
height: 100%;
overflow: hidden;
border: 1px solid #1e55a4;
border-radius: 16px;
background:
radial-gradient(ellipse 70% 55% at 72% 10%, rgba(119, 182, 255, 0.24), transparent 68%),
linear-gradient(150deg, #3b7edd 0%, #2f6fd0 48%, #2559ac 100%);
box-shadow:
0 18px 44px rgba(31, 77, 147, 0.24),
inset 0 1px 0 rgba(255, 255, 255, 0.18);
}
.spectrum-chart__svg {
width: 100%;
height: 100%;
}
.spectrum-chart__status {
position: absolute;
top: 49%;
left: 50%;
display: flex;
align-items: center;
gap: 14px;
color: #fff;
font-size: 36px;
font-weight: 500;
letter-spacing: 5px;
text-shadow: 0 3px 14px rgba(11, 48, 108, 0.5);
transform: translate(-50%, -50%);
white-space: nowrap;
}
.spectrum-chart__pulse {
width: 10px;
height: 10px;
border-radius: 50%;
background: #8df6ff;
box-shadow: 0 0 14px rgba(141, 246, 255, 0.85);
animation: chart-pulse 1.8s ease-in-out infinite;
}
@keyframes chart-pulse {
0%,
100% {
opacity: 0.35;
transform: scale(0.8);
}
50% {
opacity: 1;
transform: scale(1.15);
}
}
</style>
@@ -0,0 +1,74 @@
<script setup lang="ts">
withDefaults(
defineProps<{
items: string[]
icon?: 'laser' | 'info'
}>(),
{ icon: undefined },
)
</script>
<template>
<footer class="status-footer">
<span v-if="icon" class="status-footer__icon" aria-hidden="true">
<svg v-if="icon === 'laser'" viewBox="0 0 24 24">
<path d="M4 17.5h8.5l2-3H22" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
<path d="M4 17.5v2.2M9 17.5v2.2M14 17.5v2.2M19 17.5v2.2" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
<path d="m15 4 3 3M18 4l-3 3M12 7h3M13.5 5.5v3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
</svg>
<svg v-else viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="1.6" />
<path d="M12 10.5v5.5M12 7.5v.6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
</span>
<span class="status-footer__text">
<template v-for="(item, index) in items" :key="item">
<span>{{ item }}</span>
<span v-if="index < items.length - 1" class="status-footer__sep" aria-hidden="true">|</span>
</template>
</span>
</footer>
</template>
<style scoped>
.status-footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
display: flex;
align-items: center;
gap: 12px;
height: 62px;
padding: 0 42px;
border-top: 1px solid #dde3eb;
background: #fff;
color: #4d5968;
font-size: 20px;
letter-spacing: 0.5px;
}
.status-footer__icon {
display: grid;
place-items: center;
width: 24px;
height: 24px;
color: #7d8a99;
}
.status-footer__icon svg {
width: 22px;
height: 22px;
}
.status-footer__text {
display: flex;
align-items: center;
gap: 14px;
}
.status-footer__sep {
color: #c5cdd8;
}
</style>
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
import { useToast } from '@/composables/useToast'
const { message, visible } = useToast()
</script>
<template>
<Teleport to="body">
<Transition name="toast">
<div v-if="visible" class="toast" role="status" aria-live="polite">
<span class="toast__icon" aria-hidden="true">
<svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="1.6" />
<path d="M12 10.5v5.5M12 7.5v.6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
</span>
<span>{{ message }}</span>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.toast {
position: fixed;
bottom: 54px;
left: 50%;
z-index: 80;
display: flex;
align-items: center;
gap: 12px;
min-width: 280px;
max-width: 720px;
padding: 14px 28px;
border: 1px solid var(--line);
border-radius: 40px;
background: rgba(255, 255, 255, 0.98);
color: var(--ink);
font-size: 18px;
letter-spacing: 0.5px;
box-shadow: 0 16px 44px rgba(22, 39, 65, 0.18);
transform: translateX(-50%);
}
.toast__icon {
display: grid;
place-items: center;
width: 24px;
height: 24px;
color: var(--blue);
}
.toast__icon svg {
width: 22px;
height: 22px;
}
.toast-enter-active,
.toast-leave-active {
transition: opacity 0.22s ease, transform 0.22s ease;
}
.toast-enter-from,
.toast-leave-to {
opacity: 0;
transform: translate(-50%, 10px);
}
</style>
@@ -0,0 +1,168 @@
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
const props = defineProps<{
open: boolean
moduleName: string
}>()
const emit = defineEmits<{
close: []
}>()
const confirmButton = ref<HTMLButtonElement | null>(null)
function close() {
emit('close')
}
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') close()
}
watch(
() => props.open,
async (open) => {
if (open) {
window.addEventListener('keydown', onKeydown)
await nextTick()
confirmButton.value?.focus()
} else {
window.removeEventListener('keydown', onKeydown)
}
},
)
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown)
})
</script>
<template>
<Teleport to="body">
<Transition name="modal">
<div v-if="open" class="modal-backdrop" @click.self="close">
<section
class="modal-card"
role="dialog"
aria-modal="true"
:aria-label="`${moduleName}功能研发中`"
>
<div class="modal-card__icon" aria-hidden="true">
<svg viewBox="0 0 64 64">
<path
d="M39 9a11 11 0 0 0-13.4 13.4L11 37a5 5 0 0 0 7 7l14.6-14.6A11 11 0 0 0 46 16l-6.5 6.5-5-5L41 11Z"
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linejoin="round"
/>
<path d="m13 35 16 16" stroke="currentColor" stroke-width="3" stroke-linecap="round" />
</svg>
</div>
<h2>{{ moduleName }}功能研发中</h2>
<p>该模块正在研发中,敬请期待。</p>
<button ref="confirmButton" class="modal-card__button" type="button" @click="close">
我知道了
</button>
</section>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 60;
display: grid;
place-items: center;
padding: 24px;
background: rgba(18, 33, 54, 0.44);
backdrop-filter: blur(5px);
}
.modal-card {
width: 560px;
padding: 42px 44px 38px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 24px;
background: #fff;
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
text-align: center;
}
.modal-card__icon {
display: grid;
place-items: center;
width: 86px;
height: 86px;
margin: 0 auto 24px;
border-radius: 50%;
color: var(--blue);
background: linear-gradient(145deg, #f1f7ff, #dfeaff);
box-shadow: inset 0 1px 0 #fff, 0 8px 22px rgba(47, 111, 208, 0.14);
}
.modal-card__icon svg {
width: 46px;
height: 46px;
}
.modal-card h2 {
color: #1f2937;
font-size: 30px;
font-weight: 600;
letter-spacing: 1px;
}
.modal-card p {
margin-top: 14px;
color: #778394;
font-size: 19px;
letter-spacing: 0.5px;
}
.modal-card__button {
width: 210px;
height: 56px;
margin-top: 30px;
border-radius: 12px;
color: #fff;
font-size: 20px;
font-weight: 600;
letter-spacing: 3px;
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.modal-card__button:hover {
transform: translateY(-1px);
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
}
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.24s ease;
}
.modal-enter-active .modal-card,
.modal-leave-active .modal-card {
transition: transform 0.24s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.24s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
.modal-enter-from .modal-card,
.modal-leave-to .modal-card {
opacity: 0;
transform: translateY(16px) scale(0.97);
}
</style>
@@ -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<CameraConnectionState>('checking')
const connected = ref<boolean | null>(null)
const lastChecked = ref<Date | null>(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,
}
}
@@ -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<StreamState>('idle')
const frameUrl = ref<string | null>(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,
}
}
@@ -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 }
}
@@ -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 }
}
@@ -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 }
}
+26
View File
@@ -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),
}
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="vite/client" />
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<string, unknown>, Record<string, unknown>, unknown>
export default component
}
+6
View File
@@ -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')
+52
View File
@@ -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
+190
View File
@@ -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;
}
}
+174
View File
@@ -0,0 +1,174 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue'
import ModuleButton from '@/components/ModuleButton.vue'
import PrinciplePlayer from '@/components/PrinciplePlayer.vue'
import UnderDevelopmentModal from '@/components/UnderDevelopmentModal.vue'
import logo from '@/assets/logo.png'
type ModuleTone = 'blue' | 'orange' | 'green' | 'teal'
type ModuleIconName = 'detect' | 'metal' | 'soil' | 'water'
interface HomeModule {
key: string
title: string
tone: ModuleTone
icon: ModuleIconName
}
const modules: HomeModule[] = [
{ key: 'element', title: '元素检测', tone: 'blue', icon: 'detect' },
{ key: 'metal', title: '金属鉴别', tone: 'orange', icon: 'metal' },
{ key: 'soil', title: '土壤与沉积物筛查', tone: 'green', icon: 'soil' },
{ key: 'water', title: '水体液体分析', tone: 'teal', icon: 'water' },
]
const router = useRouter()
const modalOpen = ref(false)
const modalModule = ref('')
function openModule(module: HomeModule) {
if (module.key === 'element') {
void router.push({ name: 'sample' })
return
}
modalModule.value = module.title
modalOpen.value = true
}
</script>
<template>
<AppStage>
<div class="home">
<header class="home-header">
<div class="brand">
<img :src="logo" alt="泽科技 LIBS 标识" />
<span>LIBS</span>
</div>
<div class="headline">
<h1>激光诱导击穿光谱 元素分析系统</h1>
<p>开放 · 共享 · 自助式元素检测平台</p>
</div>
</header>
<main class="home-main">
<section class="modules-panel">
<div class="modules-grid">
<ModuleButton
v-for="module in modules"
:key="module.key"
:title="module.title"
:tone="module.tone"
:icon="module.icon"
@click="openModule(module)"
/>
</div>
</section>
<PrinciplePlayer class="home-player" />
</main>
</div>
<UnderDevelopmentModal
:open="modalOpen"
:module-name="modalModule"
@close="modalOpen = false"
/>
</AppStage>
</template>
<style scoped>
.home {
position: absolute;
inset: 0;
background: #f0f2f5;
}
.home-header {
position: absolute;
top: 0;
right: 0;
left: 0;
height: 180px;
padding: 24px 44px;
background: #f4f5f7;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand img {
width: 100px;
height: 100px;
object-fit: contain;
mix-blend-mode: multiply;
}
.brand span {
color: #253243;
font-size: 32px;
font-weight: 700;
letter-spacing: 2px;
}
.headline {
position: absolute;
top: 40px;
left: 50%;
text-align: center;
transform: translateX(-50%);
white-space: nowrap;
}
.headline h1 {
color: #1f2937;
font-size: 44px;
font-weight: 600;
letter-spacing: 6px;
line-height: 1.2;
}
.headline p {
margin-top: 16px;
color: #4d5969;
font-size: 20px;
letter-spacing: 4px;
}
.home-main {
position: absolute;
top: 196px;
right: 44px;
bottom: 40px;
left: 44px;
display: grid;
grid-template-columns: 868px minmax(0, 1fr);
gap: 36px;
}
.modules-panel {
display: flex;
align-items: center;
padding: 34px;
border-radius: 20px;
background: #fff;
box-shadow: var(--shadow-card);
}
.modules-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 32px;
width: 100%;
}
.home-player {
min-width: 0;
}
</style>
+290
View File
@@ -0,0 +1,290 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue'
import MiniSpectrum from '@/components/MiniSpectrum.vue'
import { useCountdown } from '@/composables/useCountdown'
import { showToast } from '@/composables/useToast'
import reportQr from '@/assets/report-qr.png'
const router = useRouter()
function goHome() {
void router.replace({ name: 'home' })
}
const { remaining } = useCountdown(60, goHome)
const rows = [
{ element: 'Fe', intensity: '高', content: '3.82%', verdict: '检出' },
{ element: 'Cu', intensity: '中', content: '1.27%', verdict: '检出' },
{ element: 'Mg', intensity: '中', content: '0.94%', verdict: '检出' },
{ element: 'Si', intensity: '低', content: '0.41%', verdict: '痕量' },
]
function exportReport() {
showToast('报告导出功能正在研发中')
}
</script>
<template>
<AppStage>
<PageHeader title="检测完成" variant="result" />
<main class="result-main">
<section class="result-card">
<h2 class="result-card__title">元素检测结果</h2>
<div class="result-summary">
<MiniSpectrum />
<div class="result-badge">合金成分分析完成</div>
</div>
<table class="result-table">
<thead>
<tr>
<th>元素</th>
<th>强度</th>
<th>含量</th>
<th>判定</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.element">
<td class="result-table__element">{{ row.element }}</td>
<td>{{ row.intensity }}</td>
<td>{{ row.content }}</td>
<td>{{ row.verdict }}</td>
</tr>
</tbody>
</table>
</section>
<aside class="report-card">
<h2 class="report-card__title">获取完整报告</h2>
<div class="report-card__qr">
<img :src="reportQr" alt="获取完整检测报告二维码" />
</div>
<p class="report-card__caption">扫码关注微信公众号获取更详细结果</p>
</aside>
</main>
<div class="result-actions">
<p class="result-actions__countdown">
当前界面还有 <strong>{{ remaining }}</strong>s 后自动关闭...
</p>
<div class="result-actions__buttons">
<button class="result-button result-button--close" type="button" @click="goHome">
关闭
</button>
<button class="result-button result-button--export" type="button" @click="exportReport">
导出报告
</button>
</div>
</div>
</AppStage>
</template>
<style scoped>
.result-main {
position: absolute;
top: 150px;
right: 44px;
left: 44px;
display: grid;
grid-template-columns: minmax(0, 1fr) 620px;
gap: 40px;
height: 730px;
}
.result-card {
display: flex;
flex-direction: column;
padding: 28px 38px 34px;
overflow: hidden;
border-radius: 20px;
background:
radial-gradient(ellipse 70% 50% at 60% 0%, rgba(131, 185, 255, 0.28), transparent 70%),
linear-gradient(150deg, #3c7fdf 0%, #2f6fd0 48%, #2559ad 100%);
box-shadow:
0 18px 44px rgba(31, 77, 147, 0.26),
inset 0 1px 0 rgba(255, 255, 255, 0.2);
}
.result-card__title {
color: #fff;
font-size: 38px;
font-weight: 600;
letter-spacing: 4px;
text-align: center;
text-shadow: 0 2px 6px rgba(15, 47, 98, 0.22);
}
.result-summary {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 28px;
margin-top: 22px;
}
.result-badge {
display: flex;
align-items: center;
justify-content: center;
min-width: 300px;
height: 58px;
padding: 0 24px;
border: 1px solid #e4c98e;
border-radius: 10px;
background: linear-gradient(180deg, #faf0d8 0%, #f3e3bd 100%);
color: #5e4726;
font-size: 24px;
letter-spacing: 2px;
box-shadow: 0 6px 16px rgba(24, 55, 105, 0.14);
}
.result-table {
width: 100%;
margin-top: 22px;
border-collapse: collapse;
table-layout: fixed;
}
.result-table th {
height: 58px;
border: 1px solid rgba(255, 255, 255, 0.5);
background: rgba(37, 89, 173, 0.2);
color: #fff;
font-size: 27px;
font-weight: 500;
letter-spacing: 2px;
}
.result-table td {
height: 94px;
border: 1px solid rgba(255, 255, 255, 0.66);
background: rgba(255, 255, 255, 0.95);
color: #222b38;
font-size: 26px;
text-align: center;
}
.result-table__element {
font-weight: 600;
}
.report-card {
display: flex;
flex-direction: column;
align-items: center;
padding: 28px 34px 34px;
overflow: hidden;
border-radius: 20px;
background:
radial-gradient(ellipse 75% 55% at 28% 0%, rgba(255, 220, 170, 0.34), transparent 70%),
linear-gradient(150deg, #f7a44b 0%, #ee8a2f 52%, #e67720 100%);
box-shadow:
0 18px 44px rgba(190, 104, 27, 0.24),
inset 0 1px 0 rgba(255, 255, 255, 0.28);
}
.report-card__title {
color: #fff;
font-size: 38px;
font-weight: 600;
letter-spacing: 4px;
text-align: center;
text-shadow: 0 2px 5px rgba(139, 73, 14, 0.22);
}
.report-card__qr {
width: 336px;
height: 356px;
margin-top: 28px;
padding: 18px;
border-radius: 14px;
background: #fff;
box-shadow: 0 14px 30px rgba(129, 69, 13, 0.2);
}
.report-card__qr img {
width: 100%;
height: 100%;
object-fit: contain;
image-rendering: auto;
}
.report-card__caption {
max-width: 480px;
margin-top: 26px;
color: #fff;
font-size: 21px;
line-height: 1.6;
letter-spacing: 1px;
text-align: center;
text-shadow: 0 1px 3px rgba(139, 73, 14, 0.2);
}
.result-actions {
position: absolute;
right: 44px;
bottom: 48px;
left: 44px;
display: flex;
align-items: center;
justify-content: space-between;
}
.result-actions__countdown {
color: #303a48;
font-size: 27px;
letter-spacing: 1px;
}
.result-actions__countdown strong {
color: var(--orange-dark);
font-size: 32px;
font-weight: 700;
}
.result-actions__buttons {
display: flex;
gap: 22px;
}
.result-button {
display: grid;
place-items: center;
width: 208px;
height: 70px;
border-radius: 10px;
font-size: 29px;
font-weight: 600;
letter-spacing: 5px;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.result-button:hover {
transform: translateY(-1px);
}
.result-button--close {
color: #fff;
background: linear-gradient(180deg, #ffc42b 0%, #f1ab0c 100%);
box-shadow:
0 10px 22px rgba(225, 154, 6, 0.26),
inset 0 1px 0 rgba(255, 255, 255, 0.55);
text-shadow: 0 1px 2px rgba(151, 94, 0, 0.24);
}
.result-button--export {
border: 1px solid #e2cb9f;
color: #755329;
background: linear-gradient(180deg, #fbf1dd 0%, #f1e0bd 100%);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
}
</style>
+228
View File
@@ -0,0 +1,228 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue'
import CameraPreview from '@/components/CameraPreview.vue'
import GuideIcon from '@/components/GuideIcon.vue'
import StatusFooter from '@/components/StatusFooter.vue'
import { showToast } from '@/composables/useToast'
const router = useRouter()
const steps = [
{ title: '打开样品仓', icon: 'door' as const },
{ title: '放置待测样品', icon: 'tray' as const },
{ title: '调整聚焦位置', icon: 'focus' as const },
]
function goHome() {
void router.push({ name: 'home' })
}
function startDetection() {
void router.push({ name: 'scan' })
}
function previewFocus() {
showToast('预览对焦功能正在研发中')
}
</script>
<template>
<AppStage>
<PageHeader title="放置待测样品">
<template #left>
<button class="header-button header-button--outline" type="button" @click="goHome">
返回
</button>
</template>
</PageHeader>
<main class="sample-main">
<CameraPreview class="sample-camera" />
<aside class="guide-column">
<section class="guide-card">
<header class="guide-card__header">
<h2>样品放置操作指引</h2>
</header>
<ol class="guide-steps">
<li v-for="(step, index) in steps" :key="step.title" class="guide-step">
<span class="guide-step__number">{{ index + 1 }}</span>
<span class="guide-step__title">{{ step.title }}</span>
<span class="guide-step__icon">
<GuideIcon :name="step.icon" />
</span>
</li>
</ol>
</section>
<div class="guide-actions">
<button class="action-button action-button--start" type="button" @click="startDetection">
开始检测
</button>
<button class="action-button action-button--ghost" type="button" @click="previewFocus">
预览对焦
</button>
</div>
</aside>
</main>
<StatusFooter
:items="['样品仓已关闭', '激光安全等级 Class 1', '环境温度 22℃']"
/>
</AppStage>
</template>
<style scoped>
.sample-main {
position: absolute;
top: 220px;
right: 44px;
left: 44px;
display: grid;
grid-template-columns: minmax(0, 1fr) 620px;
gap: 34px;
height: 710px;
}
.sample-camera {
min-width: 0;
}
.guide-column {
display: flex;
flex-direction: column;
gap: 18px;
min-width: 0;
}
.guide-card {
display: flex;
flex: 1;
flex-direction: column;
overflow: hidden;
border-radius: 18px;
background: #2fb8ad;
box-shadow: 0 16px 34px rgba(31, 148, 139, 0.24);
}
.guide-card__header {
display: flex;
flex: none;
align-items: center;
height: 104px;
padding: 0 34px;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
background: linear-gradient(180deg, rgba(255, 255, 255, 0.1), transparent);
}
.guide-card__header h2 {
color: #fff;
font-size: 32px;
font-weight: 600;
letter-spacing: 3px;
text-shadow: 0 1px 3px rgba(10, 94, 88, 0.2);
}
.guide-steps {
display: flex;
flex: 1;
flex-direction: column;
}
.guide-step {
display: flex;
flex: 1;
align-items: center;
gap: 22px;
min-height: 0;
padding: 0 34px;
border-bottom: 1px solid rgba(255, 255, 255, 0.18);
}
.guide-step:last-child {
border-bottom: 0;
}
.guide-step__number {
display: grid;
flex: none;
place-items: center;
width: 46px;
height: 46px;
border: 2px solid rgba(255, 255, 255, 0.9);
border-radius: 50%;
color: #fff;
font-size: 24px;
font-weight: 600;
}
.guide-step__title {
flex: 1;
color: #fff;
font-size: 28px;
font-weight: 500;
letter-spacing: 1px;
text-shadow: 0 1px 3px rgba(10, 94, 88, 0.18);
}
.guide-step__icon {
display: grid;
flex: none;
place-items: center;
width: 78px;
height: 78px;
padding: 2px;
}
.guide-actions {
display: grid;
flex: none;
grid-template-columns: 1.16fr 0.84fr;
gap: 20px;
height: 78px;
}
.action-button {
display: grid;
place-items: center;
height: 78px;
border-radius: 12px;
font-size: 30px;
font-weight: 600;
letter-spacing: 4px;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.action-button:hover {
transform: translateY(-1px);
}
.action-button--start {
color: #fff;
background: linear-gradient(180deg, #ffc52c 0%, #f3ae0d 100%);
box-shadow:
0 12px 24px rgba(224, 154, 6, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.55);
text-shadow: 0 1px 2px rgba(151, 94, 0, 0.25);
}
.action-button--start:hover {
box-shadow:
0 16px 30px rgba(224, 154, 6, 0.36),
inset 0 1px 0 rgba(255, 255, 255, 0.55);
}
.action-button--ghost {
border: 2px solid #d3dbe6;
color: #253243;
background: #fff;
}
.action-button--ghost:hover {
border-color: #aebdcd;
background: #f8fafc;
}
</style>
+178
View File
@@ -0,0 +1,178 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue'
import ScanVisual from '@/components/ScanVisual.vue'
import ProgressStrip from '@/components/ProgressStrip.vue'
import StatusFooter from '@/components/StatusFooter.vue'
import { useTimedProgress } from '@/composables/useTimedProgress'
const router = useRouter()
const { progress } = useTimedProgress(15000, () => {
void router.replace({ name: 'spectrum' })
})
const progressLabel = computed(() => `点位扫描 ${Math.round(progress.value)}%`)
function abortProcess() {
void router.replace({ name: 'home' })
}
</script>
<template>
<AppStage>
<PageHeader title="样品轮廓识别与激光点位规划" variant="process">
<template #left>
<button class="header-button header-button--warn" type="button" @click="abortProcess">
中止流程
</button>
</template>
<template #right>
<button class="icon-close" type="button" aria-label="关闭并返回首页" @click="abortProcess">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
</button>
</template>
</PageHeader>
<main class="scan-main">
<ScanVisual class="scan-card" />
<aside class="params-card">
<header class="params-card__header">
<h2>采样点</h2>
</header>
<div class="params-card__body">
<div class="param-field">
<span class="param-field__label">采样点数</span>
<div class="param-field__value">5</div>
</div>
<div class="param-field">
<span class="param-field__label">脉冲能量</span>
<div class="param-field__value">120 <small>mJ</small></div>
</div>
<div class="param-field">
<span class="param-field__label">积分时间</span>
<div class="param-field__value">10 <small>ms</small></div>
</div>
<div class="param-field">
<span class="param-field__label">预扫描</span>
<div class="param-field__value">3 <small>次</small></div>
</div>
</div>
</aside>
</main>
<div class="scan-progress">
<ProgressStrip :progress="progress" :label="progressLabel" note="已规划 5 个采样点" />
</div>
<StatusFooter
icon="info"
:items="['轮廓提取完成', '点位校验通过', '等待采集光谱']"
/>
</AppStage>
</template>
<style scoped>
.scan-main {
position: absolute;
top: 142px;
right: 44px;
left: 44px;
display: grid;
grid-template-columns: minmax(0, 1fr) 342px;
gap: 20px;
height: 730px;
}
.scan-card {
width: 1120px;
max-width: 100%;
height: 100%;
justify-self: center;
}
.params-card {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
border: 1px solid #d9e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 8px 24px rgba(33, 53, 84, 0.05);
}
.params-card__header {
display: flex;
flex: none;
align-items: center;
height: 64px;
padding: 0 22px;
border-bottom: 1px solid #e4e8ee;
background: #f3f4f6;
}
.params-card__header h2 {
color: #333b46;
font-size: 23px;
font-weight: 500;
letter-spacing: 1px;
}
.params-card__body {
padding: 26px 22px;
}
.param-field {
margin-bottom: 24px;
}
.param-field:last-child {
margin-bottom: 0;
}
.param-field__label {
display: block;
margin-bottom: 10px;
color: #46505e;
font-size: 22px;
letter-spacing: 0.5px;
}
.param-field__value {
display: flex;
align-items: center;
height: 62px;
padding: 0 18px;
border: 1px solid #d8dde6;
border-radius: 7px;
background: #fff;
color: #2e3641;
font-size: 24px;
box-shadow: inset 0 1px 2px rgba(30, 45, 66, 0.03);
}
.param-field__value small {
margin-left: 8px;
color: #8d97a4;
font-size: 18px;
}
.scan-progress {
position: absolute;
top: 900px;
right: 44px;
left: 44px;
height: 54px;
}
</style>
+222
View File
@@ -0,0 +1,222 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue'
import SpectrumChart from '@/components/SpectrumChart.vue'
import ProgressStrip from '@/components/ProgressStrip.vue'
import StatusFooter from '@/components/StatusFooter.vue'
import { useTimedProgress } from '@/composables/useTimedProgress'
const router = useRouter()
const { progress } = useTimedProgress(10000, () => {
void router.replace({ name: 'result' })
})
const progressLabel = computed(() => `光谱采集 ${Math.round(progress.value)}%`)
const sampleIndex = computed(() =>
Math.min(5, Math.max(1, Math.ceil(progress.value / 20))),
)
function abortProcess() {
void router.replace({ name: 'home' })
}
</script>
<template>
<AppStage>
<PageHeader title="光谱数据采集与分析" variant="process">
<template #left>
<button class="header-button header-button--warn" type="button" @click="abortProcess">
中止流程
</button>
</template>
</PageHeader>
<main class="spectrum-main">
<SpectrumChart class="spectrum-chart" />
<aside class="analysis-card">
<header class="analysis-card__header">
<h2>分析步骤</h2>
</header>
<div class="analysis-card__body">
<div class="analysis-step">
<span class="analysis-step__icon analysis-step__icon--blue">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="1.6" />
<path d="M12 7v5l3.4 2" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
</svg>
</span>
<span class="analysis-step__text">正在拟合峰值</span>
<span class="analysis-step__chevron">›</span>
</div>
<div class="analysis-step">
<span class="analysis-step__icon analysis-step__icon--amber">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 15h14M7 15V8l5-3 5 3v7" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" />
<path d="M9 15v3h6v-3" fill="none" stroke="currentColor" stroke-width="1.6" />
</svg>
</span>
<span class="analysis-step__text">扣除连续背景</span>
<span class="analysis-step__chevron">›</span>
</div>
<div class="analysis-step">
<span class="analysis-step__icon analysis-step__icon--blue">
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="6" y="4" width="12" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" />
<path d="M9 8h6M9 11h6M9 14h3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
</svg>
</span>
<span class="analysis-step__text">计算元素浓度</span>
<span class="analysis-step__chevron">›</span>
</div>
<div class="analysis-card__track" aria-hidden="true">
<span></span>
</div>
</div>
</aside>
</main>
<div class="spectrum-progress">
<ProgressStrip
:progress="progress"
:label="progressLabel"
:note="`第 ${sampleIndex} / 5 次采样`"
/>
</div>
<StatusFooter
icon="laser"
:items="['激光发射正常', '探测器积分完成', '数据保存中']"
/>
</AppStage>
</template>
<style scoped>
.spectrum-main {
position: absolute;
top: 142px;
right: 44px;
left: 44px;
display: grid;
grid-template-columns: minmax(0, 1fr) 342px;
gap: 20px;
height: 730px;
}
.spectrum-chart {
min-width: 0;
}
.analysis-card {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
border: 1px solid #d9e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 8px 24px rgba(33, 53, 84, 0.05);
}
.analysis-card__header {
display: flex;
flex: none;
align-items: center;
height: 64px;
padding: 0 22px;
border-bottom: 1px solid #e4e8ee;
background: #f3f4f6;
}
.analysis-card__header h2 {
color: #333b46;
font-size: 23px;
font-weight: 500;
letter-spacing: 1px;
}
.analysis-card__body {
flex: 1;
padding: 16px 18px;
}
.analysis-step {
display: flex;
align-items: center;
gap: 16px;
height: 78px;
padding: 0 10px;
border-bottom: 1px solid #eef1f5;
}
.analysis-step__icon {
display: grid;
flex: none;
place-items: center;
width: 38px;
height: 38px;
border-radius: 50%;
}
.analysis-step__icon svg {
width: 26px;
height: 26px;
}
.analysis-step__icon--blue {
color: #2f6fd0;
background: #eaf2ff;
}
.analysis-step__icon--amber {
color: #d59400;
background: #fff4d6;
}
.analysis-step__text {
flex: 1;
color: #3f4b5b;
font-size: 21px;
letter-spacing: 0.5px;
}
.analysis-step__chevron {
color: #b2bcc8;
font-size: 30px;
line-height: 1;
}
.analysis-card__track {
position: relative;
width: 6px;
height: 142px;
margin: 22px 0 0 auto;
border-radius: 6px;
background: #eef1f5;
}
.analysis-card__track span {
position: absolute;
top: 18px;
left: 0;
width: 6px;
height: 54px;
border-radius: 6px;
background: #c9d3df;
}
.spectrum-progress {
position: absolute;
top: 900px;
right: 44px;
left: 44px;
height: 54px;
}
</style>
+30
View File
@@ -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"
]
}
+45
View File
@@ -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,
},
})
@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FlashCap" Version="1.12.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" />
</ItemGroup>
<ItemGroup>
<Reference Include="ArisSharp">
<HintPath>dll\aris\ArisSharp.dll</HintPath>
</Reference>
</ItemGroup>
<!--
aris.dll / libusb-1.0.dll 是 ArisSharp.dll 的原生依赖,必须和可执行文件放在同一目录。
作为项目内容复制,引用本项目的 HardwareWeb / HardwareProbe 输出目录也会带上它们。
-->
<ItemGroup>
<None Update="dll\aris\aris.dll">
<Link>aris.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
<None Update="dll\aris\libusb-1.0.dll">
<Link>libusb-1.0.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
+30
View File
@@ -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;
}
}
}
@@ -0,0 +1,68 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{
/// <summary>
/// aris 光谱仪服务。
/// 单台使用 AcquireFrame 同步单帧;多台使用 StartMeasurement 一次性武装,
/// 收齐回调后按波长拼接。所有操作在内部串行化,单帧/多台采集互斥。
/// </summary>
public interface IArisSpectrometerService : IAsyncDisposable
{
/// <summary>是否已经成功连接(不保证设备此刻仍在线)。</summary>
bool IsConnected { get; }
/// <summary>连接时发现并初始化的设备数量。</summary>
int DeviceCount { get; }
/// <summary>当前选中的设备;未连接时为 null。</summary>
SpectrometerDeviceInfo? SelectedDevice { get; }
/// <summary>选中设备的像素数;未连接时为 null。</summary>
int? PixelCount { get; }
/// <summary>连接时缓存的设备列表;未连接时为空。</summary>
IReadOnlyList<SpectrometerDeviceInfo> Devices { get; }
/// <summary>本次连接累计成功采集的帧数。</summary>
long FramesAcquired { get; }
/// <summary>最近一次成功采集的完成时间;尚未采集时为 null。</summary>
DateTimeOffset? LastAcquireAt { get; }
Task ConnectAsync(CancellationToken ct = default);
Task DisconnectAsync(CancellationToken ct = default);
/// <summary>
/// 同步采一帧。内部串行化所有原生调用,因此并发调用会排队,
/// <paramref name="ct"/> 只影响排队阶段,已开始的曝光无法取消。
/// </summary>
Task<SpectrumFrame> AcquireFrameAsync(
SpectrumAcquisitionRequest? request = null,
CancellationToken ct = default);
/// <summary>
/// 多台光谱仪同步采集一帧:StartMeasurement 一次武装所有设备,
/// 收齐每台设备的回调后按波长自动拼接(重合区间各去一半)。
/// 由第三台设备触发激光的场景使用 Software 触发模式;
/// 有外部 AD/TTL 触发源时使用 FreeRunEdge/External。
/// 部分设备超时会返回已收到的帧,并通过 MissingSerials 标记缺失设备。
/// </summary>
Task<SynchronizedSpectrumResult> AcquireSynchronizedAsync(
SynchronizedSpectrumRequest? request = null,
CancellationToken ct = default);
/// <summary>查询设备运行时状态(一次 USB 往返)。</summary>
Task<SpectrometerDeviceStatus> GetDeviceStatusAsync(
int? deviceIndex = null,
CancellationToken ct = default);
/// <summary>读取波长数组(用于单独绘制坐标轴)。</summary>
Task<float[]> GetWavelengthsAsync(
int? deviceIndex = null,
CancellationToken ct = default);
event EventHandler<SpectrometerStatusChangedEventArgs>? StatusChanged;
}
}
@@ -0,0 +1,27 @@
using HardwareControl.Core.UsbCamera;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{
public interface IUsbCameraService : IAsyncDisposable
{
bool IsConnected { get; }
/// <summary>最近一次成功打开的设备名称。</summary>
string? DeviceName { get; }
/// <summary>当前(或最近一次)采集格式;未打开过设备时为 null。</summary>
CameraFrameFormat? FrameFormat { get; }
/// <summary>最近一帧的到达时间(UTC);尚未收到帧时为 null。</summary>
DateTimeOffset? LastFrameAt { get; }
/// <summary>本次连接累计收到的帧数。</summary>
long FramesReceived { get; }
Task ConnectAsync(CancellationToken ct = default);
Task DisconnectAsync(CancellationToken ct = default);
event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
event EventHandler<FrameArrivedEventArgs>? FrameArrived;
}
}
@@ -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
{
/// <summary>
/// aris 光谱仪服务实现。
///
/// 线程模型:
/// * 所有原生调用(连接、单帧采集、多台同步采集、状态、波长)都由 <see cref="_gate"/> 串行化,
/// 因为 <see cref="ArisSpectrometer"/> / aris.dll 内部虽然也加锁,但采集是长事务,
/// 在业务层排队更容易控制超时与日志;
/// * 原生调用是同步阻塞的,因此放到线程池执行,避免占用 ASP.NET Core 请求线程;
/// * 单台使用同步 <c>AcquireFrame</c>;多台使用 <c>StartMeasurement</c> 一次武装,
/// 回调只做拷贝/入队,收齐后调用 <c>StopMeasurement</c> 并拼接。
/// 单帧与多台测量在 SDK 层互斥(测量中调用单帧会返回 InvalidState)。
/// </summary>
public sealed class ArisSpectrometerService : IArisSpectrometerService
{
private readonly ArisSpectrometerOptions _options;
private readonly ILogger<ArisSpectrometerService> _logger;
// 串行化全部原生调用
private readonly SemaphoreSlim _gate = new(1, 1);
private ArisSpectrometer? _spectrometer;
private volatile SpectrometerDeviceInfo[] _devices = Array.Empty<SpectrometerDeviceInfo>();
private volatile SpectrometerDeviceInfo? _selectedDevice;
private volatile bool _connected;
private bool _disposed;
private long _framesAcquired;
private long _lastAcquireAtTicks;
public ArisSpectrometerService(
IOptions<ArisSpectrometerOptions> options,
ILogger<ArisSpectrometerService> 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<SpectrometerDeviceInfo> 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<SpectrometerStatusChangedEventArgs>? 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();
}
}
/// <summary>停止测量、断开并销毁上下文;异常只记日志,保证状态一定归零。</summary>
private void DisposeSpectrometerCore()
{
var spectrometer = _spectrometer;
_spectrometer = null;
_connected = false;
_devices = Array.Empty<SpectrometerDeviceInfo>();
_selectedDevice = null;
if (spectrometer is null)
{
return;
}
try
{
// ArisSpectrometer.Dispose 内部会先 stop 再 disconnect,然后销毁上下文。
spectrometer.Dispose();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "释放 aris 光谱仪上下文时发生异常");
}
}
// ---------- 单帧采集 ----------
public async Task<SpectrumFrame> 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<SynchronizedSpectrumResult> 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<string, SpectrometerDeviceInfo>(
StringComparer.OrdinalIgnoreCase);
foreach (var device in devices)
{
if (!bySerial.TryAdd(device.SerialNumber, device))
{
_logger.LogWarning(
"重复的光谱仪序列号 {SerialNumber},只保留第一台",
device.SerialNumber);
}
}
var frames = new ConcurrentDictionary<string, CapturedSpectrum>(
StringComparer.OrdinalIgnoreCase);
var errors = new ConcurrentDictionary<string, string>(
StringComparer.OrdinalIgnoreCase);
var accounted = new ConcurrentDictionary<string, byte>(
StringComparer.OrdinalIgnoreCase);
var completion = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<SpectrumReceivedEventArgs> 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<SpectrometerErrorEventArgs> 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<SynchronizedSpectrumFrame>(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<string>(
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<SpectrometerDeviceStatus> 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<float[]> 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);
}
}
}
@@ -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<UsbCameraService> _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<UsbCameraStatusChangedEventArgs>? StatusChanged;
public event EventHandler<FrameArrivedEventArgs>? FrameArrived;
public UsbCameraService(
IOptions<UsbCameraOptions> options,
ILogger<UsbCameraService> 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<CaptureDeviceDescriptor> 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, "相机已断开"));
}
}
// ---------- 重连监控 ----------
/// <summary>
/// 保证只有一个重连监控循环。重连成功时 ConnectCoreAsync 会调用它,
/// 若当前循环仍在运行则不会重复创建。
/// </summary>
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);
}
}
}
/// <summary>检查当前连接是否长时间没有新帧。</summary>
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);
}
/// <summary>画面超时时由监控循环调用:停止旧设备并通知前端。</summary>
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();
}
}
}
@@ -0,0 +1,70 @@
using Aris;
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// aris 光谱仪配置,对应 appsettings.json 的 "ArisSpectrometer" 节。
/// 所有属性都有默认值,配置文件可只写需要覆盖的项。
/// </summary>
public sealed class ArisSpectrometerOptions
{
public const string SectionName = "ArisSpectrometer";
/// <summary>
/// 默认使用的设备索引(0 起)。多台设备时由 <see cref="PreferredSerialNumber"/> 优先。
/// </summary>
public int DeviceIndex { get; set; }
/// <summary>
/// 优先匹配的序列号;非空且能匹配到设备时覆盖 <see cref="DeviceIndex"/>。
/// </summary>
public string? PreferredSerialNumber { get; set; }
/// <summary>单帧采集默认曝光时间,单位微秒,必须大于 0。</summary>
public int ExposureUs { get; set; } = 1000;
/// <summary>单帧采集默认平均次数,必须大于等于 1。</summary>
public int Averaging { get; set; } = 1;
/// <summary>单帧采集默认触发延迟,单位微秒,必须大于等于 0。</summary>
public int DelayUs { get; set; }
/// <summary>
/// 单帧采集默认超时,单位毫秒;小于等于 0 时由 SDK 按
/// <c>max(3000, 曝光/1000 + 2000)</c> 计算。
/// </summary>
public int TimeoutMs { get; set; }
/// <summary>
/// 多台同步采集的默认曝光时间,单位微秒。
/// SDK 逐台武装设备,第三台通常比前两台晚约 0.6 秒启动;
/// 曝光窗口必须覆盖这段武装时间,否则前两台会在第三台触发激光前结束。
/// 默认 1 秒,可按现场时序下调,但建议不低于 0.7 秒。
/// </summary>
public int SynchronizedExposureUs { get; set; } = 1_000_000;
/// <summary>
/// 多台同步采集时,StartMeasurement 返回后等待所有设备回调的默认最长时间(毫秒)。
/// </summary>
public int SynchronizedWaitTimeoutMs { get; set; } = 8000;
/// <summary>
/// 连接成功后设置的触发模式;为 null 时保持设备当前配置。
/// 手册要求触发模式只在连接后设置一次。
/// 默认 <see cref="Aris.TriggerMode.Software"/>:纯自由运行。
/// 由第三台设备触发激光、其余设备自由收光的场景使用 Software;
/// 有外部 AD/TTL 触发源时改为 FreeRunEdge 或 External。
/// </summary>
public TriggerMode? TriggerMode { get; set; } = Aris.TriggerMode.Software;
/// <summary>
/// 连接成功后设置的增益(0=低增益,1=高增益);为 null 时保持设备当前配置。
/// </summary>
public int? Gain { get; set; }
/// <summary>
/// 是否打开 aris.dll 内部的诊断日志(默认关闭,避免刷屏)。
/// </summary>
public bool SdkLogEnabled { get; set; }
}
}
@@ -0,0 +1,18 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 多台光谱仪按波长拼接后的结果。
/// 拼接直接使用各设备原始采样点,不做插值;重合波长区间的处理规则见
/// <see cref="SpectrumMerger"/>。
/// </summary>
/// <param name="Wavelengths">拼接后的波长数组,按升序排列。</param>
/// <param name="Spectrum">拼接后的强度数组,与波长等长。</param>
/// <param name="Segments">每一段数据的来源设备,用于分段绘图。</param>
public sealed record MergedSpectrum(
float[] Wavelengths,
float[] Spectrum,
IReadOnlyList<MergedSpectrumSegment> Segments)
{
public int PixelCount => Wavelengths.Length;
}
}
@@ -0,0 +1,18 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 拼接后光谱中的一段,表示这一段采样点来自哪台设备。
/// 前端应按 Segments 分段绘制;相邻段波长不连续时应断开连线,避免把光谱间隙画成直线。
/// </summary>
/// <param name="DeviceIndex">来源设备索引。</param>
/// <param name="SerialNumber">来源设备序列号。</param>
/// <param name="WavelengthStart">该段第一个点的波长。</param>
/// <param name="WavelengthEnd">该段最后一个点的波长。</param>
/// <param name="PointCount">该段的采样点数。</param>
public sealed record MergedSpectrumSegment(
int DeviceIndex,
string SerialNumber,
float WavelengthStart,
float WavelengthEnd,
int PointCount);
}
@@ -0,0 +1,25 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 光谱仪静态信息(连接时读取一次)。
/// </summary>
/// <param name="Index">设备索引(0 起),调用单帧采集时使用。</param>
/// <param name="SerialNumber">设备序列号。</param>
/// <param name="PixelCount">光谱像素数,即波长与强度数组的长度。</param>
/// <param name="StartPixel">
/// 协议 0x2009 的原始值(手册语义为 FirstOffsetPixel),
/// 不是光谱起始像素,请勿用于切片。
/// </param>
/// <param name="EndPixel">
/// 协议 0x200A 的原始值(手册语义为 NumOffsetPixels),
/// 不是光谱结束像素,请勿用于切片。
/// </param>
/// <param name="FirmwareVersion">固件版本,形如 4.1.7.0。</param>
public sealed record SpectrometerDeviceInfo(
int Index,
string SerialNumber,
int PixelCount,
int StartPixel,
int EndPixel,
string FirmwareVersion);
}
@@ -0,0 +1,13 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 光谱仪运行时状态(每次查询都会走一次 USB 往返)。
/// </summary>
/// <param name="DeviceIndex">设备索引。</param>
/// <param name="State">设备状态名,如 Idle、TakingSpectrum。</param>
/// <param name="AvailableSpectra">设备缓冲中可读的帧数。</param>
public sealed record SpectrometerDeviceStatus(
int DeviceIndex,
string State,
int AvailableSpectra);
}
@@ -0,0 +1,18 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 光谱仪连接状态变化事件参数。
/// </summary>
public class SpectrometerStatusChangedEventArgs : EventArgs
{
public bool IsConnected { get; }
public string Message { get; }
public SpectrometerStatusChangedEventArgs(bool isConnected, string message)
{
IsConnected = isConnected;
Message = message;
}
}
}
@@ -0,0 +1,24 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 单帧同步采集参数。为 null 的字段使用
/// <see cref="ArisSpectrometerOptions"/> 中的默认值。
/// </summary>
public sealed record SpectrumAcquisitionRequest
{
/// <summary>设备索引;为 null 时使用连接时选中的设备。</summary>
public int? DeviceIndex { get; init; }
/// <summary>曝光时间,单位微秒,必须大于 0。</summary>
public int? ExposureUs { get; init; }
/// <summary>平均次数,必须大于等于 1。</summary>
public int? Averaging { get; init; }
/// <summary>触发延迟,单位微秒,必须大于等于 0。</summary>
public int? DelayUs { get; init; }
/// <summary>超时,单位毫秒;小于等于 0 时由 SDK 计算。</summary>
public int? TimeoutMs { get; init; }
}
}
@@ -0,0 +1,5 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>测量过程中 SDK 上报的单台设备错误。</summary>
public sealed record SpectrumDeviceError(string SerialNumber, string Message);
}
@@ -0,0 +1,21 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 一帧同步采集的光谱。数组已从原生内存复制到托管内存,调用方可以安全留存。
/// </summary>
/// <param name="DeviceIndex">实际采集的设备索引。</param>
/// <param name="SerialNumber">设备序列号。</param>
/// <param name="Wavelengths">波长数组,长度等于 <paramref name="Spectrum"/> 的长度。</param>
/// <param name="Spectrum">强度数组。</param>
/// <param name="Info">报文头元数据。</param>
/// <param name="AcquiredAt">采集完成的主机本地时间。</param>
/// <param name="Elapsed">从调用原生采集到返回所耗时间。</param>
public sealed record SpectrumFrame(
int DeviceIndex,
string SerialNumber,
float[] Wavelengths,
float[] Spectrum,
SpectrumFrameInfo Info,
DateTimeOffset AcquiredAt,
TimeSpan Elapsed);
}
@@ -0,0 +1,35 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 光谱帧头元数据(来自设备返回的 64 字节报文头)。
/// </summary>
/// <param name="ExposureTimeUs">实际曝光时间,单位微秒。</param>
/// <param name="Averaging">实际平均次数。</param>
/// <param name="DeviceTime10Us">设备时间戳:当日 0 点起的 0.1ms 计数。</param>
/// <param name="DeviceDateDays">设备日期戳:1970-01-01 起的天数。</param>
/// <param name="PixelCount">本帧像素数。</param>
/// <param name="DataFormat">设备数据格式;当前 SDK 只支持 0。</param>
/// <param name="LoadLevel">负载率,接近 1.0 表示接近饱和。</param>
/// <param name="SensorTemperature">传感器温度,单位摄氏度。</param>
/// <param name="DarkAvg">暗电平平均值。</param>
/// <param name="ReadoutNoise">读出噪声。</param>
/// <param name="AppliedProcessing">已应用的处理标志(原始 16 位)。</param>
/// <param name="ErrorFlags">非 0 表示该帧处理出错(报文头高 4 位)。</param>
/// <param name="IntensityUnit">强度单位(低 4 位)。</param>
/// <param name="DarkSubtracted">是否已扣除暗背景。</param>
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);
}
@@ -0,0 +1,368 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 多台光谱仪的波长拼接。
///
/// 规则:
/// * 任意两台设备的波长区间重合时,以重合区间的中点切分:
/// 低波长设备保留重合区间的下半段,高波长设备保留上半段,
/// 即“重合部分各去一半”;
/// * 三台及以上同时重合时,按两两中点划分区间,再按两两胜出次数决定该区间归属;
/// * 单台设备被其他设备覆盖时,允许该设备贡献多段不连续区间;
/// * 直接使用各设备原始采样点,不做插值;输出按波长升序排列。
/// </summary>
public static class SpectrumMerger
{
private const double Epsilon = 1e-6;
public static MergedSpectrum Merge(IReadOnlyList<SynchronizedSpectrumFrame> frames)
{
ArgumentNullException.ThrowIfNull(frames);
if (frames.Count == 0)
{
return Empty();
}
var normalized = frames
.Select(Normalize)
.Where(frame => frame is not null)
.Cast<NormalizedFrame>()
.OrderBy(frame => frame.Start)
.ThenBy(frame => frame.DeviceIndex)
.ToList();
if (normalized.Count == 0)
{
return Empty();
}
// 所有设备起止点 + 每两台设备重合区间的中点,把波长轴切成若干基本区间。
var boundaries = new List<double>(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<double>(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<float>(normalized.Sum(frame => frame.Wavelengths.Length));
var mergedSpectrum = new List<float>(mergedWavelengths.Capacity);
var owners = new List<int>(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<int>(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<int> covering,
List<NormalizedFrame> 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<NormalizedFrame> 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<MergedSpectrumSegment> BuildSegments(
List<int> owners,
List<float> wavelengths,
List<NormalizedFrame> frames)
{
var segments = new List<MergedSpectrumSegment>();
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<NormalizedFrame> 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<float>(),
Array.Empty<float>(),
Array.Empty<MergedSpectrumSegment>());
private sealed record NormalizedFrame(
int DeviceIndex,
string SerialNumber,
float[] Wavelengths,
float[] Spectrum,
double Start,
double End);
}
}
@@ -0,0 +1,22 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 多台同步采集时,某一台设备返回的一帧光谱。
/// 流式回调不携带报文头,因此这里没有温度/负载率等元数据;
/// 需要这些字段请使用单帧 <c>AcquireFrame</c> 接口。
/// </summary>
/// <param name="DeviceIndex">设备索引(0 起)。</param>
/// <param name="SerialNumber">设备序列号。</param>
/// <param name="Wavelengths">波长数组。</param>
/// <param name="Spectrum">强度数组,与波长等长。</param>
/// <param name="ReceivedAt">回调在本机收到该帧的时间。</param>
public sealed record SynchronizedSpectrumFrame(
int DeviceIndex,
string SerialNumber,
float[] Wavelengths,
float[] Spectrum,
DateTimeOffset ReceivedAt)
{
public int PixelCount => Wavelengths.Length;
}
}
@@ -0,0 +1,27 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 多台光谱仪同步采集参数。一次调用会采集所有已连接设备各一帧。
/// 为 null 的字段使用 <see cref="ArisSpectrometerOptions"/> 中的默认值。
/// </summary>
public sealed record SynchronizedSpectrumRequest
{
/// <summary>
/// 曝光时间,单位微秒,必须大于 0。
/// 为 null 时使用配置中的 <see cref="ArisSpectrometerOptions.SynchronizedExposureUs"/>。
/// </summary>
public int? ExposureUs { get; init; }
/// <summary>平均次数,必须大于等于 1。</summary>
public int? Averaging { get; init; }
/// <summary>触发延迟,单位微秒,必须大于等于 0。</summary>
public int? DelayUs { get; init; }
/// <summary>
/// StartMeasurement 返回后,等待所有设备回调的最长时间(毫秒)。
/// 小于等于 0 时使用配置中的 <see cref="ArisSpectrometerOptions.SynchronizedWaitTimeoutMs"/>。
/// </summary>
public int? WaitTimeoutMs { get; init; }
}
}
@@ -0,0 +1,29 @@
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
/// 多台光谱仪同步采集的结果:每台设备一帧原始光谱,外加按波长拼接后的完整光谱。
/// </summary>
/// <param name="Frames">实际收到的设备帧,按序列号排序。</param>
/// <param name="Merged">拼接后的光谱。</param>
/// <param name="MissingSerials">超时未收到帧的序列号。</param>
/// <param name="Errors">测量过程中 SDK 上报的设备错误。</param>
/// <param name="ExpectedDeviceCount">本次期望采集的设备数。</param>
/// <param name="AcquiredAt">采集完成的主机本地时间。</param>
/// <param name="StartElapsed">StartMeasurement 武装设备所耗时间。</param>
/// <param name="WaitElapsed">等待设备回调所耗时间。</param>
public sealed record SynchronizedSpectrumResult(
IReadOnlyList<SynchronizedSpectrumFrame> Frames,
MergedSpectrum Merged,
IReadOnlyList<string> MissingSerials,
IReadOnlyList<SpectrumDeviceError> Errors,
int ExpectedDeviceCount,
DateTimeOffset AcquiredAt,
TimeSpan StartElapsed,
TimeSpan WaitElapsed)
{
/// <summary>所有设备都返回了帧(允许存在已收到帧的设备的告警)。</summary>
public bool IsComplete => MissingSerials.Count == 0;
public int ReceivedDeviceCount => Frames.Count;
}
}
@@ -0,0 +1,34 @@
using FlashCap;
namespace HardwareControl.Core.UsbCamera
{
/// <summary>
/// 当前采集格式。前端用它选择正确的 data URL MIME,
/// MJPG/PNG 帧可直接显示,YUV 等格式由 FlashCap 转码为 BMP。
/// </summary>
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));
}
}
@@ -0,0 +1,38 @@
namespace HardwareControl.Core.UsbCamera
{
/// <summary>
/// 一帧图像。ImageData 由 <c>CopyImage()</c> 生成,
/// 调用方可以安全地在回调返回后继续持有、排队或异步发送。
/// </summary>
public class FrameArrivedEventArgs : EventArgs
{
public byte[] ImageData { get; }
public long FrameIndex { get; }
public TimeSpan Timestamp { get; }
public DateTimeOffset CapturedAt { get; }
/// <summary>采集格式与 MIME 类型,随帧一起传递。</summary>
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;
}
}
}
@@ -0,0 +1,24 @@
namespace HardwareControl.Core.UsbCamera
{
/// <summary>
/// Usb相机操作类
/// </summary>
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;
}
}
@@ -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;
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.14" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HardwareControl.Core\HardwareControl.Core.csproj" />
</ItemGroup>
</Project>
+59
View File
@@ -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<UsbCameraOptions>(opt =>
{
opt.DeviceNameKeyword = null; // 取第一个相机
opt.PreferredFormatKeyword = "MJPG"; // 找不到就回退第一个
opt.ReconnectBaseDelayMs = 1000;
opt.ReconnectMaxDelayMs = 10_000;
});
services.AddSingleton<IUsbCameraService, UsbCameraService>();
services.AddLogging(b => b.AddConsole());
})
.Build();
var service = host.Services.GetRequiredService<IUsbCameraService>();
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();
@@ -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<IActionResult> 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<IActionResult> 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
});
}
}
}
@@ -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
{
/// <summary>
/// aris 光谱仪 Web 接口。
///
/// 采集方式为同步单帧(SDK 的 AcquireFrame):POST /acquire 会阻塞到一帧采集完成,
/// 通常几十毫秒到数秒(取决于曝光时间),前端应设置足够的请求超时。
/// 所有光谱仪操作在服务层串行执行,并发请求会排队。
/// </summary>
[ApiController]
[Route("api/spectrometer")]
public class SpectrometerController : ControllerBase
{
private readonly IArisSpectrometerService _spectrometer;
private readonly ILogger<SpectrometerController> _logger;
public SpectrometerController(
IArisSpectrometerService spectrometer,
ILogger<SpectrometerController> logger)
{
_spectrometer = spectrometer;
_logger = logger;
}
/// <summary>连接光谱仪并读取设备列表。重复调用是幂等的。</summary>
[HttpPost("connect")]
[ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> Connect(CancellationToken ct)
{
try
{
await _spectrometer.ConnectAsync(ct);
return Ok(SpectrometerStatusPayload.From(_spectrometer));
}
catch (HardwareException ex)
{
return HardwareError(ex);
}
}
/// <summary>断开光谱仪,释放原生上下文。</summary>
[HttpPost("disconnect")]
[ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> Disconnect(CancellationToken ct)
{
try
{
await _spectrometer.DisconnectAsync(ct);
return Ok(SpectrometerStatusPayload.From(_spectrometer));
}
catch (HardwareException ex)
{
return HardwareError(ex);
}
}
/// <summary>读取当前连接状态、设备列表和累计采集帧数,不访问硬件。</summary>
[HttpGet("status")]
[ProducesResponseType(typeof(SpectrometerStatusPayload), StatusCodes.Status200OK)]
public IActionResult GetStatus() =>
Ok(SpectrometerStatusPayload.From(_spectrometer));
/// <summary>读取波长数组,用于单独绘制光谱坐标轴。</summary>
[HttpGet("wavelengths")]
[ProducesResponseType(typeof(WavelengthsPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> 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);
}
}
/// <summary>查询设备运行时状态(一次 USB 往返)。</summary>
[HttpGet("devices/{deviceIndex:int}/status")]
[ProducesResponseType(typeof(SpectrometerDeviceStatusPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> GetDeviceStatus(
int deviceIndex,
CancellationToken ct)
{
try
{
var status = await _spectrometer.GetDeviceStatusAsync(deviceIndex, ct);
return Ok(SpectrometerDeviceStatusPayload.From(status));
}
catch (HardwareException ex)
{
return HardwareError(ex);
}
}
/// <summary>
/// 同步采集一帧光谱。请求体可省略,此时使用 appsettings.json 中的默认参数。
/// </summary>
[HttpPost("acquire")]
[ProducesResponseType(typeof(SpectrumFramePayload), StatusCodes.Status200OK)]
public async Task<IActionResult> 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);
}
}
/// <summary>
/// 多台光谱仪同步采集一帧:一次武装所有已连接设备,收齐后按波长自动拼接。
/// 部分设备超时会返回已收到的数据,IsComplete=false。
/// </summary>
[HttpPost("acquire-synchronized")]
[ProducesResponseType(typeof(SynchronizedSpectrumPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> 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
};
}
}
}
@@ -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<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> 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();
}
}
}
+29
View File
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HardwareControl.Core\HardwareControl.Core.csproj" />
</ItemGroup>
<!--
HardwareControl.Core 通过裸 <Reference> 引用 ArisSharp.dll。
这里再显式引用一次,确保 ArisSharp 出现在 HardwareWeb.deps.json 中;
否则运行时可能报 Could not load file or assembly 'ArisSharp'。
-->
<ItemGroup>
<Reference Include="ArisSharp">
<HintPath>..\HardwareControl.Core\dll\aris\ArisSharp.dll</HintPath>
<Private>true</Private>
</Reference>
</ItemGroup>
</Project>
+74
View File
@@ -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
###
+109
View File
@@ -0,0 +1,109 @@
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareWeb.Models;
using HardwareWeb.Services;
using Microsoft.AspNetCore.SignalR;
namespace HardwareWeb.Hubs
{
/// <summary>
/// 相机实时通道:
/// - 连接后自动加入画面组,并立即收到一次 CameraStatus;
/// - 前端可调用 SubscribeFrames / UnsubscribeFrames 暂停或恢复画面;
/// - GetStatus 用于页面刷新或断线重连后的状态对齐。
/// </summary>
public class CameraHub : Hub
{
public const string FrameGroup = "camera-frames";
private readonly IUsbCameraService _cameraService;
private readonly CameraViewerRegistry _viewers;
private readonly ILogger<CameraHub> _logger;
public CameraHub(
IUsbCameraService cameraService,
CameraViewerRegistry viewers,
ILogger<CameraHub> 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);
}
/// <summary>读取当前相机状态,不改变订阅。</summary>
public CameraStatusPayload GetStatus() =>
CameraStatusPayload.From(_cameraService);
/// <summary>恢复画面推送。连接时默认已订阅,可重复调用。</summary>
public async Task<CameraStatusPayload> SubscribeFrames()
{
await JoinFrameGroupAsync(Context.ConnectionId, Context.ConnectionAborted);
return CameraStatusPayload.From(_cameraService);
}
/// <summary>停止接收画面,但仍可接收 CameraStatus。</summary>
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);
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace HardwareWeb.Models
{
/// <summary>
/// SignalR "CameraFrame" 事件负载。图像以 base64 发送,
/// MimeType 指明 JPEG / PNG / BMP,前端据此生成 data URL。
/// </summary>
public sealed record CameraFramePayload(
long FrameIndex,
TimeSpan Timestamp,
DateTimeOffset CapturedAt,
int Width,
int Height,
string MimeType,
string ImageBase64);
}
+33
View File
@@ -0,0 +1,33 @@
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.UsbCamera;
namespace HardwareWeb.Models
{
/// <summary>
/// SignalR "CameraStatus" 事件负载。
/// 前端只依赖 IsConnected / Message,其余字段用于诊断和扩展。
/// </summary>
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);
}
}
}
@@ -0,0 +1,22 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>
/// 拼接后的完整光谱。直接拼接原始采样点,不做插值;
/// 前端应按 Segments 分段绘制,段与段之间波长不连续时断开连线。
/// </summary>
public sealed record MergedSpectrumPayload(
int PixelCount,
float[] Wavelengths,
float[] Spectrum,
IReadOnlyList<MergedSpectrumSegmentPayload> Segments)
{
public static MergedSpectrumPayload From(MergedSpectrum merged) =>
new(
merged.PixelCount,
merged.Wavelengths,
merged.Spectrum,
merged.Segments.Select(MergedSpectrumSegmentPayload.From).ToArray());
}
}
@@ -0,0 +1,21 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>拼接光谱中的一段及其来源设备。</summary>
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);
}
}
@@ -0,0 +1,26 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>
/// 光谱仪静态设备信息。
/// StartPixel / EndPixel 是协议原始值,不是光谱切片起止像素。
/// </summary>
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);
}
}
@@ -0,0 +1,14 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>光谱仪运行时状态(一次 USB 往返)。</summary>
public sealed record SpectrometerDeviceStatusPayload(
int DeviceIndex,
string State,
int AvailableSpectra)
{
public static SpectrometerDeviceStatusPayload From(SpectrometerDeviceStatus status) =>
new(status.DeviceIndex, status.State, status.AvailableSpectra);
}
}
@@ -0,0 +1,50 @@
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>
/// 光谱仪状态负载。
/// 前端可只依赖 IsConnected / Message,其余字段用于诊断。
/// </summary>
public sealed record SpectrometerStatusPayload(
bool IsConnected,
string Message,
int DeviceCount,
SpectrometerDevicePayload? SelectedDevice,
IReadOnlyList<SpectrometerDevicePayload> 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);
}
}
}
@@ -0,0 +1,11 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>测量过程中 SDK 上报的单台设备错误。</summary>
public sealed record SpectrumDeviceErrorPayload(string SerialNumber, string Message)
{
public static SpectrumDeviceErrorPayload From(SpectrumDeviceError error) =>
new(error.SerialNumber, error.Message);
}
}
@@ -0,0 +1,41 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>
/// 光谱帧头元数据,字段含义见 aris C API 手册的 aris_frame_info。
/// </summary>
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);
}
}
@@ -0,0 +1,30 @@
using HardwareControl.Core.Spectrometer;
namespace HardwareWeb.Models
{
/// <summary>
/// 单帧光谱负载。Wavelengths 与 Spectrum 等长,长度见 PixelCount。
/// 前端通常把 Wavelengths 作为 x 轴、Spectrum 作为 y 轴绘制曲线。
/// </summary>
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));
}
}

Some files were not shown because too many files have changed in this diff Show More