refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目
这个提交包含在:
65
backend/app/README.md
普通文件
65
backend/app/README.md
普通文件
@ -0,0 +1,65 @@
|
||||
# 物理实验后端(FastAPI)
|
||||
|
||||
该目录实现了与前端 `ExperimentForm` 对齐的后端 API,覆盖:
|
||||
|
||||
1. 实验配置下发(`/form`)
|
||||
2. 字段值验证与会话存储(`/value`)
|
||||
3. 声速实验三方法计算(`/measurement`)
|
||||
|
||||
## 架构概览
|
||||
|
||||
- `main.py`: FastAPI 入口、CORS、路由注册
|
||||
- `models.py`: 与前端协议对应的 Pydantic 模型
|
||||
- `api/form.py`: 实验表单配置接口
|
||||
- `api/value.py`: 字段值验证与会话数据接口
|
||||
- `api/measurement.py`: 驻波法/相位法/时差法计算接口
|
||||
- `core/config_loader.py`: 配置文件加载与校验
|
||||
- `core/validation.py`: 配置驱动字段验证
|
||||
- `core/session_store.py`: 内存会话态字段存储
|
||||
- `core/measurement.py`: 声速实验计算逻辑
|
||||
- `../config/experiments/*.json`: 实验配置文件
|
||||
|
||||
## 运行
|
||||
|
||||
在 `backend` 目录执行:
|
||||
|
||||
```bash
|
||||
uv run uvicorn main:app --app-dir src --reload --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
或直接:
|
||||
|
||||
```bash
|
||||
python src/main.py
|
||||
```
|
||||
|
||||
## 主要接口
|
||||
|
||||
1. `GET /form?experiment=voice_speed`
|
||||
2. `GET /form/list`
|
||||
3. `POST /value`
|
||||
4. `GET /value`
|
||||
5. `DELETE /value`
|
||||
6. `POST /measurement/{standing_wave|phase|time_diff}`
|
||||
7. `GET /health`
|
||||
|
||||
## 会话设计
|
||||
|
||||
- 通过请求头 `X-Session-Id` 区分不同学生/实验会话。
|
||||
- 未提供时使用默认会话 `default`。
|
||||
- 当前为内存存储,后续可替换为 Redis/数据库。
|
||||
|
||||
## 计算方法说明
|
||||
|
||||
- `standing_wave` / `phase`:
|
||||
- 输入 `cursor_readings_mm` 至少 10 个读数。
|
||||
- 使用“后五次减前五次”配对差统计平均值与不确定度。
|
||||
- 依据 `frequency_hz` 计算波长与声速。
|
||||
- `time_diff`:
|
||||
- 输入 `distance_readings_mm` 与 `time_deltas_us`,按组计算速度并求均值与标准差。
|
||||
|
||||
## 下一步建议
|
||||
|
||||
1. 将 `oscilloscope.py` 与 OCR 能力接入 `measurement` 路由。
|
||||
2. 将 `session_store` 升级为持久化存储。
|
||||
3. 增加 `pytest` 接口测试覆盖边界输入。
|
||||
1
backend/app/__init__.py
普通文件
1
backend/app/__init__.py
普通文件
@ -0,0 +1 @@
|
||||
#
|
||||
0
backend/app/api/__init__.py
普通文件
0
backend/app/api/__init__.py
普通文件
48
backend/app/api/device.py
普通文件
48
backend/app/api/device.py
普通文件
@ -0,0 +1,48 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
|
||||
from app.core.dependencies import reading_guard_manager, resolve_session_id
|
||||
from app.hardware.service import oscilloscope_service
|
||||
from app.models import ManualAnswerRequest
|
||||
|
||||
|
||||
router = APIRouter(prefix="/device", tags=["device"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def get_device_status():
|
||||
snapshot = oscilloscope_service.probe()
|
||||
return {
|
||||
"status": snapshot.status,
|
||||
"device_idn": snapshot.device_idn,
|
||||
"peak_value": snapshot.peak_value,
|
||||
"frequency_hz": snapshot.frequency_hz,
|
||||
"raw_response": snapshot.raw_response,
|
||||
"note": snapshot.note,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/peak")
|
||||
async def capture_peak_value():
|
||||
snapshot = oscilloscope_service.capture_peak()
|
||||
return {
|
||||
"status": snapshot.status,
|
||||
"peak_value": snapshot.peak_value,
|
||||
"note": snapshot.note,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/manual-answer")
|
||||
async def set_manual_answer(
|
||||
request: ManualAnswerRequest,
|
||||
x_session_id: str | None = Header(default=None),
|
||||
):
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
reading_guard_manager.set_manual_answer(session_id, request.field_id, request.value)
|
||||
return {
|
||||
"success": True,
|
||||
"session_id": session_id,
|
||||
"field_id": request.field_id,
|
||||
"message": "已设置该字段标准读数",
|
||||
}
|
||||
26
backend/app/api/form.py
普通文件
26
backend/app/api/form.py
普通文件
@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.core.dependencies import config_service
|
||||
|
||||
|
||||
router = APIRouter(prefix="/form", tags=["form"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_experiment_form(experiment: str = "voice_speed"):
|
||||
config = config_service.load_validated(experiment)
|
||||
return config.model_dump(by_alias=True)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def list_available_experiments():
|
||||
experiments = config_service.list_experiments()
|
||||
return {"experiments": experiments, "count": len(experiments)}
|
||||
|
||||
|
||||
@router.get("/{experiment_name}")
|
||||
async def get_specific_experiment_form(experiment_name: str):
|
||||
config = config_service.load_validated(experiment_name)
|
||||
return config.model_dump(by_alias=True)
|
||||
19
backend/app/api/measurement.py
普通文件
19
backend/app/api/measurement.py
普通文件
@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.core.dependencies import measurement_service
|
||||
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
|
||||
|
||||
|
||||
router = APIRouter(prefix="/measurement", tags=["measurement"])
|
||||
|
||||
|
||||
@router.post("/{method}")
|
||||
async def analyze_measurement(method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
|
||||
try:
|
||||
return measurement_service.analyze(method, payload)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
72
backend/app/api/value.py
普通文件
72
backend/app/api/value.py
普通文件
@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
|
||||
from app.core.dependencies import find_field, list_fields, reading_guard_manager, resolve_session_id, session_store
|
||||
from app.core.validation import FieldValidator
|
||||
from app.schemas.validation import FieldValidationRequest, FieldValidationResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/value", tags=["value"])
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def validate_field_value(
|
||||
request: FieldValidationRequest,
|
||||
experiment: str = Query(default="voice_speed"),
|
||||
x_session_id: str | None = Header(default=None),
|
||||
) -> FieldValidationResponse:
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
field = find_field(experiment, request.field_id)
|
||||
|
||||
base_result = FieldValidator.validate_by_config(request.field_id, request.value, field.validation)
|
||||
if not base_result.accept:
|
||||
return base_result
|
||||
|
||||
guard_result = reading_guard_manager.validate(
|
||||
session_id=session_id,
|
||||
current_field=field,
|
||||
current_value=request.value,
|
||||
all_fields=list_fields(experiment),
|
||||
)
|
||||
if guard_result is not None:
|
||||
guard_accept, guard_message = guard_result
|
||||
if not guard_accept:
|
||||
return FieldValidationResponse(accept=False, message=guard_message)
|
||||
session_store.set_value(session_id, request.field_id, request.value)
|
||||
return FieldValidationResponse(accept=True, message=guard_message)
|
||||
|
||||
session_store.set_value(session_id, request.field_id, request.value)
|
||||
return base_result
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_all_field_values(x_session_id: str | None = Header(default=None)):
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
fields = session_store.get_all(session_id)
|
||||
return {"fields": fields, "count": len(fields), "session_id": session_id}
|
||||
|
||||
|
||||
@router.get("/{field_id}")
|
||||
async def get_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
value = session_store.get_value(session_id, field_id)
|
||||
if value is None:
|
||||
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found or has no value")
|
||||
return {"field_id": field_id, "value": value, "session_id": session_id}
|
||||
|
||||
|
||||
@router.delete("/{field_id}")
|
||||
async def delete_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
ok = session_store.delete_value(session_id, field_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found")
|
||||
return {"message": f"field '{field_id}' value deleted", "success": True, "session_id": session_id}
|
||||
|
||||
|
||||
@router.delete("")
|
||||
async def clear_all_field_values(x_session_id: str | None = Header(default=None)):
|
||||
session_id = resolve_session_id(x_session_id)
|
||||
removed_count = session_store.clear(session_id)
|
||||
return {"message": f"cleared {removed_count} field values", "success": True, "session_id": session_id}
|
||||
0
backend/app/core/__init__.py
普通文件
0
backend/app/core/__init__.py
普通文件
@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.schemas.experiment import ExperimentGridConfig
|
||||
|
||||
|
||||
class ExperimentConfigService:
|
||||
def __init__(self, config_root: Path):
|
||||
self.config_root = config_root
|
||||
|
||||
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]:
|
||||
path = self._config_path(experiment_name)
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
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:
|
||||
payload = self.load_raw(experiment_name)
|
||||
try:
|
||||
return ExperimentGridConfig(**payload)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=f"config validation failed: {exc}") from exc
|
||||
|
||||
def list_experiments(self) -> List[Dict[str, str]]:
|
||||
if not self.config_root.exists():
|
||||
return []
|
||||
|
||||
result: List[Dict[str, str]] = []
|
||||
for file in sorted(self.config_root.glob("*.json")):
|
||||
try:
|
||||
payload = json.loads(file.read_text(encoding="utf-8"))
|
||||
result.append(
|
||||
{
|
||||
"name": file.stem,
|
||||
"title": payload.get("title", file.stem),
|
||||
"description": payload.get("description", ""),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
return result
|
||||
45
backend/app/core/dependencies.py
普通文件
45
backend/app/core/dependencies.py
普通文件
@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.core.config_loader import ExperimentConfigService
|
||||
from app.core.measurement import MeasurementService
|
||||
from app.core.reading_guard import reading_guard_manager
|
||||
from app.core.session_store import SessionStore
|
||||
from app.schemas.experiment import ExperimentGridConfig, GridInputCell
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
CONFIG_ROOT = BASE_DIR.parent / "config" / "experiments"
|
||||
|
||||
config_service = ExperimentConfigService(config_root=CONFIG_ROOT)
|
||||
session_store = SessionStore()
|
||||
measurement_service = MeasurementService()
|
||||
|
||||
|
||||
def _iter_input_cells(config: ExperimentGridConfig):
|
||||
for sheet in config.sheets:
|
||||
for row in sheet.cells:
|
||||
for cell in row:
|
||||
if isinstance(cell, GridInputCell):
|
||||
yield cell
|
||||
|
||||
|
||||
def find_field(experiment_name: str, field_id: str) -> GridInputCell:
|
||||
config = config_service.load_validated(experiment_name)
|
||||
for cell in _iter_input_cells(config):
|
||||
if cell.fieldId == field_id:
|
||||
return cell
|
||||
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found in experiment '{experiment_name}'")
|
||||
|
||||
|
||||
def list_fields(experiment_name: str) -> List[GridInputCell]:
|
||||
config = config_service.load_validated(experiment_name)
|
||||
return list(_iter_input_cells(config))
|
||||
|
||||
|
||||
def resolve_session_id(session_id: Optional[str]) -> str:
|
||||
return session_id or "default"
|
||||
90
backend/app/core/measurement.py
普通文件
90
backend/app/core/measurement.py
普通文件
@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
from typing import Dict, List
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
|
||||
|
||||
|
||||
class MeasurementService:
|
||||
@staticmethod
|
||||
def _theoretical_velocity(temperature_c: float | None) -> float | None:
|
||||
if temperature_c is None:
|
||||
return None
|
||||
return 331.3 * ((1.0 + temperature_c / 273.15) ** 0.5)
|
||||
|
||||
@staticmethod
|
||||
def _pairwise_deltas(readings_mm: List[float]) -> List[float]:
|
||||
if len(readings_mm) < 10:
|
||||
raise HTTPException(status_code=400, detail="standing wave / phase method requires at least 10 cursor readings")
|
||||
first5 = readings_mm[:5]
|
||||
last5 = readings_mm[5:10]
|
||||
return [b - a for a, b in zip(first5, last5)]
|
||||
|
||||
def analyze(self, method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
|
||||
if method in (MeasurementMethod.STANDING_WAVE, MeasurementMethod.PHASE):
|
||||
return self._analyze_wave_method(method, payload)
|
||||
if method == MeasurementMethod.TIME_DIFF:
|
||||
return self._analyze_time_diff(payload)
|
||||
raise HTTPException(status_code=400, detail="unsupported measurement method")
|
||||
|
||||
def _analyze_wave_method(
|
||||
self,
|
||||
method: MeasurementMethod,
|
||||
payload: AnalyzeMeasurementRequest,
|
||||
) -> AnalyzeMeasurementResponse:
|
||||
if payload.frequency_hz is None:
|
||||
raise HTTPException(status_code=400, detail="standing wave / phase method requires frequency_hz")
|
||||
|
||||
deltas = self._pairwise_deltas(payload.cursor_readings_mm)
|
||||
mean_delta_mm = statistics.mean(deltas)
|
||||
std_delta_mm = statistics.pstdev(deltas) if len(deltas) > 1 else 0.0
|
||||
|
||||
wavelength_m = (2.0 * mean_delta_mm) / 1000.0
|
||||
velocity = payload.frequency_hz * wavelength_m
|
||||
uncertainty = payload.frequency_hz * (2.0 * std_delta_mm / 1000.0)
|
||||
|
||||
return AnalyzeMeasurementResponse(
|
||||
method=method,
|
||||
sample_count=len(deltas),
|
||||
velocity_mps=velocity,
|
||||
wavelength_m=wavelength_m,
|
||||
uncertainty_mps=uncertainty,
|
||||
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
|
||||
details={
|
||||
"pair_deltas_mm": deltas,
|
||||
"mean_delta_mm": mean_delta_mm,
|
||||
"std_delta_mm": std_delta_mm,
|
||||
"note": "using pairwise difference (last 5 minus first 5)",
|
||||
},
|
||||
)
|
||||
|
||||
def _analyze_time_diff(self, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
|
||||
distances = payload.distance_readings_mm
|
||||
times = payload.time_deltas_us
|
||||
if len(distances) < 1 or len(times) < 1:
|
||||
raise HTTPException(status_code=400, detail="time diff method requires distance_readings_mm and time_deltas_us")
|
||||
if len(distances) != len(times):
|
||||
raise HTTPException(status_code=400, detail="distance_readings_mm and time_deltas_us must have same length")
|
||||
|
||||
velocities: List[float] = []
|
||||
for d_mm, t_us in zip(distances, times):
|
||||
if t_us <= 0:
|
||||
raise HTTPException(status_code=400, detail="time_deltas_us must be greater than 0")
|
||||
velocities.append((d_mm / 1000.0) / (t_us / 1_000_000.0))
|
||||
|
||||
mean_v = statistics.mean(velocities)
|
||||
std_v = statistics.pstdev(velocities) if len(velocities) > 1 else 0.0
|
||||
|
||||
return AnalyzeMeasurementResponse(
|
||||
method=MeasurementMethod.TIME_DIFF,
|
||||
sample_count=len(velocities),
|
||||
velocity_mps=mean_v,
|
||||
uncertainty_mps=std_v,
|
||||
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
|
||||
details={
|
||||
"single_velocity_mps": velocities,
|
||||
},
|
||||
)
|
||||
127
backend/app/core/reading_guard.py
普通文件
127
backend/app/core/reading_guard.py
普通文件
@ -0,0 +1,127 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.hardware.service import oscilloscope_service
|
||||
from app.schemas.experiment import GridInputCell, ReadingGuardSource
|
||||
|
||||
|
||||
@dataclass
|
||||
class GuardSessionState:
|
||||
strict_fields: List[str] = field(default_factory=list)
|
||||
cursor: int = 0
|
||||
pending_field: Optional[str] = None
|
||||
pending_answer: Optional[float] = None
|
||||
tolerance: float = 0.0
|
||||
source: ReadingGuardSource = ReadingGuardSource.MANUAL
|
||||
manual_answers: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
class ReadingGuardManager:
|
||||
def __init__(self) -> None:
|
||||
self._lock = Lock()
|
||||
self._sessions: Dict[str, GuardSessionState] = {}
|
||||
|
||||
def set_manual_answer(self, session_id: str, field_id: str, value: Any) -> None:
|
||||
with self._lock:
|
||||
state = self._sessions.setdefault(session_id, GuardSessionState())
|
||||
state.manual_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()
|
||||
if snapshot.peak_value is None:
|
||||
return None
|
||||
return float(snapshot.peak_value)
|
||||
|
||||
if source == ReadingGuardSource.DEVICE_FREQUENCY:
|
||||
snapshot = oscilloscope_service.capture_frequency()
|
||||
if snapshot.frequency_hz is None:
|
||||
return None
|
||||
return float(snapshot.frequency_hz)
|
||||
|
||||
if source == ReadingGuardSource.MANUAL:
|
||||
value = state.manual_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:
|
||||
state = self._sessions.setdefault(session_id, GuardSessionState())
|
||||
if not state.strict_fields:
|
||||
strict_fields = [
|
||||
f.fieldId
|
||||
for f in fields
|
||||
if f.readingGuard is not None and f.readingGuard.enabled
|
||||
]
|
||||
state.strict_fields = strict_fields
|
||||
if strict_fields:
|
||||
state.pending_field = 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.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
|
||||
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:
|
||||
if state.cursor >= len(state.strict_fields):
|
||||
state.pending_field = None
|
||||
state.pending_answer = None
|
||||
return
|
||||
|
||||
next_field = state.strict_fields[state.cursor]
|
||||
config = fields_map[next_field].readingGuard
|
||||
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)
|
||||
|
||||
def validate(
|
||||
self,
|
||||
session_id: str,
|
||||
current_field: GridInputCell,
|
||||
current_value: Any,
|
||||
all_fields: List[GridInputCell],
|
||||
) -> Optional[tuple[bool, str]]:
|
||||
state = self._ensure_initialized(session_id, all_fields)
|
||||
if not state.strict_fields:
|
||||
return None
|
||||
|
||||
if current_field.readingGuard is None or not current_field.readingGuard.enabled:
|
||||
return None
|
||||
|
||||
if state.pending_field is None:
|
||||
return True, "reading process completed"
|
||||
|
||||
if current_field.fieldId != state.pending_field:
|
||||
return False, f"should submit field {state.pending_field}, please follow experiment reading order"
|
||||
|
||||
if state.pending_answer is None:
|
||||
return False, "standard reading not yet captured, please retry"
|
||||
|
||||
try:
|
||||
student_value = float(current_value)
|
||||
except Exception:
|
||||
return False, "reading fields must be numeric"
|
||||
|
||||
error = abs(student_value - state.pending_answer)
|
||||
if error > state.tolerance:
|
||||
return (
|
||||
False,
|
||||
f"reading mismatch, expected {state.pending_answer:.6g}, tolerance ±{state.tolerance:.6g}, please re-enter",
|
||||
)
|
||||
|
||||
state.cursor += 1
|
||||
fields_map = {f.fieldId: f for f in all_fields}
|
||||
self._arm_next(state, fields_map)
|
||||
|
||||
if state.pending_field is None:
|
||||
return True, "reading correct, all reading steps completed"
|
||||
return True, f"reading correct, awaiting next: {state.pending_field}"
|
||||
|
||||
|
||||
reading_guard_manager = ReadingGuardManager()
|
||||
@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from threading import Lock
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self) -> None:
|
||||
self._lock = Lock()
|
||||
self._values: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
def set_value(self, session_id: str, field_id: str, value: Any) -> None:
|
||||
with self._lock:
|
||||
self._values.setdefault(session_id, {})[field_id] = value
|
||||
|
||||
def get_value(self, session_id: str, field_id: str) -> Any:
|
||||
return self._values.get(session_id, {}).get(field_id)
|
||||
|
||||
def get_all(self, session_id: str) -> Dict[str, Any]:
|
||||
return dict(self._values.get(session_id, {}))
|
||||
|
||||
def delete_value(self, session_id: str, field_id: str) -> bool:
|
||||
with self._lock:
|
||||
bucket = self._values.get(session_id)
|
||||
if not bucket or field_id not in bucket:
|
||||
return False
|
||||
del bucket[field_id]
|
||||
return True
|
||||
|
||||
def clear(self, session_id: str) -> int:
|
||||
with self._lock:
|
||||
count = len(self._values.get(session_id, {}))
|
||||
self._values[session_id] = {}
|
||||
return count
|
||||
53
backend/app/core/validation.py
普通文件
53
backend/app/core/validation.py
普通文件
@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.schemas.experiment import ValidationConfig, ValidationType
|
||||
from app.schemas.validation import FieldValidationResponse
|
||||
|
||||
|
||||
class FieldValidator:
|
||||
@staticmethod
|
||||
def _as_float(value: Any) -> float:
|
||||
if isinstance(value, str) and value.strip() == "":
|
||||
raise ValueError("empty value")
|
||||
return float(value)
|
||||
|
||||
@classmethod
|
||||
def validate_by_config(
|
||||
cls,
|
||||
field_id: str,
|
||||
value: Any,
|
||||
config: ValidationConfig | None,
|
||||
) -> FieldValidationResponse:
|
||||
if config is None:
|
||||
return FieldValidationResponse(accept=True, message="validation passed")
|
||||
|
||||
if config.required and (value is None or (isinstance(value, str) and value.strip() == "")):
|
||||
return FieldValidationResponse(accept=False, message=f"field {field_id} is required")
|
||||
|
||||
if value is None:
|
||||
return FieldValidationResponse(accept=True, message="validation passed")
|
||||
|
||||
if config.type == ValidationType.NUMBER:
|
||||
try:
|
||||
num = cls._as_float(value)
|
||||
except Exception:
|
||||
return FieldValidationResponse(accept=False, message="please enter a valid number")
|
||||
if config.min is not None and num < config.min:
|
||||
return FieldValidationResponse(accept=False, message=f"value cannot be less than {config.min}")
|
||||
if config.max is not None and num > config.max:
|
||||
return FieldValidationResponse(accept=False, message=f"value cannot be greater than {config.max}")
|
||||
if math.isnan(num) or math.isinf(num):
|
||||
return FieldValidationResponse(accept=False, message="invalid numeric value")
|
||||
return FieldValidationResponse(accept=True, message="validation passed")
|
||||
|
||||
if config.type == ValidationType.REGEX and config.pattern is not None:
|
||||
text = str(value)
|
||||
if re.fullmatch(config.pattern, text) is None:
|
||||
return FieldValidationResponse(accept=False, message="field format mismatch")
|
||||
return FieldValidationResponse(accept=True, message="validation passed")
|
||||
|
||||
return FieldValidationResponse(accept=True, message="validation passed")
|
||||
100
backend/app/exp.md
普通文件
100
backend/app/exp.md
普通文件
@ -0,0 +1,100 @@
|
||||
# 声速测量实验
|
||||
|
||||
## 频率测量
|
||||
|
||||
通过示波器读取原始波形通道即可直接测量,
|
||||
学生读数五次,取平均
|
||||
|
||||
## 测量温度
|
||||
|
||||
通过温度计测量声速,输入一次
|
||||
根据公式计算理论声速
|
||||
|
||||
## 三个方法
|
||||
|
||||
### 驻波法
|
||||
|
||||
获取示波器两个通道的图像,主要是接受波通道
|
||||
|
||||
```
|
||||
:MEASUrement:CH<n>:<items>?
|
||||
功能描述
|
||||
获取通道测量项的值。
|
||||
参数
|
||||
名称
|
||||
类型
|
||||
范围
|
||||
默认值
|
||||
<n>
|
||||
离散型
|
||||
{1|2}
|
||||
1
|
||||
{MAX|MIN|PKPK|VTOP|VBASe|VAMP|AVERage|
|
||||
SQUAresum|CYCRms| CURSorrms|
|
||||
OVERShoot|PREShoot|PERiod|
|
||||
FREQuency|RTime|FTime|PWIDth|NWIDth|
|
||||
<items>
|
||||
离散型
|
||||
--
|
||||
PDUTy|NDUTy|SCREenduty|FRR|FRF|FFR|FFF|
|
||||
LRR|LRF|LFR|LFF|RDELay|FDELay|RPHAse|
|
||||
PPULsenum|NPULsenum|RISEedgenum|
|
||||
FALLedgenum|AREA|CYCLearea|HARDfrequency}
|
||||
参数注释
|
||||
Items(电压)
|
||||
注释
|
||||
Items(时间)
|
||||
注释
|
||||
MAX
|
||||
最大值
|
||||
PERiod
|
||||
周期
|
||||
MIN
|
||||
最小值
|
||||
FREQuency
|
||||
频率
|
||||
PKPK
|
||||
峰峰值
|
||||
RTime
|
||||
上升时间
|
||||
VTOP
|
||||
顶端值
|
||||
FTime
|
||||
下降时间
|
||||
VBASe
|
||||
底端值
|
||||
PWIDth
|
||||
正脉宽
|
||||
VAMP
|
||||
幅度
|
||||
NWIDth
|
||||
负脉宽
|
||||
AVERage
|
||||
平均值
|
||||
PDUTy
|
||||
正占空比
|
||||
SQUAresum
|
||||
均方根值
|
||||
NDUTy
|
||||
负占空比
|
||||
CYCRms
|
||||
周期均方根
|
||||
SCREenduty
|
||||
屏幕脉宽比
|
||||
CURSorrms
|
||||
游标均方根
|
||||
```
|
||||
|
||||
用MEASure命令测量峰值,同时截图,在峰值发生下降时将前一个图(即最高点)时游标卡尺读数送入OCR获取游标卡尺读数
|
||||
总共测十次,后五次减去前五次作差取平均算不确定度,在频率已知的情况下即可获取到声速
|
||||
|
||||
### 相位法
|
||||
|
||||
在表现上使用XY模式观测李萨如图形,但是在示波器端实现和前者没有区别,只是学生端看起来不一样
|
||||
也测量十次
|
||||
|
||||
### 时差法
|
||||
|
||||
分析读出的波形,接着计量CH1起始点到CH2起始点的时间之差(学生端使用示波器光标模式,程序端其实是找到两个波形的起始点)
|
||||
学生需要填写游标卡尺数据(程序用截图+OCR)
|
||||
测十次
|
||||
5
backend/app/form.json
普通文件
5
backend/app/form.json
普通文件
@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta":{
|
||||
"author":"AI+物理实验"
|
||||
}
|
||||
}
|
||||
14
backend/app/hardware/__init__.py
普通文件
14
backend/app/hardware/__init__.py
普通文件
@ -0,0 +1,14 @@
|
||||
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",
|
||||
]
|
||||
157
backend/app/hardware/oscilloscope.py
普通文件
157
backend/app/hardware/oscilloscope.py
普通文件
@ -0,0 +1,157 @@
|
||||
import usb.core
|
||||
import usb.util
|
||||
from typing import Optional, Tuple
|
||||
|
||||
class Oscilloscope:
|
||||
"""基于PyUSB的通用示波器SCPI协议类,支持批量端点通信"""
|
||||
|
||||
DEFAULT_VID = 0x5345
|
||||
DEFAULT_PID = 0x1234
|
||||
DEFAULT_TIMEOUT_MS = 3000
|
||||
MAX_PACKET_SIZE = 512 # 通常批量端点最大包大小,实际会从设备读取
|
||||
|
||||
def __init__(self, vid: int = DEFAULT_VID, pid: int = DEFAULT_PID):
|
||||
"""
|
||||
初始化示波器对象,但不立即连接。
|
||||
:param vid: USB Vendor ID
|
||||
:param pid: USB Product ID
|
||||
"""
|
||||
self.vid = vid
|
||||
self.pid = pid
|
||||
self.device: Optional[usb.core.Device] = None
|
||||
self.ep_out: Optional[usb.core.Endpoint] = None
|
||||
self.ep_in: Optional[usb.core.Endpoint] = None
|
||||
self._attached_drivers = [] # 记录分离的内核驱动接口
|
||||
|
||||
def connect(self) -> None:
|
||||
"""连接USB设备,配置端点,准备通信"""
|
||||
# 1. 查找设备
|
||||
dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
|
||||
if dev is None:
|
||||
raise RuntimeError(f"设备未找到 (VID={self.vid:04x}, PID={self.pid:04x})")
|
||||
if isinstance(dev, usb.core.Device):
|
||||
self.device = dev
|
||||
else:
|
||||
raise TypeError("No Device Found")
|
||||
|
||||
# 2. 分离内核驱动(若占用)
|
||||
try:
|
||||
cfg = self.device.get_active_configuration()
|
||||
for intf in cfg:
|
||||
if self.device.is_kernel_driver_active(intf.bInterfaceNumber):
|
||||
self.device.detach_kernel_driver(intf.bInterfaceNumber)
|
||||
self._attached_drivers.append(intf.bInterfaceNumber)
|
||||
except Exception as E:
|
||||
raise E
|
||||
|
||||
# 3. 设置配置(通常第一个配置即可)
|
||||
try:
|
||||
self.device.set_configuration()
|
||||
except usb.core.USBError as e:
|
||||
raise RuntimeError(f"设置USB配置失败: {e}")
|
||||
|
||||
# 4. 获取批量输入/输出端点(默认接口0,备用设置0)
|
||||
try:
|
||||
intf = self.device.get_active_configuration()[(0, 0)] #type:ignore
|
||||
except KeyError:
|
||||
raise RuntimeError("未找到接口 (0,0)")
|
||||
|
||||
self.ep_out = None
|
||||
self.ep_in = None
|
||||
for ep in intf:
|
||||
if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT and isinstance(ep, usb.core.Endpoint):
|
||||
self.ep_out = ep
|
||||
elif usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN and isinstance(ep, usb.core.Endpoint):
|
||||
self.ep_in = ep
|
||||
|
||||
if not self.ep_out or not self.ep_in:
|
||||
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 # 忽略重新附加失败
|
||||
self.device = None
|
||||
self.ep_out = None
|
||||
self.ep_in = None
|
||||
self._attached_drivers.clear()
|
||||
|
||||
def send_command_raw(self, cmd: bytes, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
|
||||
"""
|
||||
发送SCPI命令并返回响应数据。
|
||||
:param cmd: SCPI命令字符串(会自动添加换行符)
|
||||
:param timeout: 超时时间(毫秒)
|
||||
:return: 响应字节数据,若失败则返回None
|
||||
"""
|
||||
if self.device is None or self.ep_out is None or self.ep_in is None:
|
||||
raise RuntimeError("设备未连接,请先调用connect()")
|
||||
|
||||
# 发送命令
|
||||
try:
|
||||
# self.device.write(self.ep_out.bEndpointAddress, cmd_bytes, timeout=timeout)
|
||||
self.device.write(self.ep_out, cmd, timeout=timeout)
|
||||
# self.ep_out.write(cmd_bytes, timeout)
|
||||
except usb.core.USBError as e:
|
||||
print(f"发送命令失败: {e}")
|
||||
return None
|
||||
|
||||
# 读取响应(直到超时或收到短包)
|
||||
response = b''
|
||||
max_packet = self.ep_in.wMaxPacketSize # type: ignore
|
||||
while True:
|
||||
try:
|
||||
# data = self.device.read(self.ep_in.bEndpointAddress, max_packet, timeout=timeout)
|
||||
data = self.device.read(self.ep_in, max_packet, timeout=timeout)
|
||||
if not data:
|
||||
break
|
||||
response += data.tobytes()
|
||||
if len(data) < max_packet:
|
||||
break
|
||||
except usb.core.USBError as e:
|
||||
if e.errno == 110: # 超时,表示没有更多数据
|
||||
break
|
||||
else:
|
||||
print(f"读取响应失败: {e}")
|
||||
return None
|
||||
return response
|
||||
|
||||
def send_command(self, cmd: str, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
|
||||
"""
|
||||
发送SCPI命令并返回响应数据。
|
||||
:param cmd: SCPI命令字符串(会自动添加换行符)
|
||||
:param timeout: 超时时间(毫秒)
|
||||
:return: 响应字节数据,若失败则返回None
|
||||
"""
|
||||
if self.device is None or self.ep_out is None or self.ep_in is None:
|
||||
raise RuntimeError("设备未连接,请先调用connect()")
|
||||
|
||||
# 确保命令以换行结尾
|
||||
if not cmd.endswith('\n'):
|
||||
cmd += '\n'
|
||||
cmd_bytes = cmd.encode('ascii')
|
||||
|
||||
return self.send_command_raw(cmd_bytes, timeout)
|
||||
|
||||
|
||||
# 可选:提供原始端点访问属性
|
||||
@property
|
||||
def out_endpoint(self) -> Optional[usb.core.Endpoint]:
|
||||
return self.ep_out
|
||||
|
||||
@property
|
||||
def in_endpoint(self) -> Optional[usb.core.Endpoint]:
|
||||
return self.ep_in
|
||||
|
||||
# 支持上下文管理器(with语句)
|
||||
def __enter__(self):
|
||||
self.connect()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.disconnect()
|
||||
56
backend/app/hardware/progress.py
普通文件
56
backend/app/hardware/progress.py
普通文件
@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from multiprocessing.connection import Connection
|
||||
from typing import Optional
|
||||
|
||||
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)
|
||||
DATA_CH2 = (':DATA:WAVE:SCREen:CH2?', bytes)
|
||||
|
||||
def ExecuteCmdInDev(dev:Oscilloscope, cmd:Commands):
|
||||
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
|
||||
#
|
||||
|
||||
# 工作流程:
|
||||
# 发动本线程,
|
||||
# 进入空闲状态,
|
||||
# 等待用户指出
|
||||
|
||||
def work(con:Connection):
|
||||
with Oscilloscope() as OWON:
|
||||
idn = ExecuteCmdInDev(OWON, Commands.IDN)
|
||||
if idn:
|
||||
print(idn)
|
||||
|
||||
peak = ExecuteCmdInDev(OWON, Commands.MEASU_CH2)
|
||||
if peak is not None:
|
||||
con.send({"status": Status.Waiting.name, "peak": peak, "idn": idn})
|
||||
|
||||
data = ExecuteCmdInDev(OWON, Commands.DATA_CH2)
|
||||
if data is not None:
|
||||
con.send({"status": Status.IDLE.name, "data": data})
|
||||
86
backend/app/hardware/service.py
普通文件
86
backend/app/hardware/service.py
普通文件
@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
|
||||
|
||||
class HardwareStatus(str, Enum):
|
||||
ONLINE = "online"
|
||||
OFFLINE = "offline"
|
||||
SIMULATED = "simulated"
|
||||
|
||||
|
||||
@dataclass
|
||||
class HardwareSnapshot:
|
||||
status: HardwareStatus
|
||||
device_idn: Optional[str] = None
|
||||
peak_value: Optional[int] = None
|
||||
frequency_hz: Optional[float] = None
|
||||
raw_response: Optional[str] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class OscilloscopeService:
|
||||
def __init__(self) -> None:
|
||||
self._cached_status = HardwareStatus.OFFLINE
|
||||
|
||||
def _open_device(self) -> Oscilloscope:
|
||||
try:
|
||||
return Oscilloscope()
|
||||
except Exception as exc:
|
||||
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}",
|
||||
)
|
||||
|
||||
def capture_peak(self) -> HardwareSnapshot:
|
||||
snapshot = self.probe()
|
||||
if snapshot.status == HardwareStatus.ONLINE:
|
||||
return snapshot
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.SIMULATED,
|
||||
peak_value=None,
|
||||
note="当前没有连接示波器,返回模拟峰值",
|
||||
)
|
||||
|
||||
def capture_frequency(self) -> HardwareSnapshot:
|
||||
snapshot = self.probe()
|
||||
if snapshot.status == HardwareStatus.ONLINE:
|
||||
return snapshot
|
||||
return HardwareSnapshot(
|
||||
status=HardwareStatus.SIMULATED,
|
||||
frequency_hz=None,
|
||||
note="当前没有连接示波器,无法读取实时频率",
|
||||
)
|
||||
|
||||
|
||||
oscilloscope_service = OscilloscopeService()
|
||||
60
backend/app/main.py
普通文件
60
backend/app/main.py
普通文件
@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
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.measurement import router as measurement_router
|
||||
from app.api.value import router as value_router
|
||||
|
||||
|
||||
App = FastAPI(
|
||||
title="Physics Experiment Backend",
|
||||
description="Backend service for experiment forms, field validation, and sound velocity calculations",
|
||||
version="1.0.0",
|
||||
)
|
||||
|
||||
App.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
App.include_router(form_router)
|
||||
App.include_router(device_router)
|
||||
App.include_router(value_router)
|
||||
App.include_router(measurement_router)
|
||||
|
||||
|
||||
@App.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"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"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@App.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy", "service": "physics-experiment-backend"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="info")
|
||||
39
backend/app/models.py
普通文件
39
backend/app/models.py
普通文件
@ -0,0 +1,39 @@
|
||||
from app.schemas.experiment import (
|
||||
ExperimentGridConfig,
|
||||
GridCell,
|
||||
GridComputedCell,
|
||||
GridInputCell,
|
||||
GridLabelCell,
|
||||
GridSheet,
|
||||
ReadingGuardConfig,
|
||||
ReadingGuardSource,
|
||||
ValidationConfig,
|
||||
ValidationType,
|
||||
)
|
||||
from app.schemas.validation import (
|
||||
AnalyzeMeasurementRequest,
|
||||
AnalyzeMeasurementResponse,
|
||||
FieldValidationRequest,
|
||||
FieldValidationResponse,
|
||||
ManualAnswerRequest,
|
||||
MeasurementMethod,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ExperimentGridConfig",
|
||||
"GridCell",
|
||||
"GridComputedCell",
|
||||
"GridInputCell",
|
||||
"GridLabelCell",
|
||||
"GridSheet",
|
||||
"ReadingGuardConfig",
|
||||
"ReadingGuardSource",
|
||||
"ValidationConfig",
|
||||
"ValidationType",
|
||||
"AnalyzeMeasurementRequest",
|
||||
"AnalyzeMeasurementResponse",
|
||||
"FieldValidationRequest",
|
||||
"FieldValidationResponse",
|
||||
"ManualAnswerRequest",
|
||||
"MeasurementMethod",
|
||||
]
|
||||
9
backend/app/out.pyi
普通文件
9
backend/app/out.pyi
普通文件
@ -0,0 +1,9 @@
|
||||
import numbers
|
||||
|
||||
def get_number(path:str) -> numbers.Number:
|
||||
"""从一个图像文件中使用OCR技术提取数字并返回。"""
|
||||
pass
|
||||
|
||||
def capture_image() -> str:
|
||||
"""捕获图像并保存到文件系统中,返回图像文件的路径。"""
|
||||
pass
|
||||
39
backend/app/schemas/__init__.py
普通文件
39
backend/app/schemas/__init__.py
普通文件
@ -0,0 +1,39 @@
|
||||
from app.schemas.experiment import (
|
||||
ExperimentGridConfig,
|
||||
GridCell,
|
||||
GridComputedCell,
|
||||
GridInputCell,
|
||||
GridLabelCell,
|
||||
GridSheet,
|
||||
ReadingGuardConfig,
|
||||
ReadingGuardSource,
|
||||
ValidationConfig,
|
||||
ValidationType,
|
||||
)
|
||||
from app.schemas.validation import (
|
||||
AnalyzeMeasurementRequest,
|
||||
AnalyzeMeasurementResponse,
|
||||
FieldValidationRequest,
|
||||
FieldValidationResponse,
|
||||
ManualAnswerRequest,
|
||||
MeasurementMethod,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ExperimentGridConfig",
|
||||
"GridCell",
|
||||
"GridComputedCell",
|
||||
"GridInputCell",
|
||||
"GridLabelCell",
|
||||
"GridSheet",
|
||||
"ReadingGuardConfig",
|
||||
"ReadingGuardSource",
|
||||
"ValidationConfig",
|
||||
"ValidationType",
|
||||
"AnalyzeMeasurementRequest",
|
||||
"AnalyzeMeasurementResponse",
|
||||
"FieldValidationRequest",
|
||||
"FieldValidationResponse",
|
||||
"ManualAnswerRequest",
|
||||
"MeasurementMethod",
|
||||
]
|
||||
@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import Any, List, Literal, Optional, Union
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ValidationType(str, Enum):
|
||||
NUMBER = "number"
|
||||
TEXT = "text"
|
||||
REGEX = "regex"
|
||||
|
||||
|
||||
class ValidationConfig(BaseModel):
|
||||
type: ValidationType
|
||||
min: Optional[float] = None
|
||||
max: Optional[float] = None
|
||||
pattern: Optional[str] = None
|
||||
required: bool = False
|
||||
|
||||
|
||||
class ReadingGuardSource(str, Enum):
|
||||
DEVICE_PEAK = "device_peak"
|
||||
DEVICE_FREQUENCY = "device_frequency"
|
||||
MANUAL = "manual"
|
||||
|
||||
|
||||
class ReadingGuardConfig(BaseModel):
|
||||
enabled: bool = False
|
||||
source: ReadingGuardSource = ReadingGuardSource.MANUAL
|
||||
tolerance: float = 0.0
|
||||
|
||||
|
||||
class GridLabelCell(BaseModel):
|
||||
type: Literal["label"] = "label"
|
||||
content: str
|
||||
colSpan: Optional[int] = None
|
||||
rowSpan: Optional[int] = None
|
||||
style: Optional[str] = None
|
||||
|
||||
|
||||
class GridInputCell(BaseModel):
|
||||
type: Literal["input"] = "input"
|
||||
fieldId: str
|
||||
placeholder: Optional[str] = None
|
||||
unit: Optional[str] = None
|
||||
colSpan: Optional[int] = None
|
||||
rowSpan: Optional[int] = None
|
||||
validation: Optional[ValidationConfig] = None
|
||||
readingGuard: Optional[ReadingGuardConfig] = None
|
||||
defaultValue: Optional[Any] = None
|
||||
|
||||
|
||||
class GridComputedCell(BaseModel):
|
||||
type: Literal["computed"] = "computed"
|
||||
areaId: str
|
||||
expression: str
|
||||
variables: List[str] = Field(default_factory=list)
|
||||
format: Optional[str] = None
|
||||
colSpan: Optional[int] = None
|
||||
rowSpan: Optional[int] = None
|
||||
|
||||
|
||||
GridCell = Union[GridLabelCell, GridInputCell, GridComputedCell]
|
||||
|
||||
|
||||
class GridSheet(BaseModel):
|
||||
id: str
|
||||
title: Optional[str] = None
|
||||
columns: int
|
||||
columnHeaders: Optional[List[str]] = None
|
||||
columnWidths: Optional[List[str]] = None
|
||||
rowHeaders: Optional[List[str]] = None
|
||||
cells: List[List[Optional[GridCell]]]
|
||||
|
||||
|
||||
class ExperimentGridConfig(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
sheets: List[GridSheet]
|
||||
@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
|
||||
class FieldValidationRequest(BaseModel):
|
||||
field_id: str
|
||||
value: Any
|
||||
|
||||
|
||||
class FieldValidationResponse(BaseModel):
|
||||
accept: bool
|
||||
message: str
|
||||
|
||||
|
||||
class ManualAnswerRequest(BaseModel):
|
||||
field_id: str
|
||||
value: Any
|
||||
|
||||
|
||||
class MeasurementMethod(str, Enum):
|
||||
STANDING_WAVE = "standing_wave"
|
||||
PHASE = "phase"
|
||||
TIME_DIFF = "time_diff"
|
||||
|
||||
|
||||
class AnalyzeMeasurementRequest(BaseModel):
|
||||
frequency_hz: Optional[float] = Field(default=None, gt=0)
|
||||
temperature_c: Optional[float] = None
|
||||
cursor_readings_mm: List[float] = Field(default_factory=list)
|
||||
distance_readings_mm: List[float] = Field(default_factory=list)
|
||||
time_deltas_us: List[float] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ensure_enough_data(self) -> "AnalyzeMeasurementRequest":
|
||||
total = len(self.cursor_readings_mm) + len(self.distance_readings_mm) + len(self.time_deltas_us)
|
||||
if total == 0:
|
||||
raise ValueError("at least one set of measurement data required")
|
||||
return self
|
||||
|
||||
|
||||
class AnalyzeMeasurementResponse(BaseModel):
|
||||
method: MeasurementMethod
|
||||
sample_count: int
|
||||
velocity_mps: Optional[float] = None
|
||||
wavelength_m: Optional[float] = None
|
||||
uncertainty_mps: Optional[float] = None
|
||||
theoretical_velocity_mps: Optional[float] = None
|
||||
details: Dict[str, Any] = Field(default_factory=dict)
|
||||
在新工单中引用
屏蔽一个用户