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