xusbcan-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- xusbcan/__init__.py +7 -0
- xusbcan/adapters/__init__.py +1 -0
- xusbcan/adapters/registry.py +88 -0
- xusbcan/adapters/zlg/__init__.py +23 -0
- xusbcan/adapters/zlg/backend.py +225 -0
- xusbcan/adapters/zlg/device_pool.py +94 -0
- xusbcan/adapters/zlg/dll.py +192 -0
- xusbcan/cli/__init__.py +1 -0
- xusbcan/cli/__main__.py +6 -0
- xusbcan/cli/app.py +106 -0
- xusbcan/config/__init__.py +5 -0
- xusbcan/config/loader.py +78 -0
- xusbcan/core/__init__.py +50 -0
- xusbcan/core/commands.py +270 -0
- xusbcan/core/monitor.py +178 -0
- xusbcan/core/periodic.py +72 -0
- xusbcan/core/session.py +282 -0
- xusbcan/mcp/__init__.py +1 -0
- xusbcan/mcp/server.py +41 -0
- xusbcan/mcp/tools.py +90 -0
- xusbcan/models/__init__.py +14 -0
- xusbcan/models/device.py +27 -0
- xusbcan/models/frame.py +68 -0
- xusbcan/models/result.py +95 -0
- xusbcan_cli-0.1.0.dist-info/METADATA +152 -0
- xusbcan_cli-0.1.0.dist-info/RECORD +29 -0
- xusbcan_cli-0.1.0.dist-info/WHEEL +5 -0
- xusbcan_cli-0.1.0.dist-info/entry_points.txt +6 -0
- xusbcan_cli-0.1.0.dist-info/top_level.txt +1 -0
xusbcan/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""适配层:唯一接触厂商 SDK 的地方。上层只通过 registry 访问,不 import 厂商代码。"""
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""单一适配链路:DeviceSpec → registry → can.Bus。
|
|
2
|
+
|
|
3
|
+
zlg 是 python-can 的自定义 interface,经 entry point 注册,与官方 backend 地位平等。
|
|
4
|
+
本模块模块级不 import adapters.zlg,保证 Linux 上可导入(virtual 后端测试可运行)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
import can
|
|
13
|
+
|
|
14
|
+
from ..models.device import DeviceSpec
|
|
15
|
+
from ..models.result import ErrorCode, Result
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Profile:
|
|
20
|
+
"""(vendor, model) → backend 的映射。options 是 backend 专属选项,进 can.Bus kwargs。"""
|
|
21
|
+
|
|
22
|
+
interface: str # python-can interface 名
|
|
23
|
+
channels: int = 1 # 通道数(能力查询 + 越界检查)
|
|
24
|
+
fd: bool = False # 是否支持 CAN FD
|
|
25
|
+
channel_map: Callable[[int], int | str] | None = None # 逻辑通道号 → 厂商通道地址
|
|
26
|
+
options: dict | None = None # backend 专属选项(不混入厂商联合体)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# 注意:周立功手册的 "CANalyst-II+" 走 zlgcan;python-can 官方 canalystii(创芯
|
|
30
|
+
# CANalyst-II)是否覆盖它尚未证实,暂不把创芯卡列为「改配置即可」。
|
|
31
|
+
PROFILES: dict[tuple[str, str], Profile] = {
|
|
32
|
+
("zlg", "USBCAN-2E-U"): Profile(
|
|
33
|
+
"zlg", channels=2, fd=False, options={"device_type": 21, "device_index": 0}
|
|
34
|
+
),
|
|
35
|
+
("peak", "PCAN-USB"): Profile("pcan", channel_map=lambda n: f"PCAN_USBBUS{n + 1}"),
|
|
36
|
+
("vector", "VN1630"): Profile("vector"),
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def resolve(spec: DeviceSpec) -> Profile:
|
|
41
|
+
"""按 (vendor, model) 查 Profile。找不到抛 KeyError,由调用方转 CONFIG_ERROR。"""
|
|
42
|
+
key = (spec.vendor, spec.model)
|
|
43
|
+
try:
|
|
44
|
+
return PROFILES[key]
|
|
45
|
+
except KeyError as e:
|
|
46
|
+
raise KeyError(f"未注册的设备: {spec.vendor}/{spec.model}") from e
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def open_bus(spec: DeviceSpec) -> can.BusABC:
|
|
50
|
+
"""把 DeviceSpec 解析为 can.Bus。channel 经 channel_map 映射;extra/options 透传。"""
|
|
51
|
+
profile = resolve(spec)
|
|
52
|
+
|
|
53
|
+
if spec.channel < 0 or spec.channel >= profile.channels:
|
|
54
|
+
raise ValueError(f"通道号越界: {spec.channel}(该设备 {profile.channels} 路)")
|
|
55
|
+
|
|
56
|
+
kwargs: dict = dict(profile.options or {})
|
|
57
|
+
kwargs.update(spec.extra or {})
|
|
58
|
+
# 禁止覆盖 interface / channel
|
|
59
|
+
kwargs.pop("interface", None)
|
|
60
|
+
kwargs.pop("channel", None)
|
|
61
|
+
|
|
62
|
+
channel: int | str = spec.channel
|
|
63
|
+
if profile.channel_map is not None:
|
|
64
|
+
channel = profile.channel_map(spec.channel)
|
|
65
|
+
|
|
66
|
+
bitrate = spec.bitrate.nominal if spec.bitrate else None
|
|
67
|
+
|
|
68
|
+
return can.Bus(
|
|
69
|
+
interface=profile.interface,
|
|
70
|
+
channel=channel,
|
|
71
|
+
bitrate=bitrate,
|
|
72
|
+
**kwargs,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def open_device(spec: DeviceSpec) -> Result:
|
|
77
|
+
"""带错误转换的打开入口。core 通过它拿 can.Bus,不直接接触厂商异常。"""
|
|
78
|
+
try:
|
|
79
|
+
bus = open_bus(spec)
|
|
80
|
+
except KeyError as e:
|
|
81
|
+
return Result.err(ErrorCode.CONFIG_ERROR, str(e))
|
|
82
|
+
except ValueError as e:
|
|
83
|
+
return Result.err(ErrorCode.CHANNEL_OUT_OF_RANGE, str(e))
|
|
84
|
+
except can.CanError as e:
|
|
85
|
+
return Result.err(ErrorCode.DEVICE_OPEN_FAILED, f"打开设备失败: {e}")
|
|
86
|
+
except Exception as e: # noqa: BLE001 —— 收拢未知异常,避免接口层两套失败
|
|
87
|
+
return Result.err(ErrorCode.INTERNAL_ERROR, f"内部错误: {e}")
|
|
88
|
+
return Result.ok(bus)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""zlg python-can backend:把周立功 zlgcan.dll 适配成 ``can.Bus(interface='zlg')``。
|
|
2
|
+
|
|
3
|
+
经 entry point ``zlg = xusbcan.adapters.zlg.backend:ZlgBus`` 注册,与官方 backend
|
|
4
|
+
地位平等。本包模块级**不**加载 DLL(惰性 ``get_dll()``),Linux 上可安全导入。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .backend import ZlgBus
|
|
8
|
+
from .device_pool import ZlgDevicePool
|
|
9
|
+
from .dll import (
|
|
10
|
+
ZlgConfigError,
|
|
11
|
+
ZlgDllNotFoundError,
|
|
12
|
+
ZlgError,
|
|
13
|
+
get_dll,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"ZlgBus",
|
|
18
|
+
"ZlgDevicePool",
|
|
19
|
+
"get_dll",
|
|
20
|
+
"ZlgError",
|
|
21
|
+
"ZlgConfigError",
|
|
22
|
+
"ZlgDllNotFoundError",
|
|
23
|
+
]
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""ZlgBus:把 zlgcan.dll 适配成 python-can 的 ``interface='zlg'`` backend。
|
|
2
|
+
|
|
3
|
+
经 entry point ``zlg = xusbcan.adapters.zlg.backend:ZlgBus`` 注册,与官方 backend
|
|
4
|
+
地位平等。上层只面向 can.Bus / can.Message,看不到厂商细节。
|
|
5
|
+
|
|
6
|
+
关键点(架构方案 v0.4 §4.4 / §11 / §12):
|
|
7
|
+
- 打开顺序:acquire 设备池 -> ZCAN_SetValue(baud_rate)(InitCAN 之前)
|
|
8
|
+
-> ZCAN_InitCAN -> ZCAN_StartCAN。
|
|
9
|
+
- InitCAN 成功但 StartCAN 失败时,构造内反向释放(ReleaseChannel + 归还池),
|
|
10
|
+
不留半打开句柄。
|
|
11
|
+
- 实现 _recv_internal(有限等待轮询,绝不用 wait_time=-1)与 send 与 shutdown,
|
|
12
|
+
不覆盖 recv。
|
|
13
|
+
- can_id 映射与 Linux socketcan 一致:arbitration_id = can_id & 0x1FFFFFFF;
|
|
14
|
+
is_extended = can_id & 0x80000000;is_remote = can_id & 0x40000000。
|
|
15
|
+
- 时间戳:设备上电微秒 -> 在 backend 内换算成 Unix 秒(float)。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import ctypes
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
import can
|
|
24
|
+
from can import BusABC, Message
|
|
25
|
+
|
|
26
|
+
from ...models.result import ErrorCode
|
|
27
|
+
from .device_pool import device_pool
|
|
28
|
+
from .dll import (
|
|
29
|
+
INVALID_HANDLE,
|
|
30
|
+
STATUS_OK,
|
|
31
|
+
TYPE_CAN,
|
|
32
|
+
ZCAN_USBCAN_2E_U,
|
|
33
|
+
ZCAN_Receive_Data,
|
|
34
|
+
ZCAN_Transmit_Data,
|
|
35
|
+
ZlgError,
|
|
36
|
+
get_dll,
|
|
37
|
+
make_init_config,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ZlgCapabilityUnsupportedError(ZlgError):
|
|
42
|
+
"""设备不支持该能力(对应 CAPABILITY_UNSUPPORTED),如 2E 卡发 CAN FD。"""
|
|
43
|
+
|
|
44
|
+
code: ErrorCode = ErrorCode.CAPABILITY_UNSUPPORTED
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ZlgBus(BusABC):
|
|
48
|
+
"""周立功 zlgcan backend。channel 即 can_index(0/1)。"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, channel, can_filters=None, **kwargs):
|
|
51
|
+
self._channel = int(channel)
|
|
52
|
+
self._device_type = int(kwargs.pop("device_type", ZCAN_USBCAN_2E_U))
|
|
53
|
+
self._device_index = int(kwargs.pop("device_index", 0))
|
|
54
|
+
# 2E 卡不支持 CAN FD,忽略 data_bitrate
|
|
55
|
+
kwargs.pop("data_bitrate", None)
|
|
56
|
+
bitrate = kwargs.pop("bitrate", None)
|
|
57
|
+
if bitrate is None:
|
|
58
|
+
raise can.CanInitializationError(
|
|
59
|
+
"zlg backend 需要 bitrate(标称波特率),2E 卡必须显式设置"
|
|
60
|
+
)
|
|
61
|
+
self._bitrate = int(bitrate)
|
|
62
|
+
|
|
63
|
+
# 惰性加载 DLL(此时才真正触碰 WinDLL / 环境变量)
|
|
64
|
+
self._dll = get_dll()
|
|
65
|
+
# acquire 设备池(首次才 OpenDevice)
|
|
66
|
+
self._entry = device_pool.acquire(self._device_type, self._device_index)
|
|
67
|
+
self._ch_handle = INVALID_HANDLE
|
|
68
|
+
self._ts_ref: tuple[int, float] | None = None # (设备微秒, Unix 秒) 参考点
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
self._open_channel()
|
|
72
|
+
except Exception:
|
|
73
|
+
# 反向释放:InitCAN 已成功则 ReleaseChannel + 移除通道占用,再归还池引用
|
|
74
|
+
self._release_channel()
|
|
75
|
+
device_pool.release(self._device_type, self._device_index)
|
|
76
|
+
raise
|
|
77
|
+
|
|
78
|
+
self.channel_info = f"zlg: device_type={self._device_type}, can_index={self._channel}"
|
|
79
|
+
super().__init__(channel=channel, can_filters=can_filters, **kwargs)
|
|
80
|
+
|
|
81
|
+
# ---- 打开序列 ----
|
|
82
|
+
def _open_channel(self) -> None:
|
|
83
|
+
"""SetValue(baud_rate) -> InitCAN -> StartCAN(顺序不可变)。"""
|
|
84
|
+
entry = self._entry
|
|
85
|
+
dll = self._dll
|
|
86
|
+
ch = self._channel
|
|
87
|
+
with entry.lock:
|
|
88
|
+
if ch in entry.open_channels:
|
|
89
|
+
raise can.CanInitializationError(f"通道 {ch} 已被本进程占用")
|
|
90
|
+
key = f"{ch}/baud_rate".encode("ascii")
|
|
91
|
+
ok = dll.ZCAN_SetValue(
|
|
92
|
+
entry.handle, key, str(self._bitrate).encode("ascii")
|
|
93
|
+
)
|
|
94
|
+
if ok != STATUS_OK:
|
|
95
|
+
raise can.CanInitializationError(
|
|
96
|
+
f"ZCAN_SetValue({key.decode()}) 失败,返回 {ok}"
|
|
97
|
+
)
|
|
98
|
+
cfg = make_init_config()
|
|
99
|
+
ch_handle = dll.ZCAN_InitCAN(entry.handle, ch, ctypes.byref(cfg))
|
|
100
|
+
if not ch_handle:
|
|
101
|
+
raise can.CanInitializationError(f"ZCAN_InitCAN 通道 {ch} 失败(空句柄)")
|
|
102
|
+
# InitCAN 成功,记录通道占用,供反向释放判断
|
|
103
|
+
self._ch_handle = ch_handle
|
|
104
|
+
entry.open_channels.add(ch)
|
|
105
|
+
r = dll.ZCAN_StartCAN(ch_handle)
|
|
106
|
+
if r != STATUS_OK:
|
|
107
|
+
raise can.CanInitializationError(
|
|
108
|
+
f"ZCAN_StartCAN 通道 {ch} 失败,返回 {r}"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def _release_channel(self) -> None:
|
|
112
|
+
"""反向释放通道句柄(若已 InitCAN),并从设备池移除通道占用。幂等。
|
|
113
|
+
|
|
114
|
+
只有真正持有通道句柄(InitCAN 成功)才移除 open_channels,避免失败重入
|
|
115
|
+
的实例误删其它实例登记的通道占用。
|
|
116
|
+
"""
|
|
117
|
+
entry = self._entry
|
|
118
|
+
if entry is None:
|
|
119
|
+
return
|
|
120
|
+
with entry.lock:
|
|
121
|
+
if self._ch_handle not in (INVALID_HANDLE, None):
|
|
122
|
+
# 通道随 CloseDevice(最后一路)释放;zlgcan 无独立 ReleaseChannel API,
|
|
123
|
+
# 这里只做簿记(移除通道占用 + 置空句柄)。
|
|
124
|
+
self._ch_handle = INVALID_HANDLE
|
|
125
|
+
entry.open_channels.discard(self._channel)
|
|
126
|
+
|
|
127
|
+
# ---- 发送 ----
|
|
128
|
+
def send(self, msg: Message, timeout=None) -> None:
|
|
129
|
+
if msg.is_fd:
|
|
130
|
+
# 2E 卡不支持 CAN FD,不送进 DLL
|
|
131
|
+
raise ZlgCapabilityUnsupportedError(
|
|
132
|
+
"USBCAN-2E-U 不支持 CAN FD(is_fd=True)"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
data = bytes(msg.data) if msg.data is not None else b""
|
|
136
|
+
if msg.is_remote_frame:
|
|
137
|
+
dlc = int(msg.dlc or 0)
|
|
138
|
+
else:
|
|
139
|
+
dlc = len(data)
|
|
140
|
+
if dlc > 8:
|
|
141
|
+
raise can.CanOperationError(f"经典 CAN 数据长度 {dlc} 超过 8 字节")
|
|
142
|
+
|
|
143
|
+
can_id = msg.arbitration_id & 0x1FFFFFFF
|
|
144
|
+
if msg.is_extended_id:
|
|
145
|
+
can_id |= 0x80000000
|
|
146
|
+
if msg.is_remote_frame:
|
|
147
|
+
can_id |= 0x40000000
|
|
148
|
+
|
|
149
|
+
tx = ZCAN_Transmit_Data()
|
|
150
|
+
tx.frame.can_id = can_id
|
|
151
|
+
tx.frame.can_dlc = dlc
|
|
152
|
+
for i, b in enumerate(data[:8]):
|
|
153
|
+
tx.frame.data[i] = b
|
|
154
|
+
tx.transmit_type = 0 # 正常发送
|
|
155
|
+
|
|
156
|
+
# 同一张卡的发送 / 接收 / SetValue 都走设备池互斥锁
|
|
157
|
+
with self._entry.lock:
|
|
158
|
+
sent = self._dll.ZCAN_Transmit(self._ch_handle, ctypes.byref(tx), 1)
|
|
159
|
+
# 返回「成功帧数」;无 ACK 时 Transmit 阻塞约 3.5s 后返回 0
|
|
160
|
+
if sent != 1:
|
|
161
|
+
raise can.CanOperationError(
|
|
162
|
+
f"ZCAN_Transmit 发送失败,成功帧数 {sent}(期望 1)"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# ---- 接收 ----
|
|
166
|
+
def _recv_internal(self, timeout):
|
|
167
|
+
"""有限等待轮询:GetReceiveNum + Receive(wait_time<=100),绝不用 -1 阻塞。"""
|
|
168
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
169
|
+
while not self._is_shutdown:
|
|
170
|
+
if deadline is None:
|
|
171
|
+
wait_ms = 100
|
|
172
|
+
else:
|
|
173
|
+
remain = deadline - time.monotonic()
|
|
174
|
+
if remain <= 0:
|
|
175
|
+
return None, False
|
|
176
|
+
wait_ms = min(100, max(1, int(remain * 1000)))
|
|
177
|
+
|
|
178
|
+
with self._entry.lock:
|
|
179
|
+
n = self._dll.ZCAN_GetReceiveNum(self._ch_handle, TYPE_CAN)
|
|
180
|
+
if n > 0:
|
|
181
|
+
rx = ZCAN_Receive_Data()
|
|
182
|
+
if self._dll.ZCAN_Receive(
|
|
183
|
+
self._ch_handle, ctypes.byref(rx), 1, 0
|
|
184
|
+
) == 1:
|
|
185
|
+
return self._make_message(rx), False
|
|
186
|
+
rx = ZCAN_Receive_Data()
|
|
187
|
+
if self._dll.ZCAN_Receive(
|
|
188
|
+
self._ch_handle, ctypes.byref(rx), 1, wait_ms
|
|
189
|
+
) == 1:
|
|
190
|
+
return self._make_message(rx), False
|
|
191
|
+
return None, False
|
|
192
|
+
|
|
193
|
+
def _make_message(self, rx: ZCAN_Receive_Data) -> Message:
|
|
194
|
+
can_id = int(rx.frame.can_id)
|
|
195
|
+
is_extended = bool(can_id & 0x80000000)
|
|
196
|
+
is_remote = bool(can_id & 0x40000000)
|
|
197
|
+
dlc = min(int(rx.frame.can_dlc), 8)
|
|
198
|
+
data = b"" if is_remote else bytes(rx.frame.data[:dlc])
|
|
199
|
+
return Message(
|
|
200
|
+
timestamp=self._device_ts_to_unix(int(rx.timestamp)),
|
|
201
|
+
arbitration_id=can_id & 0x1FFFFFFF,
|
|
202
|
+
is_extended_id=is_extended,
|
|
203
|
+
is_remote_frame=is_remote,
|
|
204
|
+
channel=self._channel,
|
|
205
|
+
dlc=dlc,
|
|
206
|
+
data=data,
|
|
207
|
+
is_fd=False,
|
|
208
|
+
check=False,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def _device_ts_to_unix(self, device_us: int) -> float:
|
|
212
|
+
"""设备上电后微秒 -> Unix 秒(float)。首个接收帧建立参考点。"""
|
|
213
|
+
if self._ts_ref is None:
|
|
214
|
+
self._ts_ref = (device_us, time.time())
|
|
215
|
+
ref_us, ref_unix = self._ts_ref
|
|
216
|
+
return ref_unix + max(0, device_us - ref_us) / 1e6
|
|
217
|
+
|
|
218
|
+
# ---- 关闭 ----
|
|
219
|
+
def shutdown(self) -> None:
|
|
220
|
+
if getattr(self, "_is_shutdown", False):
|
|
221
|
+
return
|
|
222
|
+
super().shutdown() # 置 _is_shutdown + 停周期任务
|
|
223
|
+
# 释放通道句柄,再归还设备池引用(最后一路才 CloseDevice)
|
|
224
|
+
self._release_channel()
|
|
225
|
+
device_pool.release(self._device_type, self._device_index)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""ZlgDevicePool:一张物理卡的设备句柄共享 + 引用计数 + 互斥锁。
|
|
2
|
+
|
|
3
|
+
key = (device_type, device_index)。首次 acquire 才 ZCAN_OpenDevice,最后一路
|
|
4
|
+
release 才 ZCAN_CloseDevice。同一张卡的发送 / 接收 / SetValue 都走 entry.lock
|
|
5
|
+
这把互斥锁。进程级单例(模块级一个池实例)。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import atexit
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
import can
|
|
16
|
+
|
|
17
|
+
from .dll import INVALID_HANDLE, get_dll
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class _DeviceEntry:
|
|
22
|
+
"""一张已打开设备卡的状态。lock 覆盖该卡的发送 / 接收 / SetValue。"""
|
|
23
|
+
|
|
24
|
+
handle: int
|
|
25
|
+
refcount: int = 0
|
|
26
|
+
lock: threading.Lock = field(default_factory=threading.Lock)
|
|
27
|
+
open_channels: set[int] = field(default_factory=set)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ZlgDevicePool:
|
|
31
|
+
"""设备句柄池。key=(device_type, device_index),进程级单例。"""
|
|
32
|
+
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self._entries: dict[tuple[int, int], _DeviceEntry] = {}
|
|
35
|
+
self._pool_lock = threading.Lock() # 只保护 _entries 字典的簿记
|
|
36
|
+
|
|
37
|
+
def acquire(self, device_type: int, device_index: int) -> _DeviceEntry:
|
|
38
|
+
"""取得设备卡句柄(引用计数 +1)。首次 acquire 才 OpenDevice。"""
|
|
39
|
+
key = (device_type, device_index)
|
|
40
|
+
dll = get_dll()
|
|
41
|
+
with self._pool_lock:
|
|
42
|
+
entry = self._entries.get(key)
|
|
43
|
+
if entry is None:
|
|
44
|
+
handle = dll.ZCAN_OpenDevice(device_type, device_index, 0)
|
|
45
|
+
if not handle or handle == INVALID_HANDLE:
|
|
46
|
+
raise can.CanInitializationError(
|
|
47
|
+
f"ZCAN_OpenDevice({device_type}, {device_index}) 返回空句柄"
|
|
48
|
+
"(设备未连接或内核 DLL 缺失)"
|
|
49
|
+
)
|
|
50
|
+
entry = _DeviceEntry(handle=handle)
|
|
51
|
+
self._entries[key] = entry
|
|
52
|
+
entry.refcount += 1
|
|
53
|
+
return entry
|
|
54
|
+
|
|
55
|
+
def release(self, device_type: int, device_index: int) -> bool:
|
|
56
|
+
"""归还设备卡引用(引用计数 -1)。最后一路 release 才 CloseDevice。"""
|
|
57
|
+
key = (device_type, device_index)
|
|
58
|
+
with self._pool_lock:
|
|
59
|
+
entry = self._entries.get(key)
|
|
60
|
+
if entry is None:
|
|
61
|
+
return False
|
|
62
|
+
entry.refcount -= 1
|
|
63
|
+
if entry.refcount > 0:
|
|
64
|
+
return False
|
|
65
|
+
del self._entries[key]
|
|
66
|
+
# 引用归零,最后一路:关闭整卡(在池锁外关闭,避免阻塞其它卡)
|
|
67
|
+
dll = get_dll()
|
|
68
|
+
dll.ZCAN_CloseDevice(entry.handle)
|
|
69
|
+
# 真机实测:CloseDevice 异步,立即 reopen 会 InitCAN 失败;
|
|
70
|
+
# 需短暂等待设备复位(0.5s 已实测足够)。
|
|
71
|
+
time.sleep(0.5)
|
|
72
|
+
return True
|
|
73
|
+
|
|
74
|
+
def close_all(self) -> None:
|
|
75
|
+
"""进程退出时兜底:关闭所有仍持有的设备句柄。"""
|
|
76
|
+
with self._pool_lock:
|
|
77
|
+
entries = list(self._entries.values())
|
|
78
|
+
self._entries.clear()
|
|
79
|
+
if not entries:
|
|
80
|
+
return
|
|
81
|
+
# 有 entry 时 DLL 必然已加载(acquire 先 get_dll 再 OpenDevice),此处走缓存
|
|
82
|
+
dll = get_dll()
|
|
83
|
+
for entry in entries:
|
|
84
|
+
try:
|
|
85
|
+
dll.ZCAN_CloseDevice(entry.handle)
|
|
86
|
+
except Exception: # noqa: BLE001 —— 退出清理尽力而为
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# 进程级单例(架构方案 §4.4 / §10:设备池只存在于 adapters/zlg/)
|
|
91
|
+
device_pool = ZlgDevicePool()
|
|
92
|
+
|
|
93
|
+
# 进程退出时注册清理,把设备池里残留的句柄关掉(架构方案 §4.4 第 5 条)
|
|
94
|
+
atexit.register(device_pool.close_all)
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""zlgcan.dll 的 ctypes 封装 + 惰性加载。
|
|
2
|
+
|
|
3
|
+
结构体与函数签名**严格照抄** scripts/zlg_probe.py(真机已验证):
|
|
4
|
+
can_frame=16、ZCAN_Transmit_Data=20、ZCAN_Receive_Data=24、
|
|
5
|
+
ZCAN_CHANNEL_INIT_CONFIG=32 字节;WinDLL(__stdcall)加载。
|
|
6
|
+
|
|
7
|
+
模块级**不**加载 DLL:只有真正打开 zlg 设备时才调用 ``get_dll()``,保证
|
|
8
|
+
``import xusbcan.adapters.zlg.backend`` 在 Linux(无 DLL)上不报错。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ctypes
|
|
14
|
+
import functools
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
import can
|
|
18
|
+
|
|
19
|
+
from ...models.result import ErrorCode
|
|
20
|
+
|
|
21
|
+
# ---- 基础类型 ----
|
|
22
|
+
UINT = ctypes.c_uint
|
|
23
|
+
BYTE = ctypes.c_ubyte
|
|
24
|
+
USHORT = ctypes.c_ushort
|
|
25
|
+
UINT64 = ctypes.c_uint64
|
|
26
|
+
VOID_P = ctypes.c_void_p
|
|
27
|
+
|
|
28
|
+
# ---- 常量 ----
|
|
29
|
+
ZCAN_USBCAN_2E_U = 21
|
|
30
|
+
TYPE_CAN = 0
|
|
31
|
+
STATUS_OK = 1
|
|
32
|
+
INVALID_HANDLE = 0
|
|
33
|
+
DLL_FILENAME = "zlgcan.dll"
|
|
34
|
+
SDK_ENV_VAR = "ZLG_SDK_DIR"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ---- 异常:zlg 适配层错误,携带 error.code 供 core 集中映射 ----
|
|
38
|
+
class ZlgError(can.CanError):
|
|
39
|
+
"""zlg 适配层异常基类。``code`` 是 ErrorCode 枚举,供 core 映射。"""
|
|
40
|
+
|
|
41
|
+
code: ErrorCode = ErrorCode.INTERNAL_ERROR
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ZlgConfigError(ZlgError):
|
|
45
|
+
"""环境变量 / 配置缺失(对应 CONFIG_ERROR)。"""
|
|
46
|
+
|
|
47
|
+
code: ErrorCode = ErrorCode.CONFIG_ERROR
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ZlgDllNotFoundError(ZlgError):
|
|
51
|
+
"""SDK 目录或 DLL 缺失(对应 DLL_NOT_FOUND)。"""
|
|
52
|
+
|
|
53
|
+
code: ErrorCode = ErrorCode.DLL_NOT_FOUND
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ---- 结构体(与 zlgcan.h 自然对齐一致,照抄 zlg_probe.py)----
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class can_frame(ctypes.Structure):
|
|
60
|
+
_fields_ = [
|
|
61
|
+
("can_id", UINT),
|
|
62
|
+
("can_dlc", BYTE),
|
|
63
|
+
("_pad", BYTE),
|
|
64
|
+
("_res0", BYTE),
|
|
65
|
+
("_res1", BYTE),
|
|
66
|
+
("data", BYTE * 8),
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ZCAN_Transmit_Data(ctypes.Structure):
|
|
71
|
+
_fields_ = [
|
|
72
|
+
("frame", can_frame),
|
|
73
|
+
("transmit_type", UINT),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ZCAN_Receive_Data(ctypes.Structure):
|
|
78
|
+
_fields_ = [
|
|
79
|
+
("frame", can_frame),
|
|
80
|
+
("timestamp", UINT64),
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _InitCanCfg(ctypes.Structure):
|
|
85
|
+
_fields_ = [
|
|
86
|
+
("acc_code", UINT),
|
|
87
|
+
("acc_mask", UINT),
|
|
88
|
+
("reserved", UINT),
|
|
89
|
+
("filter", BYTE),
|
|
90
|
+
("timing0", BYTE),
|
|
91
|
+
("timing1", BYTE),
|
|
92
|
+
("mode", BYTE),
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _InitCanFdCfg(ctypes.Structure):
|
|
97
|
+
_fields_ = [
|
|
98
|
+
("acc_code", UINT),
|
|
99
|
+
("acc_mask", UINT),
|
|
100
|
+
("abit_timing", UINT),
|
|
101
|
+
("dbit_timing", UINT),
|
|
102
|
+
("brp", UINT),
|
|
103
|
+
("filter", BYTE),
|
|
104
|
+
("mode", BYTE),
|
|
105
|
+
("pad", USHORT),
|
|
106
|
+
("reserved", UINT),
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _InitUnion(ctypes.Union):
|
|
111
|
+
_fields_ = [
|
|
112
|
+
("can", _InitCanCfg),
|
|
113
|
+
("canfd", _InitCanFdCfg),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class ZCAN_CHANNEL_INIT_CONFIG(ctypes.Structure):
|
|
118
|
+
_fields_ = [
|
|
119
|
+
("can_type", UINT),
|
|
120
|
+
("config", _InitUnion),
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def make_init_config() -> ZCAN_CHANNEL_INIT_CONFIG:
|
|
125
|
+
"""构造经典 CAN 通道初始化配置(2E 卡 timing0/timing1 忽略,mode=0 正常)。"""
|
|
126
|
+
cfg = ZCAN_CHANNEL_INIT_CONFIG()
|
|
127
|
+
cfg.can_type = TYPE_CAN
|
|
128
|
+
cfg.config.can.acc_code = 0
|
|
129
|
+
cfg.config.can.acc_mask = 0xFFFFFFFF
|
|
130
|
+
cfg.config.can.filter = 0
|
|
131
|
+
cfg.config.can.mode = 0 # 正常模式,1 为只听
|
|
132
|
+
return cfg
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _resolve_dll_path() -> tuple[str, str]:
|
|
136
|
+
"""解析 SDK 目录与 DLL 路径。未设环境变量 -> CONFIG_ERROR;缺失 -> DLL_NOT_FOUND。"""
|
|
137
|
+
sdk_dir = os.environ.get(SDK_ENV_VAR)
|
|
138
|
+
if not sdk_dir:
|
|
139
|
+
raise ZlgConfigError(
|
|
140
|
+
f"环境变量 {SDK_ENV_VAR} 未设置,无法定位 {DLL_FILENAME}"
|
|
141
|
+
)
|
|
142
|
+
if not os.path.isdir(sdk_dir):
|
|
143
|
+
raise ZlgDllNotFoundError(
|
|
144
|
+
f"ZLG SDK 目录不存在: {sdk_dir}(请检查 {SDK_ENV_VAR})"
|
|
145
|
+
)
|
|
146
|
+
dll_path = os.path.join(sdk_dir, DLL_FILENAME)
|
|
147
|
+
if not os.path.isfile(dll_path):
|
|
148
|
+
raise ZlgDllNotFoundError(f"{DLL_FILENAME} 缺失: {dll_path}")
|
|
149
|
+
return sdk_dir, dll_path
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _load_dll():
|
|
153
|
+
"""加载 zlgcan.dll 并声明函数签名(__stdcall -> WinDLL)。"""
|
|
154
|
+
sdk_dir, dll_path = _resolve_dll_path()
|
|
155
|
+
os.add_dll_directory(sdk_dir)
|
|
156
|
+
dll = ctypes.WinDLL(dll_path)
|
|
157
|
+
|
|
158
|
+
dll.ZCAN_OpenDevice.restype = VOID_P
|
|
159
|
+
dll.ZCAN_OpenDevice.argtypes = [UINT, UINT, UINT]
|
|
160
|
+
|
|
161
|
+
dll.ZCAN_CloseDevice.restype = UINT
|
|
162
|
+
dll.ZCAN_CloseDevice.argtypes = [VOID_P]
|
|
163
|
+
|
|
164
|
+
dll.ZCAN_SetValue.restype = UINT
|
|
165
|
+
dll.ZCAN_SetValue.argtypes = [VOID_P, ctypes.c_char_p, ctypes.c_char_p]
|
|
166
|
+
|
|
167
|
+
dll.ZCAN_InitCAN.restype = VOID_P
|
|
168
|
+
dll.ZCAN_InitCAN.argtypes = [VOID_P, UINT, ctypes.POINTER(ZCAN_CHANNEL_INIT_CONFIG)]
|
|
169
|
+
|
|
170
|
+
dll.ZCAN_StartCAN.restype = UINT
|
|
171
|
+
dll.ZCAN_StartCAN.argtypes = [VOID_P]
|
|
172
|
+
|
|
173
|
+
dll.ZCAN_Transmit.restype = UINT
|
|
174
|
+
dll.ZCAN_Transmit.argtypes = [VOID_P, ctypes.POINTER(ZCAN_Transmit_Data), UINT]
|
|
175
|
+
|
|
176
|
+
dll.ZCAN_Receive.restype = UINT
|
|
177
|
+
dll.ZCAN_Receive.argtypes = [VOID_P, ctypes.POINTER(ZCAN_Receive_Data), UINT, ctypes.c_int]
|
|
178
|
+
|
|
179
|
+
dll.ZCAN_GetReceiveNum.restype = UINT
|
|
180
|
+
dll.ZCAN_GetReceiveNum.argtypes = [VOID_P, BYTE]
|
|
181
|
+
|
|
182
|
+
return dll
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@functools.lru_cache(maxsize=1)
|
|
186
|
+
def get_dll():
|
|
187
|
+
"""惰性获取已加载的 zlgcan.dll(进程内只加载一次)。
|
|
188
|
+
|
|
189
|
+
首次调用时才真正触碰 WinDLL / 环境变量;异常不会被 lru_cache 缓存,
|
|
190
|
+
修复配置后重试即可。
|
|
191
|
+
"""
|
|
192
|
+
return _load_dll()
|
xusbcan/cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""CLI 入口:薄封装 core,只做参数解析与 Result 序列化。"""
|