python-can-csscan-serial 2.4.1__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.
@@ -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,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.24.2
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [can.interface]
2
+ csscan_serial = python_can_csscan_serial:CSSCANSerialBus
@@ -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,297 +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
- _VID_CLX000 = 0x1CBE
16
- _VID_CANmod = 0x04D8
17
-
18
- _PID_CLX000 = 0x021A
19
- _PID_CANmod = 0xEB18
20
-
21
- def __init__(self, channel: Any, can_filters: Optional[can.typechecking.CanFilters] = None, **kwargs: object):
22
- super().__init__(channel, can_filters, **kwargs)
23
-
24
- # Serial interface to the device
25
- try:
26
- # Open the channel with a data timeout of 1 ms
27
- self._channel = serial.Serial(channel, timeout=0.001)
28
- except SerialException:
29
- self._channel = None
30
-
31
- if self._channel is None:
32
- raise CanInterfaceNotImplementedError(f"Could not open {channel}")
33
-
34
- self.channel_info = f"CSSCAN serial on {channel}"
35
-
36
- # Event queue, contains parsed frames
37
- self._events = deque()
38
-
39
- # Data queue, contains raw interface data
40
- self._data = deque()
41
-
42
- pass
43
-
44
- def _recv_internal(self, timeout: Optional[float]) -> Tuple[Optional[Message], bool]:
45
- result = None
46
-
47
- t = Timeout(timeout)
48
-
49
- # Check if there are any pending events in the queue. If so, return this
50
- while len(self._events) == 0 and t.expired() is False:
51
- # Receive new data from the serial interface and pass it to the parser
52
- data = self._channel.read(1000000)
53
- self._data.extend(data)
54
-
55
- # Parse as many frames as possible
56
- self._parse()
57
-
58
- if len(self._events) > 0:
59
- result = self._events.popleft()
60
-
61
- return result, False
62
-
63
- @classmethod
64
- def _detect_available_configs(cls) -> List[can.typechecking.AutoDetectedConfig]:
65
- # Import ports based on platform, using the tools provided by pyserial
66
- if os.name == 'nt':
67
- from serial.tools.list_ports_windows import comports
68
- elif os.name == 'posix':
69
- from serial.tools.list_ports_posix import comports
70
- else:
71
- return []
72
-
73
- result = []
74
- ports = comports(False)
75
-
76
- for port in ports:
77
- # Check for VID for CLX000, CANmod
78
- if port.vid not in [cls._VID_CLX000, cls._VID_CANmod]:
79
- continue
80
-
81
- # Check for PID for CLX000, CANmod
82
- if port.pid not in [cls._PID_CLX000, cls._PID_CANmod]:
83
- continue
84
-
85
- current = {
86
- "interface": "csscan_serial",
87
- "channel": port.device,
88
- }
89
-
90
- result.append(current)
91
-
92
- return result
93
-
94
- def send(self, msg: Message, timeout: Optional[float] = None) -> None:
95
- payload = bytearray()
96
-
97
- # All transmission requests are ID 0x03 with flags for frame type
98
- tx_req = 0x03
99
-
100
- if msg.is_remote_frame is True:
101
- tx_req |= 0x10
102
- elif msg.is_fd is True:
103
- tx_req |= 0x20
104
-
105
- payload.append(tx_req)
106
-
107
- # Encode ID
108
- id = msg.arbitration_id
109
- if msg.is_extended_id is True:
110
- id |= 0x20000000
111
- payload.extend(struct.pack("!I", id))
112
-
113
- # Encode DLC
114
- payload.append(self.nob_to_dlc(len(msg.data)))
115
-
116
- # Encode data
117
- payload.extend(msg.data)
118
-
119
- # Calculate checksum over the data and append
120
- calculated_checksum = self.calculate_crc(payload)
121
- calculated_checksum_bytes = calculated_checksum.to_bytes(2, byteorder="big")
122
- payload.extend(calculated_checksum_bytes)
123
-
124
- # Stuff frame and pack in frame delimiters
125
- packed_frame = bytearray()
126
- packed_frame.append(0x7E)
127
-
128
- for i in range(len(payload)):
129
- if (payload[i] == 0x7D) or (payload[i] == 0x7E):
130
- packed_frame.append(0x7D)
131
- packed_frame.append(payload[i] ^ 0b00100000)
132
- else:
133
- packed_frame.append(payload[i])
134
-
135
- packed_frame.append(0x7E)
136
-
137
- self._channel.write(packed_frame)
138
-
139
- return
140
-
141
- def shutdown(self) -> None:
142
- super().shutdown()
143
-
144
- if self._channel is not None:
145
- self._channel.close()
146
- self._channel = None
147
-
148
- return
149
-
150
- def _parse(self):
151
- # If there are fewer bytes available than a single frame, stop parsing
152
- if len(self._data) < 16:
153
- return
154
-
155
- while len(self._data) >= 16:
156
- # Find start and end indices of next frame
157
- try:
158
- start_of_frame = self._data.index(0x7E, 0)
159
- except ValueError:
160
- # No start flag
161
- break
162
-
163
- try:
164
- end_of_frame = self._data.index(0x7E, start_of_frame + 1)
165
- except ValueError:
166
- # No end flag (yet)
167
- break
168
-
169
- # Skip all bytes up to the start of frame
170
- for _ in range(start_of_frame):
171
- self._data.popleft()
172
-
173
- # Extract the frame
174
- current_frame_raw = bytearray()
175
-
176
- for _ in range(end_of_frame - start_of_frame + 1):
177
- current_frame_raw.append(self._data.popleft())
178
-
179
- parsed_frame = self._parse_frame(current_frame_raw)
180
- if parsed_frame is not None:
181
- self._events.append(parsed_frame)
182
-
183
- return
184
-
185
- def _parse_frame(self, current_frame_raw):
186
- frame = can.Message()
187
-
188
- # Set common frame properties
189
- frame.is_fd = False
190
- frame.is_error_frame = False
191
- frame.bitrate_switch = False
192
- frame.error_state_indicator = False
193
-
194
- # Remove the start and end of frame markers
195
- current_frame_raw = current_frame_raw[1:-1]
196
-
197
- # Look for any stuffed bytes, and revert them
198
- current_frame = bytearray()
199
- stuff_next = False
200
- for i in range(len(current_frame_raw)):
201
- if current_frame_raw[i] == 0x7D:
202
- stuff_next = True
203
- continue
204
-
205
- current_byte = current_frame_raw[i]
206
- if stuff_next is True:
207
- current_byte ^= 0b00100000
208
- stuff_next = False
209
- else:
210
- current_byte = current_frame_raw[i]
211
-
212
- current_frame.append(current_byte)
213
-
214
- # Extract the checksum
215
- checksum = current_frame[-2:]
216
- current_frame = current_frame[:-2]
217
- calculated_checksum = self.calculate_crc(current_frame).to_bytes(2, byteorder="big")
218
- if checksum != calculated_checksum:
219
- return None
220
-
221
- # Read the frame type
222
- frame_type = current_frame[0]
223
-
224
- if (frame_type == 0x01) or (frame_type == 0x02) or (frame_type == 0x21) or (frame_type == 0x22):
225
- # Regular CAN traffic, frame either received or transmitted.
226
- # Extract the metadata
227
- seconds, milliseconds, message_id, data_length = struct.unpack_from("!IHIB", current_frame, 1)
228
-
229
- frame.timestamp = datetime.datetime.now(tz=datetime.timezone.utc).timestamp()
230
- frame.arbitration_id = message_id & 0x1FFFFFFF
231
- frame.is_extended_id = (message_id & 0x20000000) == 0x20000000
232
- frame.is_rx = True if frame_type == 1 else False
233
- frame.dlc = self.dlc_to_length(data_length)
234
-
235
- frame.is_remote_frame = (frame_type & 0x10) == 0x10
236
- frame.is_fd = (frame_type & 0x20) == 0x20
237
-
238
- frame.data = current_frame[12:12 + frame.dlc]
239
- else:
240
- # Unknown frame type
241
- pass
242
-
243
- return frame
244
-
245
- @staticmethod
246
- def dlc_to_length(dlc):
247
- length = dlc
248
-
249
- if 8 >= dlc:
250
- length = dlc
251
- elif 12 >= dlc > 8:
252
- length = 4 * (dlc - 9) + 12
253
- elif 15 >= dlc > 12:
254
- length = 16 * (dlc - 13) + 32
255
-
256
- return length
257
-
258
- @staticmethod
259
- def nob_to_dlc(nob):
260
- if 0 <= nob <= 8:
261
- return nob
262
- elif 8 < nob <= 12:
263
- return 9
264
- elif 12 < nob <= 16:
265
- return 10
266
- elif 16 < nob <= 20:
267
- return 11
268
- elif 20 < nob <= 24:
269
- return 12
270
- elif 24 < nob <= 32:
271
- return 13
272
- elif 32 < nob <= 48:
273
- return 14
274
- elif 48 < nob <= 64:
275
- return 15
276
-
277
- @staticmethod
278
- def calculate_crc(data: bytes) -> int:
279
- initial = 0x0000
280
- polynomial = 0xA001
281
- final = 0x0000
282
-
283
- crc = initial
284
-
285
- for b in data:
286
- crc ^= b
287
-
288
- for i in range(8):
289
- if crc & 0x0001:
290
- crc >>= 1
291
- crc ^= polynomial
292
- else:
293
- crc >>= 1
294
-
295
- return crc ^ final
296
-
297
- pass
@@ -1,22 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: python-can-csscan-serial
3
- Version: 2.4.1
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=KHlsT6ycfZ2BjI15A9iJP41X2hoylBj99SYNnaVeuaI,9573
2
- python_can_csscan_serial/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- python_can_csscan_serial-2.4.1.dist-info/METADATA,sha256=L9zCL5t8YVL2GozfCkY7y5Qw4trv62j1uY8xM_6bpRA,924
4
- python_can_csscan_serial-2.4.1.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
5
- python_can_csscan_serial-2.4.1.dist-info/entry_points.txt,sha256=1FnKqCf9HuERSJK6nEw2H4gO2TYcVSnW7h9RX8gqdQ0,83
6
- python_can_csscan_serial-2.4.1.dist-info/licenses/LICENSE,sha256=5PR6baFF-VyANXuj_nFw8Cr4rKZbjojX3-I12Nk3oas,1091
7
- python_can_csscan_serial-2.4.1.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [can.interface]
2
- csscan_serial = python_can_csscan_serial.CSSCANSerial:CSSCANSerial