hardbyte / hardbyte/python-can

Re-connect with PCANBasic fails after failed connection attempt

Đang mở
#729 1 bình luận 0 reaction 0 người được giao Xem trên GitHub
backend:pcan
Ngôn ngữ chính
Python
Star
1.6k
Fork
697
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

I am using `python-can` with an PEAK-Dongle.
Sometimes I get an exception during Bus creation than I would like try another connection attempt, but this Fails, because `python-can` has intitialized the PCAN-DLL but did not uninitialize it.
And since [multiple Connections are not allowed with PCANBasic](378) the second connection attempt also Fails (and all other in the same process)

The issue can be Show with the following script
```python
import can
try:
bus = can.interface.Bus(bustype="pcan", channel="PCAN_USBBUS1", bitrate=5000000)
bus.shutdown()
except:
print("exception")
# the following attempt ALWAYS fails if the first attempt has also failed
bus = can.interface.Bus(bustype="pcan", channel="PCAN_USBBUS1", bitrate=5000000)
bus.shutdown()
```

The problematic code is [here](https://github.com/hardbyte/python-can/blob/develop/can/interfaces/pcan/pcan.py#L212). Before this line the PCAN-Dll get initialized but if afterwards a exception is raised, it does not get uninitilized.

A simple solution can be the following:
````python

class PcanBus(BusABC):
def __init__(…):
# ...
try:
if result != PCAN_ERROR_OK:
raise PcanError(self._get_formatted_error(result))

result = self.m_objPCANBasic.SetValue(
self.m_PcanHandle, PCAN_ALLOW_ERROR_FRAMES, PCAN_PARAMETER_ON
)

if result != PCAN_ERROR_OK:
raise PcanError(self._get_formatted_error(result))

if HAS_EVENTS:
self._recv_event = CreateEvent(None, 0, 0, None)
result = self.m_objPCANBasic.SetValue(
self.m_PcanHandle, PCAN_RECEIVE_EVENT, self._recv_event
)
if result != PCAN_ERROR_OK:
raise PcanError(self._get_formatted_error(result))

super().__init__(channel=channel, state=state, bitrate=bitrate, *args, **kwargs)
except:
self.m_objPCANBasic.Uninitialize(self.m_PcanHandle)
raise
```

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.