"""
-BDM120 从站模拟器 - 独立运行版
+BDM120 从站模拟器 - 独立运行版 (Windows + CANalyst-II)
-创建 vcan0 节点 → 启动 Modbus Slave → 启动 Web GUI
+打开 CANalyst-II 通道 → 启动 Modbus Slave → 启动 Web GUI
用法:
- python3 -m sim.slave.app [--port 9090] [--config regs.json] [--no-vcan]
+ python app.py [--port 9090] [--config regs.json] [--iface 0]
然后在浏览器中打开 http://localhost:<端口>
"""
from http.server import HTTPServer
from sim.slave_sim import SlaveSimulator
-from sim.can_layer import setup_vcan
+from sim.can_layer import setup_can
from sim.web_gui import (
HTML_PAGE, REGISTER_AREAS, REGISTER_NAMES, COIL_NAMES,
RequestHandler, get_slave, log_message,
slave = get_slave()
if not slave.running:
try:
- setup_vcan()
+ setup_can(channel=int(slave.interface))
except RuntimeError:
pass
slave.start()
help='Web GUI 端口 (默认: 9090)')
parser.add_argument('--config', '-c', default=None,
help='寄存器初始值 JSON 配置文件')
- parser.add_argument('--iface', '-i', default='vcan0',
- help='CAN 接口 (默认: vcan0)')
- parser.add_argument('--no-vcan', action='store_true',
- help='不自动创建 vcan0')
+ parser.add_argument('--iface', '-i', default='0',
+ help='CANalyst-II 通道号 (默认: 0)')
+ parser.add_argument('--bitrate', '-b', type=int, default=1000000,
+ help='CAN 位速率 bps (默认: 1000000 = 1M)')
+ parser.add_argument('--no-check', action='store_true',
+ help='不预先检查 CANalyst-II 设备')
args = parser.parse_args()
print("=" * 60)
print("=" * 60)
print()
- # 1) 创建 vcan0
- if not args.no_vcan:
- print(f"[1/3] 创建 CAN 接口 '{args.iface}'...")
+ # 1) 检查 CANalyst-II 设备
+ if not args.no_check:
+ print(f"[1/3] 检查 CANalyst-II 通道 {args.iface} @ {args.bitrate/1000:.0f} kbps...")
try:
- setup_vcan()
+ setup_can(channel=int(args.iface), bitrate=args.bitrate)
except RuntimeError as e:
print(f" 警告: {e}")
else:
- print(f"[1/3] 跳过 vcan 创建 (--no-vcan)")
+ print(f"[1/3] 跳过设备检查 (--no-check)")
# 2) 启动从站
- print(f"[2/3] 启动 Modbus 从站模拟器 ({args.iface})...")
+ print(f"[2/3] 启动 Modbus 从站模拟器 (通道 {args.iface})...")
slave = SlaveSimulator(interface=args.iface, config_path=args.config)
_set_slave(slave)
- slave.start()
+ slave.start(bitrate=args.bitrate)
print(f" 从站已启动, 监听 CAN ID=0x01")
print(f" 寄存器数量: {len(slave.registers)}")
--- /dev/null
+"""
+CANalyst-II (ControlCAN.dll) 连接诊断脚本.
+
+用法: python diag_canat.py
+逐项打印: DLL 加载 / 打开设备 / 读板信息 / 复位 / 初始化 / 启动 的返回值,
+并用多种 DevType 与 DevIndex 组合尝试, 以便定位 VCI_InitCAN 返回 0 的原因.
+"""
+import ctypes
+import os
+import sys
+import time
+from ctypes import byref
+
+
+class VCIInITConfig(ctypes.Structure):
+ _fields_ = [
+ ("AccCode", ctypes.c_uint),
+ ("AccMask", ctypes.c_uint),
+ ("Reserved", ctypes.c_uint),
+ ("Filter", ctypes.c_ubyte),
+ ("Timing0", ctypes.c_ubyte),
+ ("Timing1", ctypes.c_ubyte),
+ ("Mode", ctypes.c_ubyte),
+ ]
+
+
+class VCIBoardInfo(ctypes.Structure):
+ _fields_ = [
+ ("hw_Version", ctypes.c_ushort),
+ ("fw_Version", ctypes.c_ushort),
+ ("dr_Version", ctypes.c_ushort),
+ ("in_Version", ctypes.c_ushort),
+ ("irq_Num", ctypes.c_ushort),
+ ("can_Num", ctypes.c_ubyte),
+ ("str_Serial_Num", ctypes.c_char * 20),
+ ("str_hw_Type", ctypes.c_char * 40),
+ ("Reserved", ctypes.c_ushort * 4),
+ ]
+
+
+def load_dll():
+ root = os.path.dirname(os.path.abspath(__file__))
+ path = os.path.join(root, "ControlCAN.dll")
+ if not os.path.isfile(path):
+ print(f"[FAIL] 未找到 {path}")
+ sys.exit(1)
+ os.add_dll_directory(root)
+ dll = ctypes.CDLL(path)
+ dll.VCI_OpenDevice.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]
+ dll.VCI_OpenDevice.restype = ctypes.c_int
+ dll.VCI_CloseDevice.argtypes = [ctypes.c_uint, ctypes.c_uint]
+ dll.VCI_CloseDevice.restype = ctypes.c_int
+ dll.VCI_ReadBoardInfo.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(VCIBoardInfo)]
+ dll.VCI_ReadBoardInfo.restype = ctypes.c_int
+ dll.VCI_ResetCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_ResetCAN.restype = ctypes.c_int
+ dll.VCI_InitCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.POINTER(VCIInITConfig)]
+ dll.VCI_InitCAN.restype = ctypes.c_int
+ dll.VCI_StartCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_StartCAN.restype = ctypes.c_int
+ dll.VCI_ClearBuffer.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_ClearBuffer.restype = ctypes.c_int
+ dll.VCI_SetReference.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.c_uint, ctypes.c_void_p,
+ ]
+ dll.VCI_SetReference.restype = ctypes.c_int
+
+ dll.VCI_Receive.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort,
+ ctypes.POINTER(VCICanObj), ctypes.c_uint, ctypes.c_int,
+ ]
+ dll.VCI_Receive.restype = ctypes.c_uint
+ return dll
+
+
+class VCICanObj(ctypes.Structure):
+ _fields_ = [
+ ("ID", ctypes.c_uint),
+ ("TimeStamp", ctypes.c_uint),
+ ("TimeFlag", ctypes.c_ubyte),
+ ("SendType", ctypes.c_ubyte),
+ ("RemoteFlag", ctypes.c_ubyte),
+ ("ExternFlag", ctypes.c_ubyte),
+ ("DataLen", ctypes.c_ubyte),
+ ("Data", ctypes.c_ubyte * 8),
+ ("Reserved", ctypes.c_ubyte * 3),
+ ]
+
+
+def _rx_listen(dll, dt, di, ch, clk):
+ """打开并初始化指定通道, 侦听 12 秒, 返回收到的报文列表."""
+ got = []
+ try:
+ dll.VCI_CloseDevice(dt, di)
+ except Exception:
+ pass
+ if dll.VCI_OpenDevice(dt, di, 0) == 0:
+ return None
+ dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk)))
+ dll.VCI_ResetCAN(dt, di, ch)
+ cfg = VCIInITConfig()
+ cfg.AccCode = 0
+ cfg.AccMask = 0xFFFFFFFF
+ cfg.Reserved = 0
+ cfg.Filter = 0
+ cfg.Timing0 = 0x01 # DevType=4 成功组合
+ cfg.Timing1 = 0x14
+ cfg.Mode = 0
+ ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg))
+ if ri <= 0:
+ dll.VCI_CloseDevice(dt, di)
+ return None
+ dll.VCI_ClearBuffer(dt, di, ch)
+ st = dll.VCI_StartCAN(dt, di, ch)
+ print(f" 通道{ch}: clk={clk} InitCAN={ri} StartCAN={st} 侦听中(12s)...")
+ buf = (VCICanObj * 32)()
+ deadline = time.time() + 12
+ while time.time() < deadline:
+ n = dll.VCI_Receive(dt, di, ch, buf, 32, 300)
+ for i in range(n):
+ obj = buf[i]
+ data = bytes(obj.Data[:obj.DataLen])
+ got.append((obj.ID, obj.ExternFlag, data))
+ print(f" -> 收到 ID=0x{obj.ID:03X} {'X' if obj.ExternFlag else 'S'} "
+ f"LEN={len(data)} {' '.join('%02X' % b for b in data)}")
+ if n:
+ got.clear() # 只要收到一条即视为命中, 清掉以便按通道判定
+ dll.VCI_CloseDevice(dt, di)
+ return got
+
+
+def _rx_listen_timing(dll, dt, di, ch, clk, t0, t1, dur=8.0):
+ """以指定 主时钟(timing) 配置监听某通道, 监听 dur 秒, 返回是否收到帧.
+
+ VCI_InitCAN 成功并不代表波特率匹配! 所以这里会一直监听, 只要收到
+ 任何原始帧即认为该 (通道×主时钟×时序) 组合命中.
+ """
+ try:
+ dll.VCI_CloseDevice(dt, di)
+ except Exception:
+ pass
+ if dll.VCI_OpenDevice(dt, di, 0) == 0:
+ return False
+ # 按需设置主时钟(2E-U 等需要; 普通 USBCAN2 会忽略)
+ try:
+ dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk)))
+ except Exception:
+ pass
+ dll.VCI_ResetCAN(dt, di, ch)
+ cfg = VCIInITConfig()
+ cfg.AccCode = 0
+ cfg.AccMask = 0xFFFFFFFF
+ cfg.Reserved = 0
+ cfg.Filter = 0
+ cfg.Timing0 = t0
+ cfg.Timing1 = t1
+ cfg.Mode = 0
+ ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg))
+ if ri <= 0:
+ dll.VCI_CloseDevice(dt, di)
+ return False
+ dll.VCI_ClearBuffer(dt, di, ch)
+ st = dll.VCI_StartCAN(dt, di, ch)
+ buf = (VCICanObj * 32)()
+ deadline = time.time() + dur
+ got = False
+ while time.time() < deadline:
+ n = dll.VCI_Receive(dt, di, ch, buf, 32, 300)
+ for i in range(n):
+ obj = buf[i]
+ data = bytes(obj.Data[:obj.DataLen])
+ got = True
+ print(f" ✓ [{dt}|{di}|{ch}] clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} "
+ f"InitCAN={ri} StartCAN={st} -> 收到 ID=0x{obj.ID:03X} "
+ f"{' '.join('%02X' % b for b in data)}")
+ dll.VCI_CloseDevice(dt, di)
+ return got
+
+
+def _real_rx_test(dll):
+ """枚举所有 (DevType × 通道 × 主时钟 × 时序) 组合去真听.
+
+ 因为外部设备每约几秒发一个测试包, 只有波特率真正匹配的通道才能收到.
+ 据此锁定 can_layer.py 该用的 设备类型/通道/主时钟/时序.
+ """
+ print("=" * 60)
+ print("[真实接收枚举测试]")
+ print("请确保外部设备每约几秒发一个测试包, 并已关闭 app.py.")
+ print("将枚举 DevType(4/21) × 通道(CAN0/CAN1) × 主时钟 × 1M时序...")
+ print("=" * 60)
+
+ # 1Mbps 候选时序:
+ # 16MHz 主时钟 -> (0x00,0x14) = 1M (SJA1000 标准)
+ # 16MHz 主时钟 -> (0x01,0x14) = 1M(simple) 用户工具通用先例
+ # 12MHz 主时钟 -> (0x00,0x1C) ~=1M
+ # 8MHz 主时钟 -> (0x00,0x03)*sample 不用
+ timing_cand = {
+ 16000000: [(0x00, 0x14), (0x01, 0x14), (0x01, 0x1C)],
+ 12000000: [(0x00, 0x1C), (0x01, 0x1C)],
+ 8000000: [(0x00, 0x1C), (0x01, 0x1C)],
+ }
+
+ devtypes = [4, 21]
+ hits = []
+ for dt in devtypes:
+ for ch in (0, 1):
+ for clk, tlist in timing_cand.items():
+ for (t0, t1) in tlist:
+ print(f"[T] DevType={dt} 通道{ch} clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} ...")
+ if _rx_listen_timing(dll, dt, try_di_global, ch, clk, t0, t1, 8.0):
+ hits.append((dt, ch, clk, t0, t1))
+ if hits:
+ print("\n" + "=" * 60)
+ print("[命中] 以下组合可以真正收到外部设备的报文:")
+ for h in hits:
+ print(f" DevType={h[0]} 通道={h[1]} 主时钟={h[2]} T0=0x{h[3]:02X} T1=0x{h[4]:02X}")
+ print("=" * 60)
+ else:
+ print("\n[结果] 所有组合均未收到任何报文. 可能: 设备未连 CAN 总线/HI端,")
+ print(" 或外部设备不在网络上, 或接线/终端电阻问题.")
+ print("=" * 60)
+
+
+try_di_global = 0
+
+
+def main():
+ print("=" * 60)
+ print("CANalyst-II 连接诊断")
+ print("=" * 60)
+ dll = load_dll()
+ print("[OK] ControlCAN.dll 加载成功")
+
+ # 创建芯都设备类型: USBCAN_2E_U=21, USBCAN2=4, USBCAN1=3, USBCAN_E_U=20
+ devtypes = [21, 4, 3, 20]
+ print(f"[INFO] Python {'64位' if sys.maxsize > 2**32 else '32位'}")
+
+ found = False
+ for dt in devtypes:
+ for di in range(2): # DevIndex 0..1
+ try:
+ dll.VCI_CloseDevice(dt, di)
+ except Exception:
+ pass
+ o = dll.VCI_OpenDevice(dt, di, 0)
+ if o == 0:
+ continue
+ board = VCIBoardInfo()
+ rb = dll.VCI_ReadBoardInfo(dt, di, byref(board))
+ hw = board.str_hw_Type.decode("utf-8", "ignore").strip("\x00")
+ sn = board.str_Serial_Num.decode("utf-8", "ignore").strip("\x00")
+ print(f"\n[OK] 设备可打开: DevType={dt}, DevIndex={di}, "
+ f"OpenDevice={o}, ReadBoardInfo={rb}")
+ print(f" 硬件类型: {hw or '(空)'}")
+ print(f" 序列号 : {sn or '(空)'}")
+ print(f" CAN通道数: {board.can_Num}")
+ found = True
+ try_dt, try_di = dt, di
+ try:
+ dll.VCI_CloseDevice(dt, di)
+ except Exception:
+ pass
+ # 只测试找到的第一个设备, 避免重复
+ break
+ if found:
+ break
+
+ if not found:
+ print("[FAIL] 所有 DevType/DevIndex 组合都无法打开设备.")
+ print(" 请确认: 设备已插入、驱动已安装、未被其他程序占用。")
+ return
+
+ # 对找到的设备, 重点测试 VCI_SetReference + VCI_InitCAN 的 2E-U 标准流程
+ print(f"\n[INFO] VCIInITConfig 结构体大小 = {ctypes.sizeof(VCIInITConfig)} 字节 (期望 16)")
+
+ # 先按住找到的 DevType 测试 SetReference 前置流程
+ print("\n--- 测试: OpenDevice -> SetReference(时钟) -> ResetCAN -> InitCAN ---")
+ ch = 0
+ found_ok = 0
+
+ # 主时钟频率候选 (2E-U 设备可能是 8MHz 或 16MHz)
+ clk_values = [12000000, 16000000, 8000000, 2000000]
+ # Timing 候选
+ t0t1_list = [
+ (0x01, 0x14), # 用户工具时序
+ (0x00, 0x14),
+ (0x00, 0x1C),
+ (0x03, 0x1C),
+ ]
+
+ for dt in [try_dt] + [d for d in (21, 4, 3, 20) if d != try_dt]:
+ for clk in clk_values:
+ for (t0, t1) in t0t1_list:
+ try:
+ dll.VCI_CloseDevice(dt, try_di)
+ except Exception:
+ pass
+ if dll.VCI_OpenDevice(dt, try_di, 0) == 0:
+ continue
+ # 2E-U 关键: 先 SetReference 设置主时钟
+ ref_ret = dll.VCI_SetReference(
+ dt, try_di, ch, 1, byref(ctypes.c_uint(clk)))
+ dll.VCI_ResetCAN(dt, try_di, ch)
+
+ cfg = VCIInITConfig()
+ cfg.AccCode = 0
+ cfg.AccMask = 0xFFFFFFFF
+ cfg.Reserved = 0
+ cfg.Filter = 0
+ cfg.Timing0 = t0
+ cfg.Timing1 = t1
+ cfg.Mode = 0
+ ri = dll.VCI_InitCAN(dt, try_di, ch, byref(cfg))
+ if ri > 0:
+ found_ok += 1
+ cb = dll.VCI_ClearBuffer(dt, try_di, ch)
+ st = dll.VCI_StartCAN(dt, try_di, ch)
+ print(f"\n[OK] DevType={dt} 时钟={clk} T0=0x{t0:02X} T1=0x{t1:02X} "
+ f"-> SetRef={ref_ret} InitCAN={ri} (成功) "
+ f"ClearBuf={cb} StartCAN={st}")
+ dll.VCI_CloseDevice(dt, try_di)
+ break # 每组成功即停
+ # 无成功则静默, 少量打印
+ dll.VCI_CloseDevice(dt, try_di)
+ if found_ok:
+ break
+ if found_ok:
+ break
+
+ global try_di_global
+ try_di_global = try_di
+
+ if found_ok:
+ print(f"\n[成功] 找到可用组合, 共 {found_ok} 次成功.\n")
+ _real_rx_test(dll)
+ else:
+ print("\n[失败] 所有 DevType/SetReference/Timing 组合均失败.")
+ print(" 提示: 需要核对 ControlCAN.h 中该设备的 RefType 具体含义,")
+ print(" 以及 USBCAN_E_U(20)/USBCAN_2E_U(21) 的正确用法.")
+ print(" 请查阅随附的《4.接口函数库(二次开发库)使用说明书.pdf》")
+
+ print("\n" + "=" * 60)
+ print("诊断完成。")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
"""
-CAN Bus Communication Layer
+CAN Bus Communication Layer (Windows + CANalyst-II)
+
+直接通过 ctypes 封装致远电子 (周立功) 官方 ControlCAN.dll, 实现与 CANalyst-II
+(USB-CAN-II) 设备的通信, 默认位速率 1 Mbps。
+
+准备工作:
+ 1. 安装 CANalyst-II 设备驱动 (致远电子官网提供 ControlCAN.dll 及驱动)。
+ 2. 将与 Python 位数匹配的 ControlCAN.dll (及 x64/x86 对应版本) 拷贝到本
+ 目录 (或系统 PATH), 或确保设备驱动已安装使 DLL 可达。
CAN Frame Format:
- Standard CAN ID (11-bit)
- Last packet padded with 0x00
"""
-import socket
-import struct
+import ctypes
+import os
+import sys
import threading
import time
from collections import deque
+from ctypes import byref
CAN_MASTER_ID = 1
CAN_SLAVE_ID = 2
SLAVE_RESPONSE_ADDR = 0x82
+DEFAULT_BITRATE = 1000000 # CANalyst-II 默认 1 Mbps
+
+# ------------------------------------------------------------
+# ControlCAN.dll 常量
+# ------------------------------------------------------------
+# 创芯科技 CANalyst-II 设备类型号 (与 ControlCAN.h 一致)
+# VCI_USBCAN1=3, VCI_USBCAN2=4, VCI_USBCAN_E_U=20, VCI_USBCAN_2E_U=21
+VCI_USBCAN2 = 4 # USBCAN2 / CANalyst-II
+VCI_USBCAN1 = 3 # USBCAN1
+VCI_USBCAN_2E_U = 21 # USBCAN-2E-U / CANalyst-II (用户设备实际类型)
+
+_RET_OK = 1 # VCI_* 成功返回值 (1)
+
+
+class VCIInITConfig(ctypes.Structure):
+ """VCI_INIT_CONFIG 结构体 (CAN 初始化参数)."""
+ _fields_ = [
+ ("AccCode", ctypes.c_uint),
+ ("AccMask", ctypes.c_uint),
+ ("Reserved", ctypes.c_uint),
+ ("Filter", ctypes.c_ubyte),
+ ("Timing0", ctypes.c_ubyte),
+ ("Timing1", ctypes.c_ubyte),
+ ("Mode", ctypes.c_ubyte),
+ ]
+
+
+class VCICanObj(ctypes.Structure):
+ """VCI_CAN_OBJ 结构体.
+
+ 字段顺序必须严格与 ControlCAN.h 一致:
+ ID, TimeStamp, TimeFlag, SendType, RemoteFlag, ExternFlag,
+ DataLen, Data[8], Reserved[3]
+ 之前把 Reserved 放到 Data 前面导致数据错位 3 字节(收到的内容丢前 3 字节).
+ """
+ _fields_ = [
+ ("ID", ctypes.c_uint),
+ ("TimeStamp", ctypes.c_uint),
+ ("TimeFlag", ctypes.c_ubyte),
+ ("SendType", ctypes.c_ubyte),
+ ("RemoteFlag", ctypes.c_ubyte),
+ ("ExternFlag", ctypes.c_ubyte),
+ ("DataLen", ctypes.c_ubyte),
+ ("Data", ctypes.c_ubyte * 8),
+ ("Reserved", ctypes.c_ubyte * 3),
+ ]
+
+
+class VCIBoardInfo(ctypes.Structure):
+ """VCI_BOARD_INFO 结构体 (设备/硬件信息)."""
+ _fields_ = [
+ ("hw_Version", ctypes.c_ushort),
+ ("fw_Version", ctypes.c_ushort),
+ ("dr_Version", ctypes.c_ushort),
+ ("in_Version", ctypes.c_ushort),
+ ("irq_Num", ctypes.c_ushort),
+ ("can_Num", ctypes.c_ubyte),
+ ("str_Serial_Num", ctypes.c_char * 20),
+ ("str_hw_Type", ctypes.c_char * 40),
+ ("Reserved", ctypes.c_ushort * 4),
+ ]
+
+
+# 波特率 -> (Timing0, Timing1) 周立功标准波特率表 (16MHz 时钟)
+# 注意: CANalyst-II 主时钟为 16MHz, 1Mbps 的时序需用 (0x00,0x14).
+# 实测 (0x01,0x14) 在 16MHz 下波特率不对, 无法收到外部设备的包.
+_BITRATE_TABLE = {
+ 1000000: (0x00, 0x14), # 1M (16MHz: SJW=1, BRP=1, 传播段+PS1=13, PS2=2)
+ 800000: (0x00, 0x16), # 800K
+ 500000: (0x00, 0x1C), # 500K
+ 250000: (0x01, 0x1C), # 250K
+ 200000: (0x02, 0x1C), # 200K
+ 125000: (0x03, 0x1C), # 125K
+ 100000: (0x04, 0x1C), # 100K
+ 50000: (0x09, 0x1C), # 50K
+ 40000: (0x0B, 0x1C), # 40K
+ 20000: (0x18, 0x1C), # 20K
+ 10000: (0x31, 0x1C), # 10K
+}
+
+
+def _parse_channel(interface_name) -> int:
+ """将接口名解析为 CAN 通道号 (CAN0/CAN1, 默认 0)."""
+ if isinstance(interface_name, int):
+ return 0 if interface_name < 1 else 1
+ s = str(interface_name).lower()
+ try:
+ if "can" in s:
+ digits = "".join(ch for ch in s if ch.isdigit())
+ else:
+ digits = "".join(ch for ch in s if ch.isdigit() or ch == "-")
+ val = int(digits)
+ except (ValueError, TypeError):
+ val = 0
+ # channel 映射: 0 -> CAN0, 1 -> CAN1, 其它 -> 0
+ return 0 if val != 1 else 1
+
+
+def _project_root_dir() -> str:
+ """返回项目根目录 (app.py 所在目录)."""
+ app_dir = os.path.dirname(os.path.abspath(__file__)) # .../sim
+ root = os.path.dirname(app_dir) # .../ (项目根)
+ return root
+
+
+def _find_dll_candidates() -> list:
+ """按优先级列出候选的 ControlCAN.dll 路径.
+
+ 优先级: 当前工作目录 > 项目根目录 > sim 目录 > 环境变量指定路径.
+ """
+ roots = []
+ for r in (_project_root_dir(), os.getcwd()):
+ if r not in roots:
+ roots.append(r)
+ sim_dir = os.path.dirname(os.path.abspath(__file__))
+ if sim_dir not in roots:
+ roots.append(sim_dir)
+
+ candidates = []
+ for r in roots:
+ p = os.path.join(r, "ControlCAN.dll")
+ if os.path.isfile(p) and p not in candidates:
+ candidates.append(p)
+
+ # 环境变量 CONTROLCAN_DLL 指定的完整路径
+ env = os.environ.get("CONTROLCAN_DLL")
+ if env and os.path.isfile(env) and env not in candidates:
+ candidates.append(env)
+
+ return candidates
+
+
+def _pe_is_x64(path: str) -> bool:
+ """通过 PE 头判断 DLL 是否为 64 位. 读取失败返回 None."""
+ try:
+ with open(path, "rb") as f:
+ d = f.read()
+ if len(d) < 0x40:
+ return None
+ pe = struct.unpack_from("<I", d, 0x3C)[0]
+ if pe + 6 > len(d):
+ return None
+ machine = struct.unpack_from("<H", d, pe + 4)[0]
+ if machine == 0x8664:
+ return True
+ if machine == 0x014C:
+ return False
+ return None
+ except Exception:
+ return None
+
+
+def _load_controlcan_dll():
+ """加载 ControlCAN.dll, 返回已绑定原型的 dll 句柄."""
+ import struct as _struct
+
+ # 校验 DLL 位数是否与 Python 一致
+ is_py64 = sys.maxsize > 2**32
+ wrong_arch = []
+ for path in _find_dll_candidates():
+ is_dll64 = _pe_is_x64(path)
+ if is_dll64 is not None and is_dll64 != is_py64:
+ wrong_arch.append(path)
+
+ if wrong_arch:
+ raise RuntimeError(
+ "DLL 位数与 Python 不匹配 (WinError 193).\n"
+ f"Python : {'64 位' if is_py64 else '32 位'}\n"
+ f"DLL : {'64 位' if _pe_is_x64(wrong_arch[0]) else '32 位'} "
+ f"({wrong_arch[0]})\n"
+ "请更换为与 Python 位数一致的 ControlCAN.dll, 或将程序改用 "
+ "匹配的 Python 版本运行."
+ )
+
+ candidates = _find_dll_candidates()
+ if not candidates:
+ raise RuntimeError(
+ "未找到 ControlCAN.dll. 请将致远电子 (周立功) 官方的 "
+ "ControlCAN.dll 拷贝到程序根目录 (须与 Python 位数一致), "
+ "或通过环境变量 CONTROLCAN_DLL 指定其完整路径."
+ )
+
+ # Python 3.8+ 需将 DLL 所在目录加入搜索路径, 以便加载其依赖
+ # (如 kerneldlls/kernel.dll).
+ loaded = None
+ last_err = None
+ for path in candidates:
+ dll_dir = os.path.dirname(path)
+ try:
+ if hasattr(os, "add_dll_directory"):
+ with os.add_dll_directory(dll_dir):
+ loaded = ctypes.CDLL(path)
+ else:
+ loaded = ctypes.CDLL(path)
+ break
+ except OSError as e:
+ last_err = e
+ loaded = None
+
+ if loaded is None:
+ raise RuntimeError(
+ "无法加载 ControlCAN.dll (或缺少其依赖库).\n"
+ "曾尝试: %s\n"
+ "请确认: 1) DLL 位数与 Python 一致; 2) 其依赖的 kerneldlls/"
+ "kernel.dll 等文件与 DLL 位于同一目录并已就位; 3) 设备驱动已安装.\n"
+ "详情: %s" % ("; ".join(candidates), last_err)
+ ) from last_err
+
+ dll = loaded
+
+ # ---- 设置函数原型 ----
+ dll.VCI_OpenDevice.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]
+ dll.VCI_OpenDevice.restype = ctypes.c_int
+
+ dll.VCI_CloseDevice.argtypes = [ctypes.c_uint, ctypes.c_uint]
+ dll.VCI_CloseDevice.restype = ctypes.c_int
+
+ dll.VCI_InitCAN.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort,
+ ctypes.POINTER(VCIInITConfig),
+ ]
+ dll.VCI_InitCAN.restype = ctypes.c_int
+
+ dll.VCI_StartCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_StartCAN.restype = ctypes.c_int
+
+ dll.VCI_ClearBuffer.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_ClearBuffer.restype = ctypes.c_int
+
+ dll.VCI_ResetCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort]
+ dll.VCI_ResetCAN.restype = ctypes.c_int
+
+ dll.VCI_SetReference.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort,
+ ctypes.c_uint, ctypes.c_void_p,
+ ]
+ dll.VCI_SetReference.restype = ctypes.c_int
+
+ dll.VCI_Transmit.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort,
+ ctypes.POINTER(VCICanObj), ctypes.c_uint,
+ ]
+ dll.VCI_Transmit.restype = ctypes.c_uint
+
+ dll.VCI_Receive.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort,
+ ctypes.POINTER(VCICanObj), ctypes.c_uint, ctypes.c_int,
+ ]
+ dll.VCI_Receive.restype = ctypes.c_uint
+
+ dll.VCI_ReadBoardInfo.argtypes = [
+ ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(VCIBoardInfo),
+ ]
+ dll.VCI_ReadBoardInfo.restype = ctypes.c_int
+
+ return dll
+
class CanInterface:
- """SocketCAN interface for Modbus communication."""
+ """CANalyst-II interface for Modbus communication (Windows)."""
- def __init__(self, interface_name: str, can_id: int):
+ def __init__(self, interface_name: str, can_id: int,
+ bitrate: int = DEFAULT_BITRATE,
+ device_index: int = 0, dev_type: int = VCI_USBCAN2):
self.interface = interface_name
+ self.channel = _parse_channel(interface_name) # CAN0/CAN1
self.can_id = can_id
- self.sock = None
+ self.bitrate = bitrate
+ self.device_index = device_index
+ self.dev_type = dev_type
+ self.dll = None
self.running = False
self.rx_queue = deque()
self.rx_lock = threading.Lock()
self.rx_thread = None
+ # 可探测的设备类型号. 按此顺序尝试打开/初始化, 失败自动回退.
+ # 实测本设备(CANalyst-II)需用 DevType=4(USBCAN2) 才能正确初始化.
+ DEVICE_TYPE_CANDIDATES = (VCI_USBCAN2, VCI_USBCAN_2E_U, VCI_USBCAN1)
+
+ def _open_device(self):
+ """按候选顺序打开设备, 返回实际使用的 DevType."""
+ for dt in self.DEVICE_TYPE_CANDIDATES:
+ try:
+ self.dll.VCI_CloseDevice(dt, self.device_index)
+ except Exception:
+ pass
+ if self.dll.VCI_OpenDevice(dt, self.device_index, 0) == _RET_OK:
+ return dt
+ return None
+
def open(self):
- self.sock = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
+ self.dll = _load_controlcan_dll()
+
+ if self.bitrate not in _BITRATE_TABLE:
+ raise RuntimeError(
+ f"不支持的 CAN 位速率 {self.bitrate} bps. "
+ f"支持: {sorted(_BITRATE_TABLE)}"
+ )
+ timing0, timing1 = _BITRATE_TABLE[self.bitrate]
+
+ # 1) 打开设备 (自动探测 DevType)
+ dt = self._open_device()
+ if dt is None:
+ raise RuntimeError(
+ f"打开 CANalyst-II 设备失败 (DevIndex={self.device_index}). "
+ f"请确认设备已连接且驱动已安装, 且未被其它程序占用."
+ )
+ self.dev_type = dt
+
+ # 2) 读取设备信息, 确认 USB 设备真正被识别
+ board = VCIBoardInfo()
+ board_ok = self.dll.VCI_ReadBoardInfo(
+ self.dev_type, self.device_index, byref(board)) != 0
+ if not board_ok:
+ self._free_device()
+ raise RuntimeError(
+ "未能从 USB 读取 CANalyst-II 设备信息.\n"
+ "可能原因: 1) 设备未插入或 USB 线接触不良; 2) 设备驱动未正确安装; "
+ "3) 设备被其它软件(如 USBCAN 上位机)占用.\n"
+ "请拔插设备后重试, 或先关闭占用设备的程序."
+ )
+
+ # 2.5) 先 VCI_SetReference 设置主时钟. 本设备(CANalyst-II, DevType=4)
+ # 主时钟为 16MHz(工具显示 16000000), 时序 T0=0x01/T1=0x14
+ # 在 16MHz 下 (分频2, 总TQ=8) 才得到准确的 1Mbps.
try:
- self.sock.bind((self.interface,))
- except OSError as e:
+ clk = ctypes.c_uint(16000000)
+ self.dll.VCI_SetReference(
+ self.dev_type, self.device_index, self.channel, 1, byref(clk))
+ except Exception:
+ pass # 旧设备不支持时忽略
+
+ # 3) 复位 CAN (部分固件要求先复位再初始化)
+ self.dll.VCI_ResetCAN(self.dev_type, self.device_index, self.channel)
+
+ # 4) 初始化 CAN (接收全部报文: Filter=0 关闭地址滤波)
+ init_cfg = VCIInITConfig()
+ init_cfg.AccCode = 0
+ init_cfg.AccMask = 0xFFFFFFFF
+ init_cfg.Reserved = 0
+ init_cfg.Filter = 0
+ init_cfg.Timing0 = timing0
+ init_cfg.Timing1 = timing1
+ init_cfg.Mode = 0 # 0=正常模式
+
+ init_ret = self.dll.VCI_InitCAN(
+ self.dev_type, self.device_index, self.channel, byref(init_cfg)
+ )
+ if init_ret != _RET_OK:
+ # VCI_InitCAN 返回成功初始化的通道数, 某些固件返回 1
+ self._free_device()
raise RuntimeError(
- f"Cannot bind to {self.interface}. "
- f"Run: sudo ip link add {self.interface} type vcan && "
- f"sudo ip link set {self.interface} up"
- ) from e
- self.sock.settimeout(1.0)
+ f"初始化 CAN{self.channel} 失败 (位速率 {self.bitrate} bps, "
+ f"返回值={init_ret}, DevType={self.dev_type}).\n"
+ "可能原因: 1) 设备被其它软件(如 USBCAN 上位机/CANalyst 工具)占用; "
+ "2) 设备在位, 但需要先关闭占用程序; "
+ "3) 当前系统同时连接了多个同型号设备, DevIndex 可能不是 0."
+ )
+
+ # 5) 清空接收缓冲并启动 CAN
+ self.dll.VCI_ClearBuffer(self.dev_type, self.device_index, self.channel)
+ if self.dll.VCI_StartCAN(
+ self.dev_type, self.device_index, self.channel
+ ) != _RET_OK:
+ self._free_device()
+ raise RuntimeError(f"启动 CAN{self.channel} 失败.")
+
self.running = True
self.rx_thread = threading.Thread(target=self._rx_loop, daemon=True)
self.rx_thread.start()
+ # ===== 临时自测: 启动后发 2 个测试包, 验证收发回路 =====
+ import time as _t
+ try:
+ for i in range(2):
+ test_data = bytes([0x41, 0x42, 0x43, 0x44, i, 0x00, 0x00, 0x00])
+ self.send_raw(0x01, test_data)
+ print(f"[CAN TX] 测试包 {i+1}/2 已发送 ID=0x001 "
+ f"{' '.join('%02X' % b for b in test_data)}")
+ _t.sleep(1.0)
+ except Exception as e:
+ print(f"[CAN TX] 测试发送异常: {e}")
+ # ======================================================
+
+ def _free_device(self):
+ try:
+ self.dll.VCI_CloseDevice(self.dev_type, self.device_index)
+ except Exception:
+ pass
+
def close(self):
self.running = False
if self.rx_thread:
self.rx_thread.join(timeout=2)
- if self.sock:
- self.sock.close()
- self.sock = None
+ try:
+ if self.dll is not None:
+ self.dll.VCI_CloseDevice(self.dev_type, self.device_index)
+ except Exception:
+ pass
+ self.dll = None
def _rx_loop(self):
+ buf = (VCICanObj * 32)()
while self.running:
try:
- frame = self.sock.recv(16)
- if frame:
+ count = self.dll.VCI_Receive(
+ self.dev_type, self.device_index, self.channel,
+ buf, 32, 500, # WaitTime=500ms
+ )
+ for i in range(count):
+ obj = buf[i]
+ arb_id = obj.ID
+ data = bytes(obj.Data[:obj.DataLen])
+ ts = time.strftime("%H:%M:%S") + (".%03d" % (obj.TimeStamp))
+ hex_str = " ".join("%02X" % b for b in data)
+ print(f"[CAN RX] t={ts} ID=0x{arb_id:03X} LEN={len(data)} {hex_str}")
with self.rx_lock:
- self.rx_queue.append(frame)
- except socket.timeout:
- continue
+ self.rx_queue.append((arb_id, data))
except Exception:
if self.running:
time.sleep(0.01)
def send_raw(self, can_id: int, data: bytes):
if len(data) > 8:
raise ValueError("CAN data max 8 bytes")
- # pack: CAN ID (4 bytes) + DLC (1 byte) + padding (3 bytes) + data (8 bytes)
- can_frame = struct.pack('<IB3x', can_id, len(data)) + data.ljust(8, b'\x00')
- self.sock.send(can_frame)
+ obj = VCICanObj()
+ obj.ID = can_id & 0x7FF # 11-bit 标准帧
+ obj.TimeStamp = 0
+ obj.TimeFlag = 0
+ obj.SendType = 0 # 正常发送
+ obj.RemoteFlag = 0
+ obj.ExternFlag = 0 # 标准帧
+ obj.DataLen = len(data)
+ for i in range(len(data)):
+ obj.Data[i] = data[i]
+
+ sent = self.dll.VCI_Transmit(
+ self.dev_type, self.device_index, self.channel, byref(obj), 1
+ )
+ if sent == 0:
+ raise RuntimeError("CAN 发送失败 (发送缓冲满或总线忙).")
def recv_raw(self, timeout: float = 1.0):
deadline = time.time() + timeout
while time.time() < deadline:
with self.rx_lock:
if self.rx_queue:
- frame = self.rx_queue.popleft()
- can_id, dlc = struct.unpack_from('<IB', frame)
- data = frame[8:8 + dlc]
- return can_id, data
+ return self.rx_queue.popleft()
time.sleep(0.001)
return None
def flush_rx(self):
with self.rx_lock:
self.rx_queue.clear()
+ try:
+ self.dll.VCI_ClearBuffer(self.dev_type, self.device_index, self.channel)
+ except Exception:
+ pass
def send_modbus_frame(self, modbus_frame: bytes):
"""Send a Modbus frame via CAN packets using our own CAN ID.
-
+
Each Modbus frame is split into multiple CAN packets:
- Data[0]: Total number of packets
- Data[1]: Packet sequence number (0-based)
for seq in range(total_packets):
offset = seq * 6
chunk = modbus_frame[offset:offset + 6]
- # 不填充, 按实际长度发送。CAN 控制器通过 DLC 标识数据长度
can_data = bytes([total_packets, seq]) + chunk
self.send_raw(self.can_id, can_data)
@staticmethod
def _trim_padding(data: bytes) -> bytes:
- """Trim padding zeros from CAN-reassembled Modbus frame (安全兜底).
-
- 新协议不再填充零, 但保留此函数作为安全兜底:
- 如果出现极端字节错乱, 从长到短 CRC 遍历仍能恢复。
-
- 为什么从长到短:
- - 优先匹配完整帧, 避免短数据的假阳性 CRC
- """
+ """Trim padding zeros from CAN-reassembled Modbus frame (安全兜底)."""
from .modbus_layer import crc16 as _crc16
import struct as _struct
-
+
if len(data) < 5:
return data
-
- # 从长到短遍历, 优先匹配最长有效帧
+
for length in range(len(data), 4, -1):
candidate = data[:length]
recv_crc = _struct.unpack('<H', candidate[-2:])[0]
calc_crc = _crc16(candidate[:-2])
if recv_crc == calc_crc:
return candidate
- # Fallback: return original data
return data
def recv_modbus_frame(self, timeout: float = 3.0, src_can_id: int = None):
- """Receive a complete Modbus frame reassembled from CAN packets.
-
- Args:
- timeout: Max time to wait in seconds
- src_can_id: If set, only accept frames from this CAN ID
- """
+ """Receive a complete Modbus frame reassembled from CAN packets."""
packets = {}
total = None
deadline = time.time() + timeout
if len(data) < 2:
continue
- # Filter by source CAN ID if specified
if src_can_id is not None and can_id != src_can_id:
continue
return None
-def setup_vcan():
- """Create and bring up virtual CAN interface."""
- import os
- os.system('sudo ip link add vcan0 type vcan 2>/dev/null || true')
- os.system('sudo ip link set vcan0 up 2>/dev/null')
- print("[CAN] Virtual CAN interface vcan0 ready")
\ No newline at end of file
+def setup_can(channel: int = 0, bitrate: int = DEFAULT_BITRATE):
+ """初始化并验证 CANalyst-II 设备连接 (打开后立即关闭)."""
+ if channel not in (0, 1):
+ raise RuntimeError(f"无效的 CAN 通道号: {channel} (仅支持 0 或 1)")
+ tmp = CanInterface(str(channel), CAN_SLAVE_ID, bitrate=bitrate)
+ try:
+ tmp.open()
+ finally:
+ tmp.close()
+ print(f"[CAN] CANalyst-II channel CAN{channel} "
+ f"@{bitrate/1000:.0f} kbps ready")
\ No newline at end of file
from datetime import datetime
from .can_layer import (
- CanInterface, CAN_MASTER_ID, CAN_SLAVE_ID, setup_vcan
+ CanInterface, CAN_MASTER_ID, CAN_SLAVE_ID, setup_can
)
from .modbus_layer import (
build_read_holding_registers, extract_modbus_data
class MasterController:
"""Master controller that polls the protection board."""
- def __init__(self, interface='vcan0', poll_interval=5):
+ def __init__(self, interface='0', poll_interval=5):
self.interface = interface
self.poll_interval = poll_interval
self.can = None
import argparse
parser = argparse.ArgumentParser(description='BDM120 Master Controller')
- parser.add_argument('--iface', '-i', default='vcan0',
- help='CAN interface (default: vcan0)')
+ parser.add_argument('--iface', '-i', default='0',
+ help='CANalyst-II 通道号 (default: 0)')
parser.add_argument('--interval', '-t', type=int, default=5,
help='Poll interval in seconds (default: 5)')
parser.add_argument('--print-all', '-p', action='store_true',
args = parser.parse_args()
print("[MASTER] Setting up CAN interfaces...")
- setup_vcan()
+ setup_can(channel=int(args.iface))
master = MasterController(interface=args.iface, poll_interval=args.interval)
import os
from .slave_sim import SlaveSimulator, create_default_registers, save_default_config
-from .can_layer import setup_vcan
+from .can_layer import setup_can
# ============================================================
# Register name definitions (based on BDM120-SlaveV1.0.1.md)
class SlaveGUI:
"""Tkinter GUI for the BDM120 slave simulator."""
- def __init__(self, interface='vcan0', config_path=None):
+ def __init__(self, interface='0', config_path=None):
self.interface = interface
self.config_path = config_path
def _start_slave(self):
"""Start the slave simulator."""
try:
- setup_vcan()
+ setup_can(channel=int(self.interface))
except RuntimeError:
pass
parser = argparse.ArgumentParser(description='BDM120 Slave Simulator GUI')
parser.add_argument('--config', '-c', default=None,
help='JSON config file for register values')
- parser.add_argument('--iface', '-i', default='vcan0',
- help='CAN interface (default: vcan0)')
+ parser.add_argument('--iface', '-i', default='0',
+ help='CANalyst-II 通道号 (default: 0)')
args = parser.parse_args()
# Redirect stdout to GUI console if needed
from .can_layer import (
CanInterface, CAN_MASTER_ID, CAN_SLAVE_ID, SLAVE_RESPONSE_ADDR,
- setup_vcan
+ setup_can
)
from .modbus_layer import (
check_crc, parse_frame, build_read_response, build_read_coils_response,
class SlaveSimulator:
"""Protection board slave simulator."""
- def __init__(self, interface='vcan1', config_path=None):
+ def __init__(self, interface='0', config_path=None):
self.interface = interface
self.config_path = config_path
self.can = None
pass
print(f"[CONFIG] Applied {len(config['registers'])} register overrides from {path}")
- def start(self):
- self.can = CanInterface(self.interface, CAN_SLAVE_ID)
+ def start(self, bitrate=1000000):
+ self.can = CanInterface(self.interface, CAN_SLAVE_ID, bitrate=bitrate)
self.can.open()
self.running = True
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
- print(f"[SLAVE] Started on {self.interface}, CAN ID=0x{CAN_SLAVE_ID:X}")
+ print(f"[SLAVE] Started on channel {self.interface}, "
+ f"CAN ID=0x{CAN_SLAVE_ID:X}, "
+ f"{bitrate/1000:.0f} kbps")
def stop(self):
self.running = False
parser = argparse.ArgumentParser(description='BDM120 Protection Board Simulator')
parser.add_argument('--config', '-c', default=None,
help='JSON config file for register values')
- parser.add_argument('--iface', '-i', default='vcan1',
- help='CAN interface (default: vcan1)')
+ parser.add_argument('--iface', '-i', default='0',
+ help='CANalyst-II 通道号 (默认: 0)')
parser.add_argument('--save-defaults', '-s', action='store_true',
help='Save default register config to JSON')
args = parser.parse_args()
print("[SLAVE] Setting up CAN interfaces...")
try:
- setup_vcan()
+ setup_can(channel=int(args.iface))
except RuntimeError as e:
print(f"[SLAVE] Warning: {e}")
from urllib.parse import urlparse, parse_qs
from .slave_sim import SlaveSimulator, create_default_registers
-from .can_layer import setup_vcan
+from .can_layer import setup_can
# ============================================================
# Register name definitions (based on BDM120-SlaveV1.0.1.md)
def get_slave():
global _slave
if _slave is None:
- _slave = SlaveSimulator(interface='vcan0')
+ _slave = SlaveSimulator(interface='0')
return _slave
slave = get_slave()
if not slave.running:
try:
- setup_vcan()
+ setup_can(channel=int(slave.interface))
except RuntimeError:
pass
slave.start()
parser = argparse.ArgumentParser(description='BDM120 Slave Simulator Web GUI')
parser.add_argument('--config', '-c', default=None,
help='JSON config file for register values')
- parser.add_argument('--iface', '-i', default='vcan0',
- help='CAN interface (default: vcan0)')
+ parser.add_argument('--iface', '-i', default='0',
+ help='CANalyst-II 通道号 (default: 0)')
parser.add_argument('--port', '-p', type=int, default=8080,
help='HTTP server port (default: 8080)')
parser.add_argument('--no-browser', action='store_true',
# Initialize slave
print(f"[INIT] Setting up CAN interface '{args.iface}'...")
try:
- setup_vcan()
+ setup_can(channel=int(args.iface))
except RuntimeError as e:
print(f"[INIT] Warning: {e}")