feat: 加入了调试器

docs: 完善了文档
这个提交包含在:
2026-05-23 21:40:58 +08:00
父节点 41813abe48
当前提交 8790fcb5a9
共有 32 个文件被更改,包括 4024 次插入 和 360 次删除

171
.github/copilot-instructions.md vendored 普通文件
查看文件

@ -0,0 +1,171 @@
# PhyExp — Copilot 编码规范
> 提示:这是 Copilot 专用的编码规范。完整项目上下文请同时阅读 `AI_INSTRUCTIONS.md`。
> 前端使用 **yarn**,后端使用 **uv**,严禁使用 npm。
## 项目上下文
这是一个物理实验教学平台,前端 Vue 3 + TypeScript,后端 Python FastAPI。
## TypeScript 规范
### 组件
- 使用 `<script setup lang="ts">` 语法
- Props: `defineProps<{ propName: PropType }>()`
- Emits: `defineEmits<{ eventName: [arg: type] }>()`
- 避免使用 `any`,优先使用具体类型
```typescript
// ✅ 正确
const props = defineProps<{
sheet: GridSheet
cellInspectMode?: boolean
}>()
// ❌ 避免
const props = defineProps({
sheet: Object
})
```
### 类型导入
```typescript
// 实验相关类型统一从 @/types/experiment 导入
import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment'
// Store 从 @/stores/ 导入
import { useExperimentStore } from '@/stores/experiment'
// 工具函数从 @/utils/ 导入
import { renderTextWithLatex } from '@/utils/latex'
import { renderMarkdownWithLatex } from '@/utils/markdown'
```
### 响应式
```typescript
// 简单状态
const isOpen = ref(false)
const value = ref<string | null>(null)
// 计算属性
const displayText = computed(() => value.value ?? '--')
// 注入上下文 (AI评价)
const aiContext = inject(AIEvalContextKey, null)
```
### 模板中渲染 LaTeX
```html
<!-- 内联/块级数学公式 -->
<span v-html="renderTextWithLatex('$\\frac{a}{b}$')" />
<!-- Markdown + LaTeX 混合 -->
<div v-html="renderMarkdownWithLatex('**公式**: $E=mc^2$')" />
```
### 样式
- 使用 `<style scoped>`
- 颜色常量使用 hex 值
- grid 单元格使用 flex 布局居中
## Python 规范
### 模块结构
```python
# 每个 .py 文件第一行
from __future__ import annotations
# 导入顺序: future → 标准库 → 第三方 → 本地
from pathlib import Path
from typing import Optional
from fastapi import HTTPException
from pydantic import BaseModel
from app.schemas.experiment import GridInputCell
```
### 类型注解
```python
# ✅ 现代语法
def find_field(name: str, field_id: str) -> GridInputCell: ...
# ❌ 避免旧语法
def find_field(name: str, field_id: str) -> Optional[GridInputCell]: ...
```
### Pydantic 模型
```python
# 在 app/schemas/ 目录下定义
# 字段名使用 camelCase(与前端 JS 风格一致)
class GridInputCell(BaseModel):
type: Literal["input"] = "input"
fieldId: str
validation: Optional[ValidationConfig] = None
colSpan: Optional[int] = None
```
### FastAPI 路由
```python
# api/ 层只做参数解析,委托给 core/
@router.post("/endpoint")
async def handler(request: RequestModel) -> ResponseModel:
result = some_service.do_work(request.field)
return result
```
### 错误处理
```python
# 使用 HTTPException 返回错误
raise HTTPException(status_code=404, detail="field not found")
```
## 常见任务
### 新增实验配置字段
1. 在 `voice_speed.json` 的 `cells` 数组里添加 `{"type": "input", "fieldId": "new_id", ...}`
2. Store 的 `setConfig()` 会自动注册新字段
3. 不需要修改 TypeScript 类型或 Python 模型
### 新增 computed 计算区
1. 在 JSON cells 中添加 computed cell:
```json
{"type": "computed", "areaId": "new_calc", "expression": "f1 * 2", "variables": ["f1"], "format": "0.00"}
```
2. 如果是中间结果被其他 computed 引用,将其 `areaId` 加入后者的 `variables`
3. 级联计算自动处理
### 新增后端 API 端点
1. 在 `app/api/` 创建新路由文件
2. 业务逻辑写在 `app/core/` 对应模块
3. 在 `app/main.py` 中注册路由
### 新增前端组件
1. Vue SFC 放在 `frontend/src/components/experiment/`(实验相关)或上层目录
2. 需要全局状态时使用 Pinia store
3. 需要 AI 评价上下文时 `inject(AIEvalContextKey)`
## 文件修改检查清单
- [ ] TypeScript 类型和后端 Pydantic 模型是否同步?
- [ ] JSON 配置能否通过 Pydantic 验证?
- [ ] `yarn type-check` 是否通过?
- [ ] `yarn build` 是否通过?
- [ ] LaTeX 是否使用 `renderTextWithLatex` 而非 `v-html` 裸渲染?
- [ ] 验证状态背景色是否正确?
- [ ] 是否误提交了 `dist/`、`.venv/`、密钥?
- [ ] 架构/结构变更是否已同步更新到 `docs/ARCHITECTURE.md` 或对应的端级 `ARCHITECTURE.md`?

122
AGENTS.md 普通文件
查看文件

@ -0,0 +1,122 @@
# AGENTS.md — PhyExp 物理实验教学平台
> 提示:本文档为精简参考,完整上下文请同时阅读 `AI_INSTRUCTIONS.md`。前端使用 **yarn**,后端使用 **uv**,严禁使用 npm。
> 如果你的模型是DeepSeek系列模型,请使用中文思考和输出。
## 项目概览
Vue 3 + FastAPI 的前后端分离实验教学 SPA,学生在线完成预习→测验→实验→总结。
| 端 | 技术 |
|----|------|
| 前端 | Vue 3, TS, Vite, Pinia, KaTeX, mathjs |
| 后端 | FastAPI, Pydantic v2, Uvicorn |
## 验证命令
```
# 前端
cd frontend && yarn type-check && yarn build
# 后端
cd backend && python -c "from app.core.config_loader import config_service; c = config_service.load_validated('voice_speed'); print(len(c.sheets))"
```
## 关键文件
| 文件 | 用途 |
|------|------|
| `frontend/src/types/experiment.ts` | 前端类型定义(与后端 Pydantic 对齐) |
| `backend/app/schemas/experiment.py` | 后端 Pydantic 模型 |
| `backend/config/experiments/voice_speed.json` | 实验网格配置 |
| `frontend/src/stores/experiment.ts` | Pinia Store:字段值、验证、级联计算 |
| `frontend/src/utils/calculation.ts` | LaTeX→mathjs 表达式编译求值 |
| `frontend/src/components/experiment/ExperimentGrid.vue` | Excel 风格网格表格 |
| `frontend/src/components/experiment/ExperimentGridCell.vue` | 单元格 (label/input/computed) |
| `backend/app/core/validation.py` | 字段校验器 |
| `backend/app/core/dependencies.py` | 服务单例 + find_field/list_fields |
## 前后端类型对齐规则
前端 `types/experiment.ts` ←→ 后端 `schemas/experiment.py` 必须字段对应。
后端 Pydantic 使用 camelCase(`fieldId`, `areaId`, `colSpan`),`model_dump(by_alias=True)` 序列化。
**新增字段必须同步两端。**
## 实验配置格式 (grid-based)
JSON 配置在 `backend/config/experiments/`,格式为 `sheets` → `cells[][]` 网格。
单元格类型:
```json
{"type": "label", "content": "$LaTeX$"}
{"type": "input", "fieldId": "唯一ID", "validation": {"type":"number","min":0,"max":100,"required":true}, "unit": "$mm$"}
{"type": "computed","areaId": "唯一ID", "expression": "f1+f2", "variables": ["f1","f2"], "format": "0.00"}
null // 空占位
```
## 数据流
```
JSON配置 → Pydantic验证 → API返回
→ ExperimentForm (provide AIEvalContext)
→ ExperimentGrid[] (每个sheet一个网格)
→ ExperimentGridCell[label|input|computed]
→ store.setFieldValue() → store.validateField() → store.updateAreaCalculations()
```
输入失焦 → `POST /value { field_id, value }` → `{ accept, message }` → 背景色更新。
## 验证状态颜色
`ExperimentGridCell.vue` 的 `bgColor`:
- `#ffffff` 未填 · `#fff3cd` 已填待验证 · `#d4edda` 通过 · `#f8d7da` 失败 · `#e8f0fe` 获焦
## 后端分层
- `api/` — 路由,委托给 `core/`
- `core/` — 纯 Python 业务逻辑
- `schemas/` — Pydantic 模型唯一定义点
- `hardware/` — 示波器驱动(已解耦)
## Store 关键方法
`useExperimentStore`:
- `setConfig(config, url)` — 解析所有 input/computed,初始化数据
- `setFieldValue(id, val)` — 设值,标记未验证,触发重算
- `validateField(id)` — POST 后端,更新验证状态
- `updateAreaCalculations()` — 递归级联计算所有 computed 区
## 表达式计算
`calculation.ts`:
- `calculateExpression(expr, vars)` — 求值入口
- `convertLatexToMathJS(expr)` — `\frac{a}{b}`→`(a)/(b)`、`\sqrt{a}`→`sqrt(a)`
- `formatNumber(val, fmt)` — `"0.00"`→`toFixed(2)`
变量名带下划线(如 `v_standing`)直接传给 mathjs,与 JSON `variables` 数组一致。
## LaTeX 渲染
Vue 模板中使用:
```
v-html="renderTextWithLatex(text)" // 渲染内联/块级 $...$ $$
v-html="renderMarkdownWithLatex(text)" // Markdown + LaTeX 混合
```
## 新增实验步骤
1. `backend/config/experiments/{name}.json` — grids 配置
2. `frontend/src/assets/experiences.json` — 注册实验
3. 验证: `python -c "config_service.load_validated('{name}')"`
## 禁止修改
- `frontend/dist/` `backend/.venv/` — 构建产物/虚拟环境
- 切勿提交密钥、密码、API URL
## 架构变更后必须更新文档
修改路由、组件层级、数据流、API 端点等架构性内容后,必须同步更新 `docs/ARCHITECTURE.md`、`frontend/ARCHITECTURE.md` 或 `backend/ARCHITECTURE.md` 中对应的部分。

180
AI_INSTRUCTIONS.md 普通文件
查看文件

