juart-cli 0.1.0__py3-none-any.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.
juart/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """JTAG UART command-line terminal."""
2
+
3
+ __version__ = "0.1.0"
juart/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from juart.cli import main
2
+
3
+ raise SystemExit(main())
juart/_log_worker.py ADDED
@@ -0,0 +1,52 @@
1
+ """Isolated JSONL writer; blocking filesystem operations never run in the UI process."""
2
+
3
+ import errno
4
+ import json
5
+ import sys
6
+
7
+
8
+ def _reply(stream, **message):
9
+ stream.write(json.dumps(message, ensure_ascii=True) + "\n")
10
+ stream.flush()
11
+
12
+
13
+ def run(path, source, replies, *, opener=open):
14
+ """Serve the private pipe protocol, acknowledging only flushed records."""
15
+ try:
16
+ output = opener(path, "x", encoding="utf-8", newline="\n")
17
+ except (OSError, ValueError) as exc:
18
+ _reply(
19
+ replies,
20
+ kind="startup_error",
21
+ errno=getattr(exc, "errno", None),
22
+ message=str(exc),
23
+ invalid=isinstance(exc, ValueError),
24
+ )
25
+ return 1
26
+ _reply(replies, kind="ready")
27
+ try:
28
+ for line in source:
29
+ message = json.loads(line)
30
+ if message["kind"] == "stop":
31
+ break
32
+ record = message["record"]
33
+ output.write(json.dumps(record, ensure_ascii=True, separators=(",", ":")) + "\n")
34
+ output.flush()
35
+ _reply(replies, kind="written", sequence=record["sequence"])
36
+ output.flush()
37
+ output.close()
38
+ except (OSError, ValueError, KeyError, TypeError) as exc:
39
+ _reply(replies, kind="error", message=str(exc), errno=getattr(exc, "errno", errno.EIO))
40
+ # close() itself may block on a damaged filesystem. The parent still owns
41
+ # the finite deadline and can kill this process after receiving the error.
42
+ try:
43
+ output.close()
44
+ except (OSError, ValueError):
45
+ pass
46
+ return 1
47
+ _reply(replies, kind="closed")
48
+ return 0
49
+
50
+
51
+ if __name__ == "__main__":
52
+ raise SystemExit(run(sys.argv[1], sys.stdin, sys.stdout))
@@ -0,0 +1 @@
1
+ """Hardware transport implementations."""
@@ -0,0 +1,254 @@
1
+ """Private JSONL worker. This is the only module that calls vendor native code."""
2
+
3
+ import ctypes
4
+ import json
5
+ import os
6
+ import sys
7
+ from dataclasses import asdict
8
+ from typing import Callable
9
+
10
+ from .base import Target, TransportError
11
+ from .quartus import _installation
12
+
13
+ # C++ export names and ABI from jtag_atlantic.h (cdecl on both supported hosts).
14
+ _SYMBOLS = {
15
+ "open": ("_Z17jtagatlantic_openPKciiS0_", "?jtagatlantic_open@@YAPEAUJTAGATLANTIC@@PEBDHH0@Z"),
16
+ "read": (
17
+ "_Z17jtagatlantic_readP12JTAGATLANTICPcj",
18
+ "?jtagatlantic_read@@YAHPEAUJTAGATLANTIC@@PEADI@Z",
19
+ ),
20
+ "write": (
21
+ "_Z18jtagatlantic_writeP12JTAGATLANTICPKcj",
22
+ "?jtagatlantic_write@@YAHPEAUJTAGATLANTIC@@PEBDI@Z",
23
+ ),
24
+ "close": (
25
+ "_Z18jtagatlantic_closeP12JTAGATLANTIC",
26
+ "?jtagatlantic_close@@YAXPEAUJTAGATLANTIC@@@Z",
27
+ ),
28
+ "flush": (
29
+ "_Z18jtagatlantic_flushP12JTAGATLANTIC",
30
+ "?jtagatlantic_flush@@YAHPEAUJTAGATLANTIC@@@Z",
31
+ ),
32
+ "get_info": (
33
+ "_Z21jtagatlantic_get_infoP12JTAGATLANTICPPKcPiS4_",
34
+ "?jtagatlantic_get_info@@YAXPEAUJTAGATLANTIC@@PEAPEBDPEAH2@Z",
35
+ ),
36
+ "get_error": (
37
+ "_Z22jtagatlantic_get_errorPPKc",
38
+ "?jtagatlantic_get_error@@YA?AW4JATL_ERROR@@PEAPEBD@Z",
39
+ ),
40
+ }
41
+ _SIGNATURES = {
42
+ "open": ([ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_char_p], ctypes.c_void_p),
43
+ "read": ([ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint], ctypes.c_int),
44
+ "write": ([ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint], ctypes.c_int),
45
+ "close": ([ctypes.c_void_p], None),
46
+ "flush": ([ctypes.c_void_p], ctypes.c_int),
47
+ "get_info": (
48
+ [
49
+ ctypes.c_void_p,
50
+ ctypes.POINTER(ctypes.c_char_p),
51
+ ctypes.POINTER(ctypes.c_int),
52
+ ctypes.POINTER(ctypes.c_int),
53
+ ],
54
+ None,
55
+ ),
56
+ "get_error": ([ctypes.POINTER(ctypes.c_char_p)], ctypes.c_int),
57
+ }
58
+ _ERRORS = {
59
+ -1: (
60
+ "server",
61
+ "Unable to connect to the local JTAG server; start/check the Quartus JTAG server.",
62
+ ),
63
+ -2: ("target", "Multiple cables available; specify an exact --cable."),
64
+ -3: ("driver", "Cable unavailable; check its OS driver, permissions and JTAG server."),
65
+ -4: ("driver", "Cable unplugged; reconnect it and check its OS driver."),
66
+ -5: ("connection", "JTAG board unavailable; check board power and cable connection."),
67
+ -6: ("contention", "UART is already owned by another program"),
68
+ -7: ("target", "Multiple UARTs available; specify --device and --instance."),
69
+ -8: ("target", "No UART matches --device and --instance; check the existing FPGA design."),
70
+ -9: ("library", "UART incompatible with this Quartus library version."),
71
+ }
72
+
73
+
74
+ class NativeUART:
75
+ def __init__(self, library, system: str):
76
+ self.functions = {}
77
+ for name, symbols in _SYMBOLS.items():
78
+ function = library[symbols[system == "Windows"]]
79
+ function.argtypes, function.restype = _SIGNATURES[name]
80
+ self.functions[name] = function
81
+ self.handle = None
82
+ self._dependencies = []
83
+
84
+ @classmethod
85
+ def load(cls, root: str):
86
+ installation = _installation(root)
87
+ directories = []
88
+ try:
89
+ if installation.system == "Windows":
90
+ directories.append(os.add_dll_directory(str(installation.directory)))
91
+ # LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS.
92
+ options = {"winmode": 0x100 | 0x1000}
93
+ else:
94
+ options = {"mode": ctypes.RTLD_GLOBAL}
95
+ client = ctypes.CDLL(str(installation.client), **options)
96
+ library = ctypes.CDLL(str(installation.atlantic), **options)
97
+ native = cls(library, installation.system)
98
+ native._dependencies = [client, library, *directories]
99
+ return native
100
+ except (OSError, AttributeError, KeyError) as exc:
101
+ for directory in directories:
102
+ directory.close()
103
+ raise TransportError(
104
+ f"Cannot load Quartus x64 native libraries: {exc}. Check matching Python/library architecture and installed native dependencies.",
105
+ code="library",
106
+ ) from exc
107
+
108
+ def _require_open(self):
109
+ if self.handle is None:
110
+ raise TransportError("Quartus transport is closed.", code="closed")
111
+ return self.handle
112
+
113
+ def connect(self, target: Target) -> dict:
114
+ if not target.cable or target.device is None or target.instance is None:
115
+ raise TransportError(
116
+ "Native open requires a fully resolved cable, device and instance.", code="target"
117
+ )
118
+ self.handle = self.functions["open"](
119
+ target.cable.encode("utf-8"), target.device, target.instance, b"juart"
120
+ )
121
+ if not self.handle:
122
+ self.handle = None
123
+ owner = ctypes.c_char_p()
124
+ number = self.functions["get_error"](ctypes.byref(owner))
125
+ code, message = _ERRORS.get(
126
+ number, ("native", f"JTAG Atlantic open failed with error {number}.")
127
+ )
128
+ if number == -6 and owner.value:
129
+ message += ": " + owner.value.decode("utf-8", "replace")
130
+ raise TransportError(message, code=code)
131
+ try:
132
+ cable = ctypes.c_char_p()
133
+ device, instance = ctypes.c_int(), ctypes.c_int()
134
+ self.functions["get_info"](
135
+ self.handle, ctypes.byref(cable), ctypes.byref(device), ctypes.byref(instance)
136
+ )
137
+ actual = Target(
138
+ cable.value.decode("utf-8", "replace") if cable.value else None,
139
+ device.value,
140
+ instance.value,
141
+ )
142
+ if actual != target:
143
+ raise TransportError(
144
+ f"Native target {actual!r} does not match requested {target!r}.",
145
+ code="target_mismatch",
146
+ )
147
+ return asdict(actual)
148
+ except BaseException:
149
+ self.close()
150
+ raise
151
+
152
+ def read(self, length: int) -> str:
153
+ handle = self._require_open()
154
+ if type(length) is not int or not 0 < length <= 1024 * 1024:
155
+ raise ValueError("Invalid read length")
156
+ buffer = ctypes.create_string_buffer(length)
157
+ count = self.functions["read"](handle, buffer, length)
158
+ if count < 0:
159
+ raise TransportError("JTAG UART connection broken during read.", code="connection")
160
+ if count > length:
161
+ raise TransportError("Native read returned an invalid byte count.", code="native")
162
+ return buffer.raw[:count].hex()
163
+
164
+ def write(self, data: bytes, progress: Callable[[int], None]) -> int:
165
+ handle = self._require_open()
166
+ count = self.functions["write"](handle, data, len(data))
167
+ if not 0 <= count <= len(data):
168
+ raise TransportError(
169
+ "JTAG UART connection broken or invalid native write count.",
170
+ code="connection",
171
+ uncertain=True,
172
+ )
173
+ # Commit the accepted prefix to the parent before a potentially blocking flush.
174
+ progress(count)
175
+ try:
176
+ if count:
177
+ # The header documents waiting for drain, not numeric return semantics.
178
+ self.functions["flush"](handle)
179
+ except Exception as exc:
180
+ raise TransportError(
181
+ f"Quartus flush failed: {exc}", code="native", uncertain=True, accepted=count
182
+ ) from exc
183
+ return count
184
+
185
+ def close(self) -> None:
186
+ handle, self.handle = self.handle, None
187
+ if handle is not None:
188
+ self.functions["close"](handle)
189
+
190
+
191
+ def serve(input_stream, output_stream) -> None:
192
+ native = None
193
+
194
+ def send(response):
195
+ output_stream.write(json.dumps(response) + "\n")
196
+ output_stream.flush()
197
+
198
+ try:
199
+ for line in input_stream:
200
+ request = {}
201
+ try:
202
+ request = json.loads(line)
203
+ sequence = request["id"]
204
+ operation = request["op"]
205
+ if operation == "connect":
206
+ if native is not None:
207
+ native.close()
208
+ native = NativeUART.load(request["root"])
209
+ result = native.connect(Target(**request["target"]))
210
+ elif native is None:
211
+ raise TransportError("Quartus worker is not connected.", code="closed")
212
+ elif operation == "read":
213
+ result = native.read(request["length"])
214
+ elif operation == "write":
215
+ data = bytes.fromhex(request["data"])
216
+ result = native.write(
217
+ data,
218
+ lambda count: send(
219
+ {"id": sequence, "event": "accepted", "accepted": count}
220
+ ),
221
+ )
222
+ elif operation == "close":
223
+ native.close()
224
+ send({"id": sequence, "ok": True, "result": None})
225
+ return
226
+ else:
227
+ raise ValueError("Unknown worker operation")
228
+ send({"id": sequence, "ok": True, "result": result})
229
+ except Exception as exc:
230
+ send(
231
+ {
232
+ "id": request.get("id"),
233
+ "ok": False,
234
+ "error": {
235
+ "message": str(exc),
236
+ "code": getattr(exc, "code", "native"),
237
+ },
238
+ }
239
+ )
240
+ finally:
241
+ if native is not None:
242
+ native.close()
243
+
244
+
245
+ def main() -> None:
246
+ # Vendor stdout diagnostics must never corrupt the JSONL protocol channel.
247
+ protocol_fd = os.dup(sys.stdout.fileno())
248
+ os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
249
+ with os.fdopen(protocol_fd, "w", encoding="utf-8", buffering=1) as output:
250
+ serve(sys.stdin, output)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()
juart/backends/base.py ADDED
@@ -0,0 +1,37 @@
1
+ """Byte-oriented transport contracts, independent of terminal and vendor libraries."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Protocol
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Target:
9
+ cable: str | None = None
10
+ device: int | None = None
11
+ instance: int | None = None
12
+
13
+
14
+ class TransportError(Exception):
15
+ """An operation failed; uncertain writes may already have reached the driver."""
16
+
17
+ def __init__(
18
+ self,
19
+ message: str,
20
+ *,
21
+ code: str = "transport_error",
22
+ uncertain: bool = False,
23
+ accepted: int = 0,
24
+ ):
25
+ super().__init__(message)
26
+ self.code = code
27
+ self.uncertain = uncertain
28
+ # Bytes accepted within this failed write invocation, before a later failure.
29
+ self.accepted = accepted
30
+
31
+
32
+ class Transport(Protocol):
33
+ async def connect(self, target: Target) -> None: ...
34
+ async def read(self, max_bytes: int, timeout: float) -> bytes: ...
35
+ async def write(self, data: bytes, timeout: float) -> int: ...
36
+ async def close(self) -> None: ...
37
+ def info(self) -> dict[str, Any]: ...