pyxcp 0.22.16__cp310-cp310-manylinux_2_28_x86_64.manylinux_2_27_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pyxcp might be problematic. Click here for more details.

Files changed (128) hide show
  1. pyxcp/__init__.py +20 -0
  2. pyxcp/aml/EtasCANMonitoring.a2l +82 -0
  3. pyxcp/aml/EtasCANMonitoring.aml +67 -0
  4. pyxcp/aml/XCP_Common.aml +408 -0
  5. pyxcp/aml/XCPonCAN.aml +78 -0
  6. pyxcp/aml/XCPonEth.aml +33 -0
  7. pyxcp/aml/XCPonFlx.aml +113 -0
  8. pyxcp/aml/XCPonSxI.aml +66 -0
  9. pyxcp/aml/XCPonUSB.aml +106 -0
  10. pyxcp/aml/ifdata_CAN.a2l +20 -0
  11. pyxcp/aml/ifdata_Eth.a2l +11 -0
  12. pyxcp/aml/ifdata_Flx.a2l +94 -0
  13. pyxcp/aml/ifdata_SxI.a2l +13 -0
  14. pyxcp/aml/ifdata_USB.a2l +81 -0
  15. pyxcp/asam/__init__.py +0 -0
  16. pyxcp/asam/types.py +131 -0
  17. pyxcp/asamkeydll.c +116 -0
  18. pyxcp/asamkeydll.sh +2 -0
  19. pyxcp/checksum.py +722 -0
  20. pyxcp/cmdline.py +52 -0
  21. pyxcp/config/__init__.py +1101 -0
  22. pyxcp/config/legacy.py +120 -0
  23. pyxcp/constants.py +47 -0
  24. pyxcp/cpp_ext/__init__.py +0 -0
  25. pyxcp/cpp_ext/bin.hpp +104 -0
  26. pyxcp/cpp_ext/blockmem.hpp +58 -0
  27. pyxcp/cpp_ext/cpp_ext.cpython-310-x86_64-linux-gnu.so +0 -0
  28. pyxcp/cpp_ext/daqlist.hpp +200 -0
  29. pyxcp/cpp_ext/event.hpp +67 -0
  30. pyxcp/cpp_ext/extension_wrapper.cpp +96 -0
  31. pyxcp/cpp_ext/helper.hpp +280 -0
  32. pyxcp/cpp_ext/mcobject.hpp +246 -0
  33. pyxcp/cpp_ext/tsqueue.hpp +46 -0
  34. pyxcp/daq_stim/__init__.py +226 -0
  35. pyxcp/daq_stim/optimize/__init__.py +67 -0
  36. pyxcp/daq_stim/optimize/binpacking.py +41 -0
  37. pyxcp/daq_stim/scheduler.cpp +28 -0
  38. pyxcp/daq_stim/scheduler.hpp +75 -0
  39. pyxcp/daq_stim/stim.cpp +13 -0
  40. pyxcp/daq_stim/stim.cpython-310-x86_64-linux-gnu.so +0 -0
  41. pyxcp/daq_stim/stim.hpp +604 -0
  42. pyxcp/daq_stim/stim_wrapper.cpp +48 -0
  43. pyxcp/dllif.py +95 -0
  44. pyxcp/errormatrix.py +878 -0
  45. pyxcp/examples/conf_can.toml +19 -0
  46. pyxcp/examples/conf_can_user.toml +16 -0
  47. pyxcp/examples/conf_can_vector.json +11 -0
  48. pyxcp/examples/conf_can_vector.toml +11 -0
  49. pyxcp/examples/conf_eth.toml +9 -0
  50. pyxcp/examples/conf_nixnet.json +20 -0
  51. pyxcp/examples/conf_socket_can.toml +12 -0
  52. pyxcp/examples/conf_sxi.json +9 -0
  53. pyxcp/examples/conf_sxi.toml +7 -0
  54. pyxcp/examples/ex_arrow.py +109 -0
  55. pyxcp/examples/ex_csv.py +85 -0
  56. pyxcp/examples/ex_excel.py +95 -0
  57. pyxcp/examples/ex_mdf.py +124 -0
  58. pyxcp/examples/ex_sqlite.py +128 -0
  59. pyxcp/examples/run_daq.py +148 -0
  60. pyxcp/examples/xcp_policy.py +60 -0
  61. pyxcp/examples/xcp_read_benchmark.py +38 -0
  62. pyxcp/examples/xcp_skel.py +49 -0
  63. pyxcp/examples/xcp_unlock.py +38 -0
  64. pyxcp/examples/xcp_user_supplied_driver.py +54 -0
  65. pyxcp/examples/xcphello.py +79 -0
  66. pyxcp/examples/xcphello_recorder.py +107 -0
  67. pyxcp/master/__init__.py +9 -0
  68. pyxcp/master/errorhandler.py +436 -0
  69. pyxcp/master/master.py +2031 -0
  70. pyxcp/py.typed +0 -0
  71. pyxcp/recorder/__init__.py +102 -0
  72. pyxcp/recorder/build_clang.cmd +1 -0
  73. pyxcp/recorder/build_clang.sh +2 -0
  74. pyxcp/recorder/build_gcc.cmd +1 -0
  75. pyxcp/recorder/build_gcc.sh +2 -0
  76. pyxcp/recorder/build_gcc_arm.sh +2 -0
  77. pyxcp/recorder/converter/__init__.py +37 -0
  78. pyxcp/recorder/lz4.c +2829 -0
  79. pyxcp/recorder/lz4.h +879 -0
  80. pyxcp/recorder/lz4hc.c +2041 -0
  81. pyxcp/recorder/lz4hc.h +413 -0
  82. pyxcp/recorder/mio.hpp +1714 -0
  83. pyxcp/recorder/reader.hpp +139 -0
  84. pyxcp/recorder/reco.py +277 -0
  85. pyxcp/recorder/recorder.rst +0 -0
  86. pyxcp/recorder/rekorder.cpp +59 -0
  87. pyxcp/recorder/rekorder.cpython-310-x86_64-linux-gnu.so +0 -0
  88. pyxcp/recorder/rekorder.hpp +274 -0
  89. pyxcp/recorder/setup.py +41 -0
  90. pyxcp/recorder/test_reko.py +34 -0
  91. pyxcp/recorder/unfolder.hpp +1332 -0
  92. pyxcp/recorder/wrap.cpp +189 -0
  93. pyxcp/recorder/writer.hpp +302 -0
  94. pyxcp/scripts/__init__.py +0 -0
  95. pyxcp/scripts/pyxcp_probe_can_drivers.py +20 -0
  96. pyxcp/scripts/xcp_examples.py +64 -0
  97. pyxcp/scripts/xcp_fetch_a2l.py +40 -0
  98. pyxcp/scripts/xcp_id_scanner.py +19 -0
  99. pyxcp/scripts/xcp_info.py +109 -0
  100. pyxcp/scripts/xcp_profile.py +27 -0
  101. pyxcp/stim/__init__.py +0 -0
  102. pyxcp/tests/test_asam_types.py +24 -0
  103. pyxcp/tests/test_binpacking.py +186 -0
  104. pyxcp/tests/test_can.py +1324 -0
  105. pyxcp/tests/test_checksum.py +95 -0
  106. pyxcp/tests/test_daq.py +193 -0
  107. pyxcp/tests/test_frame_padding.py +156 -0
  108. pyxcp/tests/test_master.py +2006 -0
  109. pyxcp/tests/test_transport.py +64 -0
  110. pyxcp/tests/test_utils.py +30 -0
  111. pyxcp/timing.py +60 -0
  112. pyxcp/transport/__init__.py +10 -0
  113. pyxcp/transport/base.py +439 -0
  114. pyxcp/transport/base_transport.hpp +0 -0
  115. pyxcp/transport/can.py +443 -0
  116. pyxcp/transport/eth.py +219 -0
  117. pyxcp/transport/sxi.py +133 -0
  118. pyxcp/transport/transport_wrapper.cpp +0 -0
  119. pyxcp/transport/usb_transport.py +213 -0
  120. pyxcp/types.py +993 -0
  121. pyxcp/utils.py +102 -0
  122. pyxcp/vector/__init__.py +0 -0
  123. pyxcp/vector/map.py +82 -0
  124. pyxcp-0.22.16.dist-info/LICENSE +165 -0
  125. pyxcp-0.22.16.dist-info/METADATA +107 -0
  126. pyxcp-0.22.16.dist-info/RECORD +128 -0
  127. pyxcp-0.22.16.dist-info/WHEEL +6 -0
  128. pyxcp-0.22.16.dist-info/entry_points.txt +8 -0
