44
55import logging
66from 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
1019
1120from .serial_selector import find_serial_devices
1221from .usb2canabstractionlayer import (
@@ -78,6 +87,13 @@ class Usb2canBus(BusABC):
7887 Bitrate of channel in bit/s. Values will be limited to a maximum of 1000 Kb/s.
7988 Default is 500 Kbs
8089
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+
8197 :param flags:
8298 Flags to directly pass to open function of the usb2can abstraction layer.
8399
@@ -97,8 +113,8 @@ def __init__(
97113 channel : Optional [str ] = None ,
98114 dll : str = "usb2can.dll" ,
99115 flags : int = 0x00000008 ,
100- * _ ,
101116 bitrate : int = 500000 ,
117+ timing : Optional [Union [BitTiming , BitTimingFd ]] = None ,
102118 serial : Optional [str ] = None ,
103119 ** kwargs ,
104120 ):
@@ -114,13 +130,28 @@ def __init__(
114130 raise CanInitializationError ("could not automatically find any device" )
115131 device_id = devices [0 ]
116132
117- # convert to kb/s and cap: max rate is 1000 kb/s
118- baudrate = min (int (bitrate // 1000 ), 1000 )
119-
120133 self .channel_info = f"USB2CAN device { device_id } "
121- self ._can_protocol = CanProtocol .CAN_20
122134
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
124155 self .handle = self .can .open (connector , flags )
125156
126157 super ().__init__ (channel = channel , ** kwargs )
0 commit comments