@ -0,0 +1,180 @@
# AI 编程工具说明文档
> 本文档面向 AI 编程 Agent(Claude、Cursor、Copilot、opencode 等),提供项目上下文、约定和变更指引。请在对本项目进行任何修改前阅读本文档。
> 前端使用 **yarn**,后端使用 **uv**,严禁使用 npm。
## 项目简介
PhyExp 是一个物理实验教学 SPA 平台,前后端分离:
- **前端**: Vue 3 + TypeScript + Vite + Pinia + KaTeX + mathjs (`frontend/`)
- **后端**: Python FastAPI + Pydantic v2 + Uvicorn (`backend/`)
- **AI 服务**: 外部 REST/SSE 端点(不在本仓库内)
## 关键文件索引
| 用途 | 路径 |
|------|------|
| 前端架构文档 | `frontend/ARCHITECTURE.md` |
| 后端架构文档 | `backend/ARCHITECTURE.md` |
| 总体架构文档 | `docs/ARCHITECTURE.md` |
| 开发规范 | `docs/DEVELOPMENT.md` |
| 部署指南 | `docs/DEPLOYMENT.md` |
| API 文档 | `docs/API.md` |
| 前端类型定义 | `frontend/src/types/experiment.ts` |
| 后端模型定义 | `backend/app/schemas/experiment.py` |
| 实验配置示例 | `backend/config/experiments/voice_speed.json` |
| 实验数据 Store | `frontend/src/stores/experiment.ts` |
| 表达式计算 | `frontend/src/utils/calculation.ts` |
| LaTeX 渲染 | `frontend/src/utils/latex.ts` |
## 验证命令
```
# 前端类型检查 + 构建
cd frontend && yarn type-check && yarn build
# 后端配置校验
cd backend && python -c "
from app.core.config_loader import config_service
c = config_service.load_validated('voice_speed')
assert len(c.sheets) > 0
print('OK')
"
```
## 架构关键规则
### 1. 前后端类型对齐
前端 `types/experiment.ts` 与后端 `schemas/experiment.py` 中的模型必须保持字段对应。
后端使用 camelCase 的 `fieldId` / `areaId` / `colSpan`(通过 Pydantic 属性名直接定义),
`model_dump(by_alias=True)` 序列化。前端 TypeScript 也使用 camelCase。
**修改规则**: 如需新增字段,必须同时更新两端类型定义。
### 2. 实验配置格式 (grid-based)
实验 JSON 配置文件位于 `backend/config/experiments/` 目录。
当前是网格格式 (`sheets` → `cells[][]`),**不是**旧的 container/children 格式。
单元格类型:
- `label`: `{ type: "label", content: "文本或 $LaTeX$" }`
- `input`: `{ type: "input", fieldId: "唯一ID", validation: {...}, unit?: "$单位$" }`
- `computed`: `{ type: "computed", areaId: "唯一ID", expression: "math表达式", variables: ["依赖的fieldId或areaId"] }`
支持 `null` 作为空占位单元格,`colSpan` / `rowSpan` 实现跨列/跨行。
### 3. 数据流
```
JSON配置 → Pydantic验证 → API返回 → ExperimentGridConfig类型
→ ExperimentForm (provide AIEvalContext)
→ ExperimentGrid[] (每个sheet)
→ ExperimentGridCell[] (label | input | computed)
→ store.setFieldValue() → store.updateAreaCalculations()
```
输入数据流:
1. 用户输入 → `setFieldValue(fieldId, value)` → 标记 `validated=false`
2. 失焦 → `validateField(fieldId)` → `POST /value` → 更新 `validationResult`
3. 验证通过 → `updateAreaCalculations()` → 级联计算所有依赖的 computed 区
### 4. 验证状态颜色
在 `ExperimentGridCell.vue` 的 `bgColor` computed 中定义:
- `#ffffff` (白色) — 未填写
- `#fff3cd` (黄色) — 有值未验证
- `#d4edda` (绿色) — 验证通过
- `#f8d7da` (红色) — 验证失败
- `#e8f0fe` (蓝色) — 获得焦点
### 5. 后端层次分离
- `api/` — 路由层,只做参数解析和响应,委托给 `core/`
- `core/` — 业务逻辑层,纯 Python,不依赖 FastAPI (除了 `HTTPException`)
- `schemas/` — Pydantic 模型唯一定义点
- `hardware/` — 示波器驱动,与实验逻辑解耦
### 6. 状态管理
Pinia store: `useExperimentStore` (`frontend/src/stores/experiment.ts`)
关键方法:
- `setConfig(config, validationUrl)` — 初始化,解析所有 input/computed 区域
- `setFieldValue(fieldId, value)` — 设置值,标记未验证,触发重新计算
- `validateField(fieldId)` — 异步 POST 后端,更新验证状态
- `updateAreaCalculations()` — 递归计算所有 computed 区域(处理依赖链)
- `getAllDependentAreas(sourceId)` — 获取直接/间接依赖某字段的所有计算区
### 7. 表达式计算
`frontend/src/utils/calculation.ts`:
- `calculateExpression(expr, vars)` — LaTeX 表达式 → mathjs 求值
- `convertLatexToMathJS(expr)` — 转换 `\frac{a}{b}` → `(a)/(b)`, `\sqrt{a}` → `sqrt(a)` 等
- `formatNumber(value, format)` — `"0.00"` → `toFixed(2)`, `"0.000"` → `toFixed(3)`
变量命名规则: `v_standing` 按原样传给 mathjs(下划线保留),确保与 JSON 配置中的 `variables` 数组一致。
## 常见变更模式
### 新增实验
1. 在 `backend/config/experiments/` 创建 `{name}.json`
2. 定义 `sheets[]` → `cells[][]` 二维矩阵
3. 在 `backend/app/core/dependencies.py` 的 `_iter_input_cells` 中确认可遍历
4. 在 `frontend/src/assets/experiences.json` 注册实验
5. 验证: `python -c "from app.core.config_loader import config_service; config_service.load_validated('{name}')"`
### 新增字段
1. 在 JSON 配置对应 sheet 的 cells 中添加 `{"type": "input", "fieldId": "new_field", ...}`
2. 如果有依赖此字段的计算区,在 `variables` 中引用其 `fieldId`
3. Store 的 `setConfig()` 会自动初始化它
4. **不需要**修改 TypeScript 类型或后端 schema(已经支持)
### 新增计算表达式
1. 在 JSON 中添加 `{"type": "computed", "areaId": "new_area", "expression": "...", "variables": [...]}`
2. 表达式中引用的变量名必须是 `variables` 数组中列出的 ID
3. 级联依赖自动处理(如果 `new_area` 被其他 computed 引用,会自动级联计算)
### 修改组件
- 实验表单组件: `frontend/src/components/experiment/`
- AI 聊天: `frontend/src/components/AIChatSidebar.vue`
- 页面: `frontend/src/pages/`
- 工具函数: `frontend/src/utils/`(纯函数)或 `frontend/src/composables/`(有 Vue 状态)
## 架构/结构变更后必须更新文档
当对项目架构、路由、组件层级、数据流等进行变更后,**必须同步更新对应文档**:
| 变更类型 | 需更新的文档 |
| -------- | ------------ |
| 前端路由/页面/组件层级 | `frontend/ARCHITECTURE.md` |
| 后端 API/分层/模块 | `backend/ARCHITECTURE.md` |
| 系统级架构/数据流/跨层通信 | `docs/ARCHITECTURE.md` |
| 新增/删除依赖 | 各端 `ARCHITECTURE.md` 技术栈表 |
| 新增实验/配置格式 | `docs/DEVELOPMENT.md`、`AIGENTS.md`、`AGENTS.md` |
## 文件修改时务必注意
1. **不要**修改 `frontend/dist/`(构建产物)
2. **不要**修改 `backend/.venv/`(虚拟环境)
3. **不要**提交密钥、API URL、密码
4. 修改后端 `models.py` 时,实际定义在 `schemas/experiment.py` 和 `schemas/validation.py`
5. 修改 JSON 配置后,必须通过 Pydantic 验证(运行上述 python 命令)
6. 修改 TypeScript 类型后,运行 `yarn type-check` 确认无错误
7. LaTeX 渲染在 Vue 模板中使用: `v-html="renderTextWithLatex(text)"` 或 `v-html="renderMarkdownWithLatex(text)"`
8. 组件中 inject AI 上下文: `const aiContext = inject(AIEvalContextKey, null)`
## 文件命名约定
| 层级 | 约定 | 示例 |
|------|------|------|
| Vue 组件 | PascalCase `.vue` | `ExperimentGrid.vue` |
| TypeScript 模块 | camelCase `.ts` | `calculation.ts`, `experiment.ts` |
| Python 模块 | snake_case `.py` | `config_loader.py`, `reading_guard.py` |
| JSON 配置 | snake_case `.json` | `voice_speed.json` |
| Markdown 文档 | UPPER_SNAKE `.md` | `ARCHITECTURE.md`, `DEVELOPMENT.md` |

查看文件

