|
11 | 11 | """ |
12 | 12 |
|
13 | 13 | import logging |
| 14 | +import os |
| 15 | +import tempfile |
14 | 16 | from collections import deque |
15 | 17 |
|
16 | 18 | from can import Message, CanError, BusABC |
|
28 | 30 | ics = None |
29 | 31 |
|
30 | 32 |
|
| 33 | +try: |
| 34 | + from filelock import FileLock |
| 35 | +except ImportError as ie: |
| 36 | + |
| 37 | + logger.warning( |
| 38 | + "Using ICS NeoVi can backend without the " |
| 39 | + "filelock module installed may cause some issues!: %s", |
| 40 | + ie, |
| 41 | + ) |
| 42 | + |
| 43 | + class FileLock: |
| 44 | + """Dummy file lock that does not actually do anything""" |
| 45 | + |
| 46 | + def __init__(self, lock_file, timeout=-1): |
| 47 | + self._lock_file = lock_file |
| 48 | + self.timeout = timeout |
| 49 | + |
| 50 | + def __enter__(self): |
| 51 | + return self |
| 52 | + |
| 53 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 54 | + return None |
| 55 | + |
| 56 | + |
| 57 | +# Use inter-process mutex to prevent concurrent device open. |
| 58 | +# When neoVI server is enabled, there is an issue with concurrent device open. |
| 59 | +open_lock = FileLock(os.path.join(tempfile.gettempdir(), "neovi.lock")) |
| 60 | + |
| 61 | + |
31 | 62 | class ICSApiError(CanError): |
32 | 63 | """ |
33 | 64 | Indicates an error with the ICS API. |
@@ -122,7 +153,9 @@ def __init__(self, channel, can_filters=None, **kwargs): |
122 | 153 | type_filter = kwargs.get("type_filter") |
123 | 154 | serial = kwargs.get("serial") |
124 | 155 | self.dev = self._find_device(type_filter, serial) |
125 | | - ics.open_device(self.dev) |
| 156 | + |
| 157 | + with open_lock: |
| 158 | + ics.open_device(self.dev) |
126 | 159 |
|
127 | 160 | if "bitrate" in kwargs: |
128 | 161 | for channel in self.channels: |
|
0 commit comments