multitool-mcp 0.1.0__tar.gz → 0.2.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 (22) hide show
  1. multitool_mcp-0.2.0/PKG-INFO +127 -0
  2. multitool_mcp-0.2.0/README.md +104 -0
  3. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/pyproject.toml +1 -1
  4. multitool_mcp-0.2.0/src/dut_mcp/debug.py +332 -0
  5. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/dut_mcp/server.py +74 -6
  6. multitool_mcp-0.2.0/src/multitool_mcp.egg-info/PKG-INFO +127 -0
  7. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/multitool_mcp.egg-info/SOURCES.txt +2 -0
  8. multitool_mcp-0.2.0/tests/test_debug.py +193 -0
  9. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/tests/test_dut_mcp.py +8 -0
  10. multitool_mcp-0.1.0/PKG-INFO +0 -97
  11. multitool_mcp-0.1.0/README.md +0 -74
  12. multitool_mcp-0.1.0/src/multitool_mcp.egg-info/PKG-INFO +0 -97
  13. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/LICENSE +0 -0
  14. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/setup.cfg +0 -0
  15. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/dut_mcp/__init__.py +0 -0
  16. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/dut_mcp/__main__.py +0 -0
  17. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/dut_mcp/device.py +0 -0
  18. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/dut_mcp/websocket.py +0 -0
  19. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/multitool_mcp.egg-info/dependency_links.txt +0 -0
  20. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/multitool_mcp.egg-info/entry_points.txt +0 -0
  21. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/multitool_mcp.egg-info/requires.txt +0 -0
  22. {multitool_mcp-0.1.0 → multitool_mcp-0.2.0}/src/multitool_mcp.egg-info/top_level.txt +0 -0
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: multitool-mcp
3
+ Version: 0.2.0
4
+ Summary: MCP server for debugging devices under test through WE Multitool
5
+ Author: Wise Electronics
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/we-devices/multitool-mcp
8
+ Project-URL: Repository, https://github.com/we-devices/multitool-mcp.git
9
+ Project-URL: Issues, https://github.com/we-devices/multitool-mcp/issues
10
+ Keywords: mcp,embedded,hardware,debugging,we-multitool
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Topic :: Software Development :: Debuggers
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=8; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # WE Multitool DUT MCP
25
+
26
+ `multitool-mcp` is a dependency-free [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting and debugging a device under test (DUT) through a Wise Electronics WE Multitool.
27
+
28
+ It runs over standard input/output and bridges the Multitool's JSON-over-WebSocket API. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
29
+
30
+ ## Requirements
31
+
32
+ - Python 3.11 or later
33
+ - A WE Multitool reachable over WebSocket
34
+
35
+ ## Install
36
+
37
+ Install from PyPI once published:
38
+
39
+ ```shell
40
+ python -m pip install multitool-mcp
41
+ ```
42
+
43
+ For development from a clone:
44
+
45
+ ```shell
46
+ python -m pip install -e .
47
+ ```
48
+
49
+ ## Configure an MCP client
50
+
51
+ Run the installed command:
52
+
53
+ ```toml
54
+ [mcp_servers.we_multitool_dut]
55
+ command = "multitool-mcp"
56
+ env_vars = ["WE_MULTITOOL_URL", "WE_MULTITOOL_TIMEOUT_SECONDS"]
57
+ startup_timeout_sec = 10
58
+ tool_timeout_sec = 150
59
+ default_tools_approval_mode = "prompt"
60
+ ```
61
+
62
+ By default, the server connects to `ws://we-multitool.local/ws`. Set these environment variables before starting the MCP client to change that:
63
+
64
+ ```shell
65
+ WE_MULTITOOL_URL=ws://10.0.0.1/ws
66
+ WE_MULTITOOL_TIMEOUT_SECONDS=8
67
+ ```
68
+
69
+ On PowerShell:
70
+
71
+ ```powershell
72
+ $env:WE_MULTITOOL_URL = "ws://10.0.0.1/ws"
73
+ $env:WE_MULTITOOL_TIMEOUT_SECONDS = "8"
74
+ ```
75
+
76
+ ## Safety and firmware behavior
77
+
78
+ Read `pins_get` before configuring pins, and verify wiring, voltage, bus role, and DUT limits before driving signals.
79
+
80
+ `gpio_configure` accepts `input`, `output`, and `open-drain` directions. Open-drain mode requires firmware with `open-drain` GPIO setup support and an appropriate external pull-up.
81
+
82
+ - Commands are serialized because firmware responses do not carry request IDs.
83
+ - UART data received while another command awaits a response is buffered.
84
+ - The `gpio_set` firmware command has no acknowledgement; `gpio_write` reports it as dispatched but unverified.
85
+ - The firmware tracks one active WebSocket response socket. Do not use the browser UI and MCP bridge concurrently.
86
+
87
+ ## SWD and SWO
88
+
89
+ Version 0.2.0 adds these tools:
90
+
91
+ | Tools | Purpose |
92
+ | --- | --- |
93
+ | `swd_status`, `swd_enable`, `swd_disable` | Configure the probe and reserve/release its pins |
94
+ | `swd_session_start`, `swd_session_status`, `swd_session_stop` | Manage one owned host OpenOCD process and inspect logs |
95
+ | `swd_control`, `swd_set_speed` | Halt/resume, instruction-step, reset/halt, and request clock speed |
96
+ | `swd_read_memory`, `swd_write_memory`, `swd_flash` | Bounded memory access and ELF program/verify/reset |
97
+ | `swo_start`, `swo_read`, `swo_stop` | Capture UART/NRZ SWO and decode software ITM ports |
98
+
99
+ Install an OpenOCD build with the **CMSIS-DAP TCP backend**. The Espressif build used here supports it; some stock 0.12.0 builds do not. Python still requires no runtime packages. Provide trusted local OpenOCD configuration files that select CMSIS-DAP TCP port 4441, read the host from `WE_MULTITOOL_HOST`, and configure the target. The server sets this environment variable from its WebSocket URL. Target flash algorithms and SWO pin routing belong in these files.
100
+
101
+ OpenOCD GDB/Tcl/trace ports bind to localhost (defaults 3333/6666/3443). Only one OpenOCD client can connect to the probe: stop a VSCode debug session before starting an MCP session. MCP client shutdown stops its owned process and normally resumes a halted DUT. Stopping a session keeps probe pins reserved; `swd_disable` releases them to inputs. Use direct wiring only with 3.3 V compatible targets and a shared ground.
102
+
103
+ ### Hardware verification
104
+
105
+ MCP tools were tested on the connected Nucleo L452: probe enable/disable/status, OpenOCD startup/cleanup, halt/resume/reset, single-step in `debug_init`, and two matching 64-byte Flash reads at requested 4 MHz. SWO at 100 kbaud with an 80 MHz trace clock returned 184 raw bytes / 92 ITM port-0 bytes, including the startup banner, with zero reported overflow packets or decoder errors. This MCP smoke test did not reflash the target.
106
+
107
+ Single-step waits for the target to halt again. Stepping a sleeping RTOS idle instruction can time out; the tool reports an error instead of reporting successful completion while the target is still running.
108
+
109
+ SWO reads return raw `base64`/`hex`, decoded `itm_ports` with text and payload bytes, overflow counts, and decoder errors. Decoding persists across reads, including split packets and UTF-8 sequences. Hardware event and timestamp packets are not interpreted as text. A quiet read can return zero bytes. No lossless throughput is promised; overflow counts describe ITM overflow packets, not every possible capture loss.
110
+
111
+ Memory writes and flashing are marked destructive. Flashing verifies an existing ELF and resets the target; it does not automatically remove protection. Set the MCP client tool timeout to at least 150 seconds for flash operations. Requested SWD speed is not a measurement of the physical clock. Prior direct OpenOCD tests on this L452 passed repeated reads at requested 4 MHz; retest your wiring before using a higher speed.
112
+
113
+ After installing the updated server, restart the MCP client to discover the new tools. To use this checkout on Windows, set its MCP `command` to `D:/_projects/wise-electronics/multitool-mcp/.venv/Scripts/multitool-mcp.exe` after installing with `.venv/Scripts/python.exe -m pip install -e .`.
114
+
115
+ ## Development
116
+
117
+ ```shell
118
+ python -m pip install -e ".[test]"
119
+ python -m pytest
120
+ ```
121
+
122
+ The runtime has no third-party dependencies. The optional `test` extra installs pytest.
123
+
124
+ ## License
125
+
126
+ Licensed under the GNU General Public License, version 3 or later
127
+ (GPL-3.0-or-later). See [LICENSE](LICENSE).
@@ -0,0 +1,104 @@
1
+ # WE Multitool DUT MCP
2
+
3
+ `multitool-mcp` is a dependency-free [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting and debugging a device under test (DUT) through a Wise Electronics WE Multitool.
4
+
5
+ It runs over standard input/output and bridges the Multitool's JSON-over-WebSocket API. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
6
+
7
+ ## Requirements
8
+
9
+ - Python 3.11 or later
10
+ - A WE Multitool reachable over WebSocket
11
+
12
+ ## Install
13
+
14
+ Install from PyPI once published:
15
+
16
+ ```shell
17
+ python -m pip install multitool-mcp
18
+ ```
19
+
20
+ For development from a clone:
21
+
22
+ ```shell
23
+ python -m pip install -e .
24
+ ```
25
+
26
+ ## Configure an MCP client
27
+
28
+ Run the installed command:
29
+
30
+ ```toml
31
+ [mcp_servers.we_multitool_dut]
32
+ command = "multitool-mcp"
33
+ env_vars = ["WE_MULTITOOL_URL", "WE_MULTITOOL_TIMEOUT_SECONDS"]
34
+ startup_timeout_sec = 10
35
+ tool_timeout_sec = 150
36
+ default_tools_approval_mode = "prompt"
37
+ ```
38
+
39
+ By default, the server connects to `ws://we-multitool.local/ws`. Set these environment variables before starting the MCP client to change that:
40
+
41
+ ```shell
42
+ WE_MULTITOOL_URL=ws://10.0.0.1/ws
43
+ WE_MULTITOOL_TIMEOUT_SECONDS=8
44
+ ```
45
+
46
+ On PowerShell:
47
+
48
+ ```powershell
49
+ $env:WE_MULTITOOL_URL = "ws://10.0.0.1/ws"
50
+ $env:WE_MULTITOOL_TIMEOUT_SECONDS = "8"
51
+ ```
52
+
53
+ ## Safety and firmware behavior
54
+
55
+ Read `pins_get` before configuring pins, and verify wiring, voltage, bus role, and DUT limits before driving signals.
56
+
57
+ `gpio_configure` accepts `input`, `output`, and `open-drain` directions. Open-drain mode requires firmware with `open-drain` GPIO setup support and an appropriate external pull-up.
58
+
59
+ - Commands are serialized because firmware responses do not carry request IDs.
60
+ - UART data received while another command awaits a response is buffered.
61
+ - The `gpio_set` firmware command has no acknowledgement; `gpio_write` reports it as dispatched but unverified.
62
+ - The firmware tracks one active WebSocket response socket. Do not use the browser UI and MCP bridge concurrently.
63
+
64
+ ## SWD and SWO
65
+
66
+ Version 0.2.0 adds these tools:
67
+
68
+ | Tools | Purpose |
69
+ | --- | --- |
70
+ | `swd_status`, `swd_enable`, `swd_disable` | Configure the probe and reserve/release its pins |
71
+ | `swd_session_start`, `swd_session_status`, `swd_session_stop` | Manage one owned host OpenOCD process and inspect logs |
72
+ | `swd_control`, `swd_set_speed` | Halt/resume, instruction-step, reset/halt, and request clock speed |
73
+ | `swd_read_memory`, `swd_write_memory`, `swd_flash` | Bounded memory access and ELF program/verify/reset |
74
+ | `swo_start`, `swo_read`, `swo_stop` | Capture UART/NRZ SWO and decode software ITM ports |
75
+
76
+ Install an OpenOCD build with the **CMSIS-DAP TCP backend**. The Espressif build used here supports it; some stock 0.12.0 builds do not. Python still requires no runtime packages. Provide trusted local OpenOCD configuration files that select CMSIS-DAP TCP port 4441, read the host from `WE_MULTITOOL_HOST`, and configure the target. The server sets this environment variable from its WebSocket URL. Target flash algorithms and SWO pin routing belong in these files.
77
+
78
+ OpenOCD GDB/Tcl/trace ports bind to localhost (defaults 3333/6666/3443). Only one OpenOCD client can connect to the probe: stop a VSCode debug session before starting an MCP session. MCP client shutdown stops its owned process and normally resumes a halted DUT. Stopping a session keeps probe pins reserved; `swd_disable` releases them to inputs. Use direct wiring only with 3.3 V compatible targets and a shared ground.
79
+
80
+ ### Hardware verification
81
+
82
+ MCP tools were tested on the connected Nucleo L452: probe enable/disable/status, OpenOCD startup/cleanup, halt/resume/reset, single-step in `debug_init`, and two matching 64-byte Flash reads at requested 4 MHz. SWO at 100 kbaud with an 80 MHz trace clock returned 184 raw bytes / 92 ITM port-0 bytes, including the startup banner, with zero reported overflow packets or decoder errors. This MCP smoke test did not reflash the target.
83
+
84
+ Single-step waits for the target to halt again. Stepping a sleeping RTOS idle instruction can time out; the tool reports an error instead of reporting successful completion while the target is still running.
85
+
86
+ SWO reads return raw `base64`/`hex`, decoded `itm_ports` with text and payload bytes, overflow counts, and decoder errors. Decoding persists across reads, including split packets and UTF-8 sequences. Hardware event and timestamp packets are not interpreted as text. A quiet read can return zero bytes. No lossless throughput is promised; overflow counts describe ITM overflow packets, not every possible capture loss.
87
+
88
+ Memory writes and flashing are marked destructive. Flashing verifies an existing ELF and resets the target; it does not automatically remove protection. Set the MCP client tool timeout to at least 150 seconds for flash operations. Requested SWD speed is not a measurement of the physical clock. Prior direct OpenOCD tests on this L452 passed repeated reads at requested 4 MHz; retest your wiring before using a higher speed.
89
+
90
+ After installing the updated server, restart the MCP client to discover the new tools. To use this checkout on Windows, set its MCP `command` to `D:/_projects/wise-electronics/multitool-mcp/.venv/Scripts/multitool-mcp.exe` after installing with `.venv/Scripts/python.exe -m pip install -e .`.
91
+
92
+ ## Development
93
+
94
+ ```shell
95
+ python -m pip install -e ".[test]"
96
+ python -m pytest
97
+ ```
98
+
99
+ The runtime has no third-party dependencies. The optional `test` extra installs pytest.
100
+
101
+ ## License
102
+
103
+ Licensed under the GNU General Public License, version 3 or later
104
+ (GPL-3.0-or-later). See [LICENSE](LICENSE).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "multitool-mcp"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "MCP server for debugging devices under test through WE Multitool"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -0,0 +1,332 @@
1
+ """Owned host OpenOCD sessions and bounded UART-SWO/ITM trace reads."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import codecs
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import socket
10
+ import subprocess
11
+ import tempfile
12
+ import time
13
+ from urllib.parse import urlsplit
14
+
15
+ from .device import DeviceError
16
+
17
+
18
+ def tcl_word(value: str) -> str:
19
+ """Quote one Tcl argument, disabling command and variable substitution."""
20
+ return '"' + value.replace('\\', '\\\\').replace('{', '\\{').replace('}', '\\}').replace('$', '\\$').replace('[', '\\[').replace(']', '\\]').replace('"', '\\"').replace('\n', '\\n').replace('\r', '\\r') + '"'
21
+
22
+
23
+ class ItmDecoder:
24
+ """Incremental software stimulus decoder; raw trace is always returned too."""
25
+ def __init__(self) -> None:
26
+ self.pending = bytearray()
27
+ self.sync_zeros = 0
28
+ self.text_decoders: dict[int, object] = {}
29
+
30
+ def feed(self, data: bytes) -> dict:
31
+ self.pending.extend(data)
32
+ ports: dict[int, bytearray] = {}
33
+ overflow = errors = index = 0
34
+ while index < len(self.pending):
35
+ header = self.pending[index]
36
+ if header == 0:
37
+ self.sync_zeros += 1
38
+ index += 1
39
+ continue
40
+ if header == 0x80 and self.sync_zeros >= 5:
41
+ self.sync_zeros = 0
42
+ index += 1
43
+ continue
44
+ self.sync_zeros = 0
45
+ if header & 3:
46
+ size = (1, 2, 4)[(header & 3) - 1]
47
+ if index + 1 + size > len(self.pending):
48
+ break
49
+ if not header & 4: # Software source packet; hardware events are not text.
50
+ ports.setdefault(header >> 3, bytearray()).extend(self.pending[index + 1:index + 1 + size])
51
+ index += 1 + size
52
+ elif header == 0:
53
+ # Synchronization/padding bytes carry no stimulus data.
54
+ index += 1
55
+ elif header == 0x70:
56
+ overflow += 1
57
+ index += 1
58
+ elif header & 0x80:
59
+ end = index + 1
60
+ while end < len(self.pending) and self.pending[end] & 0x80 and end - index < 5:
61
+ end += 1
62
+ if end == len(self.pending):
63
+ break
64
+ if end - index >= 5:
65
+ errors += 1
66
+ index = end + 1
67
+ else:
68
+ index += 1 # Short timestamp/extension packet.
69
+ del self.pending[:index]
70
+ output = {}
71
+ for port, payload in ports.items():
72
+ decoder = self.text_decoders.setdefault(port, codecs.getincrementaldecoder('utf-8')(errors='replace'))
73
+ output[str(port)] = {'length': len(payload), 'base64': base64.b64encode(payload).decode(), 'text': decoder.decode(payload)}
74
+ return {'itm_ports': output, 'overflow_packets': overflow, 'decoder_errors': errors}
75
+
76
+
77
+ class DebugSession:
78
+ def __init__(self) -> None:
79
+ self.process: subprocess.Popen | None = None
80
+ self.control: socket.socket | None = None
81
+ self.trace: socket.socket | None = None
82
+ self.log_path: Path | None = None
83
+ self.tpiu: str | None = None
84
+ self.decoder = ItmDecoder()
85
+ self.gdb_port = self.tcl_port = self.trace_port = None
86
+
87
+ def status(self) -> dict:
88
+ return {'running': self.process is not None and self.process.poll() is None,
89
+ 'control_connected': self.control is not None,
90
+ 'swo_connected': self.trace is not None, 'tpiu_name': self.tpiu,
91
+ 'gdb_port': self.gdb_port, 'tcl_port': self.tcl_port,
92
+ 'trace_port': self.trace_port, 'log_tail': self.log_tail()}
93
+
94
+ def log_tail(self) -> str:
95
+ if not self.log_path:
96
+ return ''
97
+ try:
98
+ with self.log_path.open('rb') as stream:
99
+ stream.seek(max(0, self.log_path.stat().st_size - 8192))
100
+ return stream.read(8192).decode(errors='replace')
101
+ except OSError:
102
+ return ''
103
+
104
+ def start(self, url: str, executable: str, config_files: list[str], scripts_dir: str | None = None,
105
+ gdb_port: int = 3333, tcl_port: int = 6666, startup_timeout_ms: int = 15000) -> dict:
106
+ if self.process is not None:
107
+ raise DeviceError('Stop the existing MCP OpenOCD session first')
108
+ if not config_files:
109
+ raise DeviceError('Provide at least one trusted local OpenOCD configuration file')
110
+ for file in [executable, *config_files]:
111
+ if not Path(file).is_file():
112
+ raise DeviceError(f'File does not exist: {file}')
113
+ if scripts_dir and not Path(scripts_dir).is_dir():
114
+ raise DeviceError('OpenOCD scripts_dir does not exist')
115
+ if gdb_port == tcl_port:
116
+ raise DeviceError('GDB and Tcl ports must be different')
117
+ for port in (gdb_port, tcl_port):
118
+ try:
119
+ with socket.socket() as check:
120
+ check.bind(('127.0.0.1', port))
121
+ except OSError as exc:
122
+ raise DeviceError(f'Host port {port} is already occupied') from exc
123
+ host = urlsplit(url).hostname
124
+ if not host:
125
+ raise DeviceError('Invalid Multitool URL')
126
+ fd, filename = tempfile.mkstemp(prefix='multitool-openocd-', suffix='.log')
127
+ os.close(fd)
128
+ self.log_path = Path(filename)
129
+ env = os.environ.copy()
130
+ env['WE_MULTITOOL_HOST'] = host
131
+ argv = [str(Path(executable).resolve()), '-c', 'bindto 127.0.0.1',
132
+ '-c', f'gdb port {gdb_port}; tcl port {tcl_port}; telnet port disabled']
133
+ if scripts_dir:
134
+ argv += ['-s', str(Path(scripts_dir).resolve())]
135
+ for file in config_files:
136
+ argv += ['-f', str(Path(file).resolve())]
137
+ self.gdb_port, self.tcl_port = gdb_port, tcl_port
138
+ try:
139
+ with self.log_path.open('wb') as log:
140
+ self.process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
141
+ env=env, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
142
+ deadline = time.monotonic() + startup_timeout_ms / 1000
143
+ while time.monotonic() < deadline:
144
+ if self.process.poll() is not None:
145
+ raise DeviceError('OpenOCD exited during startup: ' + self.log_tail())
146
+ try:
147
+ self.control = socket.create_connection(('127.0.0.1', tcl_port), timeout=.2)
148
+ self.command('version', timeout=max(.001, deadline - time.monotonic()))
149
+ return self.status()
150
+ except (OSError, DeviceError):
151
+ if self.control:
152
+ self.control.close()
153
+ self.control = None
154
+ time.sleep(.05)
155
+ raise DeviceError('OpenOCD startup timed out: ' + self.log_tail())
156
+ except (OSError, DeviceError) as exc:
157
+ self.close()
158
+ raise DeviceError(str(exc)) from exc
159
+
160
+ def command(self, text: str, timeout: float = 10) -> str:
161
+ if self.control is None:
162
+ raise DeviceError('Start an MCP OpenOCD session first')
163
+ if '\x1a' in text:
164
+ raise DeviceError('Tcl arguments cannot contain the protocol delimiter')
165
+ wire = 'set mcp_code [catch {' + text + '} mcp_result]; format "MCP:%d\\n%s" $mcp_code $mcp_result'
166
+ deadline = time.monotonic() + timeout
167
+ data = bytearray()
168
+ try:
169
+ self.control.settimeout(timeout)
170
+ self.control.sendall(wire.encode() + b'\x1a')
171
+ while True:
172
+ self.control.settimeout(max(.001, deadline - time.monotonic()))
173
+ part = self.control.recv(65536)
174
+ if not part:
175
+ raise OSError('OpenOCD closed the Tcl connection')
176
+ data.extend(part)
177
+ if len(data) > 2 * 1024 * 1024:
178
+ raise OSError('OpenOCD response exceeds 2 MiB')
179
+ while b'\x1a' in data:
180
+ frame, _, rest = data.partition(b'\x1a')
181
+ data = bytearray(rest)
182
+ reply = frame.decode(errors='replace')
183
+ if not reply.startswith('MCP:'): # Ignore greetings/notifications.
184
+ continue
185
+ code, _, result = reply.partition('\n')
186
+ if code != 'MCP:0':
187
+ raise DeviceError('OpenOCD: ' + (result.strip() or f'command failed: {text}'))
188
+ return result
189
+ except OSError as exc:
190
+ self.control.close()
191
+ self.control = None # Discard any late reply; never reuse a timed-out stream.
192
+ raise DeviceError(f'OpenOCD communication failed: {exc}') from exc
193
+
194
+ def read_memory(self, address: int, length: int) -> dict:
195
+ self._range(address, length)
196
+ result = self.command(f'read_memory {address:#x} 8 {length}', timeout=30)
197
+ try:
198
+ data = bytes(int(word, 0) for word in result.split())
199
+ except ValueError as exc:
200
+ raise DeviceError('OpenOCD returned invalid memory data') from exc
201
+ if len(data) != length:
202
+ raise DeviceError('OpenOCD returned an incomplete memory read')
203
+ return {'address': address, 'length': len(data), 'base64': base64.b64encode(data).decode(), 'hex': data.hex()}
204
+
205
+ @staticmethod
206
+ def _range(address: int, length: int) -> None:
207
+ if length < 1 or address < 0 or address + length > 0x100000000:
208
+ raise DeviceError('Memory range must fit the 32-bit target address space')
209
+
210
+ def write_memory(self, address: int, data: list[int]) -> dict:
211
+ self._range(address, len(data))
212
+ self.command(f'write_memory {address:#x} 8 {{' + ' '.join(str(byte) for byte in data) + '}', timeout=30)
213
+ return {'address': address, 'length': len(data), 'written': True}
214
+
215
+ def control_target(self, action: str) -> dict:
216
+ command = {'halt': 'halt', 'resume': 'resume', 'step': 'step', 'reset_halt': 'reset halt'}[action]
217
+ output = self.command(command, timeout=30)
218
+ if action == 'step':
219
+ self.command('wait_halt 5000', timeout=10)
220
+ return {'action': action, 'state': self.command('[target current] curstate'), 'output': output}
221
+
222
+ def flash(self, image: str) -> dict:
223
+ path = Path(image)
224
+ if not path.is_file() or path.suffix.lower() != '.elf':
225
+ raise DeviceError('image_path must name an existing ELF file')
226
+ output = self.command('program ' + tcl_word(path.resolve().as_posix()) + ' verify reset', timeout=120)
227
+ return {'image_path': str(path.resolve()), 'verified': True, 'output': output}
228
+
229
+ def start_swo(self, tpiu_name: str, trace_clock_hz: int, baudrate: int, ports: list[int], trace_port: int = 3443) -> dict:
230
+ if not re.fullmatch(r'[A-Za-z0-9_.-]+', tpiu_name):
231
+ raise DeviceError('Invalid TPIU object name')
232
+ if self.trace is not None or self.tpiu is not None:
233
+ raise DeviceError('Stop the existing SWO capture first')
234
+ if trace_port in (self.gdb_port, self.tcl_port):
235
+ raise DeviceError('Trace port must differ from GDB and Tcl ports')
236
+ try:
237
+ with socket.socket() as check:
238
+ check.bind(('127.0.0.1', trace_port))
239
+ except OSError as exc:
240
+ raise DeviceError('Trace port is occupied') from exc
241
+ self.tpiu = tpiu_name
242
+ try:
243
+ self.command(f'{tpiu_name} configure -protocol uart -traceclk {trace_clock_hz} -pin-freq {baudrate} -output :{trace_port}')
244
+ self.command(f'{tpiu_name} enable', timeout=30)
245
+ # Cortex-M ITM port setup. Target GPIO/clock routing belongs in its config.
246
+ self.command('mmw 0xE000EDFC 0x01000000 0; mww 0xE0000FB0 0xC5ACCE55; mww 0xE0000E80 0x00010001; mww 0xE0000E40 0; itm ports off')
247
+ for port in sorted(set(ports)):
248
+ self.command(f'itm port {port} on')
249
+ self.trace = socket.create_connection(('127.0.0.1', trace_port), timeout=5)
250
+ self.trace_port = trace_port
251
+ self.decoder = ItmDecoder()
252
+ return {'capturing': True, 'trace_clock_hz': trace_clock_hz, 'requested_baudrate': baudrate, 'itm_ports': sorted(set(ports)), 'trace_port': trace_port}
253
+ except (OSError, DeviceError) as exc:
254
+ try:
255
+ self.stop_swo()
256
+ except DeviceError:
257
+ pass
258
+ raise DeviceError(str(exc)) from exc
259
+
260
+ def read_swo(self, timeout_ms: int = 1000, max_bytes: int = 4096) -> dict:
261
+ if self.trace is None:
262
+ raise DeviceError('Start SWO capture first')
263
+ data = bytearray()
264
+ deadline = time.monotonic() + timeout_ms / 1000
265
+ try:
266
+ # timeout_ms=0 performs one nonblocking read of already buffered bytes.
267
+ while len(data) < max_bytes:
268
+ remaining = deadline - time.monotonic()
269
+ self.trace.settimeout(max(0, remaining))
270
+ try:
271
+ part = self.trace.recv(min(4096, max_bytes - len(data)))
272
+ except (socket.timeout, BlockingIOError):
273
+ break
274
+ if not part:
275
+ raise DeviceError('OpenOCD closed the SWO stream')
276
+ data.extend(part)
277
+ if remaining <= 0:
278
+ break
279
+ except OSError as exc:
280
+ raise DeviceError(f'SWO communication failed: {exc}') from exc
281
+ return {'length': len(data), 'base64': base64.b64encode(data).decode(), 'hex': data.hex(), **self.decoder.feed(data)}
282
+
283
+ def stop_swo(self) -> dict:
284
+ if self.trace:
285
+ self.trace.close()
286
+ self.trace = None
287
+ name, self.tpiu = self.tpiu, None
288
+ self.trace_port = None
289
+ if name and self.control:
290
+ self.command(f'{name} disable')
291
+ return {'capturing': False}
292
+
293
+ def stop(self, resume_target: bool = True) -> dict:
294
+ try:
295
+ self.stop_swo()
296
+ if self.control and resume_target:
297
+ if self.command('[target current] curstate') == 'halted':
298
+ self.command('resume')
299
+ if self.control:
300
+ try:
301
+ self.command('shutdown')
302
+ except DeviceError:
303
+ pass # OpenOCD can close Tcl without returning a shutdown reply.
304
+ finally:
305
+ self.close()
306
+ return {'running': False}
307
+
308
+ def close(self) -> None:
309
+ for stream in (self.trace, self.control):
310
+ if stream:
311
+ stream.close()
312
+ self.trace = self.control = None
313
+ if self.process:
314
+ if self.process.poll() is None:
315
+ try:
316
+ self.process.wait(timeout=1)
317
+ except subprocess.TimeoutExpired:
318
+ self.process.terminate()
319
+ try:
320
+ self.process.wait(timeout=3)
321
+ except subprocess.TimeoutExpired:
322
+ self.process.kill()
323
+ self.process.wait(timeout=3)
324
+ self.process = None
325
+ self.tpiu = None
326
+ self.gdb_port = self.tcl_port = self.trace_port = None
327
+ if self.log_path:
328
+ try:
329
+ self.log_path.unlink(missing_ok=True)
330
+ except OSError:
331
+ pass
332
+ self.log_path = None