Skip to content

Commit bffc95b

Browse files
Use internal Py3 API for PCAN receive event
1 parent d38c0e0 commit bffc95b

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

can/interfaces/pcan/pcan.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,19 @@
2020
boottimeEpoch = 0
2121

2222
try:
23-
import win32event
23+
# Try builtin Python 3 Windows API
24+
from _overlapped import CreateEvent
25+
from _winapi import WaitForSingleObject, WAIT_OBJECT_0, INFINITE
26+
HAS_EVENTS = True
2427
except ImportError:
25-
win32event = None
28+
try:
29+
# Try pywin32 package
30+
from win32event import CreateEvent
31+
from win32event import WaitForSingleObject, WAIT_OBJECT_0, INFINITE
32+
HAS_EVENTS = True
33+
except ImportError:
34+
# Use polling instead
35+
HAS_EVENTS = False
2636

2737
if sys.version_info >= (3, 3):
2838
# new in 3.3
@@ -87,8 +97,8 @@ def __init__(self, channel, *args, **kwargs):
8797
if result != PCAN_ERROR_OK:
8898
raise PcanError(self._get_formatted_error(result))
8999

90-
if win32event is not None:
91-
self._recv_event = win32event.CreateEvent(None, 0, 0, None)
100+
if HAS_EVENTS:
101+
self._recv_event = CreateEvent(None, 0, 0, None)
92102
result = self.m_objPCANBasic.SetValue(
93103
self.m_PcanHandle, PCAN_RECEIVE_EVENT, self._recv_event)
94104
if result != PCAN_ERROR_OK:
@@ -153,28 +163,25 @@ def reset(self):
153163
return status == PCAN_ERROR_OK
154164

155165
def recv(self, timeout=None):
156-
if win32event is not None:
166+
if HAS_EVENTS:
157167
# We will utilize events for the timeout handling
158-
timeout_ms = int(timeout * 1000) if timeout is not None else win32event.INFINITE
168+
timeout_ms = int(timeout * 1000) if timeout is not None else INFINITE
159169
elif timeout is not None:
160170
# Calculate max time
161171
end_time = timeout_clock() + timeout
162-
else:
163-
# Skip timeout handling
164-
end_time = 0
165172

166173
log.debug("Trying to read a msg")
167174

168175
result = None
169176
while result is None:
170177
result = self.m_objPCANBasic.Read(self.m_PcanHandle)
171178
if result[0] == PCAN_ERROR_QRCVEMPTY:
172-
if win32event is not None:
179+
if HAS_EVENTS:
173180
result = None
174-
val = win32event.WaitForSingleObject(self._recv_event, timeout_ms)
175-
if val != win32event.WAIT_OBJECT_0:
181+
val = WaitForSingleObject(self._recv_event, timeout_ms)
182+
if val != WAIT_OBJECT_0:
176183
return None
177-
elif timeout_clock() >= end_time:
184+
elif timeout is not None and timeout_clock() >= end_time:
178185
return None
179186
else:
180187
result = None

0 commit comments

Comments
 (0)