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