python-can-csscan-serial 2.4.0__py3-none-any.whl → 2026.11.20__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.
- python_can_csscan_serial/README.md +51 -0
- python_can_csscan_serial/__init__.py +9 -0
- python_can_csscan_serial/_bus.py +118 -0
- python_can_csscan_serial/_protocol.py +146 -0
- python_can_csscan_serial-2026.11.20.dist-info/METADATA +74 -0
- python_can_csscan_serial-2026.11.20.dist-info/RECORD +9 -0
- {python_can_csscan_serial-2.4.0.dist-info → python_can_csscan_serial-2026.11.20.dist-info}/WHEEL +1 -1
- python_can_csscan_serial-2026.11.20.dist-info/entry_points.txt +2 -0
- {python_can_csscan_serial-2.4.0.dist-info → python_can_csscan_serial-2026.11.20.dist-info}/licenses/LICENSE +20 -20
- python_can_csscan_serial/CSSCANSerial.py +0 -278
- python_can_csscan_serial-2.4.0.dist-info/METADATA +0 -22
- python_can_csscan_serial-2.4.0.dist-info/RECORD +0 -7
- python_can_csscan_serial-2.4.0.dist-info/entry_points.txt +0 -2
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# python-can-csscan-serial
|
|
2
|
+
|
|
3
|
+
Adds the USB interface of [CSS Electronics](https://www.csselectronics.com/) CLX000 and CANmod devices to [python-can](https://python-can.readthedocs.io/), as the interface `csscan_serial`.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
pip install python-can-csscan-serial
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Finding the serial port
|
|
10
|
+
|
|
11
|
+
The device is listed as a USB virtual serial port. Only one process can open a serial port at a time.
|
|
12
|
+
|
|
13
|
+
| Device | USB VID:PID |
|
|
14
|
+
|---|---|
|
|
15
|
+
| CLX000 series (e.g. CL2000) | `1CBE:021A` |
|
|
16
|
+
| CANmod series | `04D8:EB18` |
|
|
17
|
+
|
|
18
|
+
- Windows: `Device Manager` > `Ports (COM & LPT)`, e.g. `COM19`.
|
|
19
|
+
- Linux: e.g. `/dev/ttyACM0`. Run `journalctl -f` while connecting the device to see the assigned port.
|
|
20
|
+
|
|
21
|
+
python-can can also find the connected devices:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
>>> can.detect_available_configs("csscan_serial")
|
|
25
|
+
[{'interface': 'csscan_serial', 'channel': '/dev/ttyACM0'}]
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
import can
|
|
32
|
+
|
|
33
|
+
with can.Bus(interface="csscan_serial", channel="/dev/ttyACM0") as bus:
|
|
34
|
+
# Send a message
|
|
35
|
+
bus.send(can.Message(arbitration_id=0x123, is_extended_id=False, data=[0x01, 0x23, 0x45, 0x67]))
|
|
36
|
+
|
|
37
|
+
# Receive messages
|
|
38
|
+
for msg in bus:
|
|
39
|
+
print(msg)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The bit rate and other bus settings are set in the device configuration. python-can arguments such as `bitrate` are ignored.
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
The interface also works with the python-can [command-line tools](https://python-can.readthedocs.io/en/stable/scripts.html), e.g.:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
can_logger --interface csscan_serial --channel /dev/ttyACM0
|
|
49
|
+
can_viewer --interface csscan_serial --channel /dev/ttyACM0
|
|
50
|
+
can_player --interface csscan_serial --channel /dev/ttyACM0 dump.log
|
|
51
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""python-can interface for CSS Electronics devices with a USB serial interface (CANmod, CLX000).
|
|
2
|
+
|
|
3
|
+
Registered with python-can as ``interface="csscan_serial"``. Full documentation: ``README.md`` in this package
|
|
4
|
+
directory (``importlib.resources.files("python_can_csscan_serial") / "README.md"``).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._bus import CSSCANSerialBus
|
|
8
|
+
|
|
9
|
+
__all__ = ["CSSCANSerialBus"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
import time
|
|
3
|
+
from collections import deque
|
|
4
|
+
from typing import Any, List, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
import can
|
|
7
|
+
import serial
|
|
8
|
+
from serial.tools.list_ports import comports
|
|
9
|
+
|
|
10
|
+
from ._protocol import FLAG, MAX_FRAME_SIZE, decode, encode
|
|
11
|
+
|
|
12
|
+
# Serial read timeout. Bounds how long recv() can overshoot its timeout
|
|
13
|
+
_READ_TIMEOUT = 0.01
|
|
14
|
+
|
|
15
|
+
# USB (VID, PID) of supported devices
|
|
16
|
+
_USB_IDS = {
|
|
17
|
+
(0x1CBE, 0x021A), # CLX000
|
|
18
|
+
(0x04D8, 0xEB18), # CANmod
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CSSCANSerialBus(can.BusABC):
|
|
23
|
+
"""python-can bus for CSS Electronics devices with a USB serial interface (CLX000 and CANmod series).
|
|
24
|
+
|
|
25
|
+
:param channel: Serial port, e.g. ``COM19`` or ``/dev/ttyACM0`` (any pyserial URL is accepted).
|
|
26
|
+
:param receive_own_messages: Also receive the messages the device reports as transmitted by itself.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
channel: Any,
|
|
32
|
+
can_filters: Optional[can.typechecking.CanFilters] = None,
|
|
33
|
+
receive_own_messages: bool = False,
|
|
34
|
+
**kwargs: object,
|
|
35
|
+
):
|
|
36
|
+
if not channel:
|
|
37
|
+
raise can.CanInitializationError("A channel (serial port) is required")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
self._serial = serial.serial_for_url(channel, timeout=_READ_TIMEOUT)
|
|
41
|
+
except (serial.SerialException, ValueError) as e:
|
|
42
|
+
raise can.CanInitializationError(f"Could not open {channel}: {e}") from e
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
# Discard data received before the bus was opened
|
|
46
|
+
self._serial.reset_input_buffer()
|
|
47
|
+
except serial.SerialException as e:
|
|
48
|
+
self._serial.close()
|
|
49
|
+
raise can.CanInitializationError(f"Could not open {channel}: {e}") from e
|
|
50
|
+
|
|
51
|
+
self._receive_own_messages = receive_own_messages
|
|
52
|
+
self._buffer = bytearray()
|
|
53
|
+
self._messages = deque()
|
|
54
|
+
self._write_lock = threading.Lock()
|
|
55
|
+
self.channel_info = f"CSSCAN serial on {channel}"
|
|
56
|
+
|
|
57
|
+
super().__init__(channel, can_filters, **kwargs)
|
|
58
|
+
|
|
59
|
+
def _recv_internal(self, timeout: Optional[float]) -> Tuple[Optional[can.Message], bool]:
|
|
60
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
while not self._messages:
|
|
64
|
+
pending = self._serial.in_waiting
|
|
65
|
+
if pending == 0 and deadline is not None and time.monotonic() >= deadline:
|
|
66
|
+
return None, False
|
|
67
|
+
# Blocks for up to _READ_TIMEOUT if no data is pending
|
|
68
|
+
data = self._serial.read(max(pending, 1))
|
|
69
|
+
self._parse(data, time.time())
|
|
70
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
71
|
+
break
|
|
72
|
+
except serial.SerialException as e:
|
|
73
|
+
raise can.CanOperationError(f"Could not read from {self.channel_info}: {e}") from e
|
|
74
|
+
|
|
75
|
+
return (self._messages.popleft() if self._messages else None), False
|
|
76
|
+
|
|
77
|
+
def _parse(self, data: bytes, timestamp: float) -> None:
|
|
78
|
+
"""Decode the frames completed by `data`. Messages are timestamped with the time the data was read."""
|
|
79
|
+
if FLAG not in data:
|
|
80
|
+
self._buffer += data
|
|
81
|
+
else:
|
|
82
|
+
# The last segment is either empty or an incomplete frame, kept for the next read. A segment preceding the
|
|
83
|
+
# first flag (e.g. the tail of a frame when connecting mid-stream) fails the CRC check and is dropped.
|
|
84
|
+
*frames, self._buffer = (self._buffer + data).split(bytes([FLAG]))
|
|
85
|
+
for frame in frames:
|
|
86
|
+
if frame:
|
|
87
|
+
msg = decode(frame, timestamp)
|
|
88
|
+
if msg is not None and (msg.is_rx or self._receive_own_messages):
|
|
89
|
+
self._messages.append(msg)
|
|
90
|
+
|
|
91
|
+
# Without flags (e.g. not a supported device), no valid frame can complete the buffer
|
|
92
|
+
if len(self._buffer) > MAX_FRAME_SIZE:
|
|
93
|
+
self._buffer.clear()
|
|
94
|
+
|
|
95
|
+
def send(self, msg: can.Message, timeout: Optional[float] = None) -> None:
|
|
96
|
+
"""Send a message. Raises ValueError for messages that can't be sent and can.CanOperationError if the message
|
|
97
|
+
could not be written within `timeout` seconds (None: wait indefinitely)."""
|
|
98
|
+
frame = encode(msg)
|
|
99
|
+
|
|
100
|
+
with self._write_lock:
|
|
101
|
+
try:
|
|
102
|
+
if self._serial.write_timeout != timeout:
|
|
103
|
+
self._serial.write_timeout = timeout
|
|
104
|
+
self._serial.write(frame)
|
|
105
|
+
except serial.SerialException as e:
|
|
106
|
+
raise can.CanOperationError(f"Could not write to {self.channel_info}: {e}") from e
|
|
107
|
+
|
|
108
|
+
def shutdown(self) -> None:
|
|
109
|
+
super().shutdown()
|
|
110
|
+
self._serial.close()
|
|
111
|
+
|
|
112
|
+
@staticmethod
|
|
113
|
+
def _detect_available_configs() -> List[can.typechecking.AutoDetectedConfig]:
|
|
114
|
+
return [
|
|
115
|
+
{"interface": "csscan_serial", "channel": port.device}
|
|
116
|
+
for port in comports()
|
|
117
|
+
if (port.vid, port.pid) in _USB_IDS
|
|
118
|
+
]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Serial protocol of the device USB interface.
|
|
2
|
+
|
|
3
|
+
Frames are HDLC-like: each frame is enclosed in flag bytes (0x7E), and flag/escape bytes inside a frame are escaped
|
|
4
|
+
(0x7D followed by the byte XOR 0x20). A frame ends with a CRC-16 (big endian) over its unescaped content.
|
|
5
|
+
|
|
6
|
+
Frames from the device: type (1), seconds (4), milliseconds (2), ID (4), DLC (1), data (0-64), CRC (2)
|
|
7
|
+
Frames to the device: type (1), ID (4), DLC (1), data (0-64), CRC (2)
|
|
8
|
+
|
|
9
|
+
The lower nibble of the type is the kind (0x01: received, 0x02: transmitted, 0x03: transmit request), the upper nibble
|
|
10
|
+
holds flags (0x10: remote frame, 0x20: CAN FD). Bit 29 of the ID marks an extended (29-bit) ID.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import struct
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
import can
|
|
17
|
+
|
|
18
|
+
FLAG = 0x7E
|
|
19
|
+
_ESCAPE = 0x7D
|
|
20
|
+
_ESCAPE_XOR = 0x20
|
|
21
|
+
|
|
22
|
+
_KIND_RX = 0x01
|
|
23
|
+
_KIND_TX = 0x02
|
|
24
|
+
_KIND_TX_REQUEST = 0x03
|
|
25
|
+
_FLAG_REMOTE = 0x10
|
|
26
|
+
_FLAG_FD = 0x20
|
|
27
|
+
|
|
28
|
+
_ID_EXTENDED = 0x20000000
|
|
29
|
+
_ID_MASK = 0x1FFFFFFF
|
|
30
|
+
|
|
31
|
+
_RX_HEADER = struct.Struct("!BIHIB")
|
|
32
|
+
_TX_HEADER = struct.Struct("!BIB")
|
|
33
|
+
_CRC_SIZE = 2
|
|
34
|
+
|
|
35
|
+
# Largest frame (without flags) from the device: every byte escaped
|
|
36
|
+
MAX_FRAME_SIZE = 2 * (_RX_HEADER.size + 64 + _CRC_SIZE)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def crc16(data: bytes) -> int:
|
|
40
|
+
"""CRC-16/ARC (polynomial 0xA001 reflected, initial value 0)."""
|
|
41
|
+
crc = 0
|
|
42
|
+
for b in data:
|
|
43
|
+
crc ^= b
|
|
44
|
+
for _ in range(8):
|
|
45
|
+
crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
|
|
46
|
+
return crc
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def stuff(content: bytes) -> bytes:
|
|
50
|
+
"""Append the CRC, escape flag/escape bytes and enclose in flags."""
|
|
51
|
+
content = bytes(content) + crc16(content).to_bytes(_CRC_SIZE, "big")
|
|
52
|
+
out = bytearray([FLAG])
|
|
53
|
+
for b in content:
|
|
54
|
+
if b in (FLAG, _ESCAPE):
|
|
55
|
+
out += bytes([_ESCAPE, b ^ _ESCAPE_XOR])
|
|
56
|
+
else:
|
|
57
|
+
out.append(b)
|
|
58
|
+
out.append(FLAG)
|
|
59
|
+
return bytes(out)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def unstuff(frame: bytes) -> Optional[bytes]:
|
|
63
|
+
"""Revert escaping of a frame (without flags) and verify/remove the CRC. Returns None if the frame is invalid."""
|
|
64
|
+
out = bytearray()
|
|
65
|
+
it = iter(frame)
|
|
66
|
+
for b in it:
|
|
67
|
+
if b == _ESCAPE:
|
|
68
|
+
b = next(it, None)
|
|
69
|
+
if b is None:
|
|
70
|
+
return None
|
|
71
|
+
b ^= _ESCAPE_XOR
|
|
72
|
+
out.append(b)
|
|
73
|
+
|
|
74
|
+
if len(out) < _CRC_SIZE or crc16(out[:-_CRC_SIZE]) != int.from_bytes(out[-_CRC_SIZE:], "big"):
|
|
75
|
+
return None
|
|
76
|
+
return bytes(out[:-_CRC_SIZE])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _validate(msg: can.Message) -> None:
|
|
80
|
+
if msg.is_error_frame:
|
|
81
|
+
raise ValueError("Error frames can't be sent")
|
|
82
|
+
if msg.is_extended_id and not 0 <= msg.arbitration_id <= _ID_MASK:
|
|
83
|
+
raise ValueError(f"Extended ID out of range: 0x{msg.arbitration_id:X}")
|
|
84
|
+
if not msg.is_extended_id and not 0 <= msg.arbitration_id <= 0x7FF:
|
|
85
|
+
raise ValueError(f"Standard ID out of range: 0x{msg.arbitration_id:X}")
|
|
86
|
+
if msg.is_remote_frame:
|
|
87
|
+
if msg.is_fd:
|
|
88
|
+
raise ValueError("CAN FD does not have remote frames")
|
|
89
|
+
if not 0 <= msg.dlc <= 8:
|
|
90
|
+
raise ValueError(f"Remote frame DLC out of range: {msg.dlc}")
|
|
91
|
+
elif len(msg.data) > (64 if msg.is_fd else 8):
|
|
92
|
+
raise ValueError(f"Too much data for a {'CAN FD' if msg.is_fd else 'classic CAN'} frame: {len(msg.data)} bytes")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def encode(msg: can.Message) -> bytes:
|
|
96
|
+
"""Encode a message as a transmit request frame (with flags). Raises ValueError for messages that can't be sent."""
|
|
97
|
+
_validate(msg)
|
|
98
|
+
|
|
99
|
+
frame_type = _KIND_TX_REQUEST
|
|
100
|
+
if msg.is_remote_frame:
|
|
101
|
+
frame_type |= _FLAG_REMOTE
|
|
102
|
+
if msg.is_fd:
|
|
103
|
+
frame_type |= _FLAG_FD
|
|
104
|
+
|
|
105
|
+
can_id = msg.arbitration_id | (_ID_EXTENDED if msg.is_extended_id else 0)
|
|
106
|
+
|
|
107
|
+
if msg.is_remote_frame:
|
|
108
|
+
dlc, data = can.util.len2dlc(msg.dlc), b""
|
|
109
|
+
else:
|
|
110
|
+
dlc = can.util.len2dlc(len(msg.data))
|
|
111
|
+
# CAN FD lengths not matching a DLC are padded to the next DLC length
|
|
112
|
+
data = bytes(msg.data).ljust(can.util.dlc2len(dlc), b"\x00")
|
|
113
|
+
|
|
114
|
+
return stuff(_TX_HEADER.pack(frame_type, can_id, dlc) + data)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def decode(frame: bytes, timestamp: float) -> Optional[can.Message]:
|
|
118
|
+
"""Decode a frame (without flags). Returns None for invalid frames and frames that are not CAN messages.
|
|
119
|
+
|
|
120
|
+
The device timestamp is not used, as the device clock is not necessarily synchronized. Messages get `timestamp`.
|
|
121
|
+
"""
|
|
122
|
+
content = unstuff(frame)
|
|
123
|
+
if content is None or len(content) < _RX_HEADER.size:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
frame_type, _seconds, _milliseconds, can_id, dlc = _RX_HEADER.unpack_from(content)
|
|
127
|
+
kind = frame_type & 0x0F
|
|
128
|
+
if kind not in (_KIND_RX, _KIND_TX):
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
length = can.util.dlc2len(dlc)
|
|
132
|
+
is_remote = bool(frame_type & _FLAG_REMOTE)
|
|
133
|
+
data = content[_RX_HEADER.size:_RX_HEADER.size + length]
|
|
134
|
+
if not is_remote and len(data) != length:
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
return can.Message(
|
|
138
|
+
timestamp=timestamp,
|
|
139
|
+
arbitration_id=can_id & _ID_MASK,
|
|
140
|
+
is_extended_id=bool(can_id & _ID_EXTENDED),
|
|
141
|
+
is_remote_frame=is_remote,
|
|
142
|
+
is_fd=bool(frame_type & _FLAG_FD),
|
|
143
|
+
is_rx=kind == _KIND_RX,
|
|
144
|
+
dlc=length,
|
|
145
|
+
data=None if is_remote else data,
|
|
146
|
+
)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: python-can-csscan-serial
|
|
3
|
+
Version: 2026.11.20
|
|
4
|
+
Summary: python-can interface for CSS Electronics devices with a USB serial interface (CANmod, CLX000)
|
|
5
|
+
Project-URL: Homepage, https://csselectronics.com/
|
|
6
|
+
Project-URL: Source, https://github.com/CSS-Electronics/python-can-csscan-serial
|
|
7
|
+
Project-URL: Changelog, https://github.com/CSS-Electronics/python-can-csscan-serial/blob/master/CHANGELOG.md
|
|
8
|
+
Author: CSS Electronics
|
|
9
|
+
Author-email: contact@csselectronics.com
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Requires-Python: >=3.12
|
|
15
|
+
Requires-Dist: pyserial>=3.5
|
|
16
|
+
Requires-Dist: python-can>=4.6.0
|
|
17
|
+
Provides-Extra: hardware
|
|
18
|
+
Requires-Dist: pytest>=8.0; extra == 'hardware'
|
|
19
|
+
Requires-Dist: python-can-cansub>=2026.09.28; extra == 'hardware'
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest>=8.0; extra == 'test'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# python-can-csscan-serial
|
|
25
|
+
|
|
26
|
+
Adds the USB interface of [CSS Electronics](https://www.csselectronics.com/) CLX000 and CANmod devices to [python-can](https://python-can.readthedocs.io/), as the interface `csscan_serial`.
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
pip install python-can-csscan-serial
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Finding the serial port
|
|
33
|
+
|
|
34
|
+
The device is listed as a USB virtual serial port. Only one process can open a serial port at a time.
|
|
35
|
+
|
|
36
|
+
| Device | USB VID:PID |
|
|
37
|
+
|---|---|
|
|
38
|
+
| CLX000 series (e.g. CL2000) | `1CBE:021A` |
|
|
39
|
+
| CANmod series | `04D8:EB18` |
|
|
40
|
+
|
|
41
|
+
- Windows: `Device Manager` > `Ports (COM & LPT)`, e.g. `COM19`.
|
|
42
|
+
- Linux: e.g. `/dev/ttyACM0`. Run `journalctl -f` while connecting the device to see the assigned port.
|
|
43
|
+
|
|
44
|
+
python-can can also find the connected devices:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
>>> can.detect_available_configs("csscan_serial")
|
|
48
|
+
[{'interface': 'csscan_serial', 'channel': '/dev/ttyACM0'}]
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import can
|
|
55
|
+
|
|
56
|
+
with can.Bus(interface="csscan_serial", channel="/dev/ttyACM0") as bus:
|
|
57
|
+
# Send a message
|
|
58
|
+
bus.send(can.Message(arbitration_id=0x123, is_extended_id=False, data=[0x01, 0x23, 0x45, 0x67]))
|
|
59
|
+
|
|
60
|
+
# Receive messages
|
|
61
|
+
for msg in bus:
|
|
62
|
+
print(msg)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The bit rate and other bus settings are set in the device configuration. python-can arguments such as `bitrate` are ignored.
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
The interface also works with the python-can [command-line tools](https://python-can.readthedocs.io/en/stable/scripts.html), e.g.:
|
|
69
|
+
|
|
70
|
+
```
|
|
71
|
+
can_logger --interface csscan_serial --channel /dev/ttyACM0
|
|
72
|
+
can_viewer --interface csscan_serial --channel /dev/ttyACM0
|
|
73
|
+
can_player --interface csscan_serial --channel /dev/ttyACM0 dump.log
|
|
74
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
python_can_csscan_serial/__init__.py,sha256=fPrtwnWrhBaK3fYQ5sEPl6NPImBs6RsIzrunnUkGi88,365
|
|
2
|
+
python_can_csscan_serial/_bus.py,sha256=EeIfxf0lYMX3mBKB_tYChZ_0udQ3ClF9MpspViQnI_0,4833
|
|
3
|
+
python_can_csscan_serial/_protocol.py,sha256=5Svh3igM8Pnfrj7ssLYHGT_wKxqBALhT2d5qTWuoG-Y,5032
|
|
4
|
+
python_can_csscan_serial/README.md,sha256=jSIg9mx8-D_Y57kTKt93f8tcsocMayIDE4HESL5o_Sg,1604
|
|
5
|
+
python_can_csscan_serial-2026.11.20.dist-info/METADATA,sha256=hC496WamtTzZA90X-L6NAhK5y6YnCmrIFRx1eCqe3gE,2558
|
|
6
|
+
python_can_csscan_serial-2026.11.20.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
python_can_csscan_serial-2026.11.20.dist-info/entry_points.txt,sha256=LGyKp_Wjk6VZ0uaIMAOu_fOdZT-ruC7rayGo_DmDApk,73
|
|
8
|
+
python_can_csscan_serial-2026.11.20.dist-info/licenses/LICENSE,sha256=KZHCkOv2mlCJIFIMh6ASnDS75zQe3IsxgmvAOoKuHJI,1071
|
|
9
|
+
python_can_csscan_serial-2026.11.20.dist-info/RECORD,,
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 CSS-Electronics
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 CSS-Electronics
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
import datetime
|
|
2
|
-
|
|
3
|
-
import can
|
|
4
|
-
import os
|
|
5
|
-
import serial
|
|
6
|
-
import struct
|
|
7
|
-
|
|
8
|
-
from can import Message, CanInterfaceNotImplementedError
|
|
9
|
-
from collections import deque
|
|
10
|
-
from serial.serialutil import SerialException, Timeout
|
|
11
|
-
from typing import Any, List, Optional, Tuple
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class CSSCANSerial(can.BusABC):
|
|
15
|
-
|
|
16
|
-
_VID_CLX000 = 0x1CBE
|
|
17
|
-
_VID_CANmod = 0x04D8
|
|
18
|
-
|
|
19
|
-
_PID_CLX000 = 0x021A
|
|
20
|
-
_PID_CANmod = 0xEB18
|
|
21
|
-
|
|
22
|
-
def __init__(self, channel: Any, can_filters: Optional[can.typechecking.CanFilters] = None, **kwargs: object):
|
|
23
|
-
super().__init__(channel, can_filters, **kwargs)
|
|
24
|
-
|
|
25
|
-
# Serial interface to the device
|
|
26
|
-
try:
|
|
27
|
-
# Open the channel with a data timeout of 1 ms
|
|
28
|
-
self._channel = serial.Serial(channel, timeout=0.001)
|
|
29
|
-
except SerialException:
|
|
30
|
-
self._channel = None
|
|
31
|
-
|
|
32
|
-
if self._channel is None:
|
|
33
|
-
raise CanInterfaceNotImplementedError(f"Could not open {channel}")
|
|
34
|
-
|
|
35
|
-
self.channel_info = f"CSSCAN serial on {channel}"
|
|
36
|
-
|
|
37
|
-
# Event queue, contains parsed frames
|
|
38
|
-
self._events = deque()
|
|
39
|
-
|
|
40
|
-
# Data queue, contains raw interface data
|
|
41
|
-
self._data = deque()
|
|
42
|
-
|
|
43
|
-
pass
|
|
44
|
-
|
|
45
|
-
def _recv_internal(self, timeout: Optional[float]) -> Tuple[Optional[Message], bool]:
|
|
46
|
-
result = None
|
|
47
|
-
|
|
48
|
-
t = Timeout(timeout)
|
|
49
|
-
|
|
50
|
-
# Check if there are any pending events in the queue. If so, return this
|
|
51
|
-
while len(self._events) == 0 and t.expired() is False:
|
|
52
|
-
# Receive new data from the serial interface and pass it to the parser
|
|
53
|
-
data = self._channel.read(1000000)
|
|
54
|
-
self._data.extend(data)
|
|
55
|
-
|
|
56
|
-
# Parse as many frames as possible
|
|
57
|
-
self._parse()
|
|
58
|
-
|
|
59
|
-
if len(self._events) > 0:
|
|
60
|
-
result = self._events.pop()
|
|
61
|
-
|
|
62
|
-
return result, False
|
|
63
|
-
|
|
64
|
-
@classmethod
|
|
65
|
-
def _detect_available_configs(cls) -> List[can.typechecking.AutoDetectedConfig]:
|
|
66
|
-
# Import ports based on platform, using the tools provided by pyserial
|
|
67
|
-
if os.name == 'nt':
|
|
68
|
-
from serial.tools.list_ports_windows import comports
|
|
69
|
-
elif os.name == 'posix':
|
|
70
|
-
from serial.tools.list_ports_posix import comports
|
|
71
|
-
else:
|
|
72
|
-
return []
|
|
73
|
-
|
|
74
|
-
result = []
|
|
75
|
-
ports = comports(False)
|
|
76
|
-
|
|
77
|
-
for port in ports:
|
|
78
|
-
# Check for VID for CLX000, CANmod
|
|
79
|
-
if port.vid not in [cls._VID_CLX000, cls._VID_CANmod]:
|
|
80
|
-
continue
|
|
81
|
-
|
|
82
|
-
# Check for PID for CLX000, CANmod
|
|
83
|
-
if port.pid not in[cls._PID_CLX000, cls._PID_CANmod]:
|
|
84
|
-
continue
|
|
85
|
-
|
|
86
|
-
current = {
|
|
87
|
-
"interface": "csscan_serial",
|
|
88
|
-
"channel": port.device,
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
result.append(current)
|
|
92
|
-
|
|
93
|
-
return result
|
|
94
|
-
|
|
95
|
-
def send(self, msg: Message, timeout: Optional[float] = None) -> None:
|
|
96
|
-
payload = bytearray()
|
|
97
|
-
|
|
98
|
-
# All transmission requests are ID 0x03 with flags for frame type
|
|
99
|
-
tx_req = 0x03
|
|
100
|
-
|
|
101
|
-
if msg.is_remote_frame is True:
|
|
102
|
-
tx_req |= 0x10
|
|
103
|
-
elif msg.is_fd is True:
|
|
104
|
-
tx_req |= 0x20
|
|
105
|
-
|
|
106
|
-
payload.append(tx_req)
|
|
107
|
-
|
|
108
|
-
# Encode ID
|
|
109
|
-
id = msg.arbitration_id
|
|
110
|
-
if msg.is_extended_id is True:
|
|
111
|
-
id |= 0x20000000
|
|
112
|
-
payload.extend(struct.pack("!I", id))
|
|
113
|
-
|
|
114
|
-
# Encode DLC
|
|
115
|
-
payload.append(msg.dlc)
|
|
116
|
-
|
|
117
|
-
# Encode data
|
|
118
|
-
payload.extend(msg.data)
|
|
119
|
-
|
|
120
|
-
# Calculate checksum over the data and append
|
|
121
|
-
calculated_checksum = self.calculate_crc(payload)
|
|
122
|
-
calculated_checksum_bytes = calculated_checksum.to_bytes(2, byteorder="big")
|
|
123
|
-
payload.extend(calculated_checksum_bytes)
|
|
124
|
-
|
|
125
|
-
# Stuff frame and pack in frame delimiters
|
|
126
|
-
packed_frame = bytearray()
|
|
127
|
-
packed_frame.append(0x7E)
|
|
128
|
-
|
|
129
|
-
for i in range(len(payload)):
|
|
130
|
-
if (payload[i] == 0x7D) or (payload[i] == 0x7E):
|
|
131
|
-
packed_frame.append(0x7D)
|
|
132
|
-
packed_frame.append(payload[i] ^ 0b00100000)
|
|
133
|
-
else:
|
|
134
|
-
packed_frame.append(payload[i])
|
|
135
|
-
|
|
136
|
-
packed_frame.append(0x7E)
|
|
137
|
-
|
|
138
|
-
self._channel.write(packed_frame)
|
|
139
|
-
|
|
140
|
-
return
|
|
141
|
-
|
|
142
|
-
def shutdown(self) -> None:
|
|
143
|
-
super().shutdown()
|
|
144
|
-
|
|
145
|
-
if self._channel is not None:
|
|
146
|
-
self._channel.close()
|
|
147
|
-
self._channel = None
|
|
148
|
-
|
|
149
|
-
return
|
|
150
|
-
|
|
151
|
-
def _parse(self):
|
|
152
|
-
# If there are fewer bytes available than a single frame, stop parsing
|
|
153
|
-
if len(self._data) < 16:
|
|
154
|
-
return
|
|
155
|
-
|
|
156
|
-
while len(self._data) >= 16:
|
|
157
|
-
# Find start and end indices of next frame
|
|
158
|
-
try:
|
|
159
|
-
start_of_frame = self._data.index(0x7E, 0)
|
|
160
|
-
except ValueError:
|
|
161
|
-
# No start flag
|
|
162
|
-
break
|
|
163
|
-
|
|
164
|
-
try:
|
|
165
|
-
end_of_frame = self._data.index(0x7E, start_of_frame + 1)
|
|
166
|
-
except ValueError:
|
|
167
|
-
# No end flag (yet)
|
|
168
|
-
break
|
|
169
|
-
|
|
170
|
-
# Skip all bytes up to the start of frame
|
|
171
|
-
for _ in range(start_of_frame):
|
|
172
|
-
self._data.popleft()
|
|
173
|
-
|
|
174
|
-
# Extract the frame
|
|
175
|
-
current_frame_raw = bytearray()
|
|
176
|
-
|
|
177
|
-
for _ in range(end_of_frame - start_of_frame + 1):
|
|
178
|
-
current_frame_raw.append(self._data.popleft())
|
|
179
|
-
|
|
180
|
-
parsed_frame = self._parse_frame(current_frame_raw)
|
|
181
|
-
if parsed_frame is not None:
|
|
182
|
-
self._events.append(parsed_frame)
|
|
183
|
-
|
|
184
|
-
return
|
|
185
|
-
|
|
186
|
-
def _parse_frame(self, current_frame_raw):
|
|
187
|
-
frame = can.Message()
|
|
188
|
-
|
|
189
|
-
# Set common frame properties
|
|
190
|
-
frame.is_fd = False
|
|
191
|
-
frame.is_error_frame = False
|
|
192
|
-
frame.bitrate_switch = False
|
|
193
|
-
frame.error_state_indicator = False
|
|
194
|
-
|
|
195
|
-
# Remove the start and end of frame markers
|
|
196
|
-
current_frame_raw = current_frame_raw[1:-1]
|
|
197
|
-
|
|
198
|
-
# Look for any stuffed bytes, and revert them
|
|
199
|
-
current_frame = bytearray()
|
|
200
|
-
stuff_next = False
|
|
201
|
-
for i in range(len(current_frame_raw)):
|
|
202
|
-
if current_frame_raw[i] == 0x7D:
|
|
203
|
-
stuff_next = True
|
|
204
|
-
continue
|
|
205
|
-
|
|
206
|
-
current_byte = current_frame_raw[i]
|
|
207
|
-
if stuff_next is True:
|
|
208
|
-
current_byte ^= 0b00100000
|
|
209
|
-
stuff_next = False
|
|
210
|
-
else:
|
|
211
|
-
current_byte = current_frame_raw[i]
|
|
212
|
-
|
|
213
|
-
current_frame.append(current_byte)
|
|
214
|
-
|
|
215
|
-
# Extract the checksum
|
|
216
|
-
checksum = current_frame[-2:]
|
|
217
|
-
current_frame = current_frame[:-2]
|
|
218
|
-
calculated_checksum = self.calculate_crc(current_frame).to_bytes(2, byteorder="big")
|
|
219
|
-
if checksum != calculated_checksum:
|
|
220
|
-
return None
|
|
221
|
-
|
|
222
|
-
# Read the frame type
|
|
223
|
-
frame_type = current_frame[0]
|
|
224
|
-
|
|
225
|
-
if (frame_type == 0x01) or (frame_type == 0x02) or (frame_type == 0x21) or (frame_type == 0x22):
|
|
226
|
-
# Regular CAN traffic, frame either received or transmitted.
|
|
227
|
-
# Extract the metadata
|
|
228
|
-
seconds, milliseconds, message_id, data_length = struct.unpack_from("!IHIB", current_frame, 1)
|
|
229
|
-
|
|
230
|
-
frame.timestamp = datetime.datetime.now(tz=datetime.timezone.utc).timestamp()
|
|
231
|
-
frame.arbitration_id = message_id & 0x1FFFFFFF
|
|
232
|
-
frame.is_extended_id = (message_id & 0x20000000) == 0x20000000
|
|
233
|
-
frame.is_rx = True if frame_type == 1 else False
|
|
234
|
-
frame.dlc = self.dlc_to_length(data_length)
|
|
235
|
-
|
|
236
|
-
frame.is_remote_frame = (frame_type & 0x10) == 0x10
|
|
237
|
-
frame.is_fd = (frame_type & 0x20) == 0x20
|
|
238
|
-
|
|
239
|
-
frame.data = current_frame[12:12 + frame.dlc]
|
|
240
|
-
else:
|
|
241
|
-
# Unknown frame type
|
|
242
|
-
pass
|
|
243
|
-
|
|
244
|
-
return frame
|
|
245
|
-
|
|
246
|
-
@staticmethod
|
|
247
|
-
def dlc_to_length(dlc):
|
|
248
|
-
length = dlc
|
|
249
|
-
|
|
250
|
-
if 8 >= dlc:
|
|
251
|
-
length = dlc
|
|
252
|
-
elif 12 >= dlc > 8:
|
|
253
|
-
length = 4 * (dlc - 9) + 12
|
|
254
|
-
elif 15 >= dlc > 12:
|
|
255
|
-
length = 16 * (dlc - 13) + 32
|
|
256
|
-
|
|
257
|
-
return length
|
|
258
|
-
|
|
259
|
-
@staticmethod
|
|
260
|
-
def calculate_crc(data: bytes) -> int:
|
|
261
|
-
initial = 0x0000
|
|
262
|
-
polynomial = 0xA001
|
|
263
|
-
final = 0x0000
|
|
264
|
-
|
|
265
|
-
crc = initial
|
|
266
|
-
|
|
267
|
-
for b in data:
|
|
268
|
-
crc ^= b
|
|
269
|
-
|
|
270
|
-
for i in range(8):
|
|
271
|
-
if crc & 0x0001:
|
|
272
|
-
crc >>= 1
|
|
273
|
-
crc ^= polynomial
|
|
274
|
-
else:
|
|
275
|
-
crc >>= 1
|
|
276
|
-
|
|
277
|
-
return crc ^ final
|
|
278
|
-
pass
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: python-can-csscan-serial
|
|
3
|
-
Version: 2.4.0
|
|
4
|
-
Summary: Interact with CSS Electronics USB devices through Python
|
|
5
|
-
Project-URL: Homepage, https://canlogger.csselectronics.com/tools-docs/csscan_serial/python_csscan/
|
|
6
|
-
Author: CSS Electronics
|
|
7
|
-
Author-email: contact@csselectronics.com
|
|
8
|
-
License: MIT
|
|
9
|
-
License-File: LICENSE
|
|
10
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
-
Classifier: Operating System :: OS Independent
|
|
12
|
-
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Requires-Python: >=3.7
|
|
14
|
-
Requires-Dist: pyserial>=3.5.0
|
|
15
|
-
Requires-Dist: python-can>=4.3.1
|
|
16
|
-
Description-Content-Type: text/markdown
|
|
17
|
-
|
|
18
|
-
# python-can-csscan-serial
|
|
19
|
-
|
|
20
|
-
The **python-can-csscan-serial** package allows for communication over USB with devices from [CSS Electronics](https://www.csselectronics.com/).
|
|
21
|
-
|
|
22
|
-
For usage guidelines, consult the manual or the documentation for the [**python-can**](https://python-can.readthedocs.io/en/stable/) package.
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
python_can_csscan_serial/CSSCANSerial.py,sha256=ze9eFOxMJSGXpvZ22H8J705pT3QVoWa4cMtjGsVHOh4,9118
|
|
2
|
-
python_can_csscan_serial/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
-
python_can_csscan_serial-2.4.0.dist-info/METADATA,sha256=WgVztPVKgCGlshsqy7qtp3rBvcagC3lv3tw510w1Q7Q,924
|
|
4
|
-
python_can_csscan_serial-2.4.0.dist-info/WHEEL,sha256=TJPnKdtrSue7xZ_AVGkp9YXcvDrobsjBds1du3Nx6dc,87
|
|
5
|
-
python_can_csscan_serial-2.4.0.dist-info/entry_points.txt,sha256=1FnKqCf9HuERSJK6nEw2H4gO2TYcVSnW7h9RX8gqdQ0,83
|
|
6
|
-
python_can_csscan_serial-2.4.0.dist-info/licenses/LICENSE,sha256=5PR6baFF-VyANXuj_nFw8Cr4rKZbjojX3-I12Nk3oas,1091
|
|
7
|
-
python_can_csscan_serial-2.4.0.dist-info/RECORD,,
|