feat: 加入了调试器
docs: 完善了文档
这个提交包含在:
@ -19,23 +19,28 @@ backend/
|
||||
│ └── _voice_speed.json # 旧版备份
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py # FastAPI 应用入口, CORS, 路由注册
|
||||
│ ├── main.py # FastAPI 应用入口, CORS, 启动示波器探针, 路由注册
|
||||
│ ├── models.py # 兼容性重导出 (实际定义在 schemas/)
|
||||
│ ├── schemas/ # Pydantic 数据模型
|
||||
│ │ ├── __init__.py # 统一导出
|
||||
│ │ ├── experiment.py # 网格实验配置模型 (GridSheet, GridCell...)
|
||||
│ │ └── validation.py # 验证请求/响应、测量分析模型
|
||||
│ │ └── validation.py # 验证请求/响应、测量分析、峰值监控模型
|
||||
│ ├── api/ # REST API 路由层
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── form.py # GET /form, /form/list — 加载实验配置
|
||||
│ │ ├── form.py # GET /form — 加载实验配置
|
||||
│ │ ├── value.py # POST/GET/DELETE /value — 字段值 CRUD + 验证
|
||||
│ │ ├── 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/ # 业务逻辑层
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── config_loader.py # ExperimentConfigService — 加载/验证 JSON 配置
|
||||
│ │ ├── dependencies.py # 服务单例 + 字段查找辅助函数
|
||||
│ │ ├── experiment_debug.py # ExperimentDebugProvider 抽象基类 + VoiceSpeedDebugProvider
|
||||
│ │ ├── measurement.py # MeasurementService — 声速实验统计算法
|
||||
│ │ ├── ocr_service.py # CaliperOCRService — 游标卡尺 OCR 识别 (模拟)
|
||||
│ │ ├── peak_detector.py # PeakDetector — 峰值检测状态机 (RISING/PEAK/COOLDOWN)
|
||||
│ │ ├── reading_guard.py # ReadingGuardManager — 读数顺序守卫 + 容差校验
|
||||
│ │ ├── session_store.py # SessionStore — 线程安全内存 KV 存储
|
||||
│ │ └── validation.py # FieldValidator — 基础字段校验 (数字/正则/必填)
|
||||
@ -61,7 +66,7 @@ backend/
|
||||
| 方法 | 路径 | 说明 |
|
||||
| ------ | ----------------------------------- | ------------------------ |
|
||||
| GET | `/` | 服务信息 + 端点列表 |
|
||||
| GET | `/health` | 健康检查 |
|
||||
| GET | `/health` | 健康检查 (含示波器状态) |
|
||||
| GET | `/form?experiment=voice_speed` | 加载实验网格配置 |
|
||||
| GET | `/form/list` | 列出可用实验 |
|
||||
| GET | `/form/{experiment_name}` | 按名称加载实验配置 |
|
||||
@ -73,6 +78,13 @@ backend/
|
||||
| GET | `/device/status` | 探针示波器状态 |
|
||||
| POST | `/device/peak` | 捕获峰值 |
|
||||
| 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}` | 分析测量数据 (声速计算) |
|
||||
|
||||
## 核心架构
|
||||
@ -117,7 +129,37 @@ POST /value { field_id, value }
|
||||
|
||||
- `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": "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` |
|
||||
| `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` 支持三种测量方法的统计算法:
|
||||
|
||||
123
backend/app/api/debug.py
普通文件
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("")
|
||||
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)
|
||||
return config.model_dump(by_alias=True)
|
||||
|
||||
|
||||
168
backend/app/api/peak_monitor.py
普通文件
168
backend/app/api/peak_monitor.py
普通文件
@ -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("")
|
||||
async def validate_field_value(
|
||||
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),
|
||||
) -> FieldValidationResponse:
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
|
||||
@ -16,7 +16,7 @@ class ExperimentConfigService:
|
||||
def _config_path(self, experiment_name: str) -> Path:
|
||||
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)
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
|
||||
@ -25,7 +25,7 @@ class ExperimentConfigService:
|
||||
except json.JSONDecodeError as 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)
|
||||
try:
|
||||
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())
|
||||
43
backend/app/core/ocr_service.py
普通文件
43
backend/app/core/ocr_service.py
普通文件
@ -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()
|
||||
124
backend/app/core/peak_detector.py
普通文件
124
backend/app/core/peak_detector.py
普通文件
@ -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
|
||||
source: ReadingGuardSource = ReadingGuardSource.MANUAL
|
||||
manual_answers: Dict[str, Any] = field(default_factory=dict)
|
||||
peak_ocr_answers: Dict[str, float] = field(default_factory=dict)
|
||||
|
||||
|
||||
class ReadingGuardManager:
|
||||
@ -29,6 +30,11 @@ class ReadingGuardManager:
|
||||
state = self._sessions.setdefault(session_id, GuardSessionState())
|
||||
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]:
|
||||
if source == ReadingGuardSource.DEVICE_PEAK:
|
||||
snapshot = oscilloscope_service.capture_peak()
|
||||
@ -48,6 +54,12 @@ class ReadingGuardManager:
|
||||
return None
|
||||
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
|
||||
|
||||
def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState:
|
||||
@ -64,7 +76,8 @@ class ReadingGuardManager:
|
||||
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.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
|
||||
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
|
||||
if state.source != ReadingGuardSource.PEAK_OCR:
|
||||
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
|
||||
return state
|
||||
|
||||
def _arm_next(self, state: GuardSessionState, fields_map: Dict[str, GridInputCell]) -> None:
|
||||
@ -78,7 +91,8 @@ class ReadingGuardManager:
|
||||
state.pending_field = next_field
|
||||
state.tolerance = config.tolerance if config else 0.0
|
||||
state.source = config.source if config else ReadingGuardSource.MANUAL
|
||||
state.pending_answer = self._capture_answer(state.source, next_field, state)
|
||||
if state.source != ReadingGuardSource.PEAK_OCR:
|
||||
state.pending_answer = self._capture_answer(state.source, next_field, state)
|
||||
|
||||
def validate(
|
||||
self,
|
||||
@ -100,8 +114,12 @@ class ReadingGuardManager:
|
||||
if current_field.fieldId != state.pending_field:
|
||||
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:
|
||||
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:
|
||||
student_value = float(current_value)
|
||||
@ -112,7 +130,7 @@ class ReadingGuardManager:
|
||||
if error > state.tolerance:
|
||||
return (
|
||||
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
|
||||
|
||||
@ -1,14 +1,3 @@
|
||||
from app.hardware.service import HardwareSnapshot, HardwareStatus, OscilloscopeService, oscilloscope_service
|
||||
from app.hardware.oscilloscope import Oscilloscope
|
||||
from app.hardware.progress import Commands, ExecuteCmdInDev, work
|
||||
|
||||
__all__ = [
|
||||
"HardwareSnapshot",
|
||||
"HardwareStatus",
|
||||
"OscilloscopeService",
|
||||
"oscilloscope_service",
|
||||
"Oscilloscope",
|
||||
"Commands",
|
||||
"ExecuteCmdInDev",
|
||||
"work",
|
||||
]
|
||||
__all__ = ["Oscilloscope"]
|
||||
|
||||
@ -68,15 +68,17 @@ class Oscilloscope:
|
||||
raise RuntimeError("未找到批量输入/输出端点")
|
||||
|
||||
def disconnect(self) -> None:
|
||||
"""断开设备并重新附加内核驱动(如果之前分离过)"""
|
||||
if self.device is None:
|
||||
return
|
||||
# 重新附加内核驱动
|
||||
for intf_num in self._attached_drivers:
|
||||
try:
|
||||
self.device.attach_kernel_driver(intf_num)
|
||||
except usb.core.USBError:
|
||||
pass # 忽略重新附加失败
|
||||
pass
|
||||
try:
|
||||
usb.util.dispose_resources(self.device)
|
||||
except Exception:
|
||||
pass
|
||||
self.device = None
|
||||
self.ep_out = None
|
||||
self.ep_in = None
|
||||
@ -154,4 +156,24 @@ class Oscilloscope:
|
||||
return self
|
||||
|
||||
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
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
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):
|
||||
IDLE = 0
|
||||
Waiting = 1
|
||||
|
||||
# 规范
|
||||
# CH1 接原始信号
|
||||
# CH2 接返回信号
|
||||
|
||||
class Commands(Enum):
|
||||
IDN = ('*IDN?', str)
|
||||
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)
|
||||
|
||||
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])
|
||||
ret = None
|
||||
if resp:
|
||||
parser = cmd.value[1]
|
||||
if parser is str:
|
||||
ret = resp.decode("ascii", errors="ignore")
|
||||
elif parser is bytes:
|
||||
ret = resp
|
||||
elif parser in (int, float):
|
||||
ret = parser(resp.decode("ascii", errors="ignore").strip())
|
||||
else:
|
||||
ret = parser(resp)
|
||||
return ret
|
||||
#
|
||||
if resp is None:
|
||||
return None
|
||||
|
||||
# 工作流程:
|
||||
# 发动本线程,
|
||||
# 进入空闲状态,
|
||||
# 等待用户指出
|
||||
parser = cmd.value[1]
|
||||
if parser is str:
|
||||
return resp.decode("ascii", errors="ignore").strip()
|
||||
if parser is bytes:
|
||||
return resp
|
||||
|
||||
def work(con:Connection):
|
||||
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
|
||||
|
||||
return parser(resp)
|
||||
|
||||
|
||||
def work(con: Connection) -> None:
|
||||
with Oscilloscope() as OWON:
|
||||
idn = ExecuteCmdInDev(OWON, Commands.IDN)
|
||||
if idn:
|
||||
@ -53,4 +68,4 @@ def work(con:Connection):
|
||||
|
||||
data = ExecuteCmdInDev(OWON, Commands.DATA_CH2)
|
||||
if data is not None:
|
||||
con.send({"status": Status.IDLE.name, "data": data})
|
||||
con.send({"status": Status.IDLE.name, "data": data})
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.hardware.oscilloscope import Oscilloscope
|
||||
from app.hardware.progress import Commands, ExecuteCmdInDev
|
||||
from .oscilloscope import Oscilloscope
|
||||
from .progress import Commands, ExecuteCmdInDev
|
||||
|
||||
|
||||
class HardwareStatus(str, Enum):
|
||||
@ -20,13 +21,16 @@ class HardwareStatus(str, Enum):
|
||||
class HardwareSnapshot:
|
||||
status: HardwareStatus
|
||||
device_idn: Optional[str] = None
|
||||
peak_value: Optional[int] = None
|
||||
peak_value: Optional[float] = None
|
||||
frequency_hz: Optional[float] = None
|
||||
raw_response: Optional[str] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class OscilloscopeService:
|
||||
RETRY_COUNT = 3
|
||||
RETRY_DELAY = 1.0
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._cached_status = HardwareStatus.OFFLINE
|
||||
|
||||
@ -37,30 +41,38 @@ class OscilloscopeService:
|
||||
raise HTTPException(status_code=503, detail=f"示波器初始化失败: {exc}") from exc
|
||||
|
||||
def probe(self) -> HardwareSnapshot:
|
||||
try:
|
||||
with self._open_device() as device:
|
||||
idn = ExecuteCmdInDev(device, Commands.IDN)
|
||||
peak_value = ExecuteCmdInDev(device, Commands.MEASU_CH2)
|
||||
frequency_hz = ExecuteCmdInDev(device, Commands.MEASU_CH1_FREQ)
|
||||
self._cached_status = HardwareStatus.ONLINE
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.ONLINE,
|
||||
device_idn=idn if isinstance(idn, str) else None,
|
||||
peak_value=peak_value if isinstance(peak_value, int) else None,
|
||||
frequency_hz=frequency_hz if isinstance(frequency_hz, float) else None,
|
||||
raw_response=idn if isinstance(idn, str) else None,
|
||||
note="已连接真实示波器",
|
||||
)
|
||||
except Exception as exc:
|
||||
self._cached_status = HardwareStatus.SIMULATED
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.SIMULATED,
|
||||
device_idn=None,
|
||||
peak_value=None,
|
||||
frequency_hz=None,
|
||||
raw_response=None,
|
||||
note=f"示波器不可用,已切换为模拟模式: {exc}",
|
||||
)
|
||||
last_error: Optional[Exception] = None
|
||||
for attempt in range(1, self.RETRY_COUNT + 1):
|
||||
try:
|
||||
with self._open_device() as device:
|
||||
idn = ExecuteCmdInDev(device, Commands.IDN)
|
||||
peak_value = ExecuteCmdInDev(device, Commands.MEASU_CH2)
|
||||
frequency_hz = ExecuteCmdInDev(device, Commands.MEASU_CH1_FREQ)
|
||||
self._cached_status = HardwareStatus.ONLINE
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.ONLINE,
|
||||
device_idn=idn if isinstance(idn, str) 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,
|
||||
raw_response=idn if isinstance(idn, str) else None,
|
||||
note="已连接真实示波器",
|
||||
)
|
||||
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
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.SIMULATED,
|
||||
device_idn=None,
|
||||
peak_value=None,
|
||||
frequency_hz=None,
|
||||
raw_response=None,
|
||||
note=f"示波器不可用,已切换为模拟模式: {last_error}",
|
||||
)
|
||||
|
||||
def capture_peak(self) -> HardwareSnapshot:
|
||||
snapshot = self.probe()
|
||||
@ -83,4 +95,12 @@ 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
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import uvicorn
|
||||
|
||||
from app.api.form import router as form_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.peak_monitor import router as peak_monitor_router
|
||||
from app.api.value import router as value_router
|
||||
from app.hardware.service import HardwareStatus, oscilloscope_service
|
||||
|
||||
_logger = logging.getLogger("main")
|
||||
|
||||
|
||||
App = FastAPI(
|
||||
@ -26,8 +33,20 @@ App.add_middleware(
|
||||
|
||||
App.include_router(form_router)
|
||||
App.include_router(device_router)
|
||||
App.include_router(debug_router)
|
||||
App.include_router(value_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("/")
|
||||
@ -44,7 +63,9 @@ async def root():
|
||||
"DELETE /value/{field_id}",
|
||||
"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}"],
|
||||
"system": ["GET /health"],
|
||||
},
|
||||
@ -53,7 +74,16 @@ async def root():
|
||||
|
||||
@App.get("/health")
|
||||
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__":
|
||||
|
||||
@ -13,10 +13,16 @@ from app.schemas.experiment import (
|
||||
from app.schemas.validation import (
|
||||
AnalyzeMeasurementRequest,
|
||||
AnalyzeMeasurementResponse,
|
||||
DebugMenuItem,
|
||||
DebugMenuResponse,
|
||||
DebugStatusResponse,
|
||||
FieldValidationRequest,
|
||||
FieldValidationResponse,
|
||||
ManualAnswerRequest,
|
||||
MeasurementMethod,
|
||||
PeakMonitorResponse,
|
||||
PeakMonitorStartRequest,
|
||||
PeakMonitorState,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@ -32,8 +38,14 @@ __all__ = [
|
||||
"ValidationType",
|
||||
"AnalyzeMeasurementRequest",
|
||||
"AnalyzeMeasurementResponse",
|
||||
"DebugMenuItem",
|
||||
"DebugMenuResponse",
|
||||
"DebugStatusResponse",
|
||||
"FieldValidationRequest",
|
||||
"FieldValidationResponse",
|
||||
"ManualAnswerRequest",
|
||||
"MeasurementMethod",
|
||||
"PeakMonitorResponse",
|
||||
"PeakMonitorStartRequest",
|
||||
"PeakMonitorState",
|
||||
]
|
||||
|
||||
@ -24,6 +24,7 @@ class ReadingGuardSource(str, Enum):
|
||||
DEVICE_PEAK = "device_peak"
|
||||
DEVICE_FREQUENCY = "device_frequency"
|
||||
MANUAL = "manual"
|
||||
PEAK_OCR = "peak_ocr"
|
||||
|
||||
|
||||
class ReadingGuardConfig(BaseModel):
|
||||
|
||||
@ -50,3 +50,48 @@ class AnalyzeMeasurementResponse(BaseModel):
|
||||
uncertainty_mps: Optional[float] = None
|
||||
theoretical_velocity_mps: Optional[float] = None
|
||||
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}}
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户