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 +3 -0
- juart/__main__.py +3 -0
- juart/_log_worker.py +52 -0
- juart/backends/__init__.py +1 -0
- juart/backends/_quartus_worker.py +254 -0
- juart/backends/base.py +37 -0
- juart/backends/quartus.py +561 -0
- juart/cli.py +102 -0
- juart/commands.py +127 -0
- juart/logging.py +314 -0
- juart/session.py +822 -0
- juart/shell.py +96 -0
- juart/terminal.py +369 -0
- juart_cli-0.1.0.dist-info/METADATA +183 -0
- juart_cli-0.1.0.dist-info/RECORD +17 -0
- juart_cli-0.1.0.dist-info/WHEEL +4 -0
- juart_cli-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
"""Quartus discovery and bounded, subprocess-isolated JTAG Atlantic transport."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import asdict, dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .base import Target, TransportError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Installation:
|
|
19
|
+
root: Path
|
|
20
|
+
directory: Path
|
|
21
|
+
client: Path
|
|
22
|
+
atlantic: Path
|
|
23
|
+
jtagconfig: Path
|
|
24
|
+
system: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _installation(root: str | None = None) -> Installation:
|
|
28
|
+
system = platform.system()
|
|
29
|
+
if (
|
|
30
|
+
system not in {"Windows", "Linux"}
|
|
31
|
+
or platform.machine().lower()
|
|
32
|
+
not in {
|
|
33
|
+
"amd64",
|
|
34
|
+
"x86_64",
|
|
35
|
+
}
|
|
36
|
+
or sys.maxsize <= 2**32
|
|
37
|
+
):
|
|
38
|
+
raise TransportError(
|
|
39
|
+
"Quartus requires native Windows x64 or Linux x64 Python and matching libraries.",
|
|
40
|
+
code="architecture",
|
|
41
|
+
)
|
|
42
|
+
value = root if root is not None else os.environ.get("QUARTUS_ROOTDIR")
|
|
43
|
+
if not value:
|
|
44
|
+
raise TransportError(
|
|
45
|
+
"Set --quartus-root or QUARTUS_ROOTDIR to the Quartus installation directory.",
|
|
46
|
+
code="installation",
|
|
47
|
+
)
|
|
48
|
+
try:
|
|
49
|
+
base = Path(value).expanduser().resolve()
|
|
50
|
+
except (OSError, ValueError, RuntimeError) as exc:
|
|
51
|
+
raise TransportError(
|
|
52
|
+
f"Invalid Quartus installation root: {exc}. Set --quartus-root to a readable installation directory.",
|
|
53
|
+
code="installation",
|
|
54
|
+
) from exc
|
|
55
|
+
directory = base / ("bin64" if system == "Windows" else "linux64")
|
|
56
|
+
names = (
|
|
57
|
+
("jtag_client.dll", "jtag_atlantic.dll", "jtagconfig.exe")
|
|
58
|
+
if system == "Windows"
|
|
59
|
+
else (
|
|
60
|
+
"libjtag_client.so",
|
|
61
|
+
"libjtag_atlantic.so",
|
|
62
|
+
"jtagconfig",
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
files = [directory / name for name in names]
|
|
66
|
+
missing = [str(path) for path in files if not path.is_file()]
|
|
67
|
+
if missing:
|
|
68
|
+
raise TransportError(
|
|
69
|
+
"Missing Quartus x64 libraries/tools: "
|
|
70
|
+
+ ", ".join(missing)
|
|
71
|
+
+ ". Set --quartus-root to the installation containing bin64/linux64.",
|
|
72
|
+
code="library",
|
|
73
|
+
)
|
|
74
|
+
return Installation(base, directory, *files, system)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def availability(root: str | None = None) -> dict[str, Any]:
|
|
78
|
+
"""Inspect installation files only; never load vendor code in the UI process."""
|
|
79
|
+
try:
|
|
80
|
+
installation = _installation(root)
|
|
81
|
+
except TransportError as exc:
|
|
82
|
+
return {
|
|
83
|
+
"available": False,
|
|
84
|
+
"detail": str(exc),
|
|
85
|
+
"root": root or os.environ.get("QUARTUS_ROOTDIR"),
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
"available": True,
|
|
89
|
+
"detail": "Quartus x64 files found; server, cable driver and native dependencies are checked on connection.",
|
|
90
|
+
"root": str(installation.root),
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _environment(installation: Installation) -> dict[str, str]:
|
|
95
|
+
env = os.environ.copy()
|
|
96
|
+
env["QUARTUS_ROOTDIR"] = str(installation.root)
|
|
97
|
+
if installation.system == "Linux":
|
|
98
|
+
env["LD_LIBRARY_PATH"] = str(installation.directory)
|
|
99
|
+
else:
|
|
100
|
+
windows = Path(env.get("SystemRoot", r"C:\Windows"))
|
|
101
|
+
env["PATH"] = os.pathsep.join(
|
|
102
|
+
map(str, (installation.directory, windows / "System32", windows))
|
|
103
|
+
)
|
|
104
|
+
return env
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
_CABLE = re.compile(r"^\s*\d+\)\s+(.+?)\s*$")
|
|
108
|
+
_DEVICE = re.compile(r"^ {2}([0-9a-fA-F]{8})\s+[ !]\s*(.*)$")
|
|
109
|
+
_NODE = re.compile(r"^(?P<indent>[ \t]*)\+ Node (?P<node>[0-9a-fA-F]{8})(?:\s|$)")
|
|
110
|
+
_FAILURE = re.compile(
|
|
111
|
+
r"\berror\b|\bunable\b|\bfailed\b|\bcannot\b|\bcan't\b|no JTAG hardware|"
|
|
112
|
+
r"no devices on chain|not connected|not accessible|cannot be accessed|"
|
|
113
|
+
r"please use latest version|incompatible|permission denied",
|
|
114
|
+
re.I,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _parse_cables(output: str) -> list[str]:
|
|
119
|
+
return [
|
|
120
|
+
match.group(1)
|
|
121
|
+
for line in output.splitlines()
|
|
122
|
+
if (match := _CABLE.match(line)) and not match.group(1).startswith("Remote server ")
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _parse_nodes(
|
|
127
|
+
output: str, *, cable: str | None = None, device: int | None = None
|
|
128
|
+
) -> dict[str, dict[int, list[int] | None]]:
|
|
129
|
+
"""Validate only selected sections, preserving devices with an incomplete scan."""
|
|
130
|
+
result: dict[str, dict[int, list[int] | None]] = {}
|
|
131
|
+
devices: dict[int, list[int] | None] | None = None
|
|
132
|
+
number = 0
|
|
133
|
+
for line in output.splitlines():
|
|
134
|
+
if match := _CABLE.match(line):
|
|
135
|
+
name = match.group(1)
|
|
136
|
+
devices = (
|
|
137
|
+
None
|
|
138
|
+
if name.startswith("Remote server ") or (cable is not None and name != cable)
|
|
139
|
+
else result.setdefault(name, {})
|
|
140
|
+
)
|
|
141
|
+
number = 0
|
|
142
|
+
elif devices is not None and _DEVICE.match(line):
|
|
143
|
+
number += 1
|
|
144
|
+
if device is None or number == device:
|
|
145
|
+
devices[number] = None
|
|
146
|
+
elif devices is not None and number in devices and (match := _NODE.match(line)):
|
|
147
|
+
if devices[number] is None:
|
|
148
|
+
devices[number] = []
|
|
149
|
+
node = int(match.group("node"), 16)
|
|
150
|
+
if (node >> 8) & 0x7FF == 110 and (node >> 19) & 0xFF == 128:
|
|
151
|
+
if len(match.group("indent").expandtabs()) > 4:
|
|
152
|
+
raise TransportError(
|
|
153
|
+
"Hierarchical JTAG UART nodes cannot be selected safely by device/instance.",
|
|
154
|
+
code="target",
|
|
155
|
+
)
|
|
156
|
+
instance = node & 0xFF
|
|
157
|
+
if instance in devices[number]:
|
|
158
|
+
raise TransportError(
|
|
159
|
+
"Duplicate JTAG UART instance IDs are ambiguous; hierarchical UART selection is unsupported.",
|
|
160
|
+
code="target",
|
|
161
|
+
)
|
|
162
|
+
devices[number].append(instance)
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def _reap(process: asyncio.subprocess.Process, timeout: float = 1.0) -> None:
|
|
167
|
+
try:
|
|
168
|
+
if process.returncode is None:
|
|
169
|
+
try:
|
|
170
|
+
process.kill()
|
|
171
|
+
except ProcessLookupError:
|
|
172
|
+
pass
|
|
173
|
+
await asyncio.wait_for(process.wait(), timeout)
|
|
174
|
+
except (TimeoutError, OSError) as exc:
|
|
175
|
+
raise TransportError(
|
|
176
|
+
f"Cannot confirm release of Quartus child PID {process.pid}; kill/reap failed. Retry disconnect before using an external programmer.",
|
|
177
|
+
code="release",
|
|
178
|
+
) from exc
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _local_discovery_output(output: str) -> str:
|
|
182
|
+
lines = []
|
|
183
|
+
remote = False
|
|
184
|
+
for line in output.splitlines():
|
|
185
|
+
if match := _CABLE.match(line):
|
|
186
|
+
remote = match.group(1).startswith("Remote server ")
|
|
187
|
+
elif line and not line[0].isspace():
|
|
188
|
+
# Unsectioned diagnostics are global, not part of an ignored remote server.
|
|
189
|
+
remote = False
|
|
190
|
+
if not remote:
|
|
191
|
+
lines.append(line)
|
|
192
|
+
return "\n".join(lines)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async def _discover(
|
|
196
|
+
installation: Installation,
|
|
197
|
+
arguments: list[str],
|
|
198
|
+
timeout: float,
|
|
199
|
+
*,
|
|
200
|
+
owner: "QuartusTransport",
|
|
201
|
+
) -> str:
|
|
202
|
+
process = await asyncio.create_subprocess_exec(
|
|
203
|
+
str(installation.jtagconfig),
|
|
204
|
+
*arguments,
|
|
205
|
+
stdout=asyncio.subprocess.PIPE,
|
|
206
|
+
stderr=asyncio.subprocess.PIPE,
|
|
207
|
+
env=_environment(installation),
|
|
208
|
+
)
|
|
209
|
+
owner._discovery_process = process
|
|
210
|
+
try:
|
|
211
|
+
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
|
|
212
|
+
except BaseException:
|
|
213
|
+
await _reap(process)
|
|
214
|
+
owner._discovery_process = None
|
|
215
|
+
raise
|
|
216
|
+
owner._discovery_process = None
|
|
217
|
+
output = stdout.decode("utf-8", "replace")
|
|
218
|
+
diagnostic = stderr.decode("utf-8", "replace")
|
|
219
|
+
local_output = _local_discovery_output(output)
|
|
220
|
+
local_diagnostic = _local_discovery_output(diagnostic)
|
|
221
|
+
if process.returncode or _FAILURE.search(local_output + "\n" + local_diagnostic):
|
|
222
|
+
raise TransportError(
|
|
223
|
+
"jtagconfig discovery failed: "
|
|
224
|
+
+ (
|
|
225
|
+
local_diagnostic.strip()
|
|
226
|
+
or local_output.strip()
|
|
227
|
+
or diagnostic.strip()
|
|
228
|
+
or output.strip()
|
|
229
|
+
or f"exit {process.returncode}"
|
|
230
|
+
)
|
|
231
|
+
+ ". Check the JTAG server, cable OS driver, permissions and board power.",
|
|
232
|
+
code="discovery",
|
|
233
|
+
)
|
|
234
|
+
return output
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
async def list_cables(root: str | None = None) -> list[str]:
|
|
238
|
+
installation = _installation(root)
|
|
239
|
+
owner = QuartusTransport(root)
|
|
240
|
+
try:
|
|
241
|
+
return _parse_cables(await _discover(installation, ["--listhardware"], 3.0, owner=owner))
|
|
242
|
+
except TimeoutError as exc:
|
|
243
|
+
raise TransportError(
|
|
244
|
+
"JTAG cable discovery timed out; check the JTAG server and cable driver.",
|
|
245
|
+
code="timeout",
|
|
246
|
+
) from exc
|
|
247
|
+
except OSError as exc:
|
|
248
|
+
raise TransportError(
|
|
249
|
+
f"Cannot run jtagconfig: {exc}. Check Quartus native dependencies.", code="library"
|
|
250
|
+
) from exc
|
|
251
|
+
finally:
|
|
252
|
+
await owner.close()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _resolve_cable(cable: str | None, cables: list[str]) -> str:
|
|
256
|
+
if cable is not None:
|
|
257
|
+
if cable not in cables:
|
|
258
|
+
raise TransportError(
|
|
259
|
+
f"Requested cable {cable!r} is unavailable; use --list-cables and check its driver.",
|
|
260
|
+
code="target",
|
|
261
|
+
)
|
|
262
|
+
return cable
|
|
263
|
+
if len(cables) == 1:
|
|
264
|
+
return cables[0]
|
|
265
|
+
raise TransportError(
|
|
266
|
+
"No unique cable; select an exact --cable from --list-cables.", code="target"
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _resolve_target(
|
|
271
|
+
target: Target, cables: list[str], nodes: dict[str, dict[int, list[int] | None]] | None
|
|
272
|
+
) -> Target:
|
|
273
|
+
if target.device is not None and (type(target.device) is not int or target.device < 1):
|
|
274
|
+
raise TransportError(
|
|
275
|
+
"--device must be a positive device index starting at 1.", code="target"
|
|
276
|
+
)
|
|
277
|
+
if target.instance is not None and (
|
|
278
|
+
type(target.instance) is not int or not 0 <= target.instance <= 255
|
|
279
|
+
):
|
|
280
|
+
raise TransportError("--instance must be an index from 0 to 255.", code="target")
|
|
281
|
+
cable = _resolve_cable(target.cable, cables)
|
|
282
|
+
if target.device is not None and target.instance is not None:
|
|
283
|
+
return Target(cable, target.device, target.instance)
|
|
284
|
+
devices = (nodes or {}).get(cable, {})
|
|
285
|
+
if not devices:
|
|
286
|
+
raise TransportError(
|
|
287
|
+
"UART discovery unavailable; specify both --device and --instance.", code="target"
|
|
288
|
+
)
|
|
289
|
+
if target.device is None:
|
|
290
|
+
# None means no node records; aji_get_nodes may fail even at exit status 0.
|
|
291
|
+
if any(instances is None for instances in devices.values()):
|
|
292
|
+
raise TransportError(
|
|
293
|
+
"Incomplete UART node scan; specify --device and --instance explicitly.",
|
|
294
|
+
code="target",
|
|
295
|
+
)
|
|
296
|
+
candidates = [
|
|
297
|
+
number
|
|
298
|
+
for number, instances in devices.items()
|
|
299
|
+
if instances and (target.instance is None or target.instance in instances)
|
|
300
|
+
]
|
|
301
|
+
if len(candidates) != 1:
|
|
302
|
+
raise TransportError(
|
|
303
|
+
"No unique UART device; specify --device and --instance.", code="target"
|
|
304
|
+
)
|
|
305
|
+
device = candidates[0]
|
|
306
|
+
else:
|
|
307
|
+
device = target.device
|
|
308
|
+
instances = devices.get(device) or []
|
|
309
|
+
if target.instance is None and len(instances) != 1:
|
|
310
|
+
raise TransportError(
|
|
311
|
+
"No unique UART instance; specify --instance (and --device if needed).", code="target"
|
|
312
|
+
)
|
|
313
|
+
return Target(cable, device, target.instance if target.instance is not None else instances[0])
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
class QuartusTransport:
|
|
317
|
+
def __init__(self, root: str | None = None, *, operation_timeout: float = 3.0):
|
|
318
|
+
if not math.isfinite(operation_timeout) or operation_timeout <= 0:
|
|
319
|
+
raise ValueError("operation_timeout must be finite and positive")
|
|
320
|
+
self.root = root
|
|
321
|
+
self.operation_timeout = operation_timeout
|
|
322
|
+
self._lock = asyncio.Lock()
|
|
323
|
+
self._process: asyncio.subprocess.Process | None = None
|
|
324
|
+
self._discovery_process: asyncio.subprocess.Process | None = None
|
|
325
|
+
self._selected: Target | None = None
|
|
326
|
+
self._connected = False
|
|
327
|
+
self._sequence = 0
|
|
328
|
+
self._connecting: asyncio.Task | None = None
|
|
329
|
+
self._epoch = 0
|
|
330
|
+
|
|
331
|
+
def info(self) -> dict[str, Any]:
|
|
332
|
+
return {
|
|
333
|
+
"driver": "quartus",
|
|
334
|
+
"connected": self._connected,
|
|
335
|
+
**asdict(self._selected or Target()),
|
|
336
|
+
"root": self.root,
|
|
337
|
+
"worker_pid": self._process.pid if self._process is not None else None,
|
|
338
|
+
"discovery_pid": (
|
|
339
|
+
self._discovery_process.pid if self._discovery_process is not None else None
|
|
340
|
+
),
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
def _worker_argv(self) -> list[str]:
|
|
344
|
+
return [sys.executable, "-m", "juart.backends._quartus_worker"]
|
|
345
|
+
|
|
346
|
+
async def _stop(self) -> None:
|
|
347
|
+
self._connected = False
|
|
348
|
+
discovery = self._discovery_process
|
|
349
|
+
if discovery is not None:
|
|
350
|
+
await _reap(discovery)
|
|
351
|
+
if self._discovery_process is discovery:
|
|
352
|
+
self._discovery_process = None
|
|
353
|
+
process = self._process
|
|
354
|
+
if process is not None:
|
|
355
|
+
await _reap(process)
|
|
356
|
+
if self._process is process:
|
|
357
|
+
self._process = None
|
|
358
|
+
|
|
359
|
+
async def _rpc(self, operation: str, *, timeout: float | None = None, **fields: Any) -> Any:
|
|
360
|
+
process = self._process
|
|
361
|
+
if process is None or process.stdin is None or process.stdout is None:
|
|
362
|
+
raise TransportError("Quartus transport is closed.", code="closed")
|
|
363
|
+
self._sequence += 1
|
|
364
|
+
sequence = self._sequence
|
|
365
|
+
accepted = 0
|
|
366
|
+
try:
|
|
367
|
+
async with asyncio.timeout(
|
|
368
|
+
min(timeout, self.operation_timeout)
|
|
369
|
+
if timeout is not None
|
|
370
|
+
else self.operation_timeout
|
|
371
|
+
):
|
|
372
|
+
process.stdin.write(
|
|
373
|
+
(json.dumps({"id": sequence, "op": operation, **fields}) + "\n").encode()
|
|
374
|
+
)
|
|
375
|
+
await process.stdin.drain()
|
|
376
|
+
while True:
|
|
377
|
+
line = await process.stdout.readline()
|
|
378
|
+
if not line:
|
|
379
|
+
raise TransportError(
|
|
380
|
+
"Quartus worker exited; check native library architecture/dependencies and JTAG server.",
|
|
381
|
+
code="worker",
|
|
382
|
+
)
|
|
383
|
+
response = json.loads(line)
|
|
384
|
+
if response.get("id") != sequence:
|
|
385
|
+
raise ValueError("unexpected RPC response")
|
|
386
|
+
if response.get("event") == "accepted":
|
|
387
|
+
count = response.get("accepted")
|
|
388
|
+
if type(count) is not int or not 0 <= count <= fields.get("length", 0):
|
|
389
|
+
raise ValueError("invalid write acknowledgement")
|
|
390
|
+
accepted = count
|
|
391
|
+
continue
|
|
392
|
+
if not response.get("ok"):
|
|
393
|
+
error = response.get("error", {})
|
|
394
|
+
raise TransportError(
|
|
395
|
+
error.get("message", "Quartus worker failed"),
|
|
396
|
+
code=error.get("code", "native"),
|
|
397
|
+
uncertain=operation == "write",
|
|
398
|
+
accepted=accepted,
|
|
399
|
+
)
|
|
400
|
+
return response.get("result")
|
|
401
|
+
except asyncio.CancelledError as exc:
|
|
402
|
+
try:
|
|
403
|
+
await self._stop()
|
|
404
|
+
except TransportError as release:
|
|
405
|
+
release.accepted = accepted
|
|
406
|
+
release.uncertain = operation == "write"
|
|
407
|
+
raise
|
|
408
|
+
if operation == "write":
|
|
409
|
+
raise TransportError(
|
|
410
|
+
"Quartus write interrupted; worker killed and reaped.",
|
|
411
|
+
code="cancelled",
|
|
412
|
+
uncertain=True,
|
|
413
|
+
accepted=accepted,
|
|
414
|
+
) from exc
|
|
415
|
+
raise
|
|
416
|
+
except Exception as exc:
|
|
417
|
+
try:
|
|
418
|
+
await self._stop()
|
|
419
|
+
except TransportError as release:
|
|
420
|
+
release.accepted = accepted
|
|
421
|
+
release.uncertain = operation == "write"
|
|
422
|
+
raise
|
|
423
|
+
if isinstance(exc, TransportError):
|
|
424
|
+
exc.uncertain = exc.uncertain or operation == "write"
|
|
425
|
+
exc.accepted = accepted
|
|
426
|
+
raise
|
|
427
|
+
raise TransportError(
|
|
428
|
+
"Quartus operation timed out; worker killed and reaped."
|
|
429
|
+
if isinstance(exc, TimeoutError)
|
|
430
|
+
else f"Quartus worker communication failed: {exc}",
|
|
431
|
+
code="timeout" if isinstance(exc, TimeoutError) else "worker",
|
|
432
|
+
uncertain=operation == "write",
|
|
433
|
+
accepted=accepted,
|
|
434
|
+
) from exc
|
|
435
|
+
|
|
436
|
+
async def connect(self, target: Target) -> None:
|
|
437
|
+
epoch = self._epoch
|
|
438
|
+
async with self._lock:
|
|
439
|
+
if epoch != self._epoch:
|
|
440
|
+
raise TransportError("Connection interrupted by disconnect.", code="closed")
|
|
441
|
+
self._connecting = asyncio.current_task()
|
|
442
|
+
try:
|
|
443
|
+
await self._stop()
|
|
444
|
+
async with asyncio.timeout(self.operation_timeout):
|
|
445
|
+
installation = _installation(self.root)
|
|
446
|
+
cables = _parse_cables(
|
|
447
|
+
await _discover(
|
|
448
|
+
installation, ["--listhardware"], self.operation_timeout, owner=self
|
|
449
|
+
)
|
|
450
|
+
)
|
|
451
|
+
cable = _resolve_cable(target.cable, cables)
|
|
452
|
+
nodes = None
|
|
453
|
+
if target.device is None or target.instance is None:
|
|
454
|
+
try:
|
|
455
|
+
nodes = _parse_nodes(
|
|
456
|
+
await _discover(
|
|
457
|
+
installation, ["--nodes"], self.operation_timeout, owner=self
|
|
458
|
+
),
|
|
459
|
+
cable=cable,
|
|
460
|
+
device=target.device,
|
|
461
|
+
)
|
|
462
|
+
except TransportError as exc:
|
|
463
|
+
if exc.code == "release":
|
|
464
|
+
raise
|
|
465
|
+
raise TransportError(
|
|
466
|
+
f"{exc} Specify explicit --device and --instance when node discovery is unavailable.",
|
|
467
|
+
code="target",
|
|
468
|
+
) from exc
|
|
469
|
+
selected = _resolve_target(target, cables, nodes)
|
|
470
|
+
self._process = await asyncio.create_subprocess_exec(
|
|
471
|
+
*self._worker_argv(),
|
|
472
|
+
stdin=asyncio.subprocess.PIPE,
|
|
473
|
+
stdout=asyncio.subprocess.PIPE,
|
|
474
|
+
stderr=asyncio.subprocess.DEVNULL,
|
|
475
|
+
limit=2 * 1024 * 1024 + 4096,
|
|
476
|
+
env=_environment(installation),
|
|
477
|
+
)
|
|
478
|
+
result = await self._rpc(
|
|
479
|
+
"connect", root=str(installation.root), target=asdict(selected)
|
|
480
|
+
)
|
|
481
|
+
actual = Target(**result)
|
|
482
|
+
if actual != selected:
|
|
483
|
+
raise TransportError(
|
|
484
|
+
f"Quartus opened {actual!r}, not requested {selected!r}.",
|
|
485
|
+
code="target_mismatch",
|
|
486
|
+
)
|
|
487
|
+
self._selected = actual
|
|
488
|
+
self.root = str(installation.root)
|
|
489
|
+
self._connected = True
|
|
490
|
+
except BaseException as exc:
|
|
491
|
+
await self._stop()
|
|
492
|
+
if isinstance(exc, TimeoutError):
|
|
493
|
+
raise TransportError(
|
|
494
|
+
"Quartus connection timed out; worker and discovery process reaped.",
|
|
495
|
+
code="timeout",
|
|
496
|
+
) from exc
|
|
497
|
+
if isinstance(exc, OSError):
|
|
498
|
+
raise TransportError(
|
|
499
|
+
f"Cannot start Quartus tools: {exc}. Check installation and native dependencies.",
|
|
500
|
+
code="library",
|
|
501
|
+
) from exc
|
|
502
|
+
raise
|
|
503
|
+
finally:
|
|
504
|
+
self._connecting = None
|
|
505
|
+
|
|
506
|
+
async def read(self, max_bytes: int, timeout: float) -> bytes:
|
|
507
|
+
if type(max_bytes) is not int or not 0 < max_bytes <= 1024 * 1024:
|
|
508
|
+
raise ValueError("max_bytes must be between 1 and 1048576")
|
|
509
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
510
|
+
raise ValueError("timeout must be finite and positive")
|
|
511
|
+
async with self._lock:
|
|
512
|
+
result = await self._rpc("read", timeout=timeout, length=max_bytes)
|
|
513
|
+
try:
|
|
514
|
+
data = bytes.fromhex(result)
|
|
515
|
+
if len(data) > max_bytes:
|
|
516
|
+
raise ValueError("oversized read")
|
|
517
|
+
return data
|
|
518
|
+
except (TypeError, ValueError) as exc:
|
|
519
|
+
await self._stop()
|
|
520
|
+
raise TransportError(
|
|
521
|
+
"Invalid read result from Quartus worker.", code="worker"
|
|
522
|
+
) from exc
|
|
523
|
+
|
|
524
|
+
async def write(self, data: bytes, timeout: float) -> int:
|
|
525
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
526
|
+
raise ValueError("timeout must be finite and positive")
|
|
527
|
+
async with self._lock:
|
|
528
|
+
count = await self._rpc("write", timeout=timeout, data=data.hex(), length=len(data))
|
|
529
|
+
if type(count) is not int or not 0 <= count <= len(data):
|
|
530
|
+
await self._stop()
|
|
531
|
+
raise TransportError(
|
|
532
|
+
"Invalid accepted count from Quartus worker.", code="worker", uncertain=True
|
|
533
|
+
)
|
|
534
|
+
return count
|
|
535
|
+
|
|
536
|
+
async def close(self) -> None:
|
|
537
|
+
self._epoch += 1
|
|
538
|
+
connecting = self._connecting
|
|
539
|
+
if connecting is not None and connecting is not asyncio.current_task():
|
|
540
|
+
connecting.cancel()
|
|
541
|
+
try:
|
|
542
|
+
results = await asyncio.wait_for(
|
|
543
|
+
asyncio.gather(connecting, return_exceptions=True), 2.0
|
|
544
|
+
)
|
|
545
|
+
except TimeoutError as exc:
|
|
546
|
+
raise TransportError(
|
|
547
|
+
"Cannot confirm connection/discovery worker release; retry disconnect.",
|
|
548
|
+
code="release",
|
|
549
|
+
) from exc
|
|
550
|
+
if isinstance(results[0], TransportError) and results[0].code == "release":
|
|
551
|
+
raise results[0]
|
|
552
|
+
# Do not wait behind a potentially blocked native operation to interrupt it.
|
|
553
|
+
if self._lock.locked():
|
|
554
|
+
await self._stop()
|
|
555
|
+
return
|
|
556
|
+
async with self._lock:
|
|
557
|
+
try:
|
|
558
|
+
if self._process is not None:
|
|
559
|
+
await self._rpc("close")
|
|
560
|
+
finally:
|
|
561
|
+
await self._stop()
|
juart/cli.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Package entry point and non-interactive device discovery commands."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from juart import __version__
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def nonnegative_index(value: str) -> int:
|
|
11
|
+
try:
|
|
12
|
+
index = int(value)
|
|
13
|
+
except ValueError as exc:
|
|
14
|
+
raise argparse.ArgumentTypeError("index must be an integer") from exc
|
|
15
|
+
if index < 0:
|
|
16
|
+
raise argparse.ArgumentTypeError("index must be nonnegative")
|
|
17
|
+
return index
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parser() -> argparse.ArgumentParser:
|
|
21
|
+
result = argparse.ArgumentParser(
|
|
22
|
+
prog="juart",
|
|
23
|
+
description="JTAG UART terminal: :direct, :buffer, :help, :disconnect, :quit",
|
|
24
|
+
epilog=(
|
|
25
|
+
"Use native Windows Python or a Linux Python/Quartus runtime in WSL. "
|
|
26
|
+
"Install the matching cable OS driver separately. "
|
|
27
|
+
"Buffer Enter submits only edited bytes (empty is a no-op); direct Enter sends CR. Use :hex 0d for an explicit CR. Direct Ctrl+D sends 0x04."
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
result.add_argument("--version", action="version", version=f"juart {__version__}")
|
|
31
|
+
result.add_argument("--driver", choices=["quartus"], default="quartus")
|
|
32
|
+
discovery = result.add_mutually_exclusive_group()
|
|
33
|
+
discovery.add_argument("--list-drivers", action="store_true")
|
|
34
|
+
discovery.add_argument("--list-cables", action="store_true")
|
|
35
|
+
result.add_argument("--cable", help="exact cable identifier reported by --list-cables")
|
|
36
|
+
result.add_argument("--device", type=nonnegative_index, help="driver-reported device index")
|
|
37
|
+
result.add_argument("--instance", type=nonnegative_index, help="driver-reported UART index")
|
|
38
|
+
result.add_argument("--quartus-root", help="Quartus directory (or QUARTUS_ROOTDIR)")
|
|
39
|
+
result.add_argument("--shell", help="shell executable for :! (cmd, PowerShell, or POSIX shell)")
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def run(args: argparse.Namespace) -> int:
|
|
44
|
+
# Vendor loading occurs only in an isolated backend child, never at CLI import.
|
|
45
|
+
from juart.backends.base import Target, TransportError
|
|
46
|
+
from juart.backends.quartus import QuartusTransport, availability, list_cables
|
|
47
|
+
|
|
48
|
+
if args.list_drivers:
|
|
49
|
+
status = availability(args.quartus_root)
|
|
50
|
+
label = "available" if status["available"] else "unavailable"
|
|
51
|
+
print(f"quartus\t{label}\t{status['detail']}")
|
|
52
|
+
return 0
|
|
53
|
+
if args.list_cables:
|
|
54
|
+
try:
|
|
55
|
+
cables = await list_cables(args.quartus_root)
|
|
56
|
+
except (TransportError, OSError, ValueError) as exc:
|
|
57
|
+
print(f"juart: {exc}", file=sys.stderr)
|
|
58
|
+
return 1
|
|
59
|
+
if not cables:
|
|
60
|
+
print("No JTAG cables detected.", file=sys.stderr)
|
|
61
|
+
return 1
|
|
62
|
+
for cable in cables:
|
|
63
|
+
print(cable)
|
|
64
|
+
return 0
|
|
65
|
+
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
|
66
|
+
print(
|
|
67
|
+
"juart: an interactive terminal is required; use --help for discovery options.",
|
|
68
|
+
file=sys.stderr,
|
|
69
|
+
)
|
|
70
|
+
return 2
|
|
71
|
+
|
|
72
|
+
from juart.logging import JsonLogger
|
|
73
|
+
from juart.session import Session
|
|
74
|
+
from juart.terminal import run_terminal
|
|
75
|
+
|
|
76
|
+
transport = QuartusTransport(args.quartus_root)
|
|
77
|
+
|
|
78
|
+
def log_error(message: str) -> None:
|
|
79
|
+
if session.notify is not None:
|
|
80
|
+
session.notify(message)
|
|
81
|
+
else:
|
|
82
|
+
print(f"juart: {message}", file=sys.stderr)
|
|
83
|
+
if session.on_change is not None:
|
|
84
|
+
session.on_change()
|
|
85
|
+
|
|
86
|
+
session = Session(
|
|
87
|
+
transport,
|
|
88
|
+
Target(args.cable, args.device, args.instance),
|
|
89
|
+
logger=JsonLogger(on_error=log_error),
|
|
90
|
+
)
|
|
91
|
+
return await run_terminal(session, shell=args.shell)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def main(argv: list[str] | None = None) -> int:
|
|
95
|
+
args = parser().parse_args(argv)
|
|
96
|
+
try:
|
|
97
|
+
return asyncio.run(run(args))
|
|
98
|
+
except KeyboardInterrupt:
|
|
99
|
+
return 130
|
|
100
|
+
except (OSError, ValueError) as exc:
|
|
101
|
+
print(f"juart: {exc}", file=sys.stderr)
|
|
102
|
+
return 1
|