@ -19,23 +19,28 @@ backend/
│ └── _voice_speed.json # 旧版备份 │ └── _voice_speed.json # 旧版备份
├── app/ ├── app/
│ ├── __init__.py │ ├── __init__.py
│ ├── main.py # FastAPI 应用入口, CORS, 路由注册 │ ├── main.py # FastAPI 应用入口, CORS, 启动示波器探针, 路由注册
│ ├── models.py # 兼容性重导出 (实际定义在 schemas/) │ ├── models.py # 兼容性重导出 (实际定义在 schemas/)
│ ├── schemas/ # Pydantic 数据模型 │ ├── schemas/ # Pydantic 数据模型
│ │ ├── __init__.py # 统一导出 │ │ ├── __init__.py # 统一导出
│ │ ├── experiment.py # 网格实验配置模型 (GridSheet, GridCell...) │ │ ├── experiment.py # 网格实验配置模型 (GridSheet, GridCell...)
│ │ └── validation.py # 验证请求/响应、测量分析模型 │ │ └── validation.py # 验证请求/响应、测量分析、峰值监控模型
│ ├── api/ # REST API 路由层 │ ├── api/ # REST API 路由层
│ │ ├── __init__.py │ │ ├── __init__.py
│ │ ├── form.py # GET /form, /form/list — 加载实验配置 │ │ ├── form.py # GET /form — 加载实验配置
│ │ ├── value.py # POST/GET/DELETE /value — 字段值 CRUD + 验证 │ │ ├── value.py # POST/GET/DELETE /value — 字段值 CRUD + 验证
│ │ ├── device.py # GET /device/status, POST /device/peak — 示波器控制 │ │ ├── device.py # GET /device/status, POST /device/peak — 示波器控制
│ │ └── measurement.py # POST /measurement/{method} — 测量数据分析 │ │ ├── debug.py # 调试模式接口 (探针状态、示波器连接监控)
│ │ ├── measurement.py # POST /measurement/{method} — 测量数据分析
│ │ └── peak_monitor.py # 峰值检测监控 (start/stop/status/acknowledge)
│ ├── core/ # 业务逻辑层 │ ├── core/ # 业务逻辑层
│ │ ├── __init__.py │ │ ├── __init__.py
│ │ ├── config_loader.py # ExperimentConfigService — 加载/验证 JSON 配置 │ │ ├── config_loader.py # ExperimentConfigService — 加载/验证 JSON 配置
│ │ ├── dependencies.py # 服务单例 + 字段查找辅助函数 │ │ ├── dependencies.py # 服务单例 + 字段查找辅助函数
│ │ ├── experiment_debug.py # ExperimentDebugProvider 抽象基类 + VoiceSpeedDebugProvider
│ │ ├── measurement.py # MeasurementService — 声速实验统计算法 │ │ ├── measurement.py # MeasurementService — 声速实验统计算法
│ │ ├── ocr_service.py # CaliperOCRService — 游标卡尺 OCR 识别 (模拟)
│ │ ├── peak_detector.py # PeakDetector — 峰值检测状态机 (RISING/PEAK/COOLDOWN)
│ │ ├── reading_guard.py # ReadingGuardManager — 读数顺序守卫 + 容差校验 │ │ ├── reading_guard.py # ReadingGuardManager — 读数顺序守卫 + 容差校验
│ │ ├── session_store.py # SessionStore — 线程安全内存 KV 存储 │ │ ├── session_store.py # SessionStore — 线程安全内存 KV 存储
│ │ └── validation.py # FieldValidator — 基础字段校验 (数字/正则/必填) │ │ └── validation.py # FieldValidator — 基础字段校验 (数字/正则/必填)
@ -61,7 +66,7 @@ backend/
| 方法 | 路径 | 说明 | | 方法 | 路径 | 说明 |
| ------ | ----------------------------------- | ------------------------ | | ------ | ----------------------------------- | ------------------------ |
| GET | `/` | 服务信息 + 端点列表 | | GET | `/` | 服务信息 + 端点列表 |
| GET | `/health` | 健康检查 | | GET | `/health` | 健康检查 (含示波器状态) |
| GET | `/form?experiment=voice_speed` | 加载实验网格配置 | | GET | `/form?experiment=voice_speed` | 加载实验网格配置 |
| GET | `/form/list` | 列出可用实验 | | GET | `/form/list` | 列出可用实验 |
| GET | `/form/{experiment_name}` | 按名称加载实验配置 | | GET | `/form/{experiment_name}` | 按名称加载实验配置 |
@ -73,6 +78,13 @@ backend/
| GET | `/device/status` | 探针示波器状态 | | GET | `/device/status` | 探针示波器状态 |
| POST | `/device/peak` | 捕获峰值 | | POST | `/device/peak` | 捕获峰值 |
| POST | `/device/manual-answer` | 设置读数守卫手动答案 | | POST | `/device/manual-answer` | 设置读数守卫手动答案 |
| GET | `/debug/status` | 实验调试状态 |
| POST | `/debug/probe` | 重新探针硬件 |
| GET | `/debug/oscilloscope` | 示波器调试信息 |
| POST | `/peak-monitor/start` | 启动峰值监控 |
| POST | `/peak-monitor/stop` | 停止峰值监控 |
| GET | `/peak-monitor/status` | 当前峰值监控状态 |
| POST | `/peak-monitor/acknowledge` | 确认峰值 (提交OCR读数) |
| POST | `/measurement/{method}` | 分析测量数据 (声速计算) | | POST | `/measurement/{method}` | 分析测量数据 (声速计算) |
## 核心架构 ## 核心架构
@ -117,7 +129,37 @@ POST /value { field_id, value }
- `OscilloscopeService` 提供三层设备状态:`ONLINE | OFFLINE | SIMULATED` - `OscilloscopeService` 提供三层设备状态:`ONLINE | OFFLINE | SIMULATED`
- 连接真实示波器失败时自动回退到模拟模式 - 连接真实示波器失败时自动回退到模拟模式
- `ReadingGuardManager` 可通过 `source: "device_peak"` 自动从示波器采集参考值 - `ReadingGuardManager` 可通过 `source: "device_peak"` 或 `"peak_ocr"` 自动从示波器采集参考值
- 应用启动时自动探针示波器,输出连接状态至日志
### 调试模式 (Debug Mode)
通用实验特定调试模式接口:
- `ExperimentDebugProvider` 抽象基类定义 `status()`, `capabilities()`, `probe()` 方法
- `DebugProviderRegistry` 管理所有实验的调试提供者
- `VoiceSpeedDebugProvider` 封装示波器探针/峰值/频率监控功能
- 通过 `/debug/*` 端点暴露给前端调试模式
### 峰值检测工作流程 (Peak Detection)
声速测量实验中,驻波法距离 (s_l0~s_l9) 字段配置 `readingGuard.source = "peak_ocr"`,工作流程如下:
```
学生转动旋钮 → 示波器 CH2 峰值起伏
→ PeakDetector 后台线程持续轮询 (0.3s 间隔)
→ RISING 状态跟踪 → 峰值越过最高点后下降 5% → PEAK_TRIGGERED
→ CaliperOCRService 捕获游标卡尺读数 (OCR)
→ 前端通知学生:"峰值已检测到,请读取游标卡尺并填入表格"
→ 学生填入读数 → POST /value → ReadingGuardManager 比对 OCR 值
→ 验证通过 → 确认峰值 → COOLDOWN 状态 (等待下降后重新上升)
→ 下一轮峰值 ...
```
峰值检测状态机 (`PeakDetector`):
- **IDLE** → 初始化/未启动
- **RISING** → 跟踪上升趋势,记录最大值
- **PEAK_TRIGGERED** → 检测到下降超过阈值,等待学生确认
- **COOLDOWN** → 已确认,等待值充分下降后再上升以开始下一轮
## 实验配置格式 ## 实验配置格式
@ -137,7 +179,6 @@ POST /value { field_id, value }
[ [
{"type": "label", "content": "$f/kHz$"}, {"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "validation": {"type": "number", "min": 30, "max": 45, "required": true}}, {"type": "input", "fieldId": "f1", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", ...},
... ...
], ],
[ [
@ -156,6 +197,24 @@ POST /value { field_id, value }
| `input` | 学生数据输入 | `fieldId`, `validation`, `readingGuard` | | `input` | 学生数据输入 | `fieldId`, `validation`, `readingGuard` |
| `computed` | 自动计算结果 | `areaId`, `expression`, `variables`, `format` | | `computed` | 自动计算结果 | `areaId`, `expression`, `variables`, `format` |
### ReadingGuard 配置
```json
{
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
}
}
```
| 字段 | 说明 |
| --------- | ----------------------------------------------------------------- |
| `enabled` | 是否启用读数守卫 |
| `source` | 参考值来源: `manual` / `device_peak` / `device_frequency` / `peak_ocr` |
| `tolerance` | 允许误差范围 |
## 声速实验计算 ## 声速实验计算
`MeasurementService` 支持三种测量方法的统计算法: `MeasurementService` 支持三种测量方法的统计算法:

123
backend/app/api/debug.py 普通文件
查看文件

@ -0,0 +1,123 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from app.core.experiment_debug import VoiceSpeedDebugProvider, debug_registry
from app.schemas.validation import DebugMenuItem, DebugMenuResponse
router = APIRouter(prefix="/debug", tags=["debug"])
def _oscilloscope_menu_items() -> list[DebugMenuItem]:
return [
DebugMenuItem(
label="示波器状态",
action="oscilloscope_status",
method="GET",
endpoint="/debug/oscilloscope?action=status",
description="查看示波器连接状态、设备ID、当前峰值和频率",
),
DebugMenuItem(
label="读取CH2峰值",
action="oscilloscope_peak",
method="GET",
endpoint="/debug/oscilloscope?action=peak",
description="捕获示波器 CH2 通道的当前峰值",
),
DebugMenuItem(
label="读取CH1频率",
action="oscilloscope_frequency",
method="GET",
endpoint="/debug/oscilloscope?action=frequency",
description="捕获示波器 CH1 通道的信号频率",
),
]
def _peak_monitor_menu_items() -> list[DebugMenuItem]:
return [
DebugMenuItem(
label="峰值监控 - 启动",
action="peak_monitor_start",
method="POST",
endpoint="/peak-monitor/start",
description="启动驻波法峰值检测监控线程",
),
DebugMenuItem(
label="峰值监控 - 状态",
action="peak_monitor_status",
method="GET",
endpoint="/peak-monitor/status",
description="查询当前峰值监控的状态和OCR读数",
),
DebugMenuItem(
label="峰值监控 - 停止",
action="peak_monitor_stop",
method="POST",
endpoint="/peak-monitor/stop",
description="停止峰值监控线程",
),
]
@router.get("/menu")
async def debug_menu(experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed")):
provider = debug_registry.get(experiment)
if provider is None:
raise HTTPException(status_code=404, detail=f"no debug provider for experiment '{experiment}'")
items: list[DebugMenuItem] = []
capabilities = provider.capabilities()
if "oscilloscope_status" in capabilities:
items.extend(_oscilloscope_menu_items())
if "peak_monitor" in capabilities:
items.extend(_peak_monitor_menu_items())
return DebugMenuResponse(
experiment=experiment,
title=f"{experiment} 实验调试工具",
description=f"{experiment} 实验特有的调试功能列表",
items=items,
)
@router.get("/status")
async def debug_status(experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed")):
provider = debug_registry.get(experiment)
if provider is None:
raise HTTPException(status_code=404, detail=f"no debug provider for experiment '{experiment}'")
status = provider.status()
return {
"experiment": experiment,
"capabilities": provider.capabilities(),
**status,
}
@router.post("/probe")
async def debug_probe(experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed")):
provider = debug_registry.get(experiment)
if provider is None:
raise HTTPException(status_code=404, detail=f"no debug provider for experiment '{experiment}'")
result = provider.probe()
return {"experiment": experiment, **result}
@router.get("/oscilloscope")
async def debug_oscilloscope(action: str = Query(default="status")):
provider = debug_registry.get("cn.edu.muc.lxy.phyexp.voicespeed")
if provider is None:
raise HTTPException(status_code=404, detail="no debug provider for cn.edu.muc.lxy.phyexp.voicespeed")
if not isinstance(provider, VoiceSpeedDebugProvider):
raise HTTPException(status_code=400, detail="oscilloscope debug only available for cn.edu.muc.lxy.phyexp.voicespeed")
if action == "status":
return provider.status()
elif action == "peak":
return provider.capture_peak()
elif action == "frequency":
return provider.capture_frequency()
else:
raise HTTPException(status_code=400, detail=f"unknown action '{action}', use: status, peak, frequency")

查看文件

@ -9,7 +9,7 @@ router = APIRouter(prefix="/form", tags=["form"])
@router.get("") @router.get("")
async def get_experiment_form(experiment: str = "voice_speed"): async def get_experiment_form(experiment: str = "cn.edu.muc.lxy.phyexp.voicespeed"):
config = config_service.load_validated(experiment) config = config_service.load_validated(experiment)
return config.model_dump(by_alias=True) return config.model_dump(by_alias=True)

查看文件

@ -0,0 +1,168 @@
from __future__ import annotations
import logging
import threading
import time
from typing import Optional
from fastapi import APIRouter, Header, HTTPException
from app.core.dependencies import resolve_session_id
from app.core.ocr_service import caliper_ocr_service
from app.core.peak_detector import PeakDetector, PeakState
from app.core.reading_guard import reading_guard_manager
from app.hardware.service import oscilloscope_service
from app.schemas.validation import PeakMonitorResponse, PeakMonitorStartRequest
_logger = logging.getLogger("peak_monitor")
router = APIRouter(prefix="/peak-monitor", tags=["peak_monitor"])
POLL_INTERVAL: float = 0.3
_active_monitors: dict[str, "_PeakMonitor"] = {}
_lock = threading.Lock()
class _PeakMonitor:
def __init__(
self,
session_id: str,
detector: PeakDetector,
) -> None:
self.session_id = session_id
self.detector = detector
self._running = False
self._thread: Optional[threading.Thread] = None
def start(self) -> None:
self._running = True
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
def stop(self) -> None:
self._running = False
if self._thread is not None:
self._thread.join(timeout=2.0)
self._thread = None
def _poll_loop(self) -> None:
_logger.info("峰值监控线程启动 session=%s", self.session_id)
while self._running:
try:
peak_value = _fetch_peak()
if peak_value is not None:
result = self.detector.feed(peak_value)
if result.state == PeakState.PEAK_TRIGGERED and result.ocr_reading is None:
ocr_result = caliper_ocr_service.capture()
if ocr_result.success and ocr_result.reading_mm is not None:
self.detector.set_ocr_reading(ocr_result.reading_mm)
_logger.info("峰值 %d 已检测 OCR读数=%.2f mm session=%s",
result.peak_index, ocr_result.reading_mm, self.session_id)
except Exception as exc:
_logger.warning("峰值轮询异常: %s", exc)
time.sleep(POLL_INTERVAL)
_logger.info("峰值监控线程停止 session=%s", self.session_id)
def _fetch_peak() -> Optional[float]:
snapshot = oscilloscope_service.capture_peak()
if snapshot.peak_value is None:
return None
return float(snapshot.peak_value)
def _get_monitor(session_id: str) -> Optional["_PeakMonitor"]:
return _active_monitors.get(session_id)
@router.get("/status")
async def peak_monitor_status(
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
monitor = _get_monitor(session_id)
if monitor is None:
return PeakMonitorResponse(running=False)
detector = monitor.detector
current_peak = _fetch_peak()
with detector._lock:
result = detector._snapshot(current_peak)
return PeakMonitorResponse(
running=monitor._running,
state=result.state,
current_peak=result.current_peak,
peak_max=result.peak_max,
ocr_reading=result.ocr_reading,
pending_field=result.pending_field,
peak_index=result.peak_index,
trend=result.trend,
)
@router.post("/start")
async def peak_monitor_start(
request: PeakMonitorStartRequest,
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
with _lock:
existing = _active_monitors.pop(session_id, None)
if existing is not None:
existing.stop()
detector = PeakDetector(
drop_ratio=request.drop_ratio,
cooldown_ratio=request.cooldown_ratio,
)
caliper_ocr_service.reset()
monitor = _PeakMonitor(session_id, detector)
_active_monitors[session_id] = monitor
monitor.start()
_logger.info("峰值监控已启动 session=%s experiment=%s", session_id, request.experiment)
return {
"success": True,
"message": "峰值监控已启动,请转动旋钮寻找峰值",
"session_id": session_id,
}
@router.post("/stop")
async def peak_monitor_stop(
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
with _lock:
monitor = _active_monitors.pop(session_id, None)
if monitor is not None:
monitor.stop()
monitor.detector.reset()
caliper_ocr_service.reset()
return {"success": True, "message": "峰值监控已停止", "session_id": session_id}
@router.post("/acknowledge")
async def peak_monitor_acknowledge(
field_id: str,
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
monitor = _get_monitor(session_id)
if monitor is None:
raise HTTPException(status_code=400, detail="峰值监控未启动")
detector = monitor.detector
result = detector.acknowledge_peak()
if result.ocr_reading is not None:
reading_guard_manager.submit_peak_ocr_answer(
session_id, field_id, result.ocr_reading
)
_logger.info("峰值已确认 field=%s ocr=%.2f session=%s", field_id, result.ocr_reading, session_id)
return {
"success": True,
"message": f"峰值 {result.peak_index} 已确认,OCR 读数已记录",
"peak_index": result.peak_index,
"state": result.state,
}

查看文件

@ -13,7 +13,7 @@ router = APIRouter(prefix="/value", tags=["value"])
@router.post("") @router.post("")
async def validate_field_value( async def validate_field_value(
request: FieldValidationRequest, request: FieldValidationRequest,
experiment: str = Query(default="voice_speed"), experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed"),
x_session_id: str | None = Header(default=None), x_session_id: str | None = Header(default=None),
) -> FieldValidationResponse: ) -> FieldValidationResponse:
session_id = resolve_session_id(x_session_id) session_id = resolve_session_id(x_session_id)

查看文件

@ -16,7 +16,7 @@ class ExperimentConfigService:
def _config_path(self, experiment_name: str) -> Path: def _config_path(self, experiment_name: str) -> Path:
return self.config_root / f"{experiment_name}.json" return self.config_root / f"{experiment_name}.json"
def load_raw(self, experiment_name: str = "voice_speed") -> Dict[str, Any]: def load_raw(self, experiment_name: str = "cn.edu.muc.lxy.phyexp.voicespeed") -> Dict[str, Any]:
path = self._config_path(experiment_name) path = self._config_path(experiment_name)
if not path.exists(): if not path.exists():
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found") raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
@ -25,7 +25,7 @@ class ExperimentConfigService:
except json.JSONDecodeError as exc: except json.JSONDecodeError as exc:
raise HTTPException(status_code=500, detail=f"experiment config format error: {exc}") from exc raise HTTPException(status_code=500, detail=f"experiment config format error: {exc}") from exc
def load_validated(self, experiment_name: str = "voice_speed") -> ExperimentGridConfig: def load_validated(self, experiment_name: str = "cn.edu.muc.lxy.phyexp.voicespeed") -> ExperimentGridConfig:
payload = self.load_raw(experiment_name) payload = self.load_raw(experiment_name)
try: try:
return ExperimentGridConfig(**payload) return ExperimentGridConfig(**payload)

查看文件

@ -0,0 +1,82 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from app.hardware.service import HardwareSnapshot, oscilloscope_service
class ExperimentDebugProvider(ABC):
@abstractmethod
def experiment_name(self) -> str:
...
@abstractmethod
def capabilities(self) -> List[str]:
...
@abstractmethod
def status(self) -> Dict[str, Any]:
...
def probe(self) -> Dict[str, Any]:
return {"error": "not supported"}
class VoiceSpeedDebugProvider(ExperimentDebugProvider):
def experiment_name(self) -> str:
return "cn.edu.muc.lxy.phyexp.voicespeed"
def capabilities(self) -> List[str]:
return [
"oscilloscope_status",
"oscilloscope_probe",
"oscilloscope_peak",
"oscilloscope_frequency",
"peak_monitor",
]
def status(self) -> Dict[str, Any]:
snapshot: HardwareSnapshot = oscilloscope_service.probe()
return {
"oscilloscope": {
"status": snapshot.status,
"device_idn": snapshot.device_idn,
"peak_value": snapshot.peak_value,
"frequency_hz": snapshot.frequency_hz,
"note": snapshot.note,
},
"peak_monitor_available": True,
}
def probe(self) -> Dict[str, Any]:
return self.status()
def capture_peak(self) -> Dict[str, Any]:
snapshot = oscilloscope_service.capture_peak()
return {"status": snapshot.status, "peak_value": snapshot.peak_value, "note": snapshot.note}
def capture_frequency(self) -> Dict[str, Any]:
snapshot = oscilloscope_service.capture_frequency()
return {"status": snapshot.status, "frequency_hz": snapshot.frequency_hz, "note": snapshot.note}
class DebugProviderRegistry:
def __init__(self) -> None:
self._providers: Dict[str, ExperimentDebugProvider] = {}
def register(self, provider: ExperimentDebugProvider) -> None:
self._providers[provider.experiment_name()] = provider
def get(self, experiment_name: str) -> Optional[ExperimentDebugProvider]:
return self._providers.get(experiment_name)
def list_experiments(self) -> List[str]:
return list(self._providers.keys())
def all_status(self) -> Dict[str, Dict[str, Any]]:
return {name: p.status() for name, p in self._providers.items()}
debug_registry = DebugProviderRegistry()
debug_registry.register(VoiceSpeedDebugProvider())

查看文件

@ -0,0 +1,43 @@
from __future__ import annotations
import random
from dataclasses import dataclass
from typing import Optional
@dataclass
class OCRResult:
success: bool
reading_mm: Optional[float] = None
confidence: float = 0.0
note: str = ""
class CaliperOCRService:
def __init__(self) -> None:
self._base_distances: list[float] = [
144.02, 148.80, 153.50, 158.30, 163.00,
167.80, 172.66, 177.30, 182.29, 186.84,
]
self._index: int = 0
def reset(self) -> None:
self._index = 0
def capture(self) -> OCRResult:
if self._index >= len(self._base_distances):
return OCRResult(success=False, note="所有预设读数已用完,请手动输入")
base = self._base_distances[self._index]
noise = round(random.uniform(-0.02, 0.02), 2)
reading = base + noise
self._index += 1
return OCRResult(
success=True,
reading_mm=reading,
confidence=round(random.uniform(0.85, 0.99), 3),
note=f"游标卡尺 OCR 识别: {reading:.2f} mm (置信度 {random.uniform(0.85, 0.99):.3f})",
)
caliper_ocr_service = CaliperOCRService()

查看文件

@ -0,0 +1,124 @@
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
from enum import Enum
from threading import Lock
from typing import Deque, Optional
class PeakState(str, Enum):
IDLE = "idle"
RISING = "rising"
PEAK_TRIGGERED = "peak_triggered"
COOLDOWN = "cooldown"
@dataclass
class PeakDetectionResult:
state: PeakState
current_peak: Optional[float] = None
peak_max: Optional[float] = None
ocr_reading: Optional[float] = None
pending_field: Optional[str] = None
peak_index: int = 0
trend: str = "flat"
class PeakDetector:
def __init__(
self,
drop_ratio: float = 0.05,
cooldown_ratio: float = 0.30,
window_size: int = 5,
) -> None:
self.drop_ratio = drop_ratio
self.cooldown_ratio = cooldown_ratio
self.window_size = max(window_size, 3)
self._lock = Lock()
self._state = PeakState.IDLE
self._peak_max: float = 0.0
self._value_buffer: Deque[float] = deque(maxlen=self.window_size)
self._ocr_reading: Optional[float] = None
self._pending_field: Optional[str] = None
self._peak_index: int = 0
def reset(self) -> None:
with self._lock:
self._state = PeakState.IDLE
self._peak_max = 0.0
self._value_buffer.clear()
self._ocr_reading = None
self._pending_field = None
self._peak_index = 0
def set_pending_field(self, field_id: Optional[str]) -> None:
with self._lock:
self._pending_field = field_id
def set_ocr_reading(self, value: float) -> None:
with self._lock:
self._ocr_reading = value
def feed(self, peak_value: float) -> PeakDetectionResult:
with self._lock:
self._value_buffer.append(peak_value)
if self._state == PeakState.IDLE:
if len(self._value_buffer) >= self.window_size:
self._state = PeakState.RISING
self._peak_max = max(self._value_buffer)
return self._snapshot(peak_value)
if self._state == PeakState.RISING:
if peak_value > self._peak_max:
self._peak_max = peak_value
elif peak_value < self._peak_max * (1.0 - self.drop_ratio):
self._state = PeakState.PEAK_TRIGGERED
self._peak_index += 1
return self._snapshot(peak_value)
return self._snapshot(peak_value)
if self._state == PeakState.PEAK_TRIGGERED:
return self._snapshot(peak_value)
if self._state == PeakState.COOLDOWN:
valley = self._peak_max * (1.0 - self.cooldown_ratio)
if peak_value > valley * (1.0 + self.drop_ratio * 2):
self._state = PeakState.RISING
self._peak_max = max(self._value_buffer)
return self._snapshot(peak_value)
return self._snapshot(peak_value)
def acknowledge_peak(self) -> PeakDetectionResult:
with self._lock:
if self._state == PeakState.PEAK_TRIGGERED:
self._state = PeakState.COOLDOWN
self._ocr_reading = None
self._pending_field = None
return self._snapshot(self._peak_max if self._value_buffer else None)
@property
def state(self) -> PeakState:
with self._lock:
return self._state
def _snapshot(self, current_peak: Optional[float]) -> PeakDetectionResult:
trend = "flat"
if len(self._value_buffer) >= 2:
buf = list(self._value_buffer)
if buf[-1] > buf[-2]:
trend = "rising"
elif buf[-1] < buf[-2]:
trend = "falling"
return PeakDetectionResult(
state=self._state,
current_peak=current_peak,
peak_max=self._peak_max if self._state != PeakState.IDLE else None,
ocr_reading=self._ocr_reading,
pending_field=self._pending_field,
peak_index=self._peak_index,
trend=trend,
)

查看文件

@ -17,6 +17,7 @@ class GuardSessionState:
tolerance: float = 0.0 tolerance: float = 0.0
source: ReadingGuardSource = ReadingGuardSource.MANUAL source: ReadingGuardSource = ReadingGuardSource.MANUAL
manual_answers: Dict[str, Any] = field(default_factory=dict) manual_answers: Dict[str, Any] = field(default_factory=dict)
peak_ocr_answers: Dict[str, float] = field(default_factory=dict)
class ReadingGuardManager: class ReadingGuardManager:
@ -29,6 +30,11 @@ class ReadingGuardManager:
state = self._sessions.setdefault(session_id, GuardSessionState()) state = self._sessions.setdefault(session_id, GuardSessionState())
state.manual_answers[field_id] = value state.manual_answers[field_id] = value
def submit_peak_ocr_answer(self, session_id: str, field_id: str, value: float) -> None:
with self._lock:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.peak_ocr_answers[field_id] = value
def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]: def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]:
if source == ReadingGuardSource.DEVICE_PEAK: if source == ReadingGuardSource.DEVICE_PEAK:
snapshot = oscilloscope_service.capture_peak() snapshot = oscilloscope_service.capture_peak()
@ -48,6 +54,12 @@ class ReadingGuardManager:
return None return None
return float(value) return float(value)
if source == ReadingGuardSource.PEAK_OCR:
value = state.peak_ocr_answers.get(field_id)
if value is None:
return None
return float(value)
return None return None
def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState: def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState:
@ -64,6 +76,7 @@ class ReadingGuardManager:
field0 = next(f for f in fields if f.fieldId == strict_fields[0]) field0 = next(f for f in fields if f.fieldId == strict_fields[0])
state.tolerance = field0.readingGuard.tolerance if field0.readingGuard else 0.0 state.tolerance = field0.readingGuard.tolerance if field0.readingGuard else 0.0
state.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL state.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
if state.source != ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, state.pending_field, state) state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
return state return state
@ -78,6 +91,7 @@ class ReadingGuardManager:
state.pending_field = next_field state.pending_field = next_field
state.tolerance = config.tolerance if config else 0.0 state.tolerance = config.tolerance if config else 0.0
state.source = config.source if config else ReadingGuardSource.MANUAL state.source = config.source if config else ReadingGuardSource.MANUAL
if state.source != ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, next_field, state) state.pending_answer = self._capture_answer(state.source, next_field, state)
def validate( def validate(
@ -100,8 +114,12 @@ class ReadingGuardManager:
if current_field.fieldId != state.pending_field: if current_field.fieldId != state.pending_field:
return False, f"should submit field {state.pending_field}, please follow experiment reading order" return False, f"should submit field {state.pending_field}, please follow experiment reading order"
if state.source == ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, current_field.fieldId, state)
if state.pending_answer is None: if state.pending_answer is None:
return False, "standard reading not yet captured, please retry" source_label = "OCR" if state.source == ReadingGuardSource.PEAK_OCR else "standard reading"
return False, f"{source_label} not yet captured, please wait for peak detection or retry"
try: try:
student_value = float(current_value) student_value = float(current_value)
@ -112,7 +130,7 @@ class ReadingGuardManager:
if error > state.tolerance: if error > state.tolerance:
return ( return (
False, False,
f"reading mismatch, expected {state.pending_answer:.6g}, tolerance ±{state.tolerance:.6g}, please re-enter", f"reading mismatch, reference {state.pending_answer:.2f}, tolerance ±{state.tolerance:.2f}, please re-enter",
) )
state.cursor += 1 state.cursor += 1

查看文件

@ -1,14 +1,3 @@
from app.hardware.service import HardwareSnapshot, HardwareStatus, OscilloscopeService, oscilloscope_service
from app.hardware.oscilloscope import Oscilloscope from app.hardware.oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev, work
__all__ = [ __all__ = ["Oscilloscope"]
"HardwareSnapshot",
"HardwareStatus",
"OscilloscopeService",
"oscilloscope_service",
"Oscilloscope",
"Commands",
"ExecuteCmdInDev",
"work",
]

查看文件

@ -68,15 +68,17 @@ class Oscilloscope:
raise RuntimeError("未找到批量输入/输出端点") raise RuntimeError("未找到批量输入/输出端点")
def disconnect(self) -> None: def disconnect(self) -> None:
"""断开设备并重新附加内核驱动(如果之前分离过)"""
if self.device is None: if self.device is None:
return return
# 重新附加内核驱动
for intf_num in self._attached_drivers: for intf_num in self._attached_drivers:
try: try:
self.device.attach_kernel_driver(intf_num) self.device.attach_kernel_driver(intf_num)
except usb.core.USBError: except usb.core.USBError:
pass # 忽略重新附加失败 pass
try:
usb.util.dispose_resources(self.device)
except Exception:
pass
self.device = None self.device = None
self.ep_out = None self.ep_out = None
self.ep_in = None self.ep_in = None
@ -155,3 +157,23 @@ class Oscilloscope:
def __exit__(self, exc_type, exc_val, exc_tb): def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect() self.disconnect()
if __name__ == "__main__":
# 简单测试示例
osc = Oscilloscope()
try:
osc.connect()
response = osc.send_command(":MEASUrement:CH2:MAX?")
if response:
print("设备ID:", response.decode('ascii').strip())
else:
print("未收到响应")
response = osc.send_command(":MEASUrement:CH2:VTOP?")
if response:
print("设备ID:", response.decode('ascii').strip())
else:
print("未收到响应")
finally:
osc.disconnect()

查看文件

@ -1,47 +1,62 @@
from __future__ import annotations from __future__ import annotations
import re
from enum import Enum from enum import Enum
from multiprocessing.connection import Connection from multiprocessing.connection import Connection
from typing import Optional from typing import Optional, Union
from .oscilloscope import Oscilloscope
from app.hardware.oscilloscope import Oscilloscope
class Status(Enum): class Status(Enum):
IDLE = 0 IDLE = 0
Waiting = 1 Waiting = 1
# 规范
# CH1 接原始信号
# CH2 接返回信号
class Commands(Enum): class Commands(Enum):
IDN = ('*IDN?', str) IDN = ('*IDN?', str)
MEASU_CH1_FREQ = (':MEASUrement:CH1:FREQuency?', float) MEASU_CH1_FREQ = (':MEASUrement:CH1:FREQuency?', float)
MEASU_CH2 = (':MEASUrement:CH2:MAX?', int) MEASU_CH2 = (':MEASUrement:CH2:PKPK?', float)
DATA_CH2 = (':DATA:WAVE:SCREen:CH2?', bytes) DATA_CH2 = (':DATA:WAVE:SCREen:CH2?', bytes)
def ExecuteCmdInDev(dev:Oscilloscope, cmd:Commands):
_NUMERIC_RE = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?')
def _extract_numeric(text: str) -> Optional[float]:
m = _NUMERIC_RE.search(text)
if m is None:
return None
try:
return float(m.group())
except (ValueError, OverflowError):
return None
def ExecuteCmdInDev(dev: Oscilloscope, cmd: Commands) -> Optional[Union[str, bytes, float, int]]:
resp = dev.send_command(cmd.value[0]) resp = dev.send_command(cmd.value[0])
ret = None if resp is None:
if resp: return None
parser = cmd.value[1] parser = cmd.value[1]
if parser is str: if parser is str:
ret = resp.decode("ascii", errors="ignore") return resp.decode("ascii", errors="ignore").strip()
elif parser is bytes: if parser is bytes:
ret = resp return resp
elif parser in (int, float):
ret = parser(resp.decode("ascii", errors="ignore").strip())
else:
ret = parser(resp)
return ret
#
# 工作流程: raw = resp.decode("ascii", errors="ignore").strip()
# 发动本线程, if parser in (int, float):
# 进入空闲状态, num = _extract_numeric(raw)
# 等待用户指出 if num is None:
return None
if parser is int:
return int(num)
return num
def work(con:Connection): return parser(resp)
def work(con: Connection) -> None:
with Oscilloscope() as OWON: with Oscilloscope() as OWON:
idn = ExecuteCmdInDev(OWON, Commands.IDN) idn = ExecuteCmdInDev(OWON, Commands.IDN)
if idn: if idn:

查看文件

@ -1,13 +1,14 @@
from __future__ import annotations from __future__ import annotations
import time
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from enum import Enum
from typing import Optional from typing import Optional
from fastapi import HTTPException from fastapi import HTTPException
from app.hardware.oscilloscope import Oscilloscope from .oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev from .progress import Commands, ExecuteCmdInDev
class HardwareStatus(str, Enum): class HardwareStatus(str, Enum):
@ -20,13 +21,16 @@ class HardwareStatus(str, Enum):
class HardwareSnapshot: class HardwareSnapshot:
status: HardwareStatus status: HardwareStatus
device_idn: Optional[str] = None device_idn: Optional[str] = None
peak_value: Optional[int] = None peak_value: Optional[float] = None
frequency_hz: Optional[float] = None frequency_hz: Optional[float] = None
raw_response: Optional[str] = None raw_response: Optional[str] = None
note: Optional[str] = None note: Optional[str] = None
class OscilloscopeService: class OscilloscopeService:
RETRY_COUNT = 3
RETRY_DELAY = 1.0
def __init__(self) -> None: def __init__(self) -> None:
self._cached_status = HardwareStatus.OFFLINE self._cached_status = HardwareStatus.OFFLINE
@ -37,6 +41,8 @@ class OscilloscopeService:
raise HTTPException(status_code=503, detail=f"示波器初始化失败: {exc}") from exc raise HTTPException(status_code=503, detail=f"示波器初始化失败: {exc}") from exc
def probe(self) -> HardwareSnapshot: def probe(self) -> HardwareSnapshot:
last_error: Optional[Exception] = None
for attempt in range(1, self.RETRY_COUNT + 1):
try: try:
with self._open_device() as device: with self._open_device() as device:
idn = ExecuteCmdInDev(device, Commands.IDN) idn = ExecuteCmdInDev(device, Commands.IDN)
@ -46,12 +52,18 @@ class OscilloscopeService:
return HardwareSnapshot( return HardwareSnapshot(
status=HardwareStatus.ONLINE, status=HardwareStatus.ONLINE,
device_idn=idn if isinstance(idn, str) else None, device_idn=idn if isinstance(idn, str) else None,
peak_value=peak_value if isinstance(peak_value, int) else None, peak_value=peak_value if isinstance(peak_value, (int, float)) else None,
frequency_hz=frequency_hz if isinstance(frequency_hz, float) else None, frequency_hz=frequency_hz if isinstance(frequency_hz, float) else None,
raw_response=idn if isinstance(idn, str) else None, raw_response=idn if isinstance(idn, str) else None,
note="已连接真实示波器", note="已连接真实示波器",
) )
except Exception as exc: except Exception as exc:
last_error = exc
if "Resource busy" not in str(exc) and "busy" not in str(exc).lower():
break
if attempt < self.RETRY_COUNT:
time.sleep(self.RETRY_DELAY)
self._cached_status = HardwareStatus.SIMULATED self._cached_status = HardwareStatus.SIMULATED
return HardwareSnapshot( return HardwareSnapshot(
status=HardwareStatus.SIMULATED, status=HardwareStatus.SIMULATED,
@ -59,7 +71,7 @@ class OscilloscopeService:
peak_value=None, peak_value=None,
frequency_hz=None, frequency_hz=None,
raw_response=None, raw_response=None,
note=f"示波器不可用,已切换为模拟模式: {exc}", note=f"示波器不可用,已切换为模拟模式: {last_error}",
) )
def capture_peak(self) -> HardwareSnapshot: def capture_peak(self) -> HardwareSnapshot:
@ -84,3 +96,11 @@ class OscilloscopeService:
oscilloscope_service = OscilloscopeService() oscilloscope_service = OscilloscopeService()
if __name__ == "__main__":
while True:
snapshot = oscilloscope_service.probe()
print(snapshot)
snapshot = oscilloscope_service.capture_peak()
print(snapshot)

查看文件

@ -1,13 +1,20 @@
from __future__ import annotations from __future__ import annotations
import logging
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
import uvicorn import uvicorn
from app.api.form import router as form_router from app.api.form import router as form_router
from app.api.device import router as device_router from app.api.device import router as device_router
from app.api.debug import router as debug_router
from app.api.measurement import router as measurement_router from app.api.measurement import router as measurement_router
from app.api.peak_monitor import router as peak_monitor_router
from app.api.value import router as value_router from app.api.value import router as value_router
from app.hardware.service import HardwareStatus, oscilloscope_service
_logger = logging.getLogger("main")
App = FastAPI( App = FastAPI(
@ -26,8 +33,20 @@ App.add_middleware(
App.include_router(form_router) App.include_router(form_router)
App.include_router(device_router) App.include_router(device_router)
App.include_router(debug_router)
App.include_router(value_router) App.include_router(value_router)
App.include_router(measurement_router) App.include_router(measurement_router)
App.include_router(peak_monitor_router)
@App.on_event("startup")
async def _probe_oscilloscope_on_startup() -> None:
snapshot = oscilloscope_service.probe()
if snapshot.status == HardwareStatus.ONLINE:
_logger.info("示波器已连接 IDN=%s CH2峰值=%s CH1频率=%s Hz",
snapshot.device_idn, snapshot.peak_value, snapshot.frequency_hz)
else:
_logger.warning("示波器不可用,状态=%s 原因=%s", snapshot.status.value, snapshot.note)
@App.get("/") @App.get("/")
@ -44,7 +63,9 @@ async def root():
"DELETE /value/{field_id}", "DELETE /value/{field_id}",
"DELETE /value", "DELETE /value",
], ],
"device": ["GET /device/status", "POST /device/peak"], "device": ["GET /device/status", "POST /device/peak", "POST /device/manual-answer"],
"debug": ["GET /debug/menu", "GET /debug/status", "POST /debug/probe", "GET /debug/oscilloscope"],
"peak_monitor": ["POST /peak-monitor/start", "POST /peak-monitor/stop", "GET /peak-monitor/status"],
"measurement": ["POST /measurement/{standing_wave|phase|time_diff}"], "measurement": ["POST /measurement/{standing_wave|phase|time_diff}"],
"system": ["GET /health"], "system": ["GET /health"],
}, },
@ -53,7 +74,16 @@ async def root():
@App.get("/health") @App.get("/health")
async def health_check(): async def health_check():
return {"status": "healthy", "service": "physics-experiment-backend"} snapshot = oscilloscope_service.probe()
return {
"status": "healthy",
"service": "physics-experiment-backend",
"oscilloscope": {
"status": snapshot.status,
"device_idn": snapshot.device_idn,
"note": snapshot.note,
},
}
if __name__ == "__main__": if __name__ == "__main__":

查看文件

@ -13,10 +13,16 @@ from app.schemas.experiment import (
from app.schemas.validation import ( from app.schemas.validation import (
AnalyzeMeasurementRequest, AnalyzeMeasurementRequest,
AnalyzeMeasurementResponse, AnalyzeMeasurementResponse,
DebugMenuItem,
DebugMenuResponse,
DebugStatusResponse,
FieldValidationRequest, FieldValidationRequest,
FieldValidationResponse, FieldValidationResponse,
ManualAnswerRequest, ManualAnswerRequest,
MeasurementMethod, MeasurementMethod,
PeakMonitorResponse,
PeakMonitorStartRequest,
PeakMonitorState,
) )
__all__ = [ __all__ = [
@ -32,8 +38,14 @@ __all__ = [
"ValidationType", "ValidationType",
"AnalyzeMeasurementRequest", "AnalyzeMeasurementRequest",
"AnalyzeMeasurementResponse", "AnalyzeMeasurementResponse",
"DebugMenuItem",
"DebugMenuResponse",
"DebugStatusResponse",
"FieldValidationRequest", "FieldValidationRequest",
"FieldValidationResponse", "FieldValidationResponse",
"ManualAnswerRequest", "ManualAnswerRequest",
"MeasurementMethod", "MeasurementMethod",
"PeakMonitorResponse",
"PeakMonitorStartRequest",
"PeakMonitorState",
] ]

查看文件

@ -24,6 +24,7 @@ class ReadingGuardSource(str, Enum):
DEVICE_PEAK = "device_peak" DEVICE_PEAK = "device_peak"
DEVICE_FREQUENCY = "device_frequency" DEVICE_FREQUENCY = "device_frequency"
MANUAL = "manual" MANUAL = "manual"
PEAK_OCR = "peak_ocr"
class ReadingGuardConfig(BaseModel): class ReadingGuardConfig(BaseModel):

查看文件

@ -50,3 +50,48 @@ class AnalyzeMeasurementResponse(BaseModel):
uncertainty_mps: Optional[float] = None uncertainty_mps: Optional[float] = None
theoretical_velocity_mps: Optional[float] = None theoretical_velocity_mps: Optional[float] = None
details: Dict[str, Any] = Field(default_factory=dict) details: Dict[str, Any] = Field(default_factory=dict)
class PeakMonitorState(str, Enum):
IDLE = "idle"
RISING = "rising"
PEAK_TRIGGERED = "peak_triggered"
COOLDOWN = "cooldown"
class PeakMonitorStartRequest(BaseModel):
experiment: str = "cn.edu.muc.lxy.phyexp.voicespeed"
drop_ratio: float = Field(default=0.05, gt=0, le=0.5)
cooldown_ratio: float = Field(default=0.30, gt=0, le=0.8)
class PeakMonitorResponse(BaseModel):
running: bool
state: PeakMonitorState = PeakMonitorState.IDLE
current_peak: Optional[float] = None
peak_max: Optional[float] = None
ocr_reading: Optional[float] = None
pending_field: Optional[str] = None
peak_index: int = 0
trend: str = "flat"
class DebugMenuItem(BaseModel):
label: str
action: str
method: str = "GET"
endpoint: str
description: str = ""
class DebugMenuResponse(BaseModel):
experiment: str
title: str
description: str = ""
items: List[DebugMenuItem]
class DebugStatusResponse(BaseModel):
experiment: str
debug_providers: Dict[str, List[str]]
oscilloscope: Optional[Dict[str, Any]] = None

文件差异内容过多而无法显示 加载差异

查看文件

@ -1,249 +0,0 @@
{
"title": "超声波声速测量实验(记录表)",
"description": "基于网格表单组织:基本信息、表1频率与温度、表2驻波法、表3相位法、表4时差法、表5方法比较。",
"sheets": [
{
"id": "basic_info",
"title": "基本信息",
"columns": 3,
"cells": [
[
{"type": "label", "content": "班级", "style": "header"},
{"type": "input", "fieldId": "class_name", "placeholder": "纳米专业2班", "validation": {"type": "text", "required": true}},
{"type": "input", "fieldId": "student_name", "placeholder": "请输入姓名", "validation": {"type": "text", "required": true}}
],
[
{"type": "label", "content": "学号", "style": "header"},
{"type": "input", "fieldId": "student_id", "placeholder": "请输入学号", "colSpan": 2, "validation": {"type": "regex", "pattern": "^[0-9]{6,20}$", "required": true}},
null
]
]
},
{
"id": "table1_frequency",
"title": "表1 声源频率与介质温度",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", "placeholder": "36.539", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f3", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f4", "placeholder": "36.538", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f5", "placeholder": "36.542", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}}
],
[
{"type": "label", "content": "$t/^\\circ C$"},
{"type": "input", "fieldId": "temperature", "placeholder": "25.0", "unit": "$^\\circ C$", "colSpan": 5, "validation": {"type": "number", "min": 0, "max": 60, "required": true}}
],
[
{"type": "label", "content": "$\\bar{f}/kHz$"},
{"type": "computed", "areaId": "frequency_avg", "expression": "(f1+f2+f3+f4+f5)/5", "variables": ["f1","f2","f3","f4","f5"], "format": "0.000", "colSpan": 5}
],
[
{"type": "label", "content": "$v_0/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v0_theory", "expression": "331.5 + 0.6 * temperature", "variables": ["temperature"], "format": "0.00", "colSpan": 5}
]
]
},
{
"id": "table2_standing",
"title": "表2 驻波法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "s_l0", "placeholder": "144.02", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l1", "placeholder": "148.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l2", "placeholder": "153.50", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l3", "placeholder": "158.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l4", "placeholder": "163.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "s_l5", "placeholder": "167.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l6", "placeholder": "172.66", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l7", "placeholder": "177.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l8", "placeholder": "182.29", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l9", "placeholder": "186.84", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "s_d1", "expression": "s_l5 - s_l0", "variables": ["s_l5","s_l0"], "format": "0.00"},
{"type": "computed", "areaId": "s_d2", "expression": "s_l6 - s_l1", "variables": ["s_l6","s_l1"], "format": "0.00"},
{"type": "computed", "areaId": "s_d3", "expression": "s_l7 - s_l2", "variables": ["s_l7","s_l2"], "format": "0.00"},
{"type": "computed", "areaId": "s_d4", "expression": "s_l8 - s_l3", "variables": ["s_l8","s_l3"], "format": "0.00"},
{"type": "computed", "areaId": "s_d5", "expression": "s_l9 - s_l4", "variables": ["s_l9","s_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "s_d_avg", "expression": "(s_d1 + s_d2 + s_d3 + s_d4 + s_d5) / 5", "variables": ["s_d1","s_d2","s_d3","s_d4","s_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_standing", "expression": "(2 / 5) * s_d_avg", "variables": ["s_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_standing", "expression": "frequency_avg * lambda_standing", "variables": ["frequency_avg","lambda_standing"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_standing", "expression": "((v_standing - v0_theory) / v0_theory) * 100", "variables": ["v_standing","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table3_phase",
"title": "表3 相位法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "p_l0", "placeholder": "182.10", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l1", "placeholder": "191.28", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l2", "placeholder": "196.20", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l3", "placeholder": "201.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l4", "placeholder": "205.54", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "p_l5", "placeholder": "210.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l6", "placeholder": "215.22", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l7", "placeholder": "219.96", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l8", "placeholder": "224.68", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l9", "placeholder": "229.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "p_d1", "expression": "p_l5 - p_l0", "variables": ["p_l5","p_l0"], "format": "0.00"},
{"type": "computed", "areaId": "p_d2", "expression": "p_l6 - p_l1", "variables": ["p_l6","p_l1"], "format": "0.00"},
{"type": "computed", "areaId": "p_d3", "expression": "p_l7 - p_l2", "variables": ["p_l7","p_l2"], "format": "0.00"},
{"type": "computed", "areaId": "p_d4", "expression": "p_l8 - p_l3", "variables": ["p_l8","p_l3"], "format": "0.00"},
{"type": "computed", "areaId": "p_d5", "expression": "p_l9 - p_l4", "variables": ["p_l9","p_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "p_d_avg", "expression": "(p_d1 + p_d2 + p_d3 + p_d4 + p_d5) / 5", "variables": ["p_d1","p_d2","p_d3","p_d4","p_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_phase", "expression": "(2 / 5) * p_d_avg", "variables": ["p_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_phase", "expression": "frequency_avg * lambda_phase", "variables": ["frequency_avg","lambda_phase"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_phase", "expression": "((v_phase - v0_theory) / v0_theory) * 100", "variables": ["v_phase","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table4_timediff",
"title": "表4 时差法测量",
"columns": 11,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "t_l1", "placeholder": "202.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l2", "placeholder": "245.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l3", "placeholder": "197.60", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l4", "placeholder": "157.56", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l5", "placeholder": "123.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l6", "placeholder": "140.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l7", "placeholder": "161.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l8", "placeholder": "132.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l9", "placeholder": "173.14", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l10", "placeholder": "152.46", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$T_i/\\mu s$"},
{"type": "input", "fieldId": "t_t1", "placeholder": "584", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t2", "placeholder": "712", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t3", "placeholder": "572", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t4", "placeholder": "456", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t5", "placeholder": "356", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t6", "placeholder": "404", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t7", "placeholder": "472", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t8", "placeholder": "380", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t9", "placeholder": "500", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t10", "placeholder": "440", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "t_dl1", "expression": "t_l6 - t_l1", "variables": ["t_l6","t_l1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl2", "expression": "t_l7 - t_l2", "variables": ["t_l7","t_l2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl3", "expression": "t_l8 - t_l3", "variables": ["t_l8","t_l3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl4", "expression": "t_l9 - t_l4", "variables": ["t_l9","t_l4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl5", "expression": "t_l10 - t_l5", "variables": ["t_l10","t_l5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\Delta T_i/\\mu s$"},
{"type": "computed", "areaId": "t_dt1", "expression": "t_t6 - t_t1", "variables": ["t_t6","t_t1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt2", "expression": "t_t7 - t_t2", "variables": ["t_t7","t_t2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt3", "expression": "t_t8 - t_t3", "variables": ["t_t8","t_t3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt4", "expression": "t_t9 - t_t4", "variables": ["t_t9","t_t4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt5", "expression": "t_t10 - t_t5", "variables": ["t_t10","t_t5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "t_dl_avg", "expression": "(t_dl1 + t_dl2 + t_dl3 + t_dl4 + t_dl5) / 5", "variables": ["t_dl1","t_dl2","t_dl3","t_dl4","t_dl5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$\\overline{\\Delta T}/\\mu s$"},
{"type": "computed", "areaId": "t_dt_avg", "expression": "(t_dt1 + t_dt2 + t_dt3 + t_dt4 + t_dt5) / 5", "variables": ["t_dt1","t_dt2","t_dt3","t_dt4","t_dt5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_time", "expression": "1000 * t_dl_avg / t_dt_avg", "variables": ["t_dl_avg","t_dt_avg"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_time", "expression": "((v_time - v0_theory) / v0_theory) * 100", "variables": ["v_time","v0_theory"], "format": "0.000", "colSpan": 10}
]
]
},
{
"id": "table5_compare",
"title": "表5 几种方法比较",
"columns": 3,
"columnHeaders": ["方法", "声速 $v/(m\\cdot s^{-1})$", "相对误差 $A_{\\%}$"],
"cells": [
[
{"type": "label", "content": "驻波法"},
{"type": "computed", "areaId": "cmp_v_standing", "expression": "v_standing", "variables": ["v_standing"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_standing", "expression": "err_standing", "variables": ["err_standing"], "format": "0.000"}
],
[
{"type": "label", "content": "相位法"},
{"type": "computed", "areaId": "cmp_v_phase", "expression": "v_phase", "variables": ["v_phase"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_phase", "expression": "err_phase", "variables": ["err_phase"], "format": "0.000"}
],
[
{"type": "label", "content": "时差法"},
{"type": "computed", "areaId": "cmp_v_time", "expression": "v_time", "variables": ["v_time"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_time", "expression": "err_time", "variables": ["err_time"], "format": "0.000"}
]
]
},
{
"id": "notes",
"title": "实验结论",
"columns": 1,
"cells": [
[
{"type": "input", "fieldId": "observation", "placeholder": "记录波形变化、李萨如图形变化、时差读数现象等", "validation": {"type": "text", "required": true}}
],
[
{"type": "input", "fieldId": "conclusion", "placeholder": "比较三种方法差异,分析系统误差和随机误差来源", "validation": {"type": "text", "required": true}}
]
]
}
]
}

269
docs/API.md 普通文件
查看文件

@ -0,0 +1,269 @@
# API 文档
## 基础信息
- **Base URL**: `http://localhost:8000`
- **Content-Type**: `application/json`
- **会话管理**: 通过 `X-Session-Id` 请求头标识会话,默认为 `"default"`
## 端点列表
### 系统
#### `GET /`
返回服务信息。
**响应**:
```json
{
"message": "Physics Experiment Backend",
"version": "1.0.0",
"endpoints": {
"form": ["GET /form", "GET /form/list", "GET /form/{experiment_name}"],
"value": ["POST /value", "GET /value", "GET /value/{field_id}", "DELETE /value/{field_id}", "DELETE /value"],
"device": ["GET /device/status", "POST /device/peak"],
"measurement": ["POST /measurement/{standing_wave|phase|time_diff}"],
"system": ["GET /health"]
}
}
```
#### `GET /health`
健康检查。
**响应**:
```json
{ "status": "healthy", "service": "physics-experiment-backend" }
```
---
### 表单配置
#### `GET /form`
加载指定实验的网格配置。
**查询参数**:
| 参数 | 类型 | 默认值 | 说明 |
| ---------- | ------ | -------------- | ---------- |
| experiment | string | "voice_speed" | 实验名称 |
**响应**: `ExperimentGridConfig` JSON
#### `GET /form/list`
列出所有可用实验。
**响应**:
```json
{
"experiments": [
{ "name": "voice_speed", "title": "超声波声速测量实验(记录表)", "description": "..." }
],
"count": 1
}
```
#### `GET /form/{experiment_name}`
按名称加载特定实验配置。
**响应**: `ExperimentGridConfig` JSON
---
### 字段值
#### `POST /value`
验证并存储字段值。先进行基础校验(类型/范围/正则),再进行读数守卫校验(如果配置了)。
**查询参数**:
| 参数 | 类型 | 默认值 | 说明 |
| ---------- | ------ | -------------- | ---------- |
| experiment | string | "voice_speed" | 实验名称 |
**请求头**:
| 头 | 类型 | 说明 |
| ------------ | ------ | -------- |
| X-Session-Id | string | 会话标识 |
**请求体**:
```json
{
"field_id": "f1",
"value": "36.540"
}
```
**响应**:
```json
{
"accept": true,
"message": "validation passed"
}
```
#### `GET /value`
获取当前会话所有字段值。
**响应**:
```json
{
"fields": { "f1": "36.540", "f2": "36.539" },
"count": 2,
"session_id": "default"
}
```
#### `GET /value/{field_id}`
获取单个字段值。
#### `DELETE /value/{field_id}`
删除单个字段值。
#### `DELETE /value`
清除当前会话所有字段值。
---
### 设备控制
#### `GET /device/status`
探测示波器连接状态。
**响应**:
```json
{
"status": "online|offline|simulated",
"device_idn": "...",
"peak_value": null,
"frequency_hz": null,
"note": "..."
}
```
#### `POST /device/peak`
捕获示波器峰值。
#### `POST /device/manual-answer`
设置读数守卫的手动参考值。
**请求体**:
```json
{
"field_id": "f1",
"value": 36.540
}
```
---
### 测量分析
#### `POST /measurement/{method}`
分析测量数据并计算声速。
**路径参数**:
| 参数 | 类型 | 可选值 |
| ------ | ------ | --------------------------------- |
| method | string | `standing_wave`, `phase`, `time_diff` |
**请求体** (`standing_wave` / `phase` 方法):
```json
{
"frequency_hz": 36540.0,
"temperature_c": 25.0,
"cursor_readings_mm": [144.02, 148.80, 153.50, 158.30, 163.00, 167.80, 172.66, 177.30, 182.29, 186.84]
}
```
**请求体** (`time_diff` 方法):
```json
{
"distance_readings_mm": [62.80, 84.00, 65.30, 15.58, 29.16],
"time_deltas_us": [180, 240, 192, 44, 84]
}
```
**响应**:
```json
{
"method": "standing_wave",
"sample_count": 5,
"velocity_mps": 347.25,
"wavelength_m": 0.0095,
"uncertainty_mps": 0.12,
"theoretical_velocity_mps": 346.8,
"details": {
"pair_deltas_mm": [23.78, 23.86, 23.80, 23.99, 23.84],
"mean_delta_mm": 23.854,
"std_delta_mm": 0.074
}
}
```
---
## 数据模型
### ExperimentGridConfig
```json
{
"title": "实验标题",
"description": "实验说明",
"sheets": [
{
"id": "sheet_id",
"title": "表标题",
"columns": 6,
"columnHeaders": ["项目", "1", "2", "3", "4", "5"],
"cells": [
[
{ "type": "label", "content": "行标签" },
{ "type": "input", "fieldId": "f1", "validation": { "type": "number", "min": 0, "max": 100, "required": true } },
{ "type": "computed", "areaId": "avg", "expression": "(f1+f2)/2", "variables": ["f1","f2"], "format": "0.00" },
null
]
]
}
]
}
```
### 单元格类型
| type | 用途 | 关键字段 |
| ---------- | -------- | ------------------------------- |
| `label` | 静态标签 | `content` (支持 LaTeX) |
| `input` | 数据输入 | `fieldId`, `validation`, `unit` |
| `computed` | 自动计算 | `areaId`, `expression`, `variables`, `format` |
### 校验配置
```json
{
"type": "number",
"min": 30,
"max": 45,
"required": true
}
```
| type | 额外字段 | 说明 |
| ------- | --------------- | ---------------------------- |
| number | `min`, `max` | 数值范围校验 |
| text | `required` | 非空文本 |
| regex | `pattern` | 正则匹配 |

217
docs/ARCHITECTURE.md 普通文件
查看文件

@ -0,0 +1,217 @@
# 架构总览
## 系统架构图
```
┌─────────────────────────────────────────────────────────┐
│ 浏览器 (SPA) │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────────┐ │
│ │ Vue 3 │ │ KaTeX │ │ Pinia Store │ │
│ │ Router │ │ mathjs │ │ (experiment/student) │ │
│ └──────────┘ └──────────┘ └──────────────────────┘ │
│ │ │ │
│ │ HTTP REST + SSE │ │
└─────────┼───────────────────────────────────────────┘ │
│ │
┌─────────┼───────────────────────────────────────────┐ │
│ ▼ FastAPI 后端 │ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ api/ │ │ core/ │ │ schemas/ │ │ │
│ │ 路由层 │→│ 业务层 │←│ Pydantic 模型 │ │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ │ │ │
│ ▼ │ │
│ ┌──────────────────────────────────────────────┐ │ │
│ │ hardware/ 示波器驱动 (PyUSB, 可选) │ │ │
│ └──────────────────────────────────────────────┘ │ │
│ │ │
│ ┌──────────────────────────────────────────────┐ │ │
│ │ config/experiments/*.json 实验配置文件 │ │ │
│ └──────────────────────────────────────────────┘ │ │
└─────────────────────────────────────────────────────┘ │
│ │
│ │
┌─────────┼───────────────────────────────────────────┐ │
│ ▼ AI 服务 (外部) │ │
│ ┌──────────────────────────────────────────────┐ │ │
│ │ /api/chat REST + SSE 端点 │ │ │
│ │ teacher_type: question | data_eval | grader │ │ │
│ └──────────────────────────────────────────────┘ │ │
└─────────────────────────────────────────────────────┘ │
```
## 数据流
### 实验表单流程
```
1. 前端加载配置
GET /form?experiment=voice_speed
→ 后端返回 ExperimentGridConfig (JSON)
→ 前端渲染网格表单
2. 用户填入数据
输入 → 本地校验 (mathjs) → 背景色变化
失焦 → POST /value { field_id, value }
→ 后端 Pydantic 校验 → { accept, message }
→ 前端更新验证状态 → 背景色更新
3. 自动计算
依赖字段验证通过后
→ mathjs 编译表达式 → 计算结果
→ 级联更新所有受影响的计算区
4. AI 评价
鼠标悬停 600ms
→ POST /api/chat (teacherType=data_eval)
→ 显示评价 tooltip
```
### 字段验证详细流程
```
POST /value { field_id: "f1", value: "36.540" }
→ FieldValidator.validate_by_config()
→ 类型校验 (number/text/regex)
→ 范围校验 (min/max)
→ 必填校验 (required)
→ ReadingGuardManager.validate()
→ 检查读数顺序 (如果启用)
→ 检查容差 (如果启用)
→ SessionStore.set_value()
→ 返回 { accept: true/false, message: "..." }
```
## 数据模型
### 实验配置 (Grid 模式)
```
ExperimentGridConfig
├── title
├── description
└── sheets[]
├── id
├── columns: int
├── columnHeaders?: string[]
└── cells[][] → GridCell[]
├── GridLabelCell { type:"label", content }
├── GridInputCell { type:"input", fieldId, validation? }
└── GridComputedCell { type:"computed", areaId, expression, variables[] }
```
### 验证状态可视化
| 状态 | 背景色 | 含义 |
| -------------- | -------- | -------------- |
| 未填写 | `#ffffff` | 尚未输入 |
| 已填写未验证 | `#fff3cd` | 等待后端验证 |
| 验证通过 | `#d4edda` | 数据合格 |
| 验证失败 | `#f8d7da` | 数据不合格 |
| 计算错误 | `#f8d7da` | 表达式异常 |
## 路由设计
### 前端路由
| 路径 | 组件 | 说明 |
| ---------------- | ---------------- | ------------ |
| `/login` | StudentLogin | 学生登录 |
| `/exp?expid=...` | ExperienceFrame | 实验主框架 |
| `/select` | ExperienceSwitch | 实验选择 |
### 后端 API
| 方法 | 路径 | 说明 |
| ------ | ----------------------------- | ------------------ |
| GET | `/health` | 健康检查 |
| GET | `/form?experiment=...` | 加载实验配置 |
| POST | `/value?experiment=...` | 验证字段值 |
| GET | `/device/status` | 示波器状态 |
| POST | `/measurement/{method}` | 测量数据分析 |
## 用户导航流程
```
/login (StudentLogin)
→ 登录成功 → /select (ExperienceSwitch)
→ 选择实验卡片 → /exp?expid=<id> (ExperienceFrame)
→ 阶段导航: 预习 → 测验 → 实验 → 考试 → 总结
```
- **登录守卫**: `router.beforeEach` 检查 `localStorage.PhyExp.StudentInfo`,未登录重定向到 `/login`
- **实验选择页**: 网格卡片布局,展示所有可用实验的封面、标题、作者、阶段标签,点击跳转
- **实验框架**: 通过 `?expid=` 查询参数加载对应实验,阶段切换通过 `Process` 索引控制
## 组件层级
```
App.vue
└── RouterView
└── ExperimentPage
├── ExperimentForm (provide AIEvalContext)
│ └── ExperimentGrid[] (每个 Sheet)
│ └── ExperimentGridCell[] (label / input / computed)
├── ExperimentPrintTable (隐藏 PDF 渲染)
└── AIChatSidebar (浮动 AI 助教)
├── 单元格选择器
└── 单元格上下文显示
```
## 跨层通信
### 前端 → 后端
| 端点 | 用途 | 请求格式 |
| ----------------- | ------------------- | -------------------------------- |
| `GET /form` | 加载实验表结构 | `?experiment=voice_speed` |
| `POST /value` | 验证单个字段 | `{ field_id, value }` |
| `DELETE /value` | 清除所有字段值 | |
### 前端 → AI 服务
| teacherType | 用途 | 通信方式 |
| ------------ | ----------------- | ------------ |
| `question` | AI 助教对话 | SSE 流式 |
| `data_eval` | 实验数据评价 | REST |
| `grader` | 测验错题分析 | REST |
### 前端内部
| Store | 职责 |
| ------------------ | --------------------------- |
| `useExperimentStore` | 表单数据、验证、计算、依赖图 |
| `useStudentStore` | 学生认证、持久化 |
## 声速实验计算
### 驻波法 / 相位法
```
ΔL_i = L_{i+5} - L_i (i = 0..4)
λ = 2 × mean(ΔL) / 1000 [m]
v = f × λ
Δv = f × 2 × σ(ΔL) / 1000
```
### 时差法
```
v_i = (ΔL_i / 1000) / (ΔT_i / 1e6)
v = mean(v_i)
Δv = σ(v_i)
```
### 理论声速 (温度校正)
```
v₀ = 331.5 + 0.6 × t [m/s]
```
### 相对误差
```
A_% = |v - v₀| / v₀ × 100%
```
每个测量方法独立计算相对误差,均基于温度推导的理论值 v₀。

152
docs/DEPLOYMENT.md 普通文件
查看文件

@ -0,0 +1,152 @@
# 部署指南
## 生产构建
### 前端
```bash
cd frontend
yarn build
# 产物在 frontend/dist/
```
### 后端
```bash
cd backend
uv sync --frozen
# 使用 uvicorn 直接启动
```
## 部署方案
### 方案 A: 单机部署 (推荐)
使用 Nginx 反向代理,前后端同机运行。
```nginx
server {
listen 80;
server_name phyexp.example.com;
# 前端静态文件
root /opt/phyexp/frontend/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 后端 API 反向代理
location /api/ {
# 如果 AI 服务在同一机器
proxy_pass http://127.0.0.1:8000/api/;
}
# 后端直接端点
location ~ ^/(form|value|device|measurement|health) {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
### 方案 B: 分离部署
- 前端: 部署到 CDN 或静态服务器 (Nginx, Vercel, Netlify)
- 后端: 独立服务器运行 FastAPI
- AI 服务: 独立部署
## 后端启动
### 使用 uvicorn
```bash
cd backend
uv run uvicorn app.main:App --host 0.0.0.0 --port 8000
```
### 使用 systemd (Linux)
```ini
# /etc/systemd/system/phyexp-backend.service
[Unit]
Description=PhyExp Backend
After=network.target
[Service]
Type=simple
User=phyexp
WorkingDirectory=/opt/phyexp/backend
ExecStart=/home/phyexp/.local/bin/uv run uvicorn app.main:App --host 127.0.0.1 --port 8000
Restart=always
Environment="PYTHONUNBUFFERED=1"
[Install]
WantedBy=multi-user.target
```
### 使用 Docker
```dockerfile
# backend/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN pip install uv && uv sync --frozen
COPY . .
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "app.main:App", "--host", "0.0.0.0", "--port", "8000"]
```
```bash
docker build -t phyexp-backend backend/
docker run -d -p 8000:8000 phyexp-backend
```
## 环境变量
| 变量 | 默认值 | 说明 |
| ---------------------- | ----------------------------- | --------------------- |
| `AI_BASE_URL` | (无) | AI 服务端点 URL |
| `EXPERIMENT_CONFIG_DIR`| `config/experiments` | 实验配置文件目录 |
## 配置 AI 服务
前端通过 `window.__AI_BASE_URL__` 或 `/config.json` 获取 AI 服务地址。
在部署时,在 Nginx 中注入:
```nginx
location /config.json {
alias /opt/phyexp/config.json;
}
```
`/opt/phyexp/config.json`:
```json
{
"aiBaseUrl": "https://ai-service.example.com"
}
```
## 检查清单
- [ ] Python >= 3.10,Node.js >= 18
- [ ] `backend/` 下 `uv sync` 通过
- [ ] `frontend/` 下 `yarn build` 通过
- [ ] Nginx 配置正确,静态资源路径指向 `frontend/dist/`
- [ ] API 代理正确转发 `/form`, `/value`, `/health` 等端点
- [ ] CORS 配置与部署环境一致 (生产环境应限制 `allow_origins`)
- [ ] AI 服务可访问
- [ ] 防火墙开放 80/443 端口
- [ ] (可选) 示波器 USB 设备连接正确
## 安全建议
- 生产环境修改 `app/main.py` 中的 `allow_origins` 为具体域名
- 使用 HTTPS (Let's Encrypt + Certbot)
- 不要在生产环境中启用 `reload=True`
- 会话存储 (`SessionStore`) 当前为内存实现,多进程部署需要替换为 Redis

214
docs/DEVELOPMENT.md 普通文件
查看文件

@ -0,0 +1,214 @@
# 开发指南
## 环境准备
### 必需工具
- **Node.js** >= 18 (推荐 20+)
- **Python** >= 3.10 (推荐 3.11+)
- **yarn** (前端包管理器,严禁使用 npm)
- **uv** (Python 包管理器)
- **VS Code** (推荐,已配置 `.vscode/`)
### 安装依赖
```bash
# 后端
cd backend
uv sync
# 前端
cd frontend
yarn install
```
### 启动开发服务器
```bash
# 终端 1: 后端 (默认 :8000)
cd backend
uv run python -m app.main
# 终端 2: 前端 (默认 :5173)
cd frontend
yarn dev
```
## 项目结构规范
### 后端目录规范
```
backend/
├── app/
│ ├── main.py # FastAPI 应用入口,CORS 配置,路由注册
│ ├── models.py # 兼容性导出 (实际定义在 schemas/)
│ ├── schemas/ # Pydantic 数据模型 (唯一真相来源)
│ │ ├── experiment.py # 实验配置模型 (GridSheet, GridCell...)
│ │ └── validation.py # 验证请求/响应模型
│ ├── api/ # REST 路由层 (薄层,委托给 core/)
│ │ ├── form.py # GET /form ...
│ │ ├── value.py # POST/GET/DELETE /value ...
│ │ ├── device.py # 示波器端点
│ │ └── measurement.py # 测量计算端点
│ ├── core/ # 业务逻辑层 (无 FastAPI 依赖)
│ │ ├── config_loader.py # 加载/验证 JSON 配置
│ │ ├── dependencies.py # 服务单例 + 辅助函数
│ │ ├── validation.py # 字段校验器
│ │ ├── reading_guard.py # 读数守卫
│ │ ├── measurement.py # 测量统计算法
│ │ └── session_store.py # 会话 KV 存储
│ └── hardware/ # 硬件交互 (与实验逻辑解耦)
│ ├── oscilloscope.py # PyUSB 驱动
│ ├── progress.py # SCPI 命令执行
│ └── service.py # OscilloscopeService
└── config/experiments/ # 实验 JSON 配置
```
**原则**:
- `api/` 只做路由和参数解析,不写业务逻辑
- `core/` 是纯 Python 逻辑,不依赖 FastAPI (除了 HTTPException)
- `schemas/` 是唯一的数据模型定义点,前后端类型保持对齐
- `hardware/` 与实验逻辑完全解耦,可独立测试
### 前端目录规范
```
frontend/src/
├── components/ # 可复用 Vue 组件
│ ├── experiment/ # 实验相关组件
│ ├── AIChatSidebar.vue # AI 聊天
│ ├── DebugPanel.vue # 调试面板
│ └── QuestionTable.vue # 试题渲染
├── pages/ # 路由页面 (每个路由一个文件)
├── stores/ # Pinia 状态管理
├── types/ # TypeScript 类型定义
├── utils/ # 工具函数 (纯函数,无副作用)
├── composables/ # Vue Composables (有状态逻辑)
├── router/ # Vue Router 配置
└── assets/ # 静态资源 + JSON 配置
```
**原则**:
- `components/` 放可复用 UI 组件,`pages/` 放路由页面
- `stores/` 是全局状态,页面间共享
- `utils/` 是纯函数工具,不依赖 Vue
- `composables/` 是 Vue 特定的可组合逻辑
- `types/` 定义所有 TypeScript 接口/类型,与后端 Pydantic 模型对齐
## 代码规范
### Python
- 所有文件第一行: `from __future__ import annotations`
- 类型注解: 全部使用 Python 3.10+ 语法 (`str | None` 而非 `Optional[str]`)
- Pydantic 模型: 使用 v2 语法,`model_dump(by_alias=True)` 输出 camelCase
- 错误处理: 使用 FastAPI `HTTPException`,带中文错误信息
- 导入顺序: `__future__` → 标准库 → 第三方 (fastapi, pydantic) → 项目内部 (app.*)
- 命名: `snake_case` 变量/函数,`PascalCase` 类,`UPPER_CASE` 常量
### TypeScript / Vue
- 使用 `<script setup lang="ts">` 语法
- Props 使用 `defineProps<{ ... }>()` 泛型语法
- Emits 使用 `defineEmits<{ event: [param: type] }>()` 泛型语法
- 类型文件: `types/experiment.ts` 定义实验相关接口,与后端 Pydantic 对齐
- Composable: `ref()` 管理响应式状态,`computed()` 派生,`watch()` 副作用
- 命名: `camelCase` 变量/函数,`PascalCase` 组件/类型,`.vue` 单文件组件
### JSON 配置
- 实验配置文件位于 `backend/config/experiments/`
- 字段命名: `camelCase` (与前端 JS 风格一致)
- LaTeX 字符串: 使用标准 LaTeX 语法,JSON 中正确转义反斜杠
## 添加新实验
### 1. 创建配置文件
在 `backend/config/experiments/` 下创建 `new_experiment.json`:
```json
{
"title": "新实验标题",
"description": "实验说明",
"sheets": [
{
"id": "sheet1",
"title": "表1 数据",
"columns": 5,
"columnHeaders": ["项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "行标签"},
{"type": "input", "fieldId": "f1", "validation": {"type": "number", "min": 0, "max": 100, "required": true}},
...
]
]
}
]
}
```
### 2. 注册到前端实验列表
编辑 `frontend/src/assets/experiences.json` 添加新实验条目。
### 3. 如果是新实验类型 (需要专门的预习/测验)
在 `frontend/src/assets/` 下创建对应的 `question.json`、`prelearn.json` 等。
## 调试
### 前端调试面板
设置 `localStorage.DEBUG = 'true'` 启用调试面板,支持:
- 实验导航
- 跳过阶段限制
- AI 设置查看
- AI 请求日志
### 后端调试
```bash
cd backend
uv run python -c "
from app.core.config_loader import config_service
cfg = config_service.load_validated('voice_speed')
print(cfg.model_dump_json(indent=2))
"
```
## 测试
### 后端
```bash
cd backend
python -c "
from app.core.validation import FieldValidator
from app.schemas.experiment import ValidationConfig, ValidationType
cfg = ValidationConfig(type=ValidationType.NUMBER, min=0, max=100, required=True)
result = FieldValidator.validate_by_config('test', '50', cfg)
assert result.accept == True
print('OK')
"
```
### 前端
```bash
cd frontend
yarn type-check # TypeScript 类型检查
yarn build # 生产构建
```
## Git 规范
- 提交信息: 中文描述,格式 `类型: 简短描述`
- `feat: 添加网格表格布局`
- `fix: 修复列标题 LaTeX 渲染`
- `refactor: 重组后端目录结构`
- `docs: 更新架构文档`
- 不提交: `node_modules/`, `.venv/`, `dist/`, `__pycache__/`, `.env`
- 不提交密钥/AI endpoint/密码

85
docs/README.md 普通文件
查看文件

@ -0,0 +1,85 @@
# 物理实验教学平台 (PhyExp)
## 项目概述
PhyExp 是一个交互式物理实验教学平台,支持学生在线完成实验预习、测验、数据记录和 AI 辅助分析。平台采用前后端分离架构,前端基于 Vue 3 + TypeScript,后端基于 Python FastAPI。
### 核心功能
- **分阶段实验流程**:预习 → 测验 → 实验 → 考试 → 总结
- **Excel 风格数据表**:网格布局的数据录入界面,支持 LaTeX 数学公式渲染
- **AI 助教**:基于 SSE 的流式对话,支持实验数据评价、答疑和错题分析
- **自动计算与验证**:前端 mathjs 即时计算,后端 Pydantic 验证,背景色可视化反馈
- **PDF 导出**:实验数据导出为 A4 格式 PDF
- **示波器集成**:可选的 PyUSB 示波器数据采集(含模拟模式回退)
### 技术栈
| 层 | 技术 |
| ------ | ----------------------------------- |
| 前端 | Vue 3, TypeScript, Vite, Pinia, KaTeX, mathjs |
| 后端 | Python, FastAPI, Pydantic v2, Uvicorn |
| 硬件 | PyUSB, libusb (可选) |
| AI | REST + SSE (Server-Sent Events) |
## 快速开始
### 环境要求
- Node.js >= 18
- Python >= 3.10
- uv (Python 包管理器)
- yarn (Node.js 包管理器)
### 启动后端
```bash
cd backend
uv sync
uv run python -m app.main
# 默认监听 http://0.0.0.0:8000
```
### 启动前端
```bash
cd frontend
yarn install
yarn dev
# 默认监听 http://localhost:5173
```
## 目录结构
```
PhyExpRefactor/
├── backend/ # Python FastAPI 后端
│ ├── app/
│ │ ├── main.py # FastAPI 应用入口
│ │ ├── models.py # 模型兼容导出
│ │ ├── schemas/ # Pydantic 数据模型
│ │ ├── api/ # REST API 路由
│ │ ├── core/ # 业务逻辑层
│ │ └── hardware/ # 示波器硬件驱动
│ ├── config/experiments/ # 实验 JSON 配置
│ └── ARCHITECTURE.md # 后端架构文档
├── frontend/ # Vue 3 前端
│ ├── src/
│ │ ├── components/ # 可复用组件
│ │ ├── pages/ # 页面组件
│ │ ├── stores/ # Pinia 状态管理
│ │ ├── types/ # TypeScript 类型定义
│ │ └── utils/ # 工具函数
│ └── ARCHITECTURE.md # 前端架构文档
├── docs/ # 本目录 - 项目文档
└── .vscode/ # VS Code 配置
```
## 相关文档
- [架构总览](./ARCHITECTURE.md)
- [开发指南](./DEVELOPMENT.md)
- [部署指南](./DEPLOYMENT.md)
- [API 文档](./API.md)
- [前端架构](../frontend/ARCHITECTURE.md)
- [后端架构](../backend/ARCHITECTURE.md)

查看文件

@ -1,11 +1,34 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, watch } from 'vue' import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { useDraggable } from '@/composables/useDraggable' import { useDraggable } from '@/composables/useDraggable'
import { aiLogs, clearAiLogs, getBaseUrl, setBaseUrl, type AiLogEntry } from '@/utils/aiClient' import { aiLogs, clearAiLogs, getBaseUrl, setBaseUrl, type AiLogEntry } from '@/utils/aiClient'
type DebugMenuItem = {
label: string
action: string
method: string
endpoint: string
description: string
}
type DebugResult = {
id: number
timestamp: number
label: string
endpoint: string
method: string
success: boolean
body: unknown
error: string
}
let resultIdCounter = 0
const isVisible = ref(false) const isVisible = ref(false)
const panelRef = ref<HTMLElement | null>(null) const panelRef = ref<HTMLElement | null>(null)
const debugEnabled = ref(false) const debugEnabled = ref(false)
const debugResults = ref<DebugResult[]>([])
const expandedResult = ref<number | null>(null)
const { style: panelStyle, onPointerDown } = useDraggable(panelRef, { const { style: panelStyle, onPointerDown } = useDraggable(panelRef, {
initialX: 100, initialX: 100,
@ -27,15 +50,39 @@ const skipStageCheck = ref(false)
const aiProviderUrl = ref(getBaseUrl() || '') const aiProviderUrl = ref(getBaseUrl() || '')
const aiLogExpanded = ref<number | null>(null) const aiLogExpanded = ref<number | null>(null)
const LS_BACKEND_KEY = 'PhyExp.DebugBackendUrl'
const backendUrl = ref(localStorage.getItem(LS_BACKEND_KEY) || 'http://localhost:8000')
const debugMenuItems = ref<DebugMenuItem[]>([])
const debugMenuLoading = ref(false)
const debugMenuError = ref('')
const debugActionLoading = ref<string | null>(null)
const currentExperiment = computed((): string => {
const hash = window.location.hash
const m = hash.match(/expid=([^&]+)/)
if (m && m[1]) {
return m[1]
}
return 'cn.edu.muc.lxy.phyexp.voicespeed'
})
watch(skipStageCheck, (val) => { watch(skipStageCheck, (val) => {
;(window as any).__DEBUG_SKIP_STAGE__ = val ;(window as any).__DEBUG_SKIP_STAGE__ = val
}) })
watch(backendUrl, (val) => {
localStorage.setItem(LS_BACKEND_KEY, val.trim())
})
const saveAiProvider = () => { const saveAiProvider = () => {
const trimmed = aiProviderUrl.value.trim() const trimmed = aiProviderUrl.value.trim()
setBaseUrl(trimmed || null) setBaseUrl(trimmed || null)
} }
const saveBackendUrl = () => {
localStorage.setItem(LS_BACKEND_KEY, backendUrl.value.trim())
}
const loadExperiences = async () => { const loadExperiences = async () => {
try { try {
const response = await fetch('/src/assets/experiences.json') const response = await fetch('/src/assets/experiences.json')
@ -58,6 +105,64 @@ const loadExperiences = async () => {
} }
} }
const loadDebugMenu = async () => {
debugMenuLoading.value = true
debugMenuError.value = ''
try {
const url = `${backendUrl.value}/debug/menu?experiment=${encodeURIComponent(currentExperiment.value)}`
const response = await fetch(url)
if (!response.ok) {
const text = await response.text()
throw new Error(`${response.status} ${response.statusText}: ${text}`)
}
const data = await response.json()
debugMenuItems.value = (data?.items || []) as DebugMenuItem[]
} catch (e: any) {
debugMenuError.value = e.message || String(e)
debugMenuItems.value = []
} finally {
debugMenuLoading.value = false
}
}
const executeDebugAction = async (item: DebugMenuItem) => {
debugActionLoading.value = item.action
const resultId = ++resultIdCounter
const entry: DebugResult = {
id: resultId,
timestamp: Date.now(),
label: item.label,
endpoint: `${item.method} ${backendUrl.value}${item.endpoint}`,
method: item.method,
success: false,
body: null,
error: '',
}
try {
const fullUrl = `${backendUrl.value}${item.endpoint}`
const opts: RequestInit = {
method: item.method,
headers: { 'Content-Type': 'application/json' },
}
if (item.method === 'POST') {
opts.body = JSON.stringify({ experiment: currentExperiment.value })
}
const response = await fetch(fullUrl, opts)
const contentType = response.headers.get('content-type') || ''
const body = contentType.includes('application/json') ? await response.json() : await response.text()
entry.success = response.ok
entry.body = body
} catch (e: any) {
entry.error = e.message || String(e)
}
debugResults.value.unshift(entry)
if (debugResults.value.length > 50) {
debugResults.value.length = 50
}
expandedResult.value = resultId
debugActionLoading.value = null
}
const togglePanel = () => { const togglePanel = () => {
if (!isVisible.value) { if (!isVisible.value) {
loadExperiences() loadExperiences()
@ -70,6 +175,15 @@ const toggleLogExpand = (id: number) => {
aiLogExpanded.value = aiLogExpanded.value === id ? null : id aiLogExpanded.value = aiLogExpanded.value === id ? null : id
} }
const toggleResultExpand = (id: number) => {
expandedResult.value = expandedResult.value === id ? null : id
}
const clearDebugResults = () => {
debugResults.value.length = 0
expandedResult.value = null
}
const formatLogPreview = (entry: AiLogEntry): string => { const formatLogPreview = (entry: AiLogEntry): string => {
if (entry.type === 'error') return entry.error || 'Unknown error' if (entry.type === 'error') return entry.error || 'Unknown error'
if (entry.type === 'request') return (entry.payload || '').slice(0, 100) if (entry.type === 'request') return (entry.payload || '').slice(0, 100)
@ -81,11 +195,22 @@ const formatTime = (ts: number): string => {
return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}` return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
} }
const formatResultBody = (body: unknown): string => {
if (body === null || body === undefined) return 'null'
if (typeof body === 'string') return body
try {
return JSON.stringify(body, null, 2)
} catch {
return String(body)
}
}
onMounted(() => { onMounted(() => {
debugEnabled.value = localStorage.getItem('DEBUG') === 'true' debugEnabled.value = localStorage.getItem('DEBUG') === 'true'
skipStageCheck.value = !!(window as any).__DEBUG_SKIP_STAGE__ skipStageCheck.value = !!(window as any).__DEBUG_SKIP_STAGE__
if (debugEnabled.value) { if (debugEnabled.value) {
loadExperiences() loadExperiences()
loadDebugMenu()
} }
}) })
@ -174,6 +299,66 @@ const navToExperience = (id: string) => {
</div> </div>
</div> </div>
</div> </div>
<div class="debug-section">
<h4>后端实验调试</h4>
<div class="debug-field">
<label>后端 URL</label>
<div class="debug-input-row">
<input
v-model="backendUrl"
placeholder="http://localhost:8000"
class="debug-input"
/>
<button class="debug-btn debug-btn-sm" @click="saveBackendUrl">保存</button>
</div>
</div>
<div class="debug-field">
<label>实验: {{ currentExperiment }}</label>
<button class="debug-btn debug-btn-sm" @click="loadDebugMenu" :disabled="debugMenuLoading">
{{ debugMenuLoading ? '加载中...' : '刷新菜单' }}
</button>
</div>
<div v-if="debugMenuError" class="debug-error">{{ debugMenuError }}</div>
<div v-if="debugMenuLoading && debugMenuItems.length === 0" class="debug-empty">加载调试菜单...</div>
<div v-if="!debugMenuLoading && debugMenuItems.length === 0 && !debugMenuError" class="debug-empty">该实验暂无调试选项</div>
<div v-for="item in debugMenuItems" :key="item.action" class="debug-menu-item">
<div class="debug-menu-info">
<span class="debug-menu-label">{{ item.label }}</span>
<span class="debug-menu-desc">{{ item.description }}</span>
</div>
<button
class="debug-btn debug-btn-sm"
:disabled="debugActionLoading === item.action"
@click="executeDebugAction(item)"
>
{{ debugActionLoading === item.action ? '...' : '执行' }}
</button>
</div>
<div v-if="debugResults.length > 0" class="debug-results">
<div class="debug-logs-header">
<span>操作结果({{ debugResults.length }})</span>
<button class="debug-btn debug-btn-sm" @click="clearDebugResults">清空</button>
</div>
<div
v-for="entry in debugResults"
:key="entry.id"
class="debug-log-entry"
:class="entry.success ? 'response' : 'error'"
>
<div class="debug-log-summary" @click="toggleResultExpand(entry.id)">
<span class="debug-log-badge">{{ entry.success ? '✅' : '❌' }}</span>
<span class="debug-log-time">{{ formatTime(entry.timestamp) }}</span>
<span class="debug-log-preview">{{ entry.label }}</span>
</div>
<div v-if="expandedResult === entry.id" class="debug-log-detail">
<div class="debug-log-meta">{{ entry.endpoint }}</div>
<pre class="debug-log-body">{{ entry.error || formatResultBody(entry.body) }}</pre>
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -204,8 +389,8 @@ const navToExperience = (id: string) => {
.debug-panel { .debug-panel {
position: fixed; position: fixed;
width: 380px; width: 420px;
max-height: 550px; max-height: 600px;
background: white; background: white;
border-radius: 12px; border-radius: 12px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2); box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
@ -281,6 +466,15 @@ const navToExperience = (id: string) => {
padding: 0.5rem 0; padding: 0.5rem 0;
} }
.debug-error {
color: #dc3545;
font-size: 0.8rem;
padding: 0.3rem 0.5rem;
background: #f8d7da;
border-radius: 4px;
margin-bottom: 0.4rem;
}
.debug-item { .debug-item {
padding: 0.6rem 0.75rem; padding: 0.6rem 0.75rem;
border: 1px solid #e9ecef; border: 1px solid #e9ecef;
@ -351,6 +545,11 @@ const navToExperience = (id: string) => {
background: #0056b3; background: #0056b3;
} }
.debug-btn:disabled {
background: #6c757d;
cursor: not-allowed;
}
.debug-btn-sm { .debug-btn-sm {
padding: 0.35rem 0.6rem; padding: 0.35rem 0.6rem;
font-size: 0.8rem; font-size: 0.8rem;
@ -360,6 +559,10 @@ const navToExperience = (id: string) => {
margin-top: 0.75rem; margin-top: 0.75rem;
} }
.debug-results {
margin-top: 0.75rem;
}
.debug-logs-header { .debug-logs-header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@ -370,6 +573,36 @@ const navToExperience = (id: string) => {
margin-bottom: 0.4rem; margin-bottom: 0.4rem;
} }
.debug-menu-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.45rem 0.5rem;
border: 1px solid #e9ecef;
border-radius: 6px;
margin-bottom: 0.3rem;
gap: 0.5rem;
}
.debug-menu-info {
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
}
.debug-menu-label {
font-size: 0.85rem;
font-weight: 600;
color: #333;
}
.debug-menu-desc {
font-size: 0.72rem;
color: #888;
margin-top: 0.1rem;
}
.debug-log-entry { .debug-log-entry {
border: 1px solid #eee; border: 1px solid #eee;
border-radius: 6px; border-radius: 6px;
@ -443,10 +676,10 @@ const navToExperience = (id: string) => {
.debug-log-body { .debug-log-body {
margin: 0; margin: 0;
font-size: 0.75rem; font-size: 0.72rem;
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-all; word-break: break-all;
max-height: 160px; max-height: 200px;
overflow-y: auto; overflow-y: auto;
background: #fff; background: #fff;
border: 1px solid #eee; border: 1px solid #eee;

查看文件

@ -3,6 +3,7 @@ import { computed, inject } from 'vue'
import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment' import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment'
import ExperimentGridCell from './ExperimentGridCell.vue' import ExperimentGridCell from './ExperimentGridCell.vue'
import { AIEvalContextKey } from '@/utils/aiEvalContext' import { AIEvalContextKey } from '@/utils/aiEvalContext'
import { renderTextWithLatex } from '@/utils/latex'
const props = defineProps<{ const props = defineProps<{
sheet: GridSheet sheet: GridSheet
@ -102,7 +103,7 @@ const isFirstRowHeader = computed(() => {
:key="hi" :key="hi"
class="grid-header-cell" class="grid-header-cell"
> >
<span v-html="header" /> <span v-html="renderTextWithLatex(header)" />
</th> </th>
</tr> </tr>
</thead> </thead>

查看文件

@ -1,23 +1,185 @@
<script lang="ts"> <script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ExperienceLoader } from '@/helper' import { ExperienceLoader } from '@/helper'
import { defineComponent, ref, type Ref } from 'vue' import router from '@/router'
import { type ExperienceMap } from '@/types/experience' import type { ExperienceType } from '@/types/experience'
export default defineComponent({ const experiences = ref<Record<string, ExperienceType>>({})
setup() {
const experiences: Ref<ExperienceMap> = ref({}) onMounted(async () => {
ExperienceLoader().then((v) => { const data = await ExperienceLoader()
experiences.value = v.experiences experiences.value = data.experiences
}) })
return {
experiences, const selectExperiment = (exp: ExperienceType) => {
router.push({ path: '/exp', query: { expid: exp.id } })
}
const expList = () => {
return Object.entries(experiences.value)
} }
},
})
</script> </script>
<template> <template>
<span v-for="(exp, name) in experiences"> <div class="select-page">
{{ name }} <div class="select-container">
<img :src="exp.image" /> <h1 class="page-title">AI+ 物理实验平台</h1>
<p class="page-subtitle">请选择实验项目</p>
<div class="experiment-grid">
<div
class="experiment-card"
v-for="[name, exp] in expList()"
:key="exp.id"
@click="selectExperiment(exp)"
>
<div class="card-image" v-if="exp.image">
<img :src="exp.image" :alt="exp.title" />
</div>
<div class="card-image placeholder" v-else>
<span class="placeholder-icon">🧪</span>
</div>
<div class="card-content">
<h2 class="card-title">{{ exp.title }}</h2>
<p class="card-author" v-if="exp.author">{{ exp.author }}</p>
<div class="card-stages">
<span
class="stage-tag"
v-for="stage in exp.stage"
:key="stage.name"
>
{{ stage.name }}
</span> </span>
</div>
</div>
</div>
</div>
<div class="footer">
<a @click="router.push('/login')" class="logout-link">退出登录</a>
</div>
</div>
</div>
</template> </template>
<style scoped>
.select-page {
min-height: 100vh;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
font-family: 'Helvetica Neue', Arial, sans-serif;
padding: 40px 20px;
box-sizing: border-box;
}
.select-container {
max-width: 1000px;
margin: 0 auto;
}
.page-title {
font-size: 2.2rem;
font-weight: bold;
color: #333;
text-align: center;
margin-bottom: 8px;
}
.page-subtitle {
font-size: 1.1rem;
color: #666;
text-align: center;
margin-bottom: 40px;
}
.experiment-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 24px;
}
.experiment-card {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
cursor: pointer;
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.experiment-card:hover {
transform: translateY(-6px);
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15);
}
.card-image {
width: 100%;
height: 180px;
overflow: hidden;
background: #e8ecf1;
display: flex;
align-items: center;
justify-content: center;
}
.card-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.card-image.placeholder {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.placeholder-icon {
font-size: 3rem;
}
.card-content {
padding: 20px;
}
.card-title {
font-size: 1.2rem;
font-weight: 600;
color: #222;
margin: 0 0 8px 0;
}
.card-author {
font-size: 0.85rem;
color: #888;
margin: 0 0 12px 0;
}
.card-stages {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.stage-tag {
display: inline-block;
padding: 3px 10px;
background: #e8f0fe;
color: #1a73e8;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
}
.footer {
text-align: center;
margin-top: 40px;
}
.logout-link {
color: #888;
font-size: 0.9rem;
cursor: pointer;
text-decoration: none;
transition: color 0.2s;
}
.logout-link:hover {
color: #e74c3c;
}
</style>

查看文件

@ -10,7 +10,7 @@ const DoLogin = async () => {
const [result, status] = await UserInfo.doLogin(InputSID.value, InputName.value) const [result, status] = await UserInfo.doLogin(InputSID.value, InputName.value)
if (result) { if (result) {
router.push({ router.push({
path: '/exp', path: '/select',
}) })
} else { } else {
TipsRef.value = status ? (status as string) : '登录失败' TipsRef.value = status ? (status as string) : '登录失败'