@@ -0,0 +1,64 @@
1
+ import pytest
2
+
3
+ import pyxcp.transport.base as tr
4
+
5
+
6
+ def test_factory_works():
7
+ assert isinstance(tr.create_transport("eth"), tr.BaseTransport)
8
+ assert isinstance(tr.create_transport("sxi"), tr.BaseTransport)
9
+ assert isinstance(
10
+ tr.create_transport(
11
+ "can",
12
+ config={
13
+ "CAN_ID_MASTER": 1,
14
+ "CAN_ID_SLAVE": 2,
15
+ "CAN_DRIVER": "MockCanInterface",
16
+ },
17
+ ),
18
+ tr.BaseTransport,
19
+ )
20
+
21
+
22
+ def test_factory_works_case_insensitive():
23
+ assert isinstance(tr.create_transport("ETH"), tr.BaseTransport)
24
+ assert isinstance(tr.create_transport("SXI"), tr.BaseTransport)
25
+ assert isinstance(
26
+ tr.create_transport(
27
+ "CAN",
28
+ config={
29
+ "CAN_ID_MASTER": 1,
30
+ "CAN_ID_SLAVE": 2,
31
+ "CAN_DRIVER": "MockCanInterface",
32
+ },
33
+ ),
34
+ tr.BaseTransport,
35
+ )
36
+
37
+
38
+ def test_factory_invalid_transport_name_raises():
39
+ with pytest.raises(ValueError):
40
+ tr.create_transport("xCp")
41
+
42
+
43
+ def test_transport_names():
44
+ transports = tr.available_transports()
45
+
46
+ assert "can" in transports
47
+ assert "eth" in transports
48
+ assert "sxi" in transports
49
+
50
+
51
+ def test_transport_names_are_lower_case_only():
52
+ transports = tr.available_transports()
53
+
54
+ assert "CAN" not in transports
55
+ assert "ETH" not in transports
56
+ assert "SXI" not in transports
57
+
58
+
59
+ def test_transport_classes():
60
+ transports = tr.available_transports()
61
+
62
+ assert issubclass(transports.get("can"), tr.BaseTransport)
63
+ assert issubclass(transports.get("eth"), tr.BaseTransport)
64
+ assert issubclass(transports.get("sxi"), tr.BaseTransport)
@@ -0,0 +1,30 @@
1
+ from sys import version_info
2
+
3
+ from pyxcp.utils import PYTHON_VERSION, flatten, getPythonVersion, hexDump, slicer
4
+
5
+
6
+ def test_hexdump(capsys):
7
+ print(hexDump(range(16)), end="")
8
+ captured = capsys.readouterr()
9
+ assert captured.out == "[00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f]"
10
+
11
+
12
+ def test_slicer1():
13
+ res = slicer([1, 2, 3, 4, 5, 6, 7, 8], 4)
14
+ assert res == [[1, 2, 3, 4], [5, 6, 7, 8]]
15
+
16
+
17
+ def test_slicer2():
18
+ res = slicer(["10", "20", "30", "40", "50", "60", "70", "80"], 4, tuple)
19
+ assert res == [("10", "20", "30", "40"), ("50", "60", "70", "80")]
20
+
21
+
22
+ def test_flatten1():
23
+ res = flatten([[1, 2, 3, 4], [5, 6, 7, 8]])
24
+ assert res == [1, 2, 3, 4, 5, 6, 7, 8]
25
+
26
+
27
+ def test_version():
28
+ assert getPythonVersion() == version_info
29
+ assert PYTHON_VERSION == version_info
30
+ assert getPythonVersion() == PYTHON_VERSION
pyxcp/timing.py ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python
2
+ import time
3
+
4
+
5
+ class Timing:
6
+ T_US = 1000 * 1000
7
+ T_MS = 1000
8
+ T_S = 1
9
+
10
+ UNIT_MAP = {
11
+ T_US: "uS",
12
+ T_MS: "mS",
13
+ T_S: "S",
14
+ }
15
+ FMT = "min: {0:2.3f} {4}\nmax: {1:2.3f} {4}\n" "avg: {2:2.3f} {4}\nlast: {3:2.3f} {4}"
16
+
17
+ def __init__(self, unit=T_MS, record=False):
18
+ self.min = None
19
+ self.max = None
20
+ self.avg = None
21
+ self._previous = None
22
+ self.unit = unit
23
+ self._record = record
24
+ self._values = []
25
+
26
+ def start(self):
27
+ self._start = time.perf_counter()
28
+
29
+ def stop(self):
30
+ self._stop = time.perf_counter()
31
+ elapsed = self._stop - self._start
32
+ if self._record:
33
+ self._values.append(elapsed)
34
+ if self._previous:
35
+ self.min = min(self._previous, elapsed)
36
+ self.max = max(self._previous, elapsed)
37
+ self.avg = (self._previous + elapsed) / 2
38
+ else:
39
+ self.min = self.max = self.avg = elapsed
40
+ self._previous = elapsed
41
+
42
+ def __str__(self):
43
+ unitName = Timing.UNIT_MAP.get(self.unit, "??")
44
+ self.min = 0 if self.min is None else self.min
45
+ self.max = 0 if self.max is None else self.max
46
+ self.avg = 0 if self.avg is None else self.avg
47
+ self._previous = 0 if self._previous is None else self._previous
48
+ return Timing.FMT.format(
49
+ self.min * self.unit,
50
+ self.max * self.unit,
51
+ self.avg * self.unit,
52
+ self._previous * self.unit,
53
+ unitName,
54
+ )
55
+
56
+ __repr__ = __str__
57
+
58
+ @property
59
+ def values(self):
60
+ return self._values
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env python
2
+ from .base import FrameAcquisitionPolicy # noqa: F401
3
+ from .base import FrameRecorderPolicy # noqa: F401
4
+ from .base import LegacyFrameAcquisitionPolicy # noqa: F401
5
+ from .base import NoOpPolicy # noqa: F401
6
+ from .base import StdoutPolicy # noqa: F401
7
+ from .can import Can # noqa: F401
8
+ from .eth import Eth # noqa: F401
9
+ from .sxi import SxI # noqa: F401
10
+ from .usb_transport import Usb # noqa: F401
@@ -0,0 +1,439 @@
1
+ #!/usr/bin/env python
2
+ import abc
3
+ import threading
4
+ from collections import deque
5
+ from typing import Any, Dict, Optional, Set, Type
6
+
7
+ import pyxcp.types as types
8
+ from pyxcp.cpp_ext.cpp_ext import Timestamp, TimestampType
9
+ from pyxcp.recorder import XcpLogFileWriter
10
+ from pyxcp.timing import Timing
11
+ from pyxcp.utils import (
12
+ CurrentDatetime,
13
+ flatten,
14
+ hexDump,
15
+ seconds_to_nanoseconds,
16
+ short_sleep,
17
+ )
18
+
19
+
20
+ class FrameAcquisitionPolicy:
21
+ """
22
+ Base class for all frame acquisition policies.
23
+
24
+ Parameters
25
+ ---------
26
+ filter_out: set or None
27
+ A set of frame types to filter out.
28
+ If None, all frame types are accepted for further processing.
29
+
30
+ Example: (FrameType.REQUEST, FrameType.RESPONSE, FrameType.EVENT, FrameType.SERV)
31
+ ==> care only about DAQ frames.
32
+ """
33
+
34
+ def __init__(self, filter_out: Optional[Set[types.FrameCategory]] = None):
35
+ self._frame_types_to_filter_out = filter_out or set()
36
+
37
+ @property
38
+ def filtered_out(self) -> Set[types.FrameCategory]:
39
+ return self._frame_types_to_filter_out
40
+
41
+ def feed(self, frame_type: types.FrameCategory, counter: int, timestamp: int, payload: bytes) -> None: ... # noqa: E704
42
+
43
+ def finalize(self) -> None:
44
+ """
45
+ Finalize the frame acquisition policy (if required).
46
+ """
47
+ ...
48
+
49
+
50
+ class NoOpPolicy(FrameAcquisitionPolicy):
51
+ """
52
+ No operation / do nothing policy.
53
+ """
54
+
55
+
56
+ class LegacyFrameAcquisitionPolicy(FrameAcquisitionPolicy):
57
+ """Dequeue based frame acquisition policy.
58
+
59
+ Deprecated: Use only for compatibility reasons.
60
+ """
61
+
62
+ def __init__(self, filter_out: Optional[Set[types.FrameCategory]] = None) -> None:
63
+ super().__init__(filter_out)
64
+ self.reqQueue = deque()
65
+ self.resQueue = deque()
66
+ self.daqQueue = deque()
67
+ self.evQueue = deque()
68
+ self.servQueue = deque()
69
+ self.metaQueue = deque()
70
+ self.errorQueue = deque()
71
+ self.stimQueue = deque()
72
+ self.QUEUE_MAP = {
73
+ types.FrameCategory.CMD: self.reqQueue,
74
+ types.FrameCategory.RESPONSE: self.resQueue,
75
+ types.FrameCategory.EVENT: self.evQueue,
76
+ types.FrameCategory.SERV: self.servQueue,
77
+ types.FrameCategory.DAQ: self.daqQueue,
78
+ types.FrameCategory.METADATA: self.metaQueue,
79
+ types.FrameCategory.ERROR: self.errorQueue,
80
+ types.FrameCategory.STIM: self.stimQueue,
81
+ }
82
+
83
+ def feed(self, frame_type: types.FrameCategory, counter: int, timestamp: int, payload: bytes) -> None:
84
+ if frame_type not in self.filtered_out:
85
+ queue = self.QUEUE_MAP.get(frame_type)
86
+ if queue is not None:
87
+ queue.append((counter, timestamp, payload))
88
+
89
+
90
+ class FrameRecorderPolicy(FrameAcquisitionPolicy):
91
+ """Frame acquisition policy that records frames."""
92
+
93
+ def __init__(
94
+ self,
95
+ file_name: str,
96
+ filter_out: Optional[Set[types.FrameCategory]] = None,
97
+ prealloc: int = 10,
98
+ chunk_size: int = 1,
99
+ ) -> None:
100
+ super().__init__(filter_out)
101
+ self.recorder = XcpLogFileWriter(file_name, prealloc=prealloc, chunk_size=chunk_size)
102
+
103
+ def feed(self, frame_type: types.FrameCategory, counter: int, timestamp: int, payload: bytes) -> None:
104
+ if frame_type not in self.filtered_out:
105
+ self.recorder.add_frame(frame_type, counter, timestamp, payload)
106
+
107
+ def finalize(self) -> None:
108
+ self.recorder.finalize()
109
+
110
+
111
+ class StdoutPolicy(FrameAcquisitionPolicy):
112
+ """Frame acquisition policy that prints frames to stdout."""
113
+
114
+ def __init__(self, filter_out: Optional[Set[types.FrameCategory]] = None) -> None:
115
+ super().__init__(filter_out)
116
+
117
+ def feed(self, frame_type: types.FrameCategory, counter: int, timestamp: int, payload: bytes) -> None:
118
+ if frame_type not in self.filtered_out:
119
+ print(f"{frame_type.name:8} {counter:6} {timestamp:8d} {hexDump(payload)}")
120
+
121
+
122
+ class EmptyFrameError(Exception):
123
+ """Raised when an empty frame is received."""
124
+
125
+
126
+ class BaseTransport(metaclass=abc.ABCMeta):
127
+ """Base class for transport-layers (Can, Eth, Sxi).
128
+
129
+ Parameters
130
+ ----------
131
+ config: dict-like
132
+ Parameters like bitrate.
133
+ loglevel: ["INFO", "WARN", "DEBUG", "ERROR", "CRITICAL"]
134
+ Controls the verbosity of log messages.
135
+
136
+ """
137
+
138
+ def __init__(self, config, policy: Optional[FrameAcquisitionPolicy] = None, transport_layer_interface: Optional[Any] = None):
139
+ self.has_user_supplied_interface: bool = transport_layer_interface is not None
140
+ self.transport_layer_interface: Optional[Any] = transport_layer_interface
141
+ self.parent = None
142
+ self.policy: FrameAcquisitionPolicy = policy or LegacyFrameAcquisitionPolicy()
143
+ self.closeEvent: threading.Event = threading.Event()
144
+
145
+ self.command_lock: threading.Lock = threading.Lock()
146
+ self.policy_lock: threading.Lock = threading.Lock()
147
+
148
+ self.logger: Any = config.log
149
+ self._debug: bool = self.logger.level == 10
150
+ if transport_layer_interface:
151
+ self.logger.info(f"Transport - User Supplied Transport-Layer Interface: '{transport_layer_interface!s}'")
152
+ self.counter_send: int = 0
153
+ self.counter_received: int = -1
154
+ self.create_daq_timestamps: bool = config.create_daq_timestamps
155
+ self.timestamp = Timestamp(TimestampType.ABSOLUTE_TS)
156
+ self._start_datetime: CurrentDatetime = CurrentDatetime(self.timestamp.initial_value)
157
+ self.alignment: int = config.alignment
158
+ self.timeout: int = seconds_to_nanoseconds(config.timeout)
159
+ self.timer_restart_event: threading.Event = threading.Event()
160
+ self.timing: Timing = Timing()
161
+ self.resQueue: deque = deque()
162
+ self.listener: threading.Thread = threading.Thread(
163
+ target=self.listen,
164
+ args=(),
165
+ kwargs={},
166
+ )
167
+
168
+ self.first_daq_timestamp: Optional[int] = None
169
+ # self.timestamp_origin = self.timestamp.value
170
+ # self.datetime_origin = datetime.fromtimestamp(self.timestamp_origin)
171
+ self.pre_send_timestamp: int = self.timestamp.value
172
+ self.post_send_timestamp: int = self.timestamp.value
173
+ self.recv_timestamp: int = self.timestamp.value
174
+
175
+ def __del__(self) -> None:
176
+ self.finish_listener()
177
+ self.close_connection()
178
+
179
+ def load_config(self, config) -> None:
180
+ """Load configuration data."""
181
+ class_name: str = self.__class__.__name__.lower()
182
+ self.config: Any = getattr(config, class_name)
183
+
184
+ def close(self) -> None:
185
+ """Close the transport-layer connection and event-loop."""
186
+ self.finish_listener()
187
+ if self.listener.is_alive():
188
+ self.listener.join()
189
+ self.close_connection()
190
+
191
+ @abc.abstractmethod
192
+ def connect(self) -> None:
193
+ pass
194
+
195
+ def get(self):
196
+ """Get an item from a deque considering a timeout condition."""
197
+ start: int = self.timestamp.value
198
+ while not self.resQueue:
199
+ if self.timer_restart_event.is_set():
200
+ start: int = self.timestamp.value
201
+ self.timer_restart_event.clear()
202
+ if self.timestamp.value - start > self.timeout:
203
+ raise EmptyFrameError
204
+ short_sleep()
205
+ item = self.resQueue.popleft()
206
+ # print("Q", item)
207
+ return item
208
+
209
+ @property
210
+ def start_datetime(self) -> int:
211
+ """datetime of program start.
212
+
213
+ Returns
214
+ -------
215
+ int
216
+ """
217
+ return self._start_datetime
218
+
219
+ def start_listener(self):
220
+ if self.listener.is_alive():
221
+ self.finish_listener()
222
+ self.listener.join()
223
+
224
+ self.listener = threading.Thread(target=self.listen)
225
+ self.listener.start()
226
+
227
+ def finish_listener(self):
228
+ if hasattr(self, "closeEvent"):
229
+ self.closeEvent.set()
230
+
231
+ def _request_internal(self, cmd, ignore_timeout=False, *data):
232
+ with self.command_lock:
233
+ frame = self._prepare_request(cmd, *data)
234
+ self.timing.start()
235
+ with self.policy_lock:
236
+ self.policy.feed(types.FrameCategory.CMD, self.counter_send, self.timestamp.value, frame)
237
+ self.send(frame)
238
+ try:
239
+ xcpPDU = self.get()
240
+ except EmptyFrameError:
241
+ if not ignore_timeout:
242
+ MSG = f"Response timed out (timeout={self.timeout}s)"
243
+ with self.policy_lock:
244
+ self.policy.feed(types.FrameCategory.METADATA, self.counter_send, self.timestamp.value, bytes(MSG, "ascii"))
245
+ raise types.XcpTimeoutError(MSG) from None
246
+ else:
247
+ self.timing.stop()
248
+ return
249
+ self.timing.stop()
250
+ pid = types.Response.parse(xcpPDU).type
251
+ if pid == "ERR" and cmd.name != "SYNCH":
252
+ with self.policy_lock:
253
+ self.policy.feed(types.FrameCategory.ERROR, self.counter_received, self.timestamp.value, xcpPDU[1:])
254
+ err = types.XcpError.parse(xcpPDU[1:])
255
+ raise types.XcpResponseError(err)
256
+ return xcpPDU[1:]
257
+
258
+ def request(self, cmd, *data):
259
+ return self._request_internal(cmd, False, *data)
260
+
261
+ def request_optional_response(self, cmd, *data):
262
+ return self._request_internal(cmd, True, *data)
263
+
264
+ def block_request(self, cmd, *data):
265
+ """
266
+ Implements packet transmission for block communication model (e.g. DOWNLOAD block mode)
267
+ All parameters are the same as in request(), but it does not receive response.
268
+ """
269
+
270
+ # check response queue before each block request, so that if the slave device
271
+ # has responded with a negative response (e.g. ACCESS_DENIED or SEQUENCE_ERROR), we can
272
+ # process it.
273
+ if self.resQueue:
274
+ xcpPDU = self.resQueue.popleft()
275
+ pid = types.Response.parse(xcpPDU).type
276
+ if pid == "ERR" and cmd.name != "SYNCH":
277
+ err = types.XcpError.parse(xcpPDU[1:])
278
+ raise types.XcpResponseError(err)
279
+ with self.command_lock:
280
+ if isinstance(*data, list):
281
+ data = data[0] # C++ interfacing.
282
+ frame = self._prepare_request(cmd, *data)
283
+ with self.policy_lock:
284
+ self.policy.feed(
285
+ types.FrameCategory.CMD if int(cmd) >= 0xC0 else types.FrameCategory.STIM,
286
+ self.counter_send,
287
+ self.timestamp.value,
288
+ frame,
289
+ )
290
+ self.send(frame)
291
+
292
+ def _prepare_request(self, cmd, *data):
293
+ """
294
+ Prepares a request to be sent
295
+ """
296
+ if self._debug:
297
+ self.logger.debug(cmd.name)
298
+ self.parent._setService(cmd)
299
+
300
+ cmd_len = cmd.bit_length() // 8 # calculate bytes needed for cmd
301
+ packet = bytes(flatten(cmd.to_bytes(cmd_len, "big"), data))
302
+
303
+ header = self.HEADER.pack(len(packet), self.counter_send)
304
+ self.counter_send = (self.counter_send + 1) & 0xFFFF
305
+
306
+ frame = header + packet
307
+
308
+ remainder = len(frame) % self.alignment
309
+ if remainder:
310
+ frame += b"\0" * (self.alignment - remainder)
311
+
312
+ if self._debug:
313
+ self.logger.debug(f"-> {hexDump(frame)}")
314
+ return frame
315
+
316
+ def block_receive(self, length_required: int) -> bytes:
317
+ """
318
+ Implements packet reception for block communication model
319
+ (e.g. for XCP on CAN)
320
+
321
+ Parameters
322
+ ----------
323
+ length_required: int
324
+ number of bytes to be expected in block response packets
325
+
326
+ Returns
327
+ -------
328
+ bytes
329
+ all payload bytes received in block response packets
330
+
331
+ Raises
332
+ ------
333
+ :class:`pyxcp.types.XcpTimeoutError`
334
+ """
335
+ block_response = b""
336
+ start = self.timestamp.value
337
+ while len(block_response) < length_required:
338
+ if len(self.resQueue):
339
+ partial_response = self.resQueue.popleft()
340
+ block_response += partial_response[1:]
341
+ else:
342
+ if self.timestamp.value - start > self.timeout:
343
+ raise types.XcpTimeoutError("Response timed out [block_receive].") from None
344
+ short_sleep()
345
+ return block_response
346
+
347
+ @abc.abstractmethod
348
+ def send(self, frame):
349
+ pass
350
+
351
+ @abc.abstractmethod
352
+ def close_connection(self):
353
+ """Does the actual connection shutdown.
354
+ Needs to be implemented by any sub-class.
355
+ """
356
+ pass
357
+
358
+ @abc.abstractmethod
359
+ def listen(self):
360
+ pass
361
+
362
+ def process_event_packet(self, packet):
363
+ packet = packet[1:]
364
+ ev_type = packet[0]
365
+ self.logger.debug(f"EVENT-PACKET: {hexDump(packet)}")
366
+ if ev_type == types.Event.EV_CMD_PENDING:
367
+ self.timer_restart_event.set()
368
+
369
+ def process_response(self, response: bytes, length: int, counter: int, recv_timestamp: int) -> None:
370
+ if counter == self.counter_received:
371
+ self.logger.warning(f"Duplicate message counter {counter} received from the XCP slave")
372
+ if self._debug:
373
+ self.logger.debug(f"<- L{length} C{counter} {hexDump(response[:512])}")
374
+ return
375
+ self.counter_received = counter
376
+ pid = response[0]
377
+ if pid >= 0xFC:
378
+ if self._debug:
379
+ self.logger.debug(f"<- L{length} C{counter} {hexDump(response)}")
380
+ if pid >= 0xFE:
381
+ self.resQueue.append(response)
382
+ with self.policy_lock:
383
+ self.policy.feed(types.FrameCategory.RESPONSE, self.counter_received, self.timestamp.value, response)
384
+ self.recv_timestamp = recv_timestamp
385
+ elif pid == 0xFD:
386
+ self.process_event_packet(response)
387
+ with self.policy_lock:
388
+ self.policy.feed(types.FrameCategory.EVENT, self.counter_received, self.timestamp.value, response)
389
+ elif pid == 0xFC:
390
+ with self.policy_lock:
391
+ self.policy.feed(types.FrameCategory.SERV, self.counter_received, self.timestamp.value, response)
392
+ else:
393
+ if self._debug:
394
+ self.logger.debug(f"<- L{length} C{counter} ODT_Data[0:8] {hexDump(response[:8])}")
395
+ if self.first_daq_timestamp is None:
396
+ self.first_daq_timestamp = recv_timestamp
397
+ if self.create_daq_timestamps:
398
+ timestamp = recv_timestamp
399
+ else:
400
+ timestamp = 0
401
+ with self.policy_lock:
402
+ self.policy.feed(types.FrameCategory.DAQ, self.counter_received, timestamp, response)
403
+
404
+ # @abc.abstractproperty
405
+ # @property
406
+ # def transport_layer_interface(self) -> Any:
407
+ # pass
408
+
409
+ # @transport_layer_interface.setter
410
+ # def transport_layer_interface(self, value: Any) -> None:
411
+ # self._transport_layer_interface = value
412
+
413
+
414
+ def create_transport(name: str, *args, **kws) -> BaseTransport:
415
+ """Factory function for transports.
416
+
417
+ Returns
418
+ -------
419
+ :class:`BaseTransport` derived instance.
420
+ """
421
+ name = name.lower()
422
+ transports = available_transports()
423
+ if name in transports:
424
+ transport_class: Type[BaseTransport] = transports[name]
425
+ else:
426
+ raise ValueError(f"{name!r} is an invalid transport -- please choose one of [{' | '.join(transports.keys())}].")
427
+ return transport_class(*args, **kws)
428
+
429
+
430
+ def available_transports() -> Dict[str, Type[BaseTransport]]:
431
+ """List all subclasses of :class:`BaseTransport`.
432
+
433
+ Returns
434
+ -------
435
+ dict
436
+ name: class
437
+ """
438
+ transports = BaseTransport.__subclasses__()
439
+ return {t.__name__.lower(): t for t in transports}
File without changes