refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目
这个提交包含在:
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()
|
||||
在新工单中引用
屏蔽一个用户