dutchmate-core 0.1.0__tar.gz

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.
Files changed (49) hide show
  1. dutchmate_core-0.1.0/LICENSE +73 -0
  2. dutchmate_core-0.1.0/PKG-INFO +13 -0
  3. dutchmate_core-0.1.0/pyproject.toml +23 -0
  4. dutchmate_core-0.1.0/pyproject.toml.orig +21 -0
  5. dutchmate_core-0.1.0/src/dutchmate_core/__init__.py +16 -0
  6. dutchmate_core-0.1.0/src/dutchmate_core/backends/__init__.py +57 -0
  7. dutchmate_core-0.1.0/src/dutchmate_core/backends/basic.py +426 -0
  8. dutchmate_core-0.1.0/src/dutchmate_core/backends/contracts.py +356 -0
  9. dutchmate_core-0.1.0/src/dutchmate_core/backends/enhanced.py +375 -0
  10. dutchmate_core-0.1.0/src/dutchmate_core/backends/enhanced_serial.py +555 -0
  11. dutchmate_core-0.1.0/src/dutchmate_core/backends/enhanced_serial_io.py +224 -0
  12. dutchmate_core-0.1.0/src/dutchmate_core/backends/settings.py +309 -0
  13. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/__init__.py +1 -0
  14. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/commands.py +218 -0
  15. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/discovery.py +99 -0
  16. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/errors.py +68 -0
  17. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/messages.py +86 -0
  18. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/parser.py +387 -0
  19. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/serial_transport.py +70 -0
  20. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/stream.py +93 -0
  21. dutchmate_core-0.1.0/src/dutchmate_core/device_connection/transport.py +55 -0
  22. dutchmate_core-0.1.0/src/dutchmate_core/diagnostics.py +40 -0
  23. dutchmate_core-0.1.0/src/dutchmate_core/gpio_config/__init__.py +1 -0
  24. dutchmate_core-0.1.0/src/dutchmate_core/gpio_config/config.py +196 -0
  25. dutchmate_core-0.1.0/src/dutchmate_core/gpio_config/configurator.py +81 -0
  26. dutchmate_core-0.1.0/src/dutchmate_core/gpio_config/modes.py +284 -0
  27. dutchmate_core-0.1.0/src/dutchmate_core/log_processing/__init__.py +1 -0
  28. dutchmate_core-0.1.0/src/dutchmate_core/log_processing/patterns.py +101 -0
  29. dutchmate_core-0.1.0/src/dutchmate_core/runtime.py +1093 -0
  30. dutchmate_core-0.1.0/src/dutchmate_core/session_store/__init__.py +1 -0
  31. dutchmate_core-0.1.0/src/dutchmate_core/session_store/baseline.py +247 -0
  32. dutchmate_core-0.1.0/src/dutchmate_core/session_store/comparison.py +312 -0
  33. dutchmate_core-0.1.0/src/dutchmate_core/session_store/evidence.py +419 -0
  34. dutchmate_core-0.1.0/src/dutchmate_core/session_store/log_replay.py +550 -0
  35. dutchmate_core-0.1.0/src/dutchmate_core/session_store/metadata.py +809 -0
  36. dutchmate_core-0.1.0/src/dutchmate_core/session_store/models.py +547 -0
  37. dutchmate_core-0.1.0/src/dutchmate_core/session_store/persistence.py +221 -0
  38. dutchmate_core-0.1.0/src/dutchmate_core/session_store/retention.py +160 -0
  39. dutchmate_core-0.1.0/src/dutchmate_core/session_store/retrieval.py +917 -0
  40. dutchmate_core-0.1.0/src/dutchmate_core/session_store/store.py +1595 -0
  41. dutchmate_core-0.1.0/src/dutchmate_core/session_store/transactions.py +423 -0
  42. dutchmate_core-0.1.0/src/dutchmate_core/uart_capture/__init__.py +1 -0
  43. dutchmate_core-0.1.0/src/dutchmate_core/uart_capture/line_buffer.py +247 -0
  44. dutchmate_core-0.1.0/src/dutchmate_core/uart_capture/processor.py +128 -0
  45. dutchmate_core-0.1.0/src/dutchmate_core/validation.py +393 -0
  46. dutchmate_core-0.1.0/src/dutchmate_core/workflows/__init__.py +1 -0
  47. dutchmate_core-0.1.0/src/dutchmate_core/workflows/capture.py +1039 -0
  48. dutchmate_core-0.1.0/src/dutchmate_core/workflows/device_actions.py +127 -0
  49. dutchmate_core-0.1.0/src/dutchmate_core/workflows/uart_send.py +357 -0
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: dutchmate-core
3
+ Version: 0.1.0
4
+ Summary: Core hardware interface, protocol parsing, session storage, and workflows for DUTchMate.
5
+ Author: Nahit Pawar
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Dist: pyserial-asyncio>=0.6
9
+ Requires-Dist: tomli>=2.0 ; python_full_version < '3.11'
10
+ Requires-Python: >=3.10
11
+ Project-URL: Homepage, https://github.com/leonahi/DUTchMate
12
+ Project-URL: Repository, https://github.com/leonahi/DUTchMate
13
+ Project-URL: Issues, https://github.com/leonahi/DUTchMate/issues
@@ -0,0 +1,23 @@
1
+ [project]
2
+ name = "dutchmate-core"
3
+ version = "0.1.0"
4
+ description = "Core hardware interface, protocol parsing, session storage, and workflows for DUTchMate."
5
+ requires-python = ">=3.10"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ dependencies = [
9
+ "pyserial-asyncio>=0.6",
10
+ "tomli>=2.0; python_version < '3.11'",
11
+ ]
12
+
13
+ [[project.authors]]
14
+ name = "Nahit Pawar"
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/leonahi/DUTchMate"
18
+ Repository = "https://github.com/leonahi/DUTchMate"
19
+ Issues = "https://github.com/leonahi/DUTchMate/issues"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.11.26,<0.12"]
23
+ build-backend = "uv_build"
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "dutchmate-core"
3
+ version = "0.1.0"
4
+ description = "Core hardware interface, protocol parsing, session storage, and workflows for DUTchMate."
5
+ requires-python = ">=3.10"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Nahit Pawar" }]
9
+ dependencies = [
10
+ "pyserial-asyncio>=0.6",
11
+ "tomli>=2.0; python_version < '3.11'",
12
+ ]
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/leonahi/DUTchMate"
16
+ Repository = "https://github.com/leonahi/DUTchMate"
17
+ Issues = "https://github.com/leonahi/DUTchMate/issues"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.11.26,<0.12"]
21
+ build-backend = "uv_build"
@@ -0,0 +1,16 @@
1
+ """Core DUTchMate library."""
2
+
3
+ from dutchmate_core.runtime import (
4
+ DeviceCoreRuntime,
5
+ DeviceCoreRuntimeError,
6
+ DeviceCoreStatus,
7
+ )
8
+
9
+ __all__ = [
10
+ "DeviceCoreRuntime",
11
+ "DeviceCoreRuntimeError",
12
+ "DeviceCoreStatus",
13
+ "__version__",
14
+ ]
15
+
16
+ __version__ = "0.1.0"
@@ -0,0 +1,57 @@
1
+ """Stable facade for normalized Device Core backend contracts."""
2
+
3
+ from dutchmate_core.backends.contracts import (
4
+ BackendCapability,
5
+ BackendCapabilityError,
6
+ BackendCapabilityPolicy,
7
+ BackendDisconnectedError,
8
+ BackendEvent,
9
+ BackendEventSource,
10
+ BackendInfo,
11
+ BackendInputError,
12
+ BackendMode,
13
+ BackendSnapshot,
14
+ BackendUartSendResult,
15
+ BackendWriteError,
16
+ BufferOverflowEvent,
17
+ BufferStatusEvent,
18
+ DeviceControl,
19
+ DeviceControlError,
20
+ LossStatus,
21
+ SegmentContext,
22
+ SegmentTimestamp,
23
+ UartIntegrity,
24
+ UartReceiveEvent,
25
+ UartSendCapabilityPolicy,
26
+ UartSender,
27
+ apply_capability_policy,
28
+ integrity_for_backend,
29
+ )
30
+
31
+ __all__ = [
32
+ "BackendCapability",
33
+ "BackendCapabilityError",
34
+ "BackendCapabilityPolicy",
35
+ "BackendDisconnectedError",
36
+ "BackendEvent",
37
+ "BackendEventSource",
38
+ "BackendInfo",
39
+ "BackendInputError",
40
+ "BackendMode",
41
+ "BackendSnapshot",
42
+ "BackendUartSendResult",
43
+ "BufferOverflowEvent",
44
+ "BufferStatusEvent",
45
+ "DeviceControl",
46
+ "DeviceControlError",
47
+ "LossStatus",
48
+ "BackendWriteError",
49
+ "SegmentContext",
50
+ "SegmentTimestamp",
51
+ "UartIntegrity",
52
+ "UartReceiveEvent",
53
+ "UartSendCapabilityPolicy",
54
+ "UartSender",
55
+ "apply_capability_policy",
56
+ "integrity_for_backend",
57
+ ]
@@ -0,0 +1,426 @@
1
+ """Basic generic USB-to-UART connection, receive, and send adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib
7
+ import math
8
+ import time
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from queue import Empty, Queue
12
+ from threading import Event, Lock, Thread
13
+ from typing import Final, Protocol, cast
14
+
15
+ from dutchmate_core.backends.contracts import (
16
+ BackendCapability,
17
+ BackendCapabilityError,
18
+ BackendCapabilityPolicy,
19
+ BackendDisconnectedError,
20
+ BackendEvent,
21
+ BackendInfo,
22
+ BackendInputError,
23
+ BackendSnapshot,
24
+ BackendUartSendResult,
25
+ BackendWriteError,
26
+ SegmentContext,
27
+ SegmentTimestamp,
28
+ UartReceiveEvent,
29
+ UartSendCapabilityPolicy,
30
+ apply_capability_policy,
31
+ integrity_for_backend,
32
+ )
33
+ from dutchmate_core.backends.settings import BackendSettings
34
+
35
+ DEFAULT_SERIAL_TIMEOUT_S: Final = 1.0
36
+ DEFAULT_EVENT_READ_TIMEOUT_S: Final = 0.1
37
+ DEFAULT_READ_SIZE: Final = 4096
38
+
39
+
40
+ class BasicSerialPort(Protocol):
41
+ """Small raw pyserial surface owned by the Basic backend."""
42
+
43
+ def read(self, size: int = 1) -> bytes:
44
+ """Read up to ``size`` raw UART bytes."""
45
+
46
+ def write(self, data: bytes) -> int:
47
+ """Write raw UART bytes."""
48
+
49
+ def close(self) -> None:
50
+ """Close the serial port."""
51
+
52
+
53
+ BasicSerialFactory = Callable[..., BasicSerialPort]
54
+
55
+
56
+ class BasicBackendConnection:
57
+ """An opened Basic serial port and its immutable backend identity."""
58
+
59
+ def __init__(
60
+ self,
61
+ *,
62
+ serial_port: BasicSerialPort,
63
+ settings: BackendSettings,
64
+ ) -> None:
65
+ if settings.mode != "basic" or settings.serial_port is None:
66
+ raise ValueError("Basic connection requires resolved Basic backend settings")
67
+ capabilities: frozenset[BackendCapability] = frozenset(
68
+ {"uart_receive", "uart_send"}
69
+ )
70
+ self._serial_port = serial_port
71
+ self._write_lock = Lock()
72
+ self._capability_policy = BackendCapabilityPolicy(
73
+ uart_send=UartSendCapabilityPolicy(
74
+ tx_policy_enabled=settings.tx_enabled,
75
+ )
76
+ )
77
+ self._info = BackendInfo(
78
+ mode="basic",
79
+ port=settings.serial_port,
80
+ device=None,
81
+ firmware=None,
82
+ capabilities=capabilities,
83
+ )
84
+
85
+ @property
86
+ def info(self) -> BackendInfo:
87
+ """Return Basic identity without a DUTchMate hello."""
88
+
89
+ return self._info
90
+
91
+ @property
92
+ def serial_port(self) -> BasicSerialPort:
93
+ """Return the owned raw serial port for the receive adapter."""
94
+
95
+ return self._serial_port
96
+
97
+ @property
98
+ def capability_policy(self) -> BackendCapabilityPolicy:
99
+ """Return the configured software capability policy."""
100
+
101
+ return self._capability_policy
102
+
103
+ @property
104
+ def capabilities(self) -> frozenset[BackendCapability]:
105
+ """Return capabilities remaining after host policy is applied."""
106
+
107
+ return apply_capability_policy(self._info.capabilities, self._capability_policy)
108
+
109
+ def send_uart(self, data: bytes) -> BackendUartSendResult:
110
+ """Write a complete UART payload, retrying ordered short writes."""
111
+
112
+ if "uart_send" not in self.capabilities:
113
+ raise BackendCapabilityError("Basic backend UART send is disabled")
114
+ if not isinstance(data, bytes):
115
+ raise TypeError("Basic UART payload must be bytes")
116
+ if not data:
117
+ raise ValueError("Basic UART payload must not be empty")
118
+
119
+ accepted = 0
120
+ with self._write_lock:
121
+ while accepted < len(data):
122
+ try:
123
+ written = self._serial_port.write(data[accepted:])
124
+ except Exception as exc:
125
+ raise BackendWriteError(
126
+ "Basic UART write failed",
127
+ bytes_accepted=accepted,
128
+ error=(
129
+ "timeout"
130
+ if isinstance(exc, TimeoutError)
131
+ or type(exc).__name__ == "SerialTimeoutException"
132
+ else "hardware_fault"
133
+ ),
134
+ ) from exc
135
+ remaining = len(data) - accepted
136
+ if (
137
+ isinstance(written, bool)
138
+ or not isinstance(written, int)
139
+ or written <= 0
140
+ or written > remaining
141
+ ):
142
+ raise BackendWriteError(
143
+ "Basic UART write made invalid progress",
144
+ bytes_accepted=accepted,
145
+ error=(
146
+ "timeout"
147
+ if written == 0 and not isinstance(written, bool)
148
+ else "hardware_fault"
149
+ ),
150
+ )
151
+ accepted += written
152
+ return BackendUartSendResult(bytes_accepted=accepted)
153
+
154
+ def close(self) -> None:
155
+ """Close the underlying serial port."""
156
+
157
+ self._serial_port.close()
158
+
159
+
160
+ @dataclass(frozen=True, slots=True)
161
+ class _ReaderFailure:
162
+ error: BackendDisconnectedError | BackendInputError
163
+
164
+
165
+ @dataclass(frozen=True, slots=True)
166
+ class _SourceClosed:
167
+ pass
168
+
169
+
170
+ _ReaderOutcome = BackendEvent | _ReaderFailure | _SourceClosed
171
+
172
+
173
+ class BasicBackendEventSource:
174
+ """Normalize raw Basic serial chunks through one FIFO reader thread."""
175
+
176
+ def __init__(
177
+ self,
178
+ connection: BasicBackendConnection,
179
+ *,
180
+ segment_id: int,
181
+ monotonic_ns: Callable[[], int] = time.monotonic_ns,
182
+ read_size: int = DEFAULT_READ_SIZE,
183
+ read_timeout_s: float = DEFAULT_EVENT_READ_TIMEOUT_S,
184
+ ) -> None:
185
+ if not isinstance(segment_id, int) or isinstance(segment_id, bool) or segment_id < 0:
186
+ raise ValueError("Basic segment ID must be a non-negative integer")
187
+ if not isinstance(read_size, int) or isinstance(read_size, bool) or read_size <= 0:
188
+ raise ValueError("Basic serial read size must be a positive integer")
189
+ _validate_timeout(read_timeout_s, field="Basic event read timeout")
190
+
191
+ source_origin_ns = monotonic_ns()
192
+ if not isinstance(source_origin_ns, int) or isinstance(source_origin_ns, bool):
193
+ raise ValueError("Basic monotonic clock must return integer nanoseconds")
194
+ source_origin_us = source_origin_ns // 1_000
195
+ if source_origin_us < 0:
196
+ raise ValueError("Basic monotonic source origin must be non-negative")
197
+
198
+ self._connection = connection
199
+ self._segment = SegmentContext(
200
+ segment_id=segment_id,
201
+ timestamp=SegmentTimestamp(
202
+ source="host",
203
+ clock="monotonic",
204
+ unit="us",
205
+ origin="segment_start",
206
+ source_origin_us=source_origin_us,
207
+ observation_point="host_serial_read",
208
+ event_granularity="serial_read_chunk",
209
+ ),
210
+ )
211
+ self._monotonic_ns = monotonic_ns
212
+ self._read_size = read_size
213
+ self._read_timeout_s = read_timeout_s
214
+ self._outcomes: Queue[_ReaderOutcome] = Queue()
215
+ self._stop = Event()
216
+ self._start_lock = Lock()
217
+ self._reader: Thread | None = None
218
+ self._terminal_error: BackendDisconnectedError | BackendInputError | None = None
219
+
220
+ @property
221
+ def info(self) -> BackendInfo:
222
+ """Return immutable Basic backend identity and capabilities."""
223
+
224
+ return self._connection.info
225
+
226
+ @property
227
+ def segment_id(self) -> int:
228
+ """Return the session-local segment ID assigned to this source."""
229
+
230
+ return self._segment.segment_id
231
+
232
+ @property
233
+ def segment(self) -> SegmentContext:
234
+ """Return host-monotonic provenance established at source creation."""
235
+
236
+ return self._segment
237
+
238
+ @property
239
+ def snapshot(self) -> BackendSnapshot:
240
+ """Return the complete Basic identity/policy/provenance snapshot."""
241
+
242
+ return BackendSnapshot(
243
+ info=self._connection.info,
244
+ capabilities=self._connection.capabilities,
245
+ capability_policy=self._connection.capability_policy,
246
+ segment=self._segment,
247
+ integrity=integrity_for_backend("basic"),
248
+ )
249
+
250
+ async def receive_event(self, timeout_s: float | None = None) -> BackendEvent | None:
251
+ """Return the next FIFO event, or ``None`` for an ordinary timeout."""
252
+
253
+ if timeout_s is not None:
254
+ _validate_timeout(timeout_s, field="Basic receive timeout", allow_zero=True)
255
+ return await asyncio.to_thread(self._next_event, timeout_s)
256
+
257
+ def read_event(self) -> BackendEvent | None:
258
+ """Blocking compatibility adapter used by the current capture runner."""
259
+
260
+ return self._next_event(self._read_timeout_s)
261
+
262
+ def discard_pending_events(self) -> None:
263
+ """Advance a workflow ingestion cursor past already-normalized UART events."""
264
+
265
+ retained: list[_ReaderOutcome] = []
266
+ while True:
267
+ try:
268
+ outcome = self._outcomes.get_nowait()
269
+ except Empty:
270
+ break
271
+ if not isinstance(outcome, UartReceiveEvent):
272
+ retained.append(outcome)
273
+ for outcome in retained:
274
+ self._outcomes.put(outcome)
275
+
276
+ def close(self) -> None:
277
+ """Stop the reader and close the Basic serial connection."""
278
+
279
+ if self._stop.is_set():
280
+ return
281
+ self._stop.set()
282
+ try:
283
+ self._connection.close()
284
+ finally:
285
+ reader = self._reader
286
+ if reader is not None:
287
+ reader.join(timeout=DEFAULT_SERIAL_TIMEOUT_S + 0.1)
288
+ self._outcomes.put(_SourceClosed())
289
+
290
+ def _ensure_reader_started(self) -> None:
291
+ if self._reader is not None:
292
+ return
293
+ with self._start_lock:
294
+ if self._reader is not None:
295
+ return
296
+ if self._stop.is_set():
297
+ self._terminal_error = BackendDisconnectedError(
298
+ "Basic backend event source is closed"
299
+ )
300
+ return
301
+ reader = Thread(
302
+ target=self._read_serial,
303
+ name="dutchmate-basic-serial-reader",
304
+ daemon=True,
305
+ )
306
+ self._reader = reader
307
+ reader.start()
308
+
309
+ def _read_serial(self) -> None:
310
+ while not self._stop.is_set():
311
+ try:
312
+ data = self._connection.serial_port.read(self._read_size)
313
+ except Exception as exc:
314
+ if not self._stop.is_set():
315
+ error = BackendDisconnectedError("Basic serial read failed")
316
+ error.__cause__ = exc
317
+ self._outcomes.put(_ReaderFailure(error))
318
+ return
319
+
320
+ if not isinstance(data, bytes):
321
+ self._outcomes.put(
322
+ _ReaderFailure(
323
+ BackendInputError("Basic serial read returned non-bytes input")
324
+ )
325
+ )
326
+ return
327
+ if not data:
328
+ continue
329
+ try:
330
+ observed_ns = self._monotonic_ns()
331
+ if not isinstance(observed_ns, int) or isinstance(observed_ns, bool):
332
+ raise TypeError("monotonic clock did not return an integer")
333
+ observed_us = observed_ns // 1_000
334
+ except Exception as exc:
335
+ input_error = BackendInputError("Basic monotonic clock sampling failed")
336
+ input_error.__cause__ = exc
337
+ self._outcomes.put(_ReaderFailure(input_error))
338
+ return
339
+ timestamp_us = observed_us - self._segment.timestamp.source_origin_us
340
+ if timestamp_us < 0:
341
+ self._outcomes.put(
342
+ _ReaderFailure(
343
+ BackendInputError(
344
+ "Basic monotonic timestamp precedes its segment origin"
345
+ )
346
+ )
347
+ )
348
+ return
349
+ self._outcomes.put(
350
+ UartReceiveEvent(
351
+ segment_id=self.segment_id,
352
+ timestamp_us=timestamp_us,
353
+ channel=0,
354
+ data=data,
355
+ )
356
+ )
357
+
358
+ def _next_event(self, timeout_s: float | None) -> BackendEvent | None:
359
+ if self._terminal_error is not None:
360
+ raise self._terminal_error
361
+ self._ensure_reader_started()
362
+ if self._terminal_error is not None:
363
+ raise self._terminal_error
364
+ try:
365
+ if timeout_s is None:
366
+ outcome = self._outcomes.get()
367
+ else:
368
+ outcome = self._outcomes.get(timeout=timeout_s)
369
+ except Empty:
370
+ return None
371
+
372
+ if isinstance(outcome, _ReaderFailure):
373
+ self._terminal_error = outcome.error
374
+ raise outcome.error
375
+ if isinstance(outcome, _SourceClosed):
376
+ self._terminal_error = BackendDisconnectedError(
377
+ "Basic backend event source is closed"
378
+ )
379
+ raise self._terminal_error
380
+ return outcome
381
+
382
+
383
+ def _validate_timeout(
384
+ value: float,
385
+ *,
386
+ field: str,
387
+ allow_zero: bool = False,
388
+ ) -> None:
389
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
390
+ raise ValueError(f"{field} must be a finite number")
391
+ normalized = float(value)
392
+ minimum_valid = normalized >= 0 if allow_zero else normalized > 0
393
+ if not math.isfinite(normalized) or not minimum_valid:
394
+ qualifier = "non-negative" if allow_zero else "positive"
395
+ raise ValueError(f"{field} must be a finite {qualifier} number")
396
+
397
+
398
+ def open_basic_backend_connection(
399
+ settings: BackendSettings,
400
+ *,
401
+ timeout_s: float = DEFAULT_SERIAL_TIMEOUT_S,
402
+ serial_factory: BasicSerialFactory | None = None,
403
+ ) -> BasicBackendConnection:
404
+ """Open a Basic backend as raw 8-N-1 serial without reading a hello."""
405
+
406
+ if settings.mode != "basic" or settings.serial_port is None:
407
+ raise ValueError("Basic connection requires resolved Basic backend settings")
408
+ factory = serial_factory or _pyserial_factory()
409
+ serial_port = factory(
410
+ port=settings.serial_port,
411
+ baudrate=settings.baudrate,
412
+ bytesize=settings.data_bits,
413
+ parity="N",
414
+ stopbits=settings.stop_bits,
415
+ timeout=timeout_s,
416
+ write_timeout=timeout_s,
417
+ xonxoff=False,
418
+ rtscts=False,
419
+ dsrdtr=False,
420
+ )
421
+ return BasicBackendConnection(serial_port=serial_port, settings=settings)
422
+
423
+
424
+ def _pyserial_factory() -> BasicSerialFactory:
425
+ serial_module = importlib.import_module("serial")
426
+ return cast(BasicSerialFactory, serial_module.Serial)