Skip to content

Commit dbdc26c

Browse files
committed
gs_usb, interface: fix bug on second .start() by repeating in shutdown()
v2: updates as per review #1790 (review) by @zariiii9003
1 parent b193ead commit dbdc26c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

can/interfaces/gs_usb.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,24 @@ def __init__(
3333
:param can_filters: not supported
3434
:param bitrate: CAN network bandwidth (bits/s)
3535
"""
36+
self._is_shutdown = False
3637
if (index is not None) and ((bus or address) is not None):
3738
raise CanInitializationError(
3839
"index and bus/address cannot be used simultaneously"
3940
)
4041

42+
if index is None and address is None and bus is None:
43+
index = channel
44+
45+
self._index = None
4146
if index is not None:
4247
devs = GsUsb.scan()
4348
if len(devs) <= index:
4449
raise CanInitializationError(
4550
f"Cannot find device {index}. Devices found: {len(devs)}"
4651
)
4752
gs_usb = devs[index]
53+
self._index = index
4854
else:
4955
gs_usb = GsUsb.find(bus=bus, address=address)
5056
if not gs_usb:
@@ -68,6 +74,7 @@ def __init__(
6874
brp=bit_timing.brp,
6975
)
7076
self.gs_usb.start()
77+
self._bitrate = bitrate
7178

7279
super().__init__(
7380
channel=channel,
@@ -154,5 +161,21 @@ def _recv_internal(
154161
return msg, False
155162

156163
def shutdown(self):
164+
if self._is_shutdown:
165+
return
166+
157167
super().shutdown()
158168
self.gs_usb.stop()
169+
if self._index is not None:
170+
# Avoid errors on subsequent __init() by repeating the .scan() and .start() that would otherwise fail
171+
# the next time the device is opened in __init__()
172+
devs = GsUsb.scan()
173+
if self._index < len(devs):
174+
gs_usb = devs[self._index]
175+
try:
176+
gs_usb.set_bitrate(self._bitrate)
177+
gs_usb.start()
178+
gs_usb.stop()
179+
except usb.core.USBError:
180+
pass
181+
self._is_shutdown = True

0 commit comments

Comments
 (0)