feat: 加入了调试器
docs: 完善了文档
这个提交包含在:
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
|
||||
|
||||
在新工单中引用
屏蔽一个用户