4
4
5
5
import logging
6
6
from ctypes import byref
7
- from typing import Optional
8
-
9
- from can import BusABC , Message , CanInitializationError , CanOperationError
7
+ from typing import Optional , Union
8
+
9
+ from can import (
10
+ BusABC ,
11
+ Message ,
12
+ CanInitializationError ,
13
+ CanOperationError ,
14
+ BitTiming ,
15
+ BitTimingFd ,
16
+ )
10
17
from .usb2canabstractionlayer import Usb2CanAbstractionLayer , CanalMsg , CanalError
11
18
from .usb2canabstractionlayer import (
12
19
IS_ERROR_FRAME ,
13
20
IS_REMOTE_FRAME ,
14
21
IS_ID_TYPE ,
15
22
)
16
23
from .serial_selector import find_serial_devices
24
+ from ...util import check_or_adjust_timing_clock
17
25
18
26
# Set up logging
19
27
log = logging .getLogger ("can.usb2can" )
@@ -75,6 +83,13 @@ class Usb2canBus(BusABC):
75
83
Bitrate of channel in bit/s. Values will be limited to a maximum of 1000 Kb/s.
76
84
Default is 500 Kbs
77
85
86
+ :param timing:
87
+ Optional :class:`~can.BitTiming` instance to use for custom bit timing setting.
88
+ If this argument is set then it overrides the bitrate argument. The
89
+ `f_clock` value of the timing instance must be set to 32_000_000 (32MHz)
90
+ for standard CAN.
91
+ CAN FD and the :class:`~can.BitTimingFd` class are not supported.
92
+
78
93
:param flags:
79
94
Flags to directly pass to open function of the usb2can abstraction layer.
80
95
@@ -96,6 +111,7 @@ def __init__(
96
111
flags : int = 0x00000008 ,
97
112
* _ ,
98
113
bitrate : int = 500000 ,
114
+ timing : Optional [Union [BitTiming , BitTimingFd ]] = None ,
99
115
serial : Optional [str ] = None ,
100
116
** kwargs ,
101
117
):
@@ -112,12 +128,26 @@ def __init__(
112
128
raise CanInitializationError ("could not automatically find any device" )
113
129
device_id = devices [0 ]
114
130
115
- # convert to kb/s and cap: max rate is 1000 kb/s
116
- baudrate = min (int (bitrate // 1000 ), 1000 )
117
-
118
131
self .channel_info = f"USB2CAN device { device_id } "
119
132
120
- connector = f"{ device_id } ; { baudrate } "
133
+ if isinstance (timing , BitTiming ):
134
+ timing = check_or_adjust_timing_clock (timing , valid_clocks = [32_000_000 ])
135
+ connector = (
136
+ f"{ device_id } ;"
137
+ "0;"
138
+ f"{ timing .tseg1 } ;"
139
+ f"{ timing .tseg2 } ;"
140
+ f"{ timing .sjw } ;"
141
+ f"{ timing .brp } "
142
+ )
143
+ elif isinstance (timing , BitTimingFd ):
144
+ raise NotImplementedError (
145
+ f"CAN FD is not supported by { self .__class__ .__name__ } ."
146
+ )
147
+ else :
148
+ # convert to kb/s and cap: max rate is 1000 kb/s
149
+ baudrate = min (int (bitrate // 1000 ), 1000 )
150
+ connector = f"{ device_id } ;{ baudrate } "
121
151
self .handle = self .can .open (connector , flags )
122
152
123
153
super ().__init__ (channel = channel , ** kwargs )
0 commit comments