Skip to content

Commit 361574f

Browse files
committed
try to set correct f_clock before raising exception
1 parent 4f0ba10 commit 361574f

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

can/interfaces/pcan/pcan.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -258,19 +258,27 @@ def __init__(
258258
raise ValueError("BusState must be Active or Passive")
259259

260260
if isinstance(timing, BitTimingFd):
261-
valid_fd_clocks = [
262-
20000000,
263-
24000000,
264-
30000000,
265-
40000000,
266-
60000000,
267-
80000000,
261+
valid_fd_f_clocks = [
262+
20_000_000,
263+
24_000_000,
264+
30_000_000,
265+
40_000_000,
266+
60_000_000,
267+
80_000_000,
268268
]
269-
if timing.f_clock not in valid_fd_clocks:
270-
raise CanInitializationError(
271-
f"The PcanBus requires one of the following CAN clocks for CAN FD: "
272-
f"{','.join([str(f) for f in valid_fd_clocks])} (timing={timing!r})"
273-
)
269+
if timing.f_clock not in valid_fd_f_clocks:
270+
# try setting a valid f_clock. Raise exception if this fails
271+
for f_clock in reversed(valid_fd_f_clocks):
272+
try:
273+
timing = BitTimingFd(**{**timing, "f_clock": f_clock})
274+
break
275+
except ValueError:
276+
continue
277+
else:
278+
raise CanInitializationError(
279+
f"The PcanBus requires one of the following CAN clocks for CAN FD: "
280+
f"{','.join([str(f) for f in valid_fd_f_clocks])} (timing={timing!r})"
281+
)
274282
self.fd_bitrate = (
275283
f"f_clock={timing.f_clock},"
276284
f"nom_brp={timing.nom_brp},"
@@ -287,9 +295,13 @@ def __init__(
287295
)
288296
elif isinstance(timing, BitTiming):
289297
if timing.f_clock != 8_000_000:
290-
raise CanInitializationError(
291-
f"The PcanBus requires a 8MHz CAN clock for CAN2.0 (timing={timing!r})"
292-
)
298+
try:
299+
# try different prescaler values
300+
timing = BitTiming(**{**timing, "f_clock": 8_000_000})
301+
except ValueError:
302+
raise CanInitializationError(
303+
f"The PcanBus requires a 8MHz CAN clock for CAN2.0 (timing={timing!r})"
304+
) from None
293305
pcan_bitrate = TPCANBaudrate(timing.btr0 << 8 | timing.btr1)
294306
result = self.m_objPCANBasic.Initialize(
295307
self.m_PcanHandle, pcan_bitrate, hwtype, ioport, interrupt

0 commit comments

Comments
 (0)