"""Exact packed ABI from the pinned Waveshare x86-64 header; no demo execution.""" import contextlib import ctypes as C import os from pathlib import Path U8, U16, U32, U64, PTR = C.c_uint8, C.c_uint16, C.c_uint32, C.c_uint64, C.c_void_p class Packed(C.Structure): _pack_ = 1 class DeviceInfo(Packed): _fields_ = [(name, U16) for name in ("hardware", "firmware", "driver", "interface", "irq")] + [ ("channels", U8), ("serial", U8 * 21), ("model", U8 * 40), ("reserved", U16 * 5), ] class Classic(Packed): _fields_ = [ ("id", U32), ("length", U8), ("flags", U8), ("res0", U8), ("res1", U8), ("data", U8 * 8), ] class FD(Packed): _fields_ = [ ("id", U32), ("length", U8), ("flags", U8), ("res0", U8), ("res1", U8), ("data", U8 * 64), ] class InitClassic(Packed): _fields_ = [ ("code", U32), ("mask", U32), ("reserved", U32), ("filter", U8), ("timing0", U8), ("timing1", U8), ("mode", U8), ] class InitFD(Packed): _fields_ = [ ("code", U32), ("mask", U32), ("abit", U32), ("dbit", U32), ("brp", U32), ("filter", U8), ("mode", U8), ("pad", U16), ("reserved", U32), ] class InitUnion(C.Union): _pack_ = 1 _fields_ = [("classic", InitClassic), ("fd", InitFD)] class Init(Packed): _fields_ = [("type", U32), ("config", InitUnion)] class Tx(Packed): _fields_ = [("frame", Classic), ("send_type", U32)] class TxFD(Packed): _fields_ = [("frame", FD), ("send_type", U32)] class Rx(Packed): _fields_ = [("frame", Classic), ("timestamp", U64)] class RxFD(Packed): _fields_ = [("frame", FD), ("timestamp", U64)] SIZES = {DeviceInfo: 82, Classic: 16, FD: 72, Init: 32, Tx: 20, TxFD: 76, Rx: 24, RxFD: 80} def check_abi(): for cls, size in SIZES.items(): if C.sizeof(cls) != size: raise RuntimeError("SDK ABI mismatch: " + cls.__name__) def library(path="/usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so"): check_abi() lib = C.CDLL(path) signatures = { "OpenDevice": (PTR, [U32, U32, U32]), "CloseDevice": (U32, [PTR]), "GetDeviceInf": (U32, [PTR, C.POINTER(DeviceInfo)]), "IsDeviceOnLine": (U32, [PTR]), "InitCAN": (PTR, [PTR, U32, C.POINTER(Init)]), "GetReceiveNum": (U32, [PTR, U8]), "SetBaudRateCustom": (U32, [PTR, U32, C.c_char_p]), } for name in ("StartCAN", "ResetCAN", "ClearBuffer", "ClearFilter", "AckFilter"): signatures[name] = (U32, [PTR]) for name in ("SetAbitBaud", "SetDbitBaud", "SetCANFDStandard"): signatures[name] = (U32, [PTR, U32, U32]) for name in ("SetFilterMode", "SetFilterStartID", "SetFilterEndID"): signatures[name] = (U32, [PTR, U32]) for suffix, tx, rx in (("", Tx, Rx), ("FD", TxFD, RxFD)): signatures["Transmit" + suffix] = (U32, [PTR, C.POINTER(tx), U32]) signatures["Receive" + suffix] = (U32, [PTR, C.POINTER(rx), U32, C.c_int]) for name, (result, args) in signatures.items(): fn = getattr(lib, "ZCAN_" + name) fn.restype, fn.argtypes = result, args return lib def text(value): return bytes(value).split(b"\0", 1)[0].decode("ascii", "strict").strip() def version(value): return f"{value >> 8:X}.{value & 255:02X}" class SDK: def __init__(self, index, expected_usb, lib=None): self.lib = lib or library() self.handle, self.handles = None, [None, None] self.handle = self.lib.ZCAN_OpenDevice(41, index, 0) if not self.handle: raise OSError("Не удалось открыть USB-CAN. Проверьте доступ и другие программы.") try: # SDK selects by index. Prove its actual open device before assigning # a physical session; USB port order is never hardware identity. opened = set() for entry in Path("/proc/self/fd").iterdir(): try: target = os.readlink(entry) if target.startswith("/dev/bus/usb/"): opened.add(target) except OSError: pass if opened != {expected_usb}: raise OSError("SDK не подтвердил однозначное соответствие USB-устройству.") info = DeviceInfo() self.ok(self.lib.ZCAN_GetDeviceInf(self.handle, C.byref(info)), "идентификация") serial = text(info.serial) if not serial or len(serial) > 20 or info.channels != 2: raise OSError("Не подтверждены серийный номер и два CAN-канала.") self.identity = { "serial": serial, "model": text(info.model), "channels": int(info.channels), **{ key: version(getattr(info, key)) for key in ("hardware", "firmware", "driver", "interface") }, } except BaseException: self.close() raise @staticmethod def ok(value, operation): if value != 1: raise OSError("SDK отклонил операцию: " + operation) def start(self, channel, config): self.stop(channel) self.ok( self.lib.ZCAN_SetAbitBaud(self.handle, channel, config["bitrate"]), "скорость арбитража" ) self.ok( self.lib.ZCAN_SetDbitBaud(self.handle, channel, config["data_bitrate"]), "скорость данных", ) self.ok( self.lib.ZCAN_SetCANFDStandard( self.handle, channel, int(config["standard"] == "bosch") ), "стандарт FD", ) init = Init() # The CAN-FD controller uses its FD init structure for classical frames # too; protocol selection governs allowed TX/RX frame formats. init.type = 1 init.config.fd.mode = int(config["mode"] == "listen") init.config.fd.mask = 0xFFFFFFFF handle = self.lib.ZCAN_InitCAN(self.handle, channel, C.byref(init)) if not handle: raise OSError("SDK не инициализировал CAN-канал.") self.handles[channel] = handle try: self.ok(self.lib.ZCAN_ClearFilter(handle), "очистка фильтров") # Explicit full ranges when no filter was requested. for item in config["filters"] or [ {"extended": False, "start": 0, "end": 0x7FF}, {"extended": True, "start": 0, "end": 0x1FFFFFFF}, ]: self.ok(self.lib.ZCAN_SetFilterMode(handle, int(item["extended"])), "тип фильтра") self.ok(self.lib.ZCAN_SetFilterStartID(handle, item["start"]), "начало фильтра") self.ok(self.lib.ZCAN_SetFilterEndID(handle, item["end"]), "конец фильтра") self.ok(self.lib.ZCAN_AckFilter(handle), "применение фильтров") self.ok(self.lib.ZCAN_StartCAN(handle), "запуск канала") except BaseException: self.stop(channel) raise def stop(self, channel): handle = self.handles[channel] if handle: self.ok(self.lib.ZCAN_ResetCAN(handle), "остановка канала") self.handles[channel] = None def clear(self, channel): if self.handles[channel]: self.ok(self.lib.ZCAN_ClearBuffer(self.handles[channel]), "очистка приёмного буфера") def receive(self, channel): handle = self.handles[channel] if not handle: return [] frames = [] for fd, cls, method in ( (False, Rx, self.lib.ZCAN_Receive), (True, RxFD, self.lib.ZCAN_ReceiveFD), ): data = (cls * 64)() count = method(handle, data, 64, 0) if count > 64: raise OSError("SDK вернул ошибку чтения CAN.") for item in data[:count]: f = item.frame if f.length > (64 if fd else 8): raise OSError("SDK вернул повреждённый CAN-кадр.") frames.append( { "channel": channel, "direction": "RX", "timestamp_us": int(item.timestamp), "id": int(f.id & 0x1FFFFFFF), "extended": bool(f.id & 0x80000000), "rtr": bool(f.id & 0x40000000), "error": bool(f.id & 0x20000000), "fd": fd, "brs": bool(f.flags & 1) if fd else False, "esi": bool(f.flags & 2) if fd else False, "dlc": int(f.length), "data": bytes(f.data[: f.length]).hex().upper(), } ) return frames def transmit(self, channel, frame): if not self.handles[channel]: raise ValueError("Канал остановлен.") value = TxFD() if frame["fd"] else Tx() value.frame.id = frame["id"] | (int(frame["extended"]) << 31) | (int(frame["rtr"]) << 30) value.frame.length = frame["dlc"] value.frame.flags = int(frame["brs"]) if frame["fd"] else 0 data = bytes.fromhex(frame["data"]) for index, byte in enumerate(data): value.frame.data[index] = byte value.send_type = frame["send_type"] fn = self.lib.ZCAN_TransmitFD if frame["fd"] else self.lib.ZCAN_Transmit self.ok(fn(self.handles[channel], C.byref(value), 1), "передача кадра") def online(self): # SDK's documented STATUS_ONLINE is 2, not STATUS_OK (1). return self.lib.ZCAN_IsDeviceOnLine(self.handle) == 2 def close(self): if self.handle: for channel in range(2): with contextlib.suppress(OSError): self.stop(channel) self.lib.ZCAN_CloseDevice(self.handle) self.handle = None