python-can-csscan-serial 2026.11.20__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ .idea
2
+ .venv
3
+ dist
4
+ venv
5
+ __pycache__
6
+ *.egg-info
7
+ .pytest_cache
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## 2026.11.20
6
+
7
+ - Breaking: Reimplementation of the package.
@@ -0,0 +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
21
+ SOFTWARE.
@@ -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,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,53 @@
1
+ [build-system]
2
+ requires = ["hatchling >= 1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "python-can-csscan-serial"
7
+ version = "2026.11.20"
8
+ authors = [
9
+ { name="CSS Electronics" },
10
+ { email="contact@csselectronics.com" },
11
+ ]
12
+ description = "python-can interface for CSS Electronics devices with a USB serial interface (CANmod, CLX000)"
13
+ license = "MIT"
14
+ license-files = ["LICENSE"]
15
+ readme = "README.md"
16
+ requires-python = ">=3.12"
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Operating System :: OS Independent",
20
+ ]
21
+ dependencies = [
22
+ 'python-can >= 4.6.0',
23
+ 'pyserial >= 3.5',
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ test = [
28
+ 'pytest >= 8.0',
29
+ ]
30
+ hardware = [
31
+ 'pytest >= 8.0',
32
+ 'python-can-cansub >= 2026.09.28',
33
+ ]
34
+
35
+ [project.entry-points."can.interface"]
36
+ csscan_serial = "python_can_csscan_serial:CSSCANSerialBus"
37
+
38
+ # Ship the README inside the installed package so it can be found and read locally.
39
+ [tool.hatch.build.targets.wheel.force-include]
40
+ "README.md" = "python_can_csscan_serial/README.md"
41
+
42
+ [project.urls]
43
+ "Homepage" = "https://csselectronics.com/"
44
+ "Source" = "https://github.com/CSS-Electronics/python-can-csscan-serial"
45
+ "Changelog" = "https://github.com/CSS-Electronics/python-can-csscan-serial/blob/master/CHANGELOG.md"
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = [
49
+ "tests",
50
+ ]
51
+ markers = [
52
+ "hardware: live tests through a CANmod/CLX000 and a CANsub (see tests/test_hardware.py)",
53
+ ]
@@ -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,266 @@
1
+ """Tests of the bus, using a pyserial loopback port (loop://) in place of a device."""
2
+
3
+ import threading
4
+ import time
5
+
6
+ import can
7
+ import pytest
8
+ import serial
9
+
10
+ from python_can_csscan_serial import CSSCANSerialBus, _bus
11
+ from python_can_csscan_serial._protocol import MAX_FRAME_SIZE, stuff, unstuff
12
+
13
+ # Frames captured from a CL2000 (with flags): extended ID 0x7E / 0x01, data 7E 7D (escaped)
14
+ DEVICE_FRAME_1 = bytes.fromhex("7e 01 6b 00 03 a4 01 c1 20 00 00 7d 5e 02 7d 5e 7d 5d 5e 6a 7e")
15
+ DEVICE_FRAME_2 = bytes.fromhex("7e 01 6b 00 03 a4 01 c2 20 00 00 01 02 7d 5e 7d 5d 9f 33 7e")
16
+
17
+ # Generous upper bound for timing assertions, to avoid flaky tests on loaded machines
18
+ SLACK = 1.0
19
+
20
+
21
+ def device_frame(arbitration_id, data, frame_type=0x01):
22
+ return stuff(bytes([frame_type]) + bytes(6) + arbitration_id.to_bytes(4, "big") + bytes([len(data)]) + bytes(data))
23
+
24
+
25
+ @pytest.fixture
26
+ def bus():
27
+ with can.Bus(interface="csscan_serial", channel="loop://") as bus:
28
+ yield bus
29
+
30
+
31
+ def feed(bus, data):
32
+ # The loop:// buffer holds 4096 bytes, and writing more blocks forever
33
+ assert len(data) <= 4096
34
+ bus._serial.write(data)
35
+
36
+
37
+ # Opening
38
+
39
+ def test_open_fails():
40
+ with pytest.raises(can.CanInitializationError):
41
+ can.Bus(interface="csscan_serial", channel="/dev/does-not-exist")
42
+
43
+
44
+ def test_open_invalid_url():
45
+ with pytest.raises(can.CanInitializationError):
46
+ can.Bus(interface="csscan_serial", channel="bogus://x")
47
+
48
+
49
+ def test_channel_required():
50
+ with pytest.raises(can.CanInitializationError):
51
+ CSSCANSerialBus(channel=None)
52
+
53
+
54
+ def test_open_closes_port_on_reset_failure(monkeypatch):
55
+ port = serial.serial_for_url("loop://")
56
+
57
+ def fail():
58
+ raise serial.SerialException("Reset failed")
59
+
60
+ monkeypatch.setattr(port, "reset_input_buffer", fail)
61
+ monkeypatch.setattr(_bus.serial, "serial_for_url", lambda *args, **kwargs: port)
62
+
63
+ with pytest.raises(can.CanInitializationError):
64
+ can.Bus(interface="csscan_serial", channel="loop://")
65
+ assert not port.is_open
66
+
67
+
68
+ def test_shutdown_closes_port():
69
+ with can.Bus(interface="csscan_serial", channel="loop://") as bus:
70
+ port = bus._serial
71
+
72
+ assert not port.is_open
73
+
74
+
75
+ # Receiving
76
+
77
+ def test_recv(bus):
78
+ feed(bus, DEVICE_FRAME_1 + DEVICE_FRAME_2)
79
+
80
+ assert bus.recv(1).arbitration_id == 0x7E
81
+ assert bus.recv(1).arbitration_id == 0x01
82
+ assert bus.recv(0) is None
83
+
84
+
85
+ def test_recv_zero_timeout_returns_pending(bus):
86
+ feed(bus, DEVICE_FRAME_1)
87
+
88
+ assert bus.recv(0).arbitration_id == 0x7E
89
+
90
+
91
+ def test_recv_timeout(bus):
92
+ start = time.monotonic()
93
+
94
+ assert bus.recv(0.1) is None
95
+ assert 0.1 <= time.monotonic() - start < 0.1 + SLACK
96
+
97
+
98
+ def test_recv_timeout_with_undecodable_data(bus, monkeypatch):
99
+ # Data keeps arriving, but never completes a valid frame
100
+ monkeypatch.setattr(type(bus._serial), "in_waiting", property(lambda _: 16))
101
+ monkeypatch.setattr(bus._serial, "read", lambda size: b"\x00" * size)
102
+
103
+ start = time.monotonic()
104
+
105
+ assert bus.recv(0.1) is None
106
+ assert time.monotonic() - start < 0.1 + SLACK
107
+
108
+
109
+ def test_recv_timestamp(bus):
110
+ feed(bus, DEVICE_FRAME_1)
111
+
112
+ before = time.time()
113
+ msg = bus.recv(1)
114
+
115
+ assert before <= msg.timestamp <= time.time()
116
+
117
+
118
+ @pytest.mark.parametrize("split", range(1, len(DEVICE_FRAME_1)))
119
+ def test_recv_frame_split_across_reads(bus, split):
120
+ feed(bus, DEVICE_FRAME_1[:split])
121
+ assert bus.recv(0.02) is None
122
+
123
+ feed(bus, DEVICE_FRAME_1[split:])
124
+ assert bus.recv(1).arbitration_id == 0x7E
125
+
126
+
127
+ def test_recv_resynchronizes_mid_stream(bus):
128
+ # Start in the middle of a frame (as when connecting while the device is sending)
129
+ feed(bus, DEVICE_FRAME_1[5:] + DEVICE_FRAME_2 + DEVICE_FRAME_1)
130
+
131
+ assert bus.recv(1).arbitration_id == 0x01
132
+ assert bus.recv(1).arbitration_id == 0x7E
133
+ assert bus.recv(0) is None
134
+
135
+
136
+ def test_recv_skips_garbage(bus):
137
+ feed(bus, b"\x00\x7e\x7e\x7d\x7e\x01\x02" + DEVICE_FRAME_1)
138
+
139
+ assert bus.recv(1).arbitration_id == 0x7E
140
+ assert bus.recv(0) is None
141
+
142
+
143
+ def test_recv_bounds_buffer_without_flags(bus):
144
+ feed(bus, b"\x00" * 4000)
145
+
146
+ assert bus.recv(0.05) is None
147
+ assert len(bus._buffer) <= MAX_FRAME_SIZE
148
+
149
+ # Receives once frames arrive
150
+ feed(bus, DEVICE_FRAME_1 + DEVICE_FRAME_2)
151
+ assert bus.recv(1).arbitration_id == 0x7E
152
+ assert bus.recv(1).arbitration_id == 0x01
153
+
154
+
155
+ def test_recv_many(bus):
156
+ frames = [device_frame(i, i.to_bytes(2, "big")) for i in range(0x7E, 0x7E + 500)]
157
+
158
+ ids = []
159
+ for i in range(0, len(frames), 100):
160
+ feed(bus, b"".join(frames[i:i + 100]))
161
+ ids += [bus.recv(1).arbitration_id for _ in range(100)]
162
+
163
+ assert ids == list(range(0x7E, 0x7E + 500))
164
+
165
+
166
+ def test_recv_drops_own_messages(bus):
167
+ feed(bus, device_frame(0x100, [1], frame_type=0x02) + device_frame(0x200, [2]))
168
+
169
+ assert bus.recv(1).arbitration_id == 0x200
170
+ assert bus.recv(0) is None
171
+
172
+
173
+ def test_recv_own_messages():
174
+ with can.Bus(interface="csscan_serial", channel="loop://", receive_own_messages=True) as bus:
175
+ feed(bus, device_frame(0x100, [1], frame_type=0x02))
176
+
177
+ msg = bus.recv(1)
178
+
179
+ assert msg.arbitration_id == 0x100
180
+ assert not msg.is_rx
181
+
182
+
183
+ def test_recv_serial_error(bus, monkeypatch):
184
+ def fail(*_):
185
+ raise serial.SerialException("Device disconnected")
186
+
187
+ monkeypatch.setattr(bus._serial, "read", fail)
188
+
189
+ with pytest.raises(can.CanOperationError):
190
+ bus.recv(0.1)
191
+
192
+
193
+ def test_filters(bus):
194
+ bus.set_filters([{"can_id": 0x01, "can_mask": 0x1FFFFFFF, "extended": True}])
195
+ feed(bus, DEVICE_FRAME_1 + DEVICE_FRAME_2)
196
+
197
+ assert bus.recv(1).arbitration_id == 0x01
198
+ assert bus.recv(0) is None
199
+
200
+
201
+ # Sending
202
+
203
+ def test_send(bus):
204
+ bus.send(can.Message(arbitration_id=0x7E, is_extended_id=False, data=[0x7E, 0x7D, 0x00, 0xFF]))
205
+
206
+ assert bus._serial.read(100) == bytes.fromhex("7e 03 00 00 00 7d 5e 04 7d 5e 7d 5d 00 ff a1 c3 7e")
207
+
208
+
209
+ def test_send_invalid(bus):
210
+ with pytest.raises(ValueError):
211
+ bus.send(can.Message(arbitration_id=0x800, is_extended_id=False))
212
+
213
+
214
+ def test_send_serial_error(bus, monkeypatch):
215
+ def fail(*_):
216
+ raise serial.SerialTimeoutException("Write timeout")
217
+
218
+ monkeypatch.setattr(bus._serial, "write", fail)
219
+
220
+ with pytest.raises(can.CanOperationError):
221
+ bus.send(can.Message(arbitration_id=0x123, is_extended_id=False), timeout=0.1)
222
+
223
+
224
+ def test_send_timeout_sets_write_timeout(bus):
225
+ bus.send(can.Message(arbitration_id=0x123, is_extended_id=False), timeout=0.5)
226
+
227
+ assert bus._serial.write_timeout == 0.5
228
+
229
+
230
+ def test_send_from_threads(bus):
231
+ """Frames sent from several threads are not interleaved."""
232
+ def send(base):
233
+ for i in range(25):
234
+ bus.send(can.Message(arbitration_id=base + i, is_extended_id=False, data=[0x7E] * 8))
235
+
236
+ threads = [threading.Thread(target=send, args=(base,)) for base in (0x100, 0x200, 0x300, 0x400)]
237
+ for t in threads:
238
+ t.start()
239
+ for t in threads:
240
+ t.join()
241
+
242
+ frames = [f for f in bus._serial.read(4096).split(b"\x7e") if f]
243
+
244
+ assert len(frames) == 100
245
+ assert all(unstuff(f) is not None for f in frames)
246
+
247
+
248
+ # Detection
249
+
250
+ def test_detect_available_configs(monkeypatch):
251
+ class Port:
252
+ def __init__(self, device, vid, pid):
253
+ self.device, self.vid, self.pid = device, vid, pid
254
+
255
+ ports = [
256
+ Port("COM1", 0x1CBE, 0x021A), # CLX000
257
+ Port("COM2", 0x04D8, 0xEB18), # CANmod
258
+ Port("COM3", 0x04D8, 0x021A), # Mixed VID/PID
259
+ Port("COM4", None, None),
260
+ ]
261
+ monkeypatch.setattr(_bus, "comports", lambda: ports)
262
+
263
+ assert CSSCANSerialBus._detect_available_configs() == [
264
+ {"interface": "csscan_serial", "channel": "COM1"},
265
+ {"interface": "csscan_serial", "channel": "COM2"},
266
+ ]
@@ -0,0 +1,145 @@
1
+ """Live test through a CSS Electronics device with a USB serial interface (e.g. CL2000), using a CANsub interface
2
+ (python-can-cansub) as the other node on the bus.
3
+
4
+ Setup:
5
+ - The device and one CANsub channel connected to the same (classic CAN) bus.
6
+ - The CANsub is opened with the bit rate the device is configured for (default 250 kbit/s).
7
+ - The device does not report its own transmitted messages (CL2000 default).
8
+
9
+ Remote frames are not tested, as the CL2000 does not support them (received remote frames are reported as data
10
+ frames, remote frames to send are ignored).
11
+
12
+ The tests are skipped unless the channels are given through environment variables, e.g.:
13
+
14
+ CSSCAN_SERIAL_CHANNEL=/dev/ttyACM0 \
15
+ CSSCAN_SERIAL_CANSUB=fea7353d-usb.local@1 \
16
+ CSSCAN_SERIAL_BITRATE=250000 \
17
+ pytest -m hardware
18
+ """
19
+
20
+ import os
21
+ import time
22
+
23
+ import can
24
+ import pytest
25
+
26
+ CHANNEL = os.environ.get("CSSCAN_SERIAL_CHANNEL")
27
+ CANSUB = os.environ.get("CSSCAN_SERIAL_CANSUB")
28
+ BITRATE = os.environ.get("CSSCAN_SERIAL_BITRATE", "250000")
29
+
30
+ pytestmark = [
31
+ pytest.mark.hardware,
32
+ pytest.mark.skipif(not CHANNEL, reason="CSSCAN_SERIAL_CHANNEL not set"),
33
+ ]
34
+ needs_cansub = pytest.mark.skipif(not CANSUB, reason="CSSCAN_SERIAL_CANSUB not set")
35
+
36
+ MESSAGES = {
37
+ "std_empty": dict(arbitration_id=0x000, is_extended_id=False),
38
+ "std_8": dict(arbitration_id=0x7FF, is_extended_id=False, data=range(8)),
39
+ # Flag (0x7E) and escape (0x7D) bytes in ID and data
40
+ "std_escaped": dict(arbitration_id=0x07E, is_extended_id=False, data=[0x7E, 0x7D, 0x7E, 0x7D]),
41
+ "ext_3": dict(arbitration_id=0x1ABCDEF0, is_extended_id=True, data=[0xDE, 0xAD, 0xBF]),
42
+ "ext_escaped": dict(arbitration_id=0x1E7D7E7D, is_extended_id=True, data=[0x7D] * 8),
43
+ "ext_max": dict(arbitration_id=0x1FFFFFFF, is_extended_id=True, data=[0xFF] * 8),
44
+ }
45
+
46
+ @pytest.fixture(scope="module")
47
+ def device():
48
+ with can.Bus(interface="csscan_serial", channel=CHANNEL) as bus:
49
+ yield bus
50
+
51
+
52
+ @pytest.fixture(scope="module")
53
+ def cansub_bus():
54
+ pytest.importorskip("python_can_cansub")
55
+ with can.Bus(interface="cansub", channel=CANSUB, bitrate=int(BITRATE)) as bus:
56
+ yield bus
57
+
58
+
59
+ @pytest.fixture
60
+ def cansub(device, cansub_bus):
61
+ """The CANsub bus, with both buses flushed before the test."""
62
+ for bus in (device, cansub_bus):
63
+ receive(bus, idle=0.05)
64
+ return cansub_bus
65
+
66
+
67
+ def receive(bus, idle=0.5):
68
+ """Receive messages until the bus has been idle for `idle` seconds."""
69
+ return list(iter(lambda: bus.recv(timeout=idle), None))
70
+
71
+
72
+ def assert_transferred(received, expected):
73
+ assert received.arbitration_id == expected.arbitration_id
74
+ assert received.is_extended_id == expected.is_extended_id
75
+ assert received.is_remote_frame == expected.is_remote_frame
76
+ assert received.dlc == expected.dlc
77
+ assert bytes(received.data) == bytes(expected.data)
78
+
79
+
80
+ def test_detect_available_configs():
81
+ assert {"interface": "csscan_serial", "channel": CHANNEL} in can.detect_available_configs("csscan_serial")
82
+
83
+
84
+ def test_recv_timeout(device):
85
+ receive(device, idle=0.05)
86
+ start = time.monotonic()
87
+
88
+ assert device.recv(timeout=0.2) is None
89
+ assert 0.2 <= time.monotonic() - start < 1.2
90
+
91
+
92
+ @needs_cansub
93
+ @pytest.mark.parametrize("name", MESSAGES)
94
+ def test_receive(device, cansub, name):
95
+ expected = can.Message(**MESSAGES[name])
96
+
97
+ before = time.time()
98
+ cansub.send(expected)
99
+ received = receive(device)
100
+
101
+ assert len(received) == 1
102
+ assert_transferred(received[0], expected)
103
+ assert received[0].is_rx
104
+ assert before <= received[0].timestamp <= time.time()
105
+
106
+
107
+ @needs_cansub
108
+ @pytest.mark.parametrize("name", MESSAGES)
109
+ def test_send(device, cansub, name):
110
+ expected = can.Message(**MESSAGES[name])
111
+
112
+ device.send(expected, timeout=1)
113
+ received = receive(cansub)
114
+
115
+ assert len(received) == 1
116
+ assert_transferred(received[0], expected)
117
+ assert receive(device, idle=0.1) == []
118
+
119
+
120
+ @needs_cansub
121
+ def test_receive_burst(device, cansub):
122
+ expected = [can.Message(arbitration_id=i, is_extended_id=False, data=i.to_bytes(2, "big")) for i in range(200)]
123
+
124
+ for msg in expected:
125
+ cansub.send(msg)
126
+ received = receive(device)
127
+
128
+ assert len(received) == len(expected)
129
+ for r, e in zip(received, expected):
130
+ assert_transferred(r, e)
131
+
132
+
133
+ @needs_cansub
134
+ def test_send_burst(device, cansub):
135
+ expected = [can.Message(arbitration_id=0x100 + i, is_extended_id=True, data=[i] * 8) for i in range(100)]
136
+
137
+ for msg in expected:
138
+ device.send(msg, timeout=1)
139
+ # Pace the messages, so the test does not depend on the size of the device transmit queue
140
+ time.sleep(0.002)
141
+ received = receive(cansub)
142
+
143
+ assert len(received) == len(expected)
144
+ for r, e in zip(received, expected):
145
+ assert_transferred(r, e)
@@ -0,0 +1,148 @@
1
+ """Tests of the serial protocol (frame encoding and decoding)."""
2
+
3
+ import can
4
+ import pytest
5
+
6
+ from python_can_csscan_serial._protocol import crc16, decode, encode, stuff, unstuff
7
+
8
+ # Frames captured from a CL2000 (without flags): extended ID 0x7E / 0x01, data 7E 7D (escaped)
9
+ DEVICE_FRAME_1 = bytes.fromhex("01 6b 00 03 a4 01 c1 20 00 00 7d 5e 02 7d 5e 7d 5d 5e 6a")
10
+ DEVICE_FRAME_2 = bytes.fromhex("01 6b 00 03 a4 01 c2 20 00 00 01 02 7d 5e 7d 5d 9f 33")
11
+
12
+
13
+ def device_frame(can_id, dlc, data=b"", frame_type=0x01):
14
+ """Frame from the device (without flags). `can_id` includes the extended flag (bit 29)."""
15
+ return stuff(bytes([frame_type]) + bytes(6) + can_id.to_bytes(4, "big") + bytes([dlc]) + bytes(data))[1:-1]
16
+
17
+
18
+ # CRC and stuffing
19
+
20
+ def test_crc_check_value():
21
+ # CRC-16/ARC check value
22
+ assert crc16(b"123456789") == 0xBB3D
23
+
24
+
25
+ def test_crc_rejects_corruption():
26
+ frame = bytearray(DEVICE_FRAME_2)
27
+ frame[12] ^= 0x01
28
+
29
+ assert unstuff(bytes(frame)) is None
30
+
31
+
32
+ def test_stuff_escapes_flag_and_escape():
33
+ assert stuff(b"\x7e\x7d\x00") == bytes.fromhex("7e 7d5e 7d5d 00") + crc16(b"\x7e\x7d\x00").to_bytes(2, "big") + b"\x7e"
34
+
35
+
36
+ def test_unstuff_reverts_stuff():
37
+ content = bytes(range(256))
38
+
39
+ assert unstuff(stuff(content)[1:-1]) == content
40
+
41
+
42
+ def test_unstuff_escape_at_end():
43
+ assert unstuff(stuff(b"\x01\x02")[1:-1] + b"\x7d") is None
44
+
45
+
46
+ # Decoding
47
+
48
+ def test_decode_device_frames():
49
+ for frame, can_id in ((DEVICE_FRAME_1, 0x7E), (DEVICE_FRAME_2, 0x01)):
50
+ msg = decode(frame, timestamp=12.5)
51
+
52
+ assert msg.timestamp == 12.5
53
+ assert msg.arbitration_id == can_id
54
+ assert msg.is_extended_id
55
+ assert msg.is_rx
56
+ assert not msg.is_fd
57
+ assert not msg.is_remote_frame
58
+ assert bytes(msg.data) == b"\x7e\x7d"
59
+
60
+
61
+ @pytest.mark.parametrize(
62
+ "frame_type, dlc, data, is_rx, is_fd, is_remote",
63
+ [
64
+ (0x01, 8, range(8), True, False, False),
65
+ (0x02, 8, range(8), False, False, False),
66
+ (0x11, 4, b"", True, False, True),
67
+ (0x12, 4, b"", False, False, True),
68
+ (0x21, 9, range(12), True, True, False),
69
+ (0x22, 9, range(12), False, True, False),
70
+ (0x21, 15, range(64), True, True, False),
71
+ ],
72
+ )
73
+ def test_decode_frame_types(frame_type, dlc, data, is_rx, is_fd, is_remote):
74
+ msg = decode(device_frame(0x123, dlc, data, frame_type=frame_type), timestamp=0)
75
+
76
+ assert (msg.is_rx, msg.is_fd, msg.is_remote_frame) == (is_rx, is_fd, is_remote)
77
+ assert msg.dlc == can.util.dlc2len(dlc)
78
+ assert bytes(msg.data) == bytes(data)
79
+
80
+
81
+ def test_decode_extended_id():
82
+ msg = decode(device_frame(0x3FFFFFFF, 0), timestamp=0)
83
+
84
+ assert msg.is_extended_id
85
+ assert msg.arbitration_id == 0x1FFFFFFF
86
+
87
+
88
+ @pytest.mark.parametrize("frame_type", [0x00, 0x03, 0x04, 0x0F])
89
+ def test_decode_drops_unknown_frame_types(frame_type):
90
+ assert decode(device_frame(0x123, 2, [1, 2], frame_type=frame_type), timestamp=0) is None
91
+
92
+
93
+ def test_decode_drops_truncated_data():
94
+ assert decode(device_frame(0x123, 8, [1, 2]), timestamp=0) is None
95
+
96
+
97
+ def test_decode_drops_short_frame_with_valid_crc():
98
+ assert decode(stuff(b"\x01\x00")[1:-1], timestamp=0) is None
99
+
100
+
101
+ def test_decode_drops_empty_frame():
102
+ assert decode(b"", timestamp=0) is None
103
+
104
+
105
+ # Encoding
106
+
107
+ def test_encode_reference_vector():
108
+ # Frame accepted and transmitted by a CL2000
109
+ msg = can.Message(arbitration_id=0x7E, is_extended_id=False, data=[0x7E, 0x7D, 0x00, 0xFF])
110
+
111
+ assert encode(msg) == bytes.fromhex("7e 03 00 00 00 7d 5e 04 7d 5e 7d 5d 00 ff a1 c3 7e")
112
+
113
+
114
+ def test_encode_extended_remote():
115
+ msg = can.Message(arbitration_id=0x1ABCDEF0, is_extended_id=True, is_remote_frame=True, dlc=3)
116
+
117
+ assert unstuff(encode(msg)[1:-1]) == bytes.fromhex("13 3ABCDEF0 03")
118
+
119
+
120
+ def test_encode_fd_pads_to_dlc_length():
121
+ msg = can.Message(arbitration_id=0x123, is_extended_id=False, is_fd=True, data=range(10))
122
+
123
+ assert unstuff(encode(msg)[1:-1]) == bytes.fromhex("23 00000123 09") + bytes(range(10)) + bytes(2)
124
+
125
+
126
+ def test_encode_fd_64():
127
+ msg = can.Message(arbitration_id=0x123, is_extended_id=False, is_fd=True, data=range(64))
128
+
129
+ assert unstuff(encode(msg)[1:-1]) == bytes.fromhex("23 00000123 0F") + bytes(range(64))
130
+
131
+
132
+ @pytest.mark.parametrize(
133
+ "kwargs",
134
+ [
135
+ dict(arbitration_id=0x800, is_extended_id=False),
136
+ dict(arbitration_id=0x20000000, is_extended_id=True),
137
+ dict(arbitration_id=-1, is_extended_id=False),
138
+ dict(arbitration_id=0x123, is_extended_id=False, data=range(9)),
139
+ dict(arbitration_id=0x123, is_extended_id=False, is_fd=True, data=range(65)),
140
+ dict(arbitration_id=0x123, is_extended_id=False, is_remote_frame=True, dlc=9),
141
+ dict(arbitration_id=0x123, is_extended_id=False, is_remote_frame=True, is_fd=True),
142
+ dict(arbitration_id=0x123, is_extended_id=False, is_error_frame=True),
143
+ ],
144
+ ids=["std_id", "ext_id", "negative_id", "classic_9", "fd_65", "remote_dlc_9", "remote_fd", "error_frame"],
145
+ )
146
+ def test_encode_rejects_invalid(kwargs):
147
+ with pytest.raises(ValueError):
148
+ encode(can.Message(**kwargs))