python-can-gs-usb-fd 0.1.0__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 A Onur
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,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-can-gs-usb-fd
3
+ Version: 0.1.0
4
+ Summary: python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
14
+ Requires-Dist: python-can>=4.6.0
15
+ Requires-Dist: pyusb>=1.3.1
16
+ Requires-Dist: libusb-package>=1.0.26
17
+ Requires-Dist: pytest>=8.0 ; extra == 'test'
18
+ Requires-Python: >=3.10
19
+ Project-URL: homepage, https://github.com/1atabey1/gs_usb_fd
20
+ Project-URL: repository, https://github.com/1atabey1/gs_usb_fd
21
+ Provides-Extra: test
22
+ Description-Content-Type: text/markdown
23
+
24
+ # python-can-gs-usb-fd
25
+
26
+ A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f, interface 0) and other gs_usb devices that advertise CAN FD.
27
+
28
+ Installing the package registers the interface `gs_usb_fd` with python-can (entry point group `can.interface`). Code only needs `import can`, and every python-can tool (`can.logger`, `can.viewer`, `can.player`, ...) can use it.
29
+
30
+ > **Why not python-can's `gs_usb` interface?** It does classic CAN only: no FD mode, no data-phase bit timing, and a fixed 87.5 % sample point. On a CAN FD network, a controller in classic mode error-frames every FD frame. The probe's firmware runs FDCAN with protocol exception handling off, so it would do exactly that.
31
+
32
+ ## Installation
33
+
34
+ In the repo's uv environment (`sw/`) it is already an editable workspace member:
35
+
36
+ ```bash
37
+ uv sync
38
+ ```
39
+
40
+ Elsewhere:
41
+
42
+ ```bash
43
+ pip install ./tools/python-can-gs-usb-fd
44
+ ```
45
+
46
+ On Windows the device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed. libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
47
+
48
+ ## Configuration
49
+
50
+ The interface is always `"gs_usb_fd"`. The `channel` is `"SERIAL@N"`, or just `N` for the first device found. Channels are **0-based**, as the device numbers them. On the probe, 0 is CAN1 (J4) and 1 is CAN2 (J5).
51
+
52
+ ```python
53
+ configs = can.detect_available_configs(interfaces=["gs_usb_fd"])
54
+ # [{'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@0'},
55
+ # {'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@1'}]
56
+ ```
57
+
58
+ Detection opens each device briefly, so devices that another process has open are skipped.
59
+
60
+ ## Opening a bus
61
+
62
+ ```python
63
+ import can
64
+
65
+ with can.Bus(interface="gs_usb_fd", channel=0, bitrate=1_000_000, data_bitrate=5_000_000) as bus:
66
+ bus.send(can.Message(arbitration_id=0x123, data=bytes(64), is_fd=True, bitrate_switch=True))
67
+ print(bus.recv(timeout=1.0))
68
+ ```
69
+
70
+ ### Bit timing
71
+
72
+ `bitrate` (plus `data_bitrate` for CAN FD) uses an 80 % sample point; `sample_point` and `data_sample_point` change it. For full control, pass `timing`: a `can.BitTimingFd` for CAN FD or a `can.BitTiming` for classic CAN. The probe's CAN clock is **80 MHz**. A timing made for another clock is rescaled if it divides evenly, otherwise it is refused.
73
+
74
+ ```python
75
+ timing = can.BitTimingFd(f_clock=80_000_000,
76
+ nom_brp=5, nom_tseg1=12, nom_tseg2=3, nom_sjw=3, # 1 Mbit/s, 81.25 %
77
+ data_brp=2, data_tseg1=5, data_tseg2=2, data_sjw=2) # 5 Mbit/s, 75 %
78
+ with can.Bus(interface="gs_usb_fd", channel="290023001551333034363238@0", timing=timing) as bus:
79
+ ...
80
+ ```
81
+
82
+ Without `data_bitrate` and with a `can.BitTiming`, the channel runs classic CAN, and sending an FD frame raises `CanOperationError`.
83
+
84
+ ### Modes
85
+
86
+ | Argument | Effect |
87
+ |---|---|
88
+ | `listen_only=True` | Never drives the bus: no ACK, no error frames, no TX (FDCAN bus monitoring). Safe on a live network. |
89
+ | `loopback=True` | Internal loopback: TX frames come back as RX and the bus is not touched. |
90
+ | `one_shot=True` | No automatic retransmission. |
91
+ | `error_frames=True` | Bus-error reporting on; error frames arrive with `is_error_frame`, with `arbitration_id`/`data` in the SocketCAN error-frame format (`linux/can/error.h`). Off by default, and error frames are dropped. |
92
+ | `receive_own_messages=True` | The device's TX confirmations are delivered too (`is_rx` False). |
93
+ | `hw_timestamps=False` | Host receive time instead of the device's microsecond timestamps (default: device time, anchored to the host clock and unwrapped). |
94
+
95
+ ### Several channels
96
+
97
+ Both channels of a device can be open at once, in one process: they share one USB connection and one reader thread that routes frames by channel.
98
+
99
+ ```python
100
+ with (can.Bus(interface="gs_usb_fd", channel=0, timing=timing) as can1,
101
+ can.Bus(interface="gs_usb_fd", channel=1, timing=timing) as can2):
102
+ ...
103
+ ```
104
+
105
+ ### Filters, state
106
+
107
+ `can_filters` are applied in software (the device has no hardware filters). `bus.state` reads the controller state: `ACTIVE` (error-active or warning), `PASSIVE` or `ERROR` (bus-off). `bus.error_counters()` returns `(state, rx_errors, tx_errors)`.
108
+
109
+ ## Command line
110
+
111
+ ```bash
112
+ gs-usb-fd detect
113
+ gs-usb-fd listen --channel 0 --seconds 3 # listen-only dump, never drives the bus
114
+ gs-usb-fd loopback --channel 0 # internal loopback self-test
115
+ ```
116
+
117
+ Both default to 1 Mbit/s / 5 Mbit/s (brp/tseg1/tseg2/sjw 5/12/3/3 and 2/5/2/2 at 80 MHz). Use `--bitrate`/`--data-bitrate` or `--nom`/`--data` to change it.
118
+
119
+ ## Tests
120
+
121
+ ```bash
122
+ uv run pytest tools/python-can-gs-usb-fd # a fake device, no hardware
123
+ GS_USB_FD_HW=1 uv run pytest tools/python-can-gs-usb-fd -m hardware # on a probe: loopback and listen-only only
124
+ ```
125
+
126
+ ## Protocol
127
+
128
+ The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `Appli/usb/gs_usb.c`: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
@@ -0,0 +1,105 @@
1
+ # python-can-gs-usb-fd
2
+
3
+ A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f, interface 0) and other gs_usb devices that advertise CAN FD.
4
+
5
+ Installing the package registers the interface `gs_usb_fd` with python-can (entry point group `can.interface`). Code only needs `import can`, and every python-can tool (`can.logger`, `can.viewer`, `can.player`, ...) can use it.
6
+
7
+ > **Why not python-can's `gs_usb` interface?** It does classic CAN only: no FD mode, no data-phase bit timing, and a fixed 87.5 % sample point. On a CAN FD network, a controller in classic mode error-frames every FD frame. The probe's firmware runs FDCAN with protocol exception handling off, so it would do exactly that.
8
+
9
+ ## Installation
10
+
11
+ In the repo's uv environment (`sw/`) it is already an editable workspace member:
12
+
13
+ ```bash
14
+ uv sync
15
+ ```
16
+
17
+ Elsewhere:
18
+
19
+ ```bash
20
+ pip install ./tools/python-can-gs-usb-fd
21
+ ```
22
+
23
+ On Windows the device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed. libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
24
+
25
+ ## Configuration
26
+
27
+ The interface is always `"gs_usb_fd"`. The `channel` is `"SERIAL@N"`, or just `N` for the first device found. Channels are **0-based**, as the device numbers them. On the probe, 0 is CAN1 (J4) and 1 is CAN2 (J5).
28
+
29
+ ```python
30
+ configs = can.detect_available_configs(interfaces=["gs_usb_fd"])
31
+ # [{'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@0'},
32
+ # {'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@1'}]
33
+ ```
34
+
35
+ Detection opens each device briefly, so devices that another process has open are skipped.
36
+
37
+ ## Opening a bus
38
+
39
+ ```python
40
+ import can
41
+
42
+ with can.Bus(interface="gs_usb_fd", channel=0, bitrate=1_000_000, data_bitrate=5_000_000) as bus:
43
+ bus.send(can.Message(arbitration_id=0x123, data=bytes(64), is_fd=True, bitrate_switch=True))
44
+ print(bus.recv(timeout=1.0))
45
+ ```
46
+
47
+ ### Bit timing
48
+
49
+ `bitrate` (plus `data_bitrate` for CAN FD) uses an 80 % sample point; `sample_point` and `data_sample_point` change it. For full control, pass `timing`: a `can.BitTimingFd` for CAN FD or a `can.BitTiming` for classic CAN. The probe's CAN clock is **80 MHz**. A timing made for another clock is rescaled if it divides evenly, otherwise it is refused.
50
+
51
+ ```python
52
+ timing = can.BitTimingFd(f_clock=80_000_000,
53
+ nom_brp=5, nom_tseg1=12, nom_tseg2=3, nom_sjw=3, # 1 Mbit/s, 81.25 %
54
+ data_brp=2, data_tseg1=5, data_tseg2=2, data_sjw=2) # 5 Mbit/s, 75 %
55
+ with can.Bus(interface="gs_usb_fd", channel="290023001551333034363238@0", timing=timing) as bus:
56
+ ...
57
+ ```
58
+
59
+ Without `data_bitrate` and with a `can.BitTiming`, the channel runs classic CAN, and sending an FD frame raises `CanOperationError`.
60
+
61
+ ### Modes
62
+
63
+ | Argument | Effect |
64
+ |---|---|
65
+ | `listen_only=True` | Never drives the bus: no ACK, no error frames, no TX (FDCAN bus monitoring). Safe on a live network. |
66
+ | `loopback=True` | Internal loopback: TX frames come back as RX and the bus is not touched. |
67
+ | `one_shot=True` | No automatic retransmission. |
68
+ | `error_frames=True` | Bus-error reporting on; error frames arrive with `is_error_frame`, with `arbitration_id`/`data` in the SocketCAN error-frame format (`linux/can/error.h`). Off by default, and error frames are dropped. |
69
+ | `receive_own_messages=True` | The device's TX confirmations are delivered too (`is_rx` False). |
70
+ | `hw_timestamps=False` | Host receive time instead of the device's microsecond timestamps (default: device time, anchored to the host clock and unwrapped). |
71
+
72
+ ### Several channels
73
+
74
+ Both channels of a device can be open at once, in one process: they share one USB connection and one reader thread that routes frames by channel.
75
+
76
+ ```python
77
+ with (can.Bus(interface="gs_usb_fd", channel=0, timing=timing) as can1,
78
+ can.Bus(interface="gs_usb_fd", channel=1, timing=timing) as can2):
79
+ ...
80
+ ```
81
+
82
+ ### Filters, state
83
+
84
+ `can_filters` are applied in software (the device has no hardware filters). `bus.state` reads the controller state: `ACTIVE` (error-active or warning), `PASSIVE` or `ERROR` (bus-off). `bus.error_counters()` returns `(state, rx_errors, tx_errors)`.
85
+
86
+ ## Command line
87
+
88
+ ```bash
89
+ gs-usb-fd detect
90
+ gs-usb-fd listen --channel 0 --seconds 3 # listen-only dump, never drives the bus
91
+ gs-usb-fd loopback --channel 0 # internal loopback self-test
92
+ ```
93
+
94
+ Both default to 1 Mbit/s / 5 Mbit/s (brp/tseg1/tseg2/sjw 5/12/3/3 and 2/5/2/2 at 80 MHz). Use `--bitrate`/`--data-bitrate` or `--nom`/`--data` to change it.
95
+
96
+ ## Tests
97
+
98
+ ```bash
99
+ uv run pytest tools/python-can-gs-usb-fd # a fake device, no hardware
100
+ GS_USB_FD_HW=1 uv run pytest tools/python-can-gs-usb-fd -m hardware # on a probe: loopback and listen-only only
101
+ ```
102
+
103
+ ## Protocol
104
+
105
+ The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `Appli/usb/gs_usb.c`: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "python-can-gs-usb-fd"
3
+ version = "0.1.0"
4
+ description = "python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3.10",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Operating System :: OS Independent",
16
+ "Topic :: System :: Hardware :: Hardware Drivers",
17
+ ]
18
+ dependencies = [
19
+ "python-can>=4.6.0",
20
+ "pyusb>=1.3.1",
21
+ "libusb-package>=1.0.26",
22
+ ]
23
+
24
+ [project.urls]
25
+ homepage = "https://github.com/1atabey1/gs_usb_fd"
26
+ repository = "https://github.com/1atabey1/gs_usb_fd"
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=8.0"]
30
+
31
+ [project.entry-points."can.interface"]
32
+ gs_usb_fd = "python_can_gs_usb_fd.bus:GsUsbFdBus"
33
+
34
+ [project.scripts]
35
+ gs-usb-fd = "python_can_gs_usb_fd.cli:main"
36
+
37
+ [build-system]
38
+ requires = ["uv_build>=0.11.8,<0.12"]
39
+ build-backend = "uv_build"
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ markers = ["hardware: needs a probe on USB (set GS_USB_FD_HW=1)"]
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "python-can-gs-usb-fd"
3
+ version = "0.1.0"
4
+ description = "python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3.10",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Operating System :: OS Independent",
16
+ "Topic :: System :: Hardware :: Hardware Drivers",
17
+ ]
18
+ dependencies = [
19
+ "python-can>=4.6.0",
20
+ "pyusb>=1.3.1",
21
+ "libusb-package>=1.0.26",
22
+ ]
23
+
24
+ [project.urls]
25
+ homepage = "https://github.com/1atabey1/gs_usb_fd"
26
+ repository = "https://github.com/1atabey1/gs_usb_fd"
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=8.0"]
30
+
31
+ # Registers the interface with python-can: can.Bus(interface="gs_usb_fd", ...)
32
+ [project.entry-points."can.interface"]
33
+ gs_usb_fd = "python_can_gs_usb_fd.bus:GsUsbFdBus"
34
+
35
+ [project.scripts]
36
+ gs-usb-fd = "python_can_gs_usb_fd.cli:main"
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.11.8,<0.12"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ markers = ["hardware: needs a probe on USB (set GS_USB_FD_HW=1)"]
@@ -0,0 +1,11 @@
1
+ """python-can interface "gs_usb_fd": CAN FD over gs_usb devices.
2
+
3
+ Installing this package registers the interface with python-can (entry point
4
+ group ``can.interface``), so ``can.Bus(interface="gs_usb_fd", ...)`` works
5
+ without importing anything from here.
6
+ """
7
+
8
+ from .bus import INTERFACE, GsUsbFdBus, parse_channel
9
+
10
+ __all__ = ["INTERFACE", "GsUsbFdBus", "parse_channel"]
11
+ __version__ = "0.1.0"
@@ -0,0 +1,304 @@
1
+ """python-can bus for CAN FD over gs_usb (interface name "gs_usb_fd")."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import queue
7
+ import struct
8
+ import time
9
+ import warnings
10
+ from typing import Any
11
+
12
+ import can
13
+ import usb.core
14
+
15
+ from . import device as _device
16
+ from . import protocol as p
17
+ from .device import GsUsbDevice, _serial
18
+
19
+ INTERFACE = "gs_usb_fd"
20
+ DEFAULT_SAMPLE_POINT = 80.0
21
+
22
+
23
+ def parse_channel(channel: Any) -> tuple[str | None, int]:
24
+ """0, "0" -> (None, 0): channel 0 of the first device found;
25
+ "SERIAL@1" -> ("SERIAL", 1). Channels are 0-based, as the device numbers
26
+ them (on the tricore-debug-machine probe 0 is CAN1 / J4, 1 is CAN2 / J5)."""
27
+ if channel is None:
28
+ return None, 0
29
+ if isinstance(channel, int):
30
+ return None, channel
31
+ text = str(channel).strip()
32
+ serial, sep, index = text.rpartition("@")
33
+ if not sep:
34
+ return None, int(text)
35
+ return (serial or None), int(index)
36
+
37
+
38
+ class GsUsbFdBus(can.BusABC):
39
+ """CAN FD (and classic CAN) over a gs_usb device.
40
+
41
+ python-can's built-in ``gs_usb`` interface is classic CAN only. On a CAN
42
+ FD network a classic-mode controller error-frames every FD frame, so use
43
+ this interface there.
44
+
45
+ Bit timing, in order of precedence:
46
+
47
+ * ``timing``: a :class:`can.BitTimingFd` (CAN FD) or :class:`can.BitTiming`
48
+ (classic CAN). Its ``f_clock`` must be the device's CAN clock (80 MHz on
49
+ the tricore-debug-machine probe), or be adjustable to it.
50
+ * ``bitrate`` (and ``data_bitrate`` for CAN FD), with a fixed sample point
51
+ of 80 % (``sample_point`` / ``data_sample_point`` change it).
52
+
53
+ :param channel: ``"SERIAL@N"`` or ``N`` (the first device found), N 0-based.
54
+ :param listen_only: never drive the bus: no ACK, no error frames, no TX.
55
+ :param loopback: internal loopback: TX frames come back as RX, the bus is
56
+ not touched (sets the device's listen-only and loopback flags, which the
57
+ tricore-debug-machine firmware maps to FDCAN internal loopback).
58
+ :param one_shot: no automatic retransmission.
59
+ :param error_frames: enable bus-error reporting and deliver error frames
60
+ (``is_error_frame``; ``arbitration_id`` and ``data`` in the SocketCAN
61
+ error-frame format). Off by default: error frames are dropped.
62
+ :param receive_own_messages: deliver the device's TX echoes (``is_rx`` False).
63
+ :param hw_timestamps: use the device's microsecond timestamps (default),
64
+ anchored to the host clock; else the host receive time.
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ channel: Any = 0,
70
+ can_filters: can.typechecking.CanFilters | None = None,
71
+ bitrate: int | None = None,
72
+ data_bitrate: int | None = None,
73
+ timing: can.BitTiming | can.BitTimingFd | None = None,
74
+ sample_point: float = DEFAULT_SAMPLE_POINT,
75
+ data_sample_point: float = DEFAULT_SAMPLE_POINT,
76
+ listen_only: bool = False,
77
+ loopback: bool = False,
78
+ one_shot: bool = False,
79
+ error_frames: bool = False,
80
+ receive_own_messages: bool = False,
81
+ hw_timestamps: bool = True,
82
+ **kwargs: Any,
83
+ ) -> None:
84
+ self._dev: GsUsbDevice | None = None
85
+ self._queue: queue.Queue | None = None
86
+ self._started = False
87
+ self._channel_open = False # this bus registered its channel with the device
88
+ serial, self._ch = parse_channel(channel)
89
+ try:
90
+ self._dev = GsUsbDevice.acquire(serial)
91
+ except (LookupError, usb.core.USBError, usb.core.NoBackendError) as e:
92
+ raise can.CanInitializationError(f"{INTERFACE}: {e}") from e
93
+ try:
94
+ self._setup(timing, bitrate, data_bitrate, sample_point, data_sample_point,
95
+ listen_only, loopback, one_shot, error_frames, hw_timestamps)
96
+ except Exception:
97
+ self._release()
98
+ raise
99
+ self._error_frames = error_frames
100
+ self._receive_own = receive_own_messages
101
+ self._echo_ids = itertools.count(1)
102
+ self.channel_info = (
103
+ f"{INTERFACE} {self._dev.serial}@{self._ch}: "
104
+ + (f"{self.timing.nom_bitrate / 1e6:g} / {self.timing.data_bitrate / 1e6:g} Mbit/s FD"
105
+ if self._fd else f"{self.timing.bitrate / 1e6:g} Mbit/s classic")
106
+ + (", listen-only" if listen_only and not loopback else "")
107
+ + (", internal loopback" if loopback else ""))
108
+ super().__init__(channel=channel, can_filters=can_filters, **kwargs)
109
+
110
+ # ---- setup
111
+ def _setup(self, timing, bitrate, data_bitrate, sample_point, data_sample_point,
112
+ listen_only, loopback, one_shot, error_frames, hw_timestamps) -> None:
113
+ dev = self._dev
114
+ if not 0 <= self._ch < dev.channel_count:
115
+ raise can.CanInitializationError(
116
+ f"{INTERFACE}: channel {self._ch} out of range, {dev.serial} has {dev.channel_count}")
117
+ btc = dev.bt_const
118
+ fclk = btc.fclk_can
119
+
120
+ if isinstance(timing, can.BitTimingFd):
121
+ self._fd = True
122
+ self.timing = can.util.check_or_adjust_timing_clock(timing, valid_clocks=[fclk])
123
+ elif isinstance(timing, can.BitTiming):
124
+ self._fd = False
125
+ self.timing = can.util.check_or_adjust_timing_clock(timing, valid_clocks=[fclk])
126
+ elif bitrate and data_bitrate:
127
+ self._fd = True
128
+ self.timing = can.BitTimingFd.from_sample_point(
129
+ f_clock=fclk, nom_bitrate=bitrate, nom_sample_point=sample_point,
130
+ data_bitrate=data_bitrate, data_sample_point=data_sample_point)
131
+ elif bitrate:
132
+ self._fd = False
133
+ self.timing = can.BitTiming.from_sample_point(f_clock=fclk, bitrate=bitrate,
134
+ sample_point=sample_point)
135
+ else:
136
+ raise can.CanInitializationError(f"{INTERFACE}: give bitrate (and data_bitrate) or timing")
137
+
138
+ if self._fd and not btc.feature & p.FEATURE_FD:
139
+ raise can.CanInitializationError(f"{INTERFACE}: {dev.serial} does not support CAN FD")
140
+ want = (p.FEATURE_LISTEN_ONLY if listen_only or loopback else 0) \
141
+ | (p.FEATURE_LOOP_BACK if loopback else 0) \
142
+ | (p.FEATURE_ONE_SHOT if one_shot else 0) \
143
+ | (p.FEATURE_BERR_REPORTING if error_frames else 0) \
144
+ | (p.FEATURE_HW_TIMESTAMP if hw_timestamps else 0)
145
+ missing = want & ~btc.feature
146
+ if missing & ~p.FEATURE_HW_TIMESTAMP:
147
+ raise can.CanInitializationError(f"{INTERFACE}: {dev.serial} lacks mode flags 0x{missing:x}")
148
+ hw_timestamps = hw_timestamps and bool(btc.feature & p.FEATURE_HW_TIMESTAMP)
149
+ flags = (want & btc.feature) | (p.FEATURE_FD if self._fd else 0)
150
+
151
+ # Claim the channel first: a channel another bus has open must not be
152
+ # reset or retimed under it.
153
+ try:
154
+ self._queue = dev.open_channel(self._ch, hw_timestamps)
155
+ except RuntimeError as e:
156
+ raise can.CanInitializationError(f"{INTERFACE}: {e}") from e
157
+ self._channel_open = True
158
+ try:
159
+ dev.ctrl_out(p.BREQ_MODE, p.pack_mode(p.MODE_RESET, 0), value=self._ch)
160
+ if self._fd:
161
+ t = self.timing
162
+ dev.ctrl_out(p.BREQ_BITTIMING, p.pack_bittiming(t.nom_tseg1, t.nom_tseg2, t.nom_sjw, t.nom_brp),
163
+ value=self._ch)
164
+ dev.ctrl_out(p.BREQ_DATA_BITTIMING,
165
+ p.pack_bittiming(t.data_tseg1, t.data_tseg2, t.data_sjw, t.data_brp), value=self._ch)
166
+ else:
167
+ t = self.timing
168
+ dev.ctrl_out(p.BREQ_BITTIMING, p.pack_bittiming(t.tseg1, t.tseg2, t.sjw, t.brp), value=self._ch)
169
+ dev.ctrl_out(p.BREQ_MODE, p.pack_mode(p.MODE_START, flags), value=self._ch)
170
+ self._started = True
171
+ except usb.core.USBError as e:
172
+ raise can.CanInitializationError(f"{INTERFACE}: {e}") from e
173
+ self._can_protocol = can.CanProtocol.CAN_FD if self._fd else can.CanProtocol.CAN_20
174
+
175
+ # ---- transmit / receive
176
+ def send(self, msg: can.Message, timeout: float | None = None) -> None:
177
+ if msg.is_fd and not self._fd:
178
+ raise can.CanOperationError(f"{INTERFACE}: CAN FD frame on a classic CAN bus")
179
+ can_id = msg.arbitration_id | (p.CAN_EFF_FLAG if msg.is_extended_id else 0)
180
+ if msg.is_remote_frame:
181
+ can_id |= p.CAN_RTR_FLAG
182
+ data = bytes(msg.data)
183
+ frame = p.pack_frame(next(self._echo_ids) & 0x7FFFFFFF, can_id, self._ch, data, fd=msg.is_fd,
184
+ brs=msg.bitrate_switch, esi=msg.error_state_indicator,
185
+ dlc=None if msg.is_fd or not msg.is_remote_frame else msg.dlc)
186
+ try:
187
+ self._dev.write(frame, int(1000 * (1.0 if timeout is None else max(timeout, 0.001))))
188
+ except usb.core.USBTimeoutError as e:
189
+ raise can.CanOperationError(f"{INTERFACE}: the device did not take the frame in time") from e
190
+ except usb.core.USBError as e:
191
+ raise can.CanOperationError(f"{INTERFACE}: {e}") from e
192
+
193
+ def _recv_internal(self, timeout: float | None) -> tuple[can.Message | None, bool]:
194
+ deadline = None if timeout is None else time.monotonic() + timeout
195
+ while True:
196
+ err = self._dev.reader_error()
197
+ if err is not None and self._queue.empty():
198
+ raise can.CanOperationError(f"{INTERFACE}: USB read failed: {err}")
199
+ wait = 0.1 if deadline is None else max(0.0, min(0.1, deadline - time.monotonic()))
200
+ try:
201
+ ts, f = self._queue.get(timeout=wait)
202
+ except queue.Empty:
203
+ if deadline is not None and time.monotonic() >= deadline:
204
+ return None, False
205
+ continue
206
+ if f.can_id & p.CAN_ERR_FLAG and not self._error_frames:
207
+ continue
208
+ if not f.is_rx and not self._receive_own:
209
+ continue
210
+ if f.flags & p.FLAG_OVERFLOW:
211
+ warnings.warn(f"{INTERFACE}: the device dropped frames (overflow)", RuntimeWarning, stacklevel=2)
212
+ return self._to_message(ts, f), False
213
+
214
+ def _to_message(self, ts: float, f: p.Frame) -> can.Message:
215
+ err = bool(f.can_id & p.CAN_ERR_FLAG)
216
+ ext = bool(f.can_id & p.CAN_EFF_FLAG)
217
+ if err:
218
+ arb = f.can_id & p.CAN_EFF_MASK
219
+ else:
220
+ arb = f.can_id & (p.CAN_EFF_MASK if ext else p.CAN_SFF_MASK)
221
+ return can.Message(
222
+ timestamp=ts,
223
+ arbitration_id=arb,
224
+ is_extended_id=ext and not err,
225
+ is_remote_frame=bool(f.can_id & p.CAN_RTR_FLAG),
226
+ is_error_frame=err,
227
+ is_fd=f.is_fd,
228
+ bitrate_switch=bool(f.flags & p.FLAG_BRS),
229
+ error_state_indicator=bool(f.flags & p.FLAG_ESI),
230
+ is_rx=f.is_rx,
231
+ channel=self._ch,
232
+ dlc=len(f.data) if f.is_fd else min(f.dlc, 8),
233
+ data=f.data,
234
+ )
235
+
236
+ # ---- state
237
+ @property
238
+ def state(self) -> can.BusState:
239
+ if not self._started or self._dev is None:
240
+ raise can.CanOperationError(f"{INTERFACE}: the bus is closed")
241
+ if not self._dev.bt_const.feature & p.FEATURE_GET_STATE:
242
+ return can.BusState.ACTIVE
243
+ st, _rx, _tx = self.error_counters()
244
+ if st in (p.STATE_ERROR_ACTIVE, p.STATE_ERROR_WARNING):
245
+ return can.BusState.ACTIVE
246
+ if st == p.STATE_ERROR_PASSIVE:
247
+ return can.BusState.PASSIVE
248
+ if st == p.STATE_BUS_OFF:
249
+ return can.BusState.ERROR
250
+ raise can.CanOperationError(f"{INTERFACE}: channel {self._ch} is stopped")
251
+
252
+ @state.setter
253
+ def state(self, new_state: can.BusState) -> None:
254
+ raise NotImplementedError(f"{INTERFACE}: set listen_only when opening the bus")
255
+
256
+ def error_counters(self) -> tuple[int, int, int]:
257
+ """(state, rx error count, tx error count) from GET_STATE."""
258
+ try:
259
+ return struct.unpack("<3I", self._dev.ctrl_in(p.BREQ_GET_STATE, 12, value=self._ch))
260
+ except usb.core.USBError as e:
261
+ raise can.CanOperationError(f"{INTERFACE}: {e}") from e
262
+
263
+ # ---- shutdown
264
+ def _release(self) -> None:
265
+ if self._dev is None:
266
+ return
267
+ if self._started:
268
+ try:
269
+ self._dev.ctrl_out(p.BREQ_MODE, p.pack_mode(p.MODE_RESET, 0), value=self._ch)
270
+ except usb.core.USBError:
271
+ pass
272
+ self._started = False
273
+ if self._channel_open:
274
+ self._dev.close_channel(self._ch)
275
+ self._channel_open = False
276
+ self._dev.release()
277
+ self._dev = None
278
+
279
+ def shutdown(self) -> None:
280
+ self._release()
281
+ super().shutdown()
282
+
283
+ # ---- discovery
284
+ @staticmethod
285
+ def _detect_available_configs() -> list[can.typechecking.AutoDetectedConfig]:
286
+ configs: list[can.typechecking.AutoDetectedConfig] = []
287
+ try:
288
+ usb_devs = _device.find_usb_devices()
289
+ except usb.core.NoBackendError:
290
+ return configs
291
+ for u in usb_devs:
292
+ serial = _serial(u)
293
+ try:
294
+ dev = GsUsbDevice.acquire(serial, usb_dev=u)
295
+ except (LookupError, usb.core.USBError):
296
+ continue # in use by another process, or not a gs_usb device
297
+ try:
298
+ if not dev.bt_const.feature & p.FEATURE_FD:
299
+ continue
300
+ for ch in range(dev.channel_count):
301
+ configs.append({"interface": INTERFACE, "channel": f"{serial}@{ch}"})
302
+ finally:
303
+ dev.release()
304
+ return configs
@@ -0,0 +1,125 @@
1
+ """gs-usb-fd: detect devices, dump a bus listen-only, or self-test in internal loopback.
2
+
3
+ gs-usb-fd detect
4
+ gs-usb-fd listen [--channel C] [--seconds S] [timing options]
5
+ gs-usb-fd loopback [--channel C] [timing options]
6
+
7
+ Timing: --bitrate/--data-bitrate (80 % sample point), or the explicit
8
+ --nom/--data quadruples (brp tseg1 tseg2 sjw) at the device's CAN clock.
9
+ Defaults: 1 Mbit/s nominal, 5 Mbit/s data, as brp/tseg1/tseg2/sjw
10
+ 5/12/3/3 and 2/5/2/2 at 80 MHz.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import sys
17
+ import time
18
+
19
+ import can
20
+
21
+ from .bus import INTERFACE
22
+
23
+ DEFAULT_NOM = (5, 12, 3, 3)
24
+ DEFAULT_DATA = (2, 5, 2, 2)
25
+ F_CLOCK = 80_000_000
26
+
27
+
28
+ def _timing(a) -> dict:
29
+ if a.bitrate:
30
+ return {"bitrate": a.bitrate, **({"data_bitrate": a.data_bitrate} if a.data_bitrate else {})}
31
+ nom = a.nom or DEFAULT_NOM
32
+ data = a.data or DEFAULT_DATA
33
+ return {"timing": can.BitTimingFd(
34
+ f_clock=a.f_clock,
35
+ nom_brp=nom[0], nom_tseg1=nom[1], nom_tseg2=nom[2], nom_sjw=nom[3],
36
+ data_brp=data[0], data_tseg1=data[1], data_tseg2=data[2], data_sjw=data[3])}
37
+
38
+
39
+ def _fmt(m: can.Message) -> str:
40
+ if m.is_error_frame:
41
+ kind = "ERR "
42
+ elif m.is_fd:
43
+ kind = "FD BRS " if m.bitrate_switch else "FD "
44
+ else:
45
+ kind = "CAN "
46
+ ident = f"{m.arbitration_id:08X}" if m.is_extended_id else f" {m.arbitration_id:03X}"
47
+ who = "rx " if m.is_rx else "echo"
48
+ return f"{m.timestamp:17.6f} {who} {kind}{ident} [{m.dlc:2}] {bytes(m.data).hex(' ')}"
49
+
50
+
51
+ def _state(bus) -> str:
52
+ st, rx, tx = bus.error_counters()
53
+ names = {0: "error active", 1: "error warning", 2: "error passive", 3: "bus off", 4: "stopped"}
54
+ return f"{names.get(st, st)}, rx errors {rx}, tx errors {tx}"
55
+
56
+
57
+ def main(argv=None) -> int:
58
+ ap = argparse.ArgumentParser(prog="gs-usb-fd", description=__doc__,
59
+ formatter_class=argparse.RawDescriptionHelpFormatter)
60
+ ap.add_argument("cmd", choices=["detect", "listen", "loopback"])
61
+ ap.add_argument("--channel", default="0", help='"SERIAL@N" or N (0-based; probe: 0 = CAN1/J4)')
62
+ ap.add_argument("--seconds", type=float, default=3.0)
63
+ ap.add_argument("--max-print", type=int, default=20)
64
+ ap.add_argument("--bitrate", type=int)
65
+ ap.add_argument("--data-bitrate", type=int)
66
+ ap.add_argument("--nom", type=int, nargs=4, metavar=("BRP", "TSEG1", "TSEG2", "SJW"))
67
+ ap.add_argument("--data", type=int, nargs=4, metavar=("BRP", "TSEG1", "TSEG2", "SJW"))
68
+ ap.add_argument("--f-clock", type=int, default=F_CLOCK)
69
+ a = ap.parse_args(argv)
70
+
71
+ if a.cmd == "detect":
72
+ configs = can.detect_available_configs(interfaces=[INTERFACE])
73
+ for c in configs:
74
+ print(c)
75
+ if not configs:
76
+ print("no CAN FD gs_usb device found (or all in use)")
77
+ return 0 if configs else 1
78
+
79
+ if a.cmd == "listen":
80
+ with can.Bus(interface=INTERFACE, channel=a.channel, listen_only=True, **_timing(a)) as bus:
81
+ print(bus.channel_info)
82
+ n = fd = brs = 0
83
+ ids: dict[int, int] = {}
84
+ t_end = time.monotonic() + a.seconds
85
+ while time.monotonic() < t_end:
86
+ m = bus.recv(0.2)
87
+ if m is None:
88
+ continue
89
+ n += 1
90
+ fd += m.is_fd
91
+ brs += m.bitrate_switch
92
+ ids[m.arbitration_id] = ids.get(m.arbitration_id, 0) + 1
93
+ if n <= a.max_print:
94
+ print(_fmt(m))
95
+ print(f"{n} frames in {a.seconds:g} s ({fd} FD, {brs} BRS), {len(ids)} IDs; {_state(bus)}")
96
+ return 0
97
+
98
+ sent = [
99
+ can.Message(arbitration_id=0x123, data=b"\xde\xad\xbe\xef", is_extended_id=False),
100
+ can.Message(arbitration_id=0x1ABCDE0, data=bytes(range(64)), is_extended_id=True,
101
+ is_fd=True, bitrate_switch=True),
102
+ can.Message(arbitration_id=0x7FF, data=bytes(range(12)), is_extended_id=False, is_fd=True),
103
+ ]
104
+ with can.Bus(interface=INTERFACE, channel=a.channel, loopback=True, receive_own_messages=True,
105
+ **_timing(a)) as bus:
106
+ print(bus.channel_info)
107
+ got = []
108
+ for s in sent:
109
+ bus.send(s, timeout=1.0)
110
+ t_end = time.monotonic() + 1.0
111
+ while time.monotonic() < t_end:
112
+ m = bus.recv(0.1)
113
+ if m is not None:
114
+ print(_fmt(m))
115
+ got.append(m)
116
+ state = _state(bus)
117
+ rx = [g for g in got if g.is_rx]
118
+ ok = all(any(g.arbitration_id == s.arbitration_id and bytes(g.data) == bytes(s.data)
119
+ and g.is_fd == s.is_fd and g.bitrate_switch == s.bitrate_switch for g in rx) for s in sent)
120
+ print(f"{'PASS' if ok else 'FAIL'}: sent {len(sent)}, received {len(rx)} (+{len(got) - len(rx)} echoes); {state}")
121
+ return 0 if ok else 1
122
+
123
+
124
+ if __name__ == "__main__":
125
+ sys.exit(main())
@@ -0,0 +1,243 @@
1
+ """One gs_usb device, shared by every bus open on its channels.
2
+
3
+ All channels of a gs_usb device share one bulk IN endpoint, so a bus per
4
+ channel that read it on its own would steal the other channels' frames. A
5
+ device is opened once per process (keyed by its serial number), one reader
6
+ thread drains the IN endpoint and routes frames to per-channel queues, and
7
+ the device is closed when its last bus shuts down.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import queue
13
+ import struct
14
+ import threading
15
+ import time
16
+ from dataclasses import dataclass
17
+
18
+ import usb.core
19
+ import usb.util
20
+
21
+ from . import protocol as p
22
+
23
+ # gs_usb devices this interface looks for (the gs_usb Python package's list).
24
+ # Only those that advertise CAN FD can be opened.
25
+ KNOWN_IDS = (
26
+ (0x1D50, 0x606F), # candleLight / gs_usb (also the tricore-debug-machine probe)
27
+ (0x1209, 0x2323), # candleLight (pid.codes)
28
+ (0x1CD2, 0x606F), # CES CANext FD
29
+ (0x16D0, 0x10B8), # ABE CANdebugger FD
30
+ (0x1209, 0xCA01), # CANnectivity
31
+ )
32
+
33
+ IFACE = 0
34
+ READ_TIMEOUT_MS = 100
35
+ QUEUE_MAX = 100_000 # per channel, frames; the oldest are dropped beyond it
36
+
37
+
38
+ def usb_backend():
39
+ """A libusb-1.0 backend: the system's, else the DLL bundled by
40
+ libusb-package. Never pyusb's default order, which falls back to libusb0:
41
+ libusb-win32 leaves libusb0.dll in System32, and libusb0 cannot see
42
+ WinUSB devices (the device then looks absent)."""
43
+ import usb.backend.libusb1
44
+
45
+ backend = usb.backend.libusb1.get_backend()
46
+ if backend is not None:
47
+ return backend
48
+ try:
49
+ import libusb_package
50
+ except ImportError:
51
+ raise usb.core.NoBackendError("no libusb-1.0 (pip install libusb-package)") from None
52
+ return libusb_package.get_libusb1_backend()
53
+
54
+
55
+ def _serial(dev) -> str:
56
+ """The device's serial number (bus/address if it has none). Reading it
57
+ opens a libusb handle; it is released again, since a second handle on the
58
+ same device (a later enumeration) cannot read strings on Windows."""
59
+ if getattr(dev, "_gs_usb_fd_serial", None):
60
+ return dev._gs_usb_fd_serial
61
+ try:
62
+ s = dev.serial_number or f"bus{dev.bus}-addr{dev.address}"
63
+ except (usb.core.USBError, ValueError, NotImplementedError):
64
+ s = f"bus{dev.bus}-addr{dev.address}"
65
+ try:
66
+ dev._gs_usb_fd_serial = s
67
+ usb.util.dispose_resources(dev)
68
+ except (AttributeError, usb.core.USBError):
69
+ pass
70
+ return s
71
+
72
+
73
+ def find_usb_devices() -> list:
74
+ backend = usb_backend()
75
+ found = []
76
+ for vid, pid in KNOWN_IDS:
77
+ found.extend(usb.core.find(find_all=True, idVendor=vid, idProduct=pid, backend=backend) or [])
78
+ return found
79
+
80
+
81
+ @dataclass
82
+ class _Channel:
83
+ queue: queue.Queue
84
+ hw_timestamp: bool = True
85
+
86
+
87
+ class GsUsbDevice:
88
+ _registry: dict[str, GsUsbDevice] = {}
89
+ _registry_lock = threading.Lock()
90
+
91
+ # ---- process-wide sharing
92
+ @classmethod
93
+ def acquire(cls, serial: str | None, usb_dev=None) -> GsUsbDevice:
94
+ """The open device with this serial (the first one found if None),
95
+ opening it on first use. `usb_dev`: an already enumerated device with
96
+ that serial (spares a second enumeration). Pair with release()."""
97
+ with cls._registry_lock:
98
+ if serial is not None and serial in cls._registry:
99
+ dev = cls._registry[serial]
100
+ dev._refs += 1
101
+ return dev
102
+ if serial is None and cls._registry:
103
+ dev = next(iter(cls._registry.values()))
104
+ dev._refs += 1
105
+ return dev
106
+ usb_devs = [usb_dev] if usb_dev is not None else find_usb_devices()
107
+ if serial is not None:
108
+ usb_devs = [d for d in usb_devs if _serial(d) == serial]
109
+ if not usb_devs:
110
+ raise LookupError("no gs_usb device found" + (f" with serial {serial}" if serial else ""))
111
+ dev = cls(usb_devs[0])
112
+ cls._registry[dev.serial] = dev
113
+ return dev
114
+
115
+ def release(self) -> None:
116
+ with self._registry_lock:
117
+ self._refs -= 1
118
+ if self._refs > 0:
119
+ return
120
+ self._registry.pop(self.serial, None)
121
+ self._close()
122
+
123
+ # ---- open / close
124
+ def __init__(self, usb_dev):
125
+ self.usb = usb_dev
126
+ self.serial = _serial(usb_dev)
127
+ self._refs = 1
128
+ self._ctrl_lock = threading.Lock()
129
+ self._write_lock = threading.Lock()
130
+ self._channels: dict[int, _Channel] = {}
131
+ self._channels_lock = threading.Lock()
132
+ self._stop = threading.Event()
133
+ self._reader: threading.Thread | None = None
134
+ self._reader_error: BaseException | None = None
135
+ self._clock = p.TimestampUnwrapper(time.time())
136
+
137
+ try:
138
+ if self.usb.is_kernel_driver_active(IFACE):
139
+ self.usb.detach_kernel_driver(IFACE)
140
+ except (NotImplementedError, usb.core.USBError):
141
+ pass
142
+ usb.util.claim_interface(self.usb, IFACE)
143
+ try:
144
+ self.ep_in, self.ep_out = self._find_endpoints()
145
+ self.ctrl_out(p.BREQ_HOST_FORMAT, struct.pack("<I", 0x0000BEEF), value=1)
146
+ cfg = self.ctrl_in(p.BREQ_DEVICE_CONFIG, 12, value=1)
147
+ self.channel_count = cfg[3] + 1
148
+ self.sw_version, self.hw_version = struct.unpack_from("<II", cfg, 4)
149
+ self.bt_const = p.BitTimingConst.from_bytes(self.ctrl_in(p.BREQ_BT_CONST, 40, value=0))
150
+ if self.bt_const.feature & p.FEATURE_BT_CONST_EXT:
151
+ self.bt_const = p.BitTimingConst.from_bytes(self.ctrl_in(p.BREQ_BT_CONST_EXT, 72, value=0))
152
+ except Exception:
153
+ usb.util.release_interface(self.usb, IFACE)
154
+ usb.util.dispose_resources(self.usb)
155
+ raise
156
+
157
+ def _find_endpoints(self) -> tuple[int, int]:
158
+ intf = self.usb.get_active_configuration()[(IFACE, 0)]
159
+ ep_in = ep_out = None
160
+ for ep in intf:
161
+ if usb.util.endpoint_type(ep.bmAttributes) != usb.util.ENDPOINT_TYPE_BULK:
162
+ continue
163
+ if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN:
164
+ ep_in = ep_in or ep.bEndpointAddress
165
+ else:
166
+ ep_out = ep_out or ep.bEndpointAddress
167
+ if ep_in is None or ep_out is None:
168
+ raise LookupError(f"interface {IFACE} has no bulk IN/OUT endpoint pair")
169
+ return ep_in, ep_out
170
+
171
+ def _close(self) -> None:
172
+ self._stop.set()
173
+ if self._reader is not None:
174
+ self._reader.join(timeout=2 * READ_TIMEOUT_MS / 1000 + 1)
175
+ try:
176
+ usb.util.release_interface(self.usb, IFACE)
177
+ except usb.core.USBError:
178
+ pass
179
+ usb.util.dispose_resources(self.usb)
180
+
181
+ # ---- control requests
182
+ def ctrl_out(self, req: int, data: bytes, value: int = 0) -> None:
183
+ with self._ctrl_lock:
184
+ self.usb.ctrl_transfer(p.REQ_OUT, req, value, IFACE, data, 1000)
185
+
186
+ def ctrl_in(self, req: int, length: int, value: int = 0) -> bytes:
187
+ with self._ctrl_lock:
188
+ return bytes(self.usb.ctrl_transfer(p.REQ_IN, req, value, IFACE, length, 1000))
189
+
190
+ # ---- channels
191
+ def open_channel(self, ch: int, hw_timestamp: bool) -> queue.Queue:
192
+ with self._channels_lock:
193
+ if ch in self._channels:
194
+ raise RuntimeError(f"channel {ch} of {self.serial} is already open")
195
+ c = _Channel(queue.Queue(QUEUE_MAX), hw_timestamp)
196
+ self._channels[ch] = c
197
+ if self._reader is None:
198
+ self._reader = threading.Thread(target=self._read_loop, name=f"gs_usb_fd {self.serial}",
199
+ daemon=True)
200
+ self._reader.start()
201
+ return c.queue
202
+
203
+ def close_channel(self, ch: int) -> None:
204
+ with self._channels_lock:
205
+ self._channels.pop(ch, None)
206
+
207
+ def reader_error(self) -> BaseException | None:
208
+ return self._reader_error
209
+
210
+ def _read_loop(self) -> None:
211
+ while not self._stop.is_set():
212
+ try:
213
+ raw = bytes(self.usb.read(self.ep_in, 512, READ_TIMEOUT_MS))
214
+ except usb.core.USBTimeoutError:
215
+ continue
216
+ except usb.core.USBError as e:
217
+ if self._stop.is_set():
218
+ return
219
+ self._reader_error = e
220
+ return
221
+ now = time.time()
222
+ with self._channels_lock:
223
+ channels = dict(self._channels)
224
+ # Every open channel was started with the same timestamp setting.
225
+ hw_ts = next(iter(channels.values())).hw_timestamp if channels else True
226
+ for f in p.unpack_frames(raw, hw_ts):
227
+ c = channels.get(f.channel)
228
+ if c is None:
229
+ continue
230
+ ts = self._clock(f.timestamp_us, now) if f.timestamp_us is not None else now
231
+ try:
232
+ c.queue.put_nowait((ts, f))
233
+ except queue.Full:
234
+ try:
235
+ c.queue.get_nowait()
236
+ except queue.Empty:
237
+ pass
238
+ c.queue.put_nowait((ts, f))
239
+
240
+ # ---- transmit
241
+ def write(self, frame: bytes, timeout_ms: int) -> None:
242
+ with self._write_lock:
243
+ self.usb.write(self.ep_out, frame, timeout_ms)
@@ -0,0 +1,203 @@
1
+ """gs_usb wire format (the Linux gs_usb host protocol with CAN FD).
2
+
3
+ Reference: the probe's firmware, Appli/usb/gs_usb.c, which follows the Linux
4
+ driver (drivers/net/can/usb/gs_usb.c) and candleLight_fw.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import struct
10
+ from dataclasses import dataclass
11
+
12
+ # bRequest (vendor, recipient interface; wValue = channel, wIndex = interface)
13
+ BREQ_HOST_FORMAT = 0
14
+ BREQ_BITTIMING = 1
15
+ BREQ_MODE = 2
16
+ BREQ_BERR = 3
17
+ BREQ_BT_CONST = 4
18
+ BREQ_DEVICE_CONFIG = 5
19
+ BREQ_TIMESTAMP = 6
20
+ BREQ_IDENTIFY = 7
21
+ BREQ_DATA_BITTIMING = 10
22
+ BREQ_BT_CONST_EXT = 11
23
+ BREQ_GET_STATE = 14
24
+
25
+ REQ_OUT = 0x41 # host to device, vendor, interface
26
+ REQ_IN = 0xC1 # device to host, vendor, interface
27
+
28
+ MODE_RESET = 0
29
+ MODE_START = 1
30
+
31
+ # Feature bits (BT_CONST) double as mode flags (MODE).
32
+ FEATURE_LISTEN_ONLY = 1 << 0
33
+ FEATURE_LOOP_BACK = 1 << 1
34
+ FEATURE_TRIPLE_SAMPLE = 1 << 2
35
+ FEATURE_ONE_SHOT = 1 << 3
36
+ FEATURE_HW_TIMESTAMP = 1 << 4
37
+ FEATURE_IDENTIFY = 1 << 5
38
+ FEATURE_FD = 1 << 8
39
+ FEATURE_BT_CONST_EXT = 1 << 10
40
+ FEATURE_BERR_REPORTING = 1 << 12
41
+ FEATURE_GET_STATE = 1 << 13
42
+
43
+ # Frame flags
44
+ FLAG_OVERFLOW = 1 << 0
45
+ FLAG_FD = 1 << 1
46
+ FLAG_BRS = 1 << 2
47
+ FLAG_ESI = 1 << 3
48
+
49
+ # can_id bits (SocketCAN)
50
+ CAN_EFF_FLAG = 0x80000000
51
+ CAN_RTR_FLAG = 0x40000000
52
+ CAN_ERR_FLAG = 0x20000000
53
+ CAN_EFF_MASK = 0x1FFFFFFF
54
+ CAN_SFF_MASK = 0x000007FF
55
+
56
+ ECHO_ID_RX = 0xFFFFFFFF # echo_id of a received frame; TX echoes carry the host's id
57
+
58
+ # GET_STATE
59
+ STATE_ERROR_ACTIVE = 0
60
+ STATE_ERROR_WARNING = 1
61
+ STATE_ERROR_PASSIVE = 2
62
+ STATE_BUS_OFF = 3
63
+ STATE_STOPPED = 4
64
+ STATE_SLEEPING = 5
65
+
66
+ HEADER = struct.Struct("<IIBBBB") # echo_id, can_id, can_dlc, channel, flags, reserved
67
+ HEADER_LEN = HEADER.size # 12
68
+
69
+ _FD_LENGTHS = (0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64)
70
+
71
+
72
+ def len_to_dlc(length: int) -> int:
73
+ """Smallest CAN FD DLC code that holds `length` bytes."""
74
+ for code, size in enumerate(_FD_LENGTHS):
75
+ if length <= size:
76
+ return code
77
+ raise ValueError(f"CAN FD payload too long: {length} bytes (max 64)")
78
+
79
+
80
+ def dlc_to_len(dlc: int, fd: bool) -> int:
81
+ """Payload length of a DLC code; classic frames cap at 8."""
82
+ return _FD_LENGTHS[dlc & 0xF] if fd else min(dlc, 8)
83
+
84
+
85
+ def frame_size(flags: int, hw_timestamp: bool) -> int:
86
+ """Bytes one frame takes on the wire: header, 8 or 64 data bytes, then the
87
+ optional 32-bit timestamp right after the data."""
88
+ return HEADER_LEN + (64 if flags & FLAG_FD else 8) + (4 if hw_timestamp else 0)
89
+
90
+
91
+ @dataclass
92
+ class Frame:
93
+ echo_id: int
94
+ can_id: int
95
+ dlc: int
96
+ channel: int
97
+ flags: int
98
+ data: bytes # the payload only (dlc_to_len bytes)
99
+ timestamp_us: int | None = None
100
+
101
+ @property
102
+ def is_rx(self) -> bool:
103
+ return self.echo_id == ECHO_ID_RX
104
+
105
+ @property
106
+ def is_fd(self) -> bool:
107
+ return bool(self.flags & FLAG_FD)
108
+
109
+
110
+ def pack_frame(echo_id: int, can_id: int, channel: int, data: bytes, fd: bool, brs: bool = False,
111
+ esi: bool = False, dlc: int | None = None) -> bytes:
112
+ """A host-to-device frame (no timestamp: the device adds those on IN only)."""
113
+ flags = 0
114
+ if fd:
115
+ flags = FLAG_FD | (FLAG_BRS if brs else 0) | (FLAG_ESI if esi else 0)
116
+ code = len_to_dlc(len(data)) if dlc is None else dlc
117
+ payload = bytes(data).ljust(64, b"\0")
118
+ else:
119
+ if len(data) > 8:
120
+ raise ValueError("classic CAN frames carry at most 8 bytes")
121
+ code = len(data) if dlc is None else dlc
122
+ payload = bytes(data).ljust(8, b"\0")
123
+ return HEADER.pack(echo_id & 0xFFFFFFFF, can_id & 0xFFFFFFFF, code, channel, flags, 0) + payload
124
+
125
+
126
+ def unpack_frames(buf: bytes, hw_timestamp: bool) -> list[Frame]:
127
+ """All frames in one IN transfer (the probe sends one per transfer; other
128
+ gs_usb devices may pack several). A truncated tail is dropped."""
129
+ frames = []
130
+ off = 0
131
+ while len(buf) - off >= HEADER_LEN + 8:
132
+ echo_id, can_id, dlc, channel, flags, _ = HEADER.unpack_from(buf, off)
133
+ size = frame_size(flags, hw_timestamp)
134
+ if len(buf) - off < size - (4 if hw_timestamp else 0):
135
+ break
136
+ fd = bool(flags & FLAG_FD)
137
+ start = off + HEADER_LEN
138
+ data = bytes(buf[start:start + dlc_to_len(dlc, fd)])
139
+ ts = None
140
+ ts_off = start + (64 if fd else 8)
141
+ if hw_timestamp and len(buf) >= ts_off + 4:
142
+ ts = struct.unpack_from("<I", buf, ts_off)[0]
143
+ frames.append(Frame(echo_id, can_id, dlc, channel, flags, data, ts))
144
+ off += size
145
+ return frames
146
+
147
+
148
+ @dataclass
149
+ class BitTimingConst:
150
+ """BT_CONST(_EXT): what the device accepts. Data limits are 0 without FD."""
151
+ feature: int
152
+ fclk_can: int
153
+ tseg1_min: int
154
+ tseg1_max: int
155
+ tseg2_min: int
156
+ tseg2_max: int
157
+ sjw_max: int
158
+ brp_min: int
159
+ brp_max: int
160
+ brp_inc: int
161
+ dtseg1_min: int = 0
162
+ dtseg1_max: int = 0
163
+ dtseg2_min: int = 0
164
+ dtseg2_max: int = 0
165
+ dsjw_max: int = 0
166
+ dbrp_min: int = 0
167
+ dbrp_max: int = 0
168
+ dbrp_inc: int = 0
169
+
170
+ @classmethod
171
+ def from_bytes(cls, raw: bytes) -> BitTimingConst:
172
+ n = len(raw) // 4
173
+ return cls(*struct.unpack(f"<{n}I", raw[:n * 4]))
174
+
175
+
176
+ def pack_bittiming(tseg1: int, tseg2: int, sjw: int, brp: int) -> bytes:
177
+ """BITTIMING / DATA_BITTIMING. The device takes tseg1 as prop_seg +
178
+ phase_seg1; one tq of prop_seg is the Linux driver's convention."""
179
+ return struct.pack("<5I", 1, tseg1 - 1, tseg2, sjw, brp)
180
+
181
+
182
+ def pack_mode(mode: int, flags: int) -> bytes:
183
+ return struct.pack("<II", mode, flags)
184
+
185
+
186
+ class TimestampUnwrapper:
187
+ """32-bit microsecond device timestamps to host seconds (wrap every
188
+ ~71.6 min). Anchored to the host clock on the first frame."""
189
+
190
+ def __init__(self, now: float):
191
+ self._now = now
192
+ self._anchor: float | None = None
193
+ self._last = 0
194
+ self._high = 0
195
+
196
+ def __call__(self, ts_us: int, now: float | None = None) -> float:
197
+ if self._anchor is None:
198
+ self._anchor = (self._now if now is None else now) - ts_us / 1e6
199
+ self._last = ts_us
200
+ if ts_us < self._last and self._last - ts_us > 0x80000000:
201
+ self._high += 1 << 32
202
+ self._last = ts_us
203
+ return self._anchor + (self._high + ts_us) / 1e6