mpy-workbench 0.2.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.
- mpy_workbench-0.2.0.dist-info/METADATA +85 -0
- mpy_workbench-0.2.0.dist-info/RECORD +14 -0
- mpy_workbench-0.2.0.dist-info/WHEEL +5 -0
- mpy_workbench-0.2.0.dist-info/entry_points.txt +3 -0
- mpy_workbench-0.2.0.dist-info/top_level.txt +1 -0
- mpywb/__init__.py +5 -0
- mpywb/board.py +371 -0
- mpywb/cli.py +125 -0
- mpywb/codegen.py +177 -0
- mpywb/deps.py +79 -0
- mpywb/linkclient.py +278 -0
- mpywb/mcp_server.py +230 -0
- mpywb/sync.py +101 -0
- mpywb/tools.py +282 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mpy-workbench
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Run, upload and debug MicroPython on a board over USB, from the terminal or any MCP client (Claude Code, Cursor…).
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/DanielBustillos/mpy-workbench/tree/main/plugin
|
|
7
|
+
Project-URL: Repository, https://github.com/DanielBustillos/mpy-workbench
|
|
8
|
+
Project-URL: Issues, https://github.com/DanielBustillos/mpy-workbench/issues
|
|
9
|
+
Keywords: micropython,esp32,raspberry-pi-pico,mpremote,mcp
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: mpremote>=1.26
|
|
13
|
+
|
|
14
|
+
# MPY Workbench for Claude Code
|
|
15
|
+
|
|
16
|
+
<!-- mcp-name: io.github.DanielBustillos/mpy-workbench -->
|
|
17
|
+
|
|
18
|
+
Let Claude run, upload and debug MicroPython on your board. Plug in an ESP32, a Raspberry Pi Pico or another MicroPython board, and ask: *"make the LED blink every half second"*. Claude writes the code, runs it on the board, reads the output and the traceback, and fixes it.
|
|
19
|
+
|
|
20
|
+
No VS Code needed. The only requirement is Python 3.8 or newer: everything else (mpremote) is installed on first use, in a folder of its own.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
In Claude Code:
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
/plugin marketplace add DanielBustillos/mpy-workbench
|
|
28
|
+
/plugin install mpy-workbench@mpy-workbench
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## What Claude can do
|
|
32
|
+
|
|
33
|
+
| Tool | What it does |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `run_file` | Uploads the file if it changed, runs it, returns output and traceback |
|
|
36
|
+
| `run_code` | Runs a few lines, like the REPL |
|
|
37
|
+
| `read_output` / `stop` | Watches or stops a program that keeps running |
|
|
38
|
+
| `upload` | Uploads a file or folder; only what changed, checked by SHA-256 |
|
|
39
|
+
| `sync` / `diff` | Makes the board match the project folder, or shows what differs (with a line diff for one file) |
|
|
40
|
+
| `list_files` / `read_file` | Looks at the board's files |
|
|
41
|
+
| `board_info` / `list_ports` | Chip, MicroPython version, memory, ports |
|
|
42
|
+
| `soft_reset` | Clears memory and imported modules |
|
|
43
|
+
|
|
44
|
+
Project files keep their path on the board: `lib/util.py` here is `/lib/util.py` there.
|
|
45
|
+
|
|
46
|
+
## The board follows the project
|
|
47
|
+
|
|
48
|
+
- **Auto-upload:** in a MicroPython project (one with a `.mpy-workbench/` folder or a `.mpyignore` file), every file Claude writes or edits goes to the board right away, and Claude is told. Other projects are never touched. Set `MPYWB_AUTO_UPLOAD=1` to do it in any project, or `0` to turn it off.
|
|
49
|
+
- **Ignore rules:** `.mpyignore` (or `.mpy-workbench/.mpyignore`, the one the VS Code extension uses) lists what stays off the board, one pattern per line: `*.md`, `docs/`, `/secret.py`, `**/test_*`. `.git`, `node_modules`, `__pycache__` and similar are always skipped.
|
|
50
|
+
- **Sync:** `sync` uploads every file that differs; files that are only on the board are kept unless you ask to delete them (`dry_run` shows the plan first).
|
|
51
|
+
|
|
52
|
+
## From the terminal
|
|
53
|
+
|
|
54
|
+
The same tool works without Claude:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install mpy-workbench # or run python3 plugin/bin/mpywb without installing
|
|
58
|
+
mpywb run main.py
|
|
59
|
+
mpywb diff # what differs between the project and the board
|
|
60
|
+
mpywb sync --dry-run # what sync would upload
|
|
61
|
+
mpywb --help
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Other MCP clients (Cursor, VS Code Copilot, Windsurf…)
|
|
65
|
+
|
|
66
|
+
The board tools are a standard MCP server on stdio:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{ "mcpServers": { "micropython-board": { "command": "uvx", "args": ["mpy-workbench", "mcp"] } } }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
(or `"command": "mpywb", "args": ["mcp"]` after `pip install mpy-workbench`).
|
|
73
|
+
|
|
74
|
+
## With VS Code
|
|
75
|
+
|
|
76
|
+
The [MPY Workbench extension](https://marketplace.visualstudio.com/items?itemName=DanielBucam.mpy-workbench) keeps the port open while VS Code works with the board. From version 0.4.5 it shares it: Claude's calls go through VS Code, and what Claude runs shows in the **MPY Board** terminal. With an older version, run **MPY Workbench: Release Serial Port** there first.
|
|
77
|
+
|
|
78
|
+
## Windows
|
|
79
|
+
|
|
80
|
+
The plugin starts `python3`. If your Python is called `python` or `py`, set `MPYWB_PYTHON` (for example in the `env` section of Claude Code's `settings.json`: `"MPYWB_PYTHON": "python"`).
|
|
81
|
+
|
|
82
|
+
## Limits
|
|
83
|
+
|
|
84
|
+
- Boards with a USB-serial chip (CP210x, CH340, FTDI: many ESP32 dev boards) open with DTR and RTS low, so opening the port doesn't reset them. If a board needs the old behaviour, set `MPYWB_RESET_ON_OPEN=1`.
|
|
85
|
+
- Tested with a board on macOS (ESP32-S3). Windows and Linux are covered by the automatic tests, without a board.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
mpywb/__init__.py,sha256=Zu0tCdmm6seaJrj3Mv3FYnA6MfvN8I8WFcgDHLgneJ8,222
|
|
2
|
+
mpywb/board.py,sha256=hTLyXhsC8NqAGrIGum_lKzPjtCb2bGijuljLSRUlpXM,13968
|
|
3
|
+
mpywb/cli.py,sha256=P-mZ4AMgSFzPd9rquWQTuyzSHE2eu6KCTK9x1hetFjQ,5073
|
|
4
|
+
mpywb/codegen.py,sha256=82G931P1i7voTO7lLUA0I1SyDojt_bcRr4rTP10K2Lk,5722
|
|
5
|
+
mpywb/deps.py,sha256=MXFDfm-3Q1H-wCjBfT7Bq5zdAb2cXlIa4NUgZ-4m5Qg,2942
|
|
6
|
+
mpywb/linkclient.py,sha256=0RYZMqQ3rL_PDhLmx1atncEaD9EcKwxsJPv0XRXTc3c,9826
|
|
7
|
+
mpywb/mcp_server.py,sha256=vbdpKrS8wfD1GgSrMxJmzIT56GICSCN5s9pGWjwRAFY,10891
|
|
8
|
+
mpywb/sync.py,sha256=lkPLNgA7KqyMI1cCPxclNfL8jyEb64PW55VEZJjJ1Ao,3947
|
|
9
|
+
mpywb/tools.py,sha256=bEP5bQ1HypUzD-i6YXhlBwo0LAJ91wFAKwKu11QHaZs,11634
|
|
10
|
+
mpy_workbench-0.2.0.dist-info/METADATA,sha256=sf2-pi_A1qQYcst-lq1vwWQToYFtd-fSN8JkcOsfCWg,4288
|
|
11
|
+
mpy_workbench-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
mpy_workbench-0.2.0.dist-info/entry_points.txt,sha256=ki7yov584tp62VuosMbOadx4RyeUfPmGexmaVw7ylhI,72
|
|
13
|
+
mpy_workbench-0.2.0.dist-info/top_level.txt,sha256=Q-JnK9MLdqdVgZfapb7TMK8YykpESTZKlPgno9tMsus,6
|
|
14
|
+
mpy_workbench-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mpywb
|
mpywb/__init__.py
ADDED
mpywb/board.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Talks to a MicroPython board over its serial port with mpremote's own transport.
|
|
2
|
+
|
|
3
|
+
Each operation opens the port, does its work and closes it again, so other tools (the
|
|
4
|
+
VS Code extension, Thonny, a serial monitor) can use the board between calls. A program
|
|
5
|
+
started with run(..., stop_at_timeout=False) keeps running after the port is closed;
|
|
6
|
+
the next operation that needs the REPL stops it with Ctrl-C.
|
|
7
|
+
"""
|
|
8
|
+
import contextlib
|
|
9
|
+
import hashlib
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from . import deps
|
|
14
|
+
from .codegen import (clean_traceback, hashes_code, info_code, make_dirs_code, parse_hashes, parse_info,
|
|
15
|
+
parse_walk, split_raw_output, walk_code)
|
|
16
|
+
|
|
17
|
+
# USB vendor IDs of boards and USB-serial chips MicroPython boards use
|
|
18
|
+
KNOWN_VIDS = {
|
|
19
|
+
0x2E8A: "Raspberry Pi",
|
|
20
|
+
0x303A: "Espressif",
|
|
21
|
+
0x10C4: "Silicon Labs CP210x",
|
|
22
|
+
0x1A86: "WCH CH340",
|
|
23
|
+
0x0403: "FTDI",
|
|
24
|
+
0xF055: "MicroPython",
|
|
25
|
+
0x239A: "Adafruit",
|
|
26
|
+
0x1B4F: "SparkFun",
|
|
27
|
+
0x2341: "Arduino",
|
|
28
|
+
}
|
|
29
|
+
MAX_OUTPUT = 64 * 1024
|
|
30
|
+
|
|
31
|
+
# USB-serial bridge chips. On many ESP32 dev boards they drive EN/IO0 from DTR/RTS, and
|
|
32
|
+
# pyserial raises both lines one after the other when it opens the port: the board
|
|
33
|
+
# resets and main.py starts again. Native-USB boards (ESP32-S3, Pico) need DTR to talk.
|
|
34
|
+
BRIDGE_VIDS = {0x10C4, 0x1A86, 0x0403}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BoardError(Exception):
|
|
38
|
+
"""Something the user (or the agent) can act on; the message says what."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def list_ports():
|
|
42
|
+
deps.ensure()
|
|
43
|
+
from serial.tools import list_ports as lp
|
|
44
|
+
|
|
45
|
+
out = []
|
|
46
|
+
for p in lp.comports():
|
|
47
|
+
vid = getattr(p, "vid", None)
|
|
48
|
+
out.append({
|
|
49
|
+
"port": p.device,
|
|
50
|
+
"description": p.description or "",
|
|
51
|
+
"maker": KNOWN_VIDS.get(vid, ""),
|
|
52
|
+
"likely_micropython": vid in KNOWN_VIDS,
|
|
53
|
+
})
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def pick_port(port=None):
|
|
58
|
+
"""The port to use: the one given, $MPYWB_PORT, or the only board plugged in."""
|
|
59
|
+
port = port or os.environ.get("MPYWB_PORT")
|
|
60
|
+
if port:
|
|
61
|
+
return port
|
|
62
|
+
likely = [p for p in list_ports() if p["likely_micropython"]]
|
|
63
|
+
if len(likely) == 1:
|
|
64
|
+
return likely[0]["port"]
|
|
65
|
+
if not likely:
|
|
66
|
+
raise BoardError("No MicroPython board found on USB. Plug it in (with a data cable), or pass the port explicitly; list_ports shows every serial port.")
|
|
67
|
+
raise BoardError("Several boards are plugged in: %s. Say which port to use." % ", ".join(p["port"] for p in likely))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _port_error(port, e):
|
|
71
|
+
text = str(e)
|
|
72
|
+
low = text.lower()
|
|
73
|
+
if "busy" in low or "lock" in low or "failed to access" in low or "access is denied" in low or "permission" in low and "denied" in low and os.name == "nt":
|
|
74
|
+
return ("The port %s is in use by another program. If it is VS Code with MPY Workbench, update the "
|
|
75
|
+
"extension to 0.4.5 or newer (it then shares the board with this plugin) or run \"MPY Workbench: "
|
|
76
|
+
"Release Serial Port\" there; otherwise close Thonny, a serial monitor or another mpremote. (%s)" % (port, text))
|
|
77
|
+
if "permission denied" in low:
|
|
78
|
+
return "No permission to open %s. On Linux, add yourself to the dialout group (then log in again). (%s)" % (port, text)
|
|
79
|
+
if "no such file" in low or "could not open port" in low or "filenotfound" in low:
|
|
80
|
+
return "The port %s does not exist (anymore). Is the board plugged in? (%s)" % (port, text)
|
|
81
|
+
return "Could not open %s: %s" % (port, text)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _Pushback:
|
|
85
|
+
"""The serial port with room to give bytes back. run() reads output in chunks, so it
|
|
86
|
+
may read past the end of a command; mpremote expects the raw REPL's ">" prompt that
|
|
87
|
+
follows to still be there for the next command, so run() puts it back."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, ser):
|
|
90
|
+
object.__setattr__(self, "ser", ser)
|
|
91
|
+
object.__setattr__(self, "buf", bytearray())
|
|
92
|
+
|
|
93
|
+
def __getattr__(self, name):
|
|
94
|
+
return getattr(self.ser, name)
|
|
95
|
+
|
|
96
|
+
def __setattr__(self, name, value):
|
|
97
|
+
setattr(self.ser, name, value)
|
|
98
|
+
|
|
99
|
+
def unread(self, data):
|
|
100
|
+
self.buf[0:0] = data
|
|
101
|
+
|
|
102
|
+
def read(self, n=1):
|
|
103
|
+
if self.buf:
|
|
104
|
+
out = bytes(self.buf[:n])
|
|
105
|
+
del self.buf[: len(out)]
|
|
106
|
+
if len(out) < n and self.ser.in_waiting:
|
|
107
|
+
out += self.ser.read(min(n - len(out), self.ser.in_waiting))
|
|
108
|
+
return out
|
|
109
|
+
return self.ser.read(n)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def in_waiting(self):
|
|
113
|
+
return len(self.buf) + self.ser.in_waiting
|
|
114
|
+
|
|
115
|
+
def inWaiting(self):
|
|
116
|
+
return self.in_waiting
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _fs_error(path, e):
|
|
120
|
+
import errno
|
|
121
|
+
|
|
122
|
+
if getattr(e, "errno", None) == errno.ENOENT or isinstance(e, FileNotFoundError):
|
|
123
|
+
return "No such file or folder on the board: %s" % path
|
|
124
|
+
if getattr(e, "errno", None) in (errno.EISDIR, errno.ENOTDIR):
|
|
125
|
+
return "%s on the board is %s" % (path, "a folder" if e.errno == errno.EISDIR else "not a folder")
|
|
126
|
+
return "%s on the board: %s" % (path, e)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _port_vid(port):
|
|
130
|
+
try:
|
|
131
|
+
from serial.tools import list_ports as lp
|
|
132
|
+
|
|
133
|
+
for p in lp.comports():
|
|
134
|
+
if p.device == port:
|
|
135
|
+
return getattr(p, "vid", None)
|
|
136
|
+
except Exception:
|
|
137
|
+
pass
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def keep_lines_low(vid):
|
|
142
|
+
"""True when the port should open with DTR and RTS low (USB-serial bridge chips).
|
|
143
|
+
MPYWB_RESET_ON_OPEN=1 keeps pyserial's default (both high)."""
|
|
144
|
+
return vid in BRIDGE_VIDS and os.environ.get("MPYWB_RESET_ON_OPEN") != "1"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@contextlib.contextmanager
|
|
148
|
+
def no_reset_on_open(enabled):
|
|
149
|
+
"""While active, serial ports created by serial_for_url (as mpremote does, before
|
|
150
|
+
opening them) start with DTR and RTS low, so opening them doesn't reset the board."""
|
|
151
|
+
if not enabled:
|
|
152
|
+
yield
|
|
153
|
+
return
|
|
154
|
+
import serial
|
|
155
|
+
|
|
156
|
+
original = serial.serial_for_url
|
|
157
|
+
|
|
158
|
+
def quiet(url, *args, **kwargs):
|
|
159
|
+
s = original(url, *args, **kwargs)
|
|
160
|
+
if not s.is_open:
|
|
161
|
+
s.dtr = False
|
|
162
|
+
s.rts = False
|
|
163
|
+
return s
|
|
164
|
+
|
|
165
|
+
serial.serial_for_url = quiet
|
|
166
|
+
try:
|
|
167
|
+
yield
|
|
168
|
+
finally:
|
|
169
|
+
serial.serial_for_url = original
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class Board:
|
|
173
|
+
def __init__(self, port):
|
|
174
|
+
deps.ensure()
|
|
175
|
+
from mpremote.transport_serial import SerialTransport
|
|
176
|
+
|
|
177
|
+
self.port = port
|
|
178
|
+
try:
|
|
179
|
+
with no_reset_on_open(keep_lines_low(_port_vid(port))):
|
|
180
|
+
self.t = SerialTransport(port, baudrate=115200, exclusive=True)
|
|
181
|
+
except Exception as e: # serial.SerialException, OSError…
|
|
182
|
+
raise BoardError(_port_error(port, e))
|
|
183
|
+
self.t.serial = _Pushback(self.t.serial)
|
|
184
|
+
self.in_raw = False
|
|
185
|
+
self.leave_running = False
|
|
186
|
+
|
|
187
|
+
def __enter__(self):
|
|
188
|
+
return self
|
|
189
|
+
|
|
190
|
+
def __exit__(self, *exc):
|
|
191
|
+
self.close()
|
|
192
|
+
|
|
193
|
+
def close(self):
|
|
194
|
+
try:
|
|
195
|
+
if self.in_raw and not self.leave_running:
|
|
196
|
+
self.t.exit_raw_repl() # back to the normal REPL, as other tools expect
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
try:
|
|
200
|
+
self.t.close()
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
|
|
204
|
+
def _raw(self):
|
|
205
|
+
if not self.in_raw:
|
|
206
|
+
from mpremote.transport import TransportError
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
self.t.enter_raw_repl(soft_reset=False) # Ctrl-C first: stops a running program
|
|
210
|
+
except TransportError as e:
|
|
211
|
+
raise BoardError("The board on %s does not answer (is it running MicroPython?): %s" % (self.port, e))
|
|
212
|
+
self.in_raw = True
|
|
213
|
+
|
|
214
|
+
def exec_quiet(self, code):
|
|
215
|
+
"""Runs short helper code and returns its output; raises BoardError if it fails."""
|
|
216
|
+
r = self.run(code, timeout=10, stop_at_timeout=True)
|
|
217
|
+
if r["error"]:
|
|
218
|
+
raise BoardError(r["error"].strip())
|
|
219
|
+
return r["output"]
|
|
220
|
+
|
|
221
|
+
def run(self, code, timeout=10.0, stop_at_timeout=False):
|
|
222
|
+
"""Runs `code` on the board and waits for it to end, at most `timeout` seconds.
|
|
223
|
+
Then either stops it with Ctrl-C (stop_at_timeout) or leaves it running.
|
|
224
|
+
Returns output (stdout), error (traceback), finished, still_running, stopped."""
|
|
225
|
+
self._raw()
|
|
226
|
+
self.t.exec_raw_no_follow(code)
|
|
227
|
+
ser = self.t.serial
|
|
228
|
+
data = bytearray()
|
|
229
|
+
deadline = time.monotonic() + timeout
|
|
230
|
+
stop_deadline = None
|
|
231
|
+
stopped = False
|
|
232
|
+
while True:
|
|
233
|
+
n = ser.in_waiting
|
|
234
|
+
if n:
|
|
235
|
+
data.extend(ser.read(n))
|
|
236
|
+
if len(data) > 2 * MAX_OUTPUT:
|
|
237
|
+
# keep the end; the markers we look for are always at the end
|
|
238
|
+
del data[: len(data) - MAX_OUTPUT]
|
|
239
|
+
else:
|
|
240
|
+
time.sleep(0.01)
|
|
241
|
+
out, err, done = split_raw_output(bytes(data))
|
|
242
|
+
if done:
|
|
243
|
+
end = bytes(data).index(b"\x04", bytes(data).index(b"\x04") + 1) + 1
|
|
244
|
+
ser.unread(bytes(data[end:])) # the ">" prompt: mpremote reads it next
|
|
245
|
+
break
|
|
246
|
+
now = time.monotonic()
|
|
247
|
+
if stop_deadline is None and now >= deadline:
|
|
248
|
+
if not stop_at_timeout:
|
|
249
|
+
self.leave_running = True
|
|
250
|
+
return self._result(out, err, finished=False, still_running=True, stopped=False)
|
|
251
|
+
ser.write(b"\x03")
|
|
252
|
+
stopped = True
|
|
253
|
+
stop_deadline = now + 5
|
|
254
|
+
elif stop_deadline is not None and now >= stop_deadline:
|
|
255
|
+
raise BoardError("The program did not stop after Ctrl-C. Reset the board (press its reset button).")
|
|
256
|
+
return self._result(out, err, finished=True, still_running=False, stopped=stopped)
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def _result(out, err, finished, still_running, stopped):
|
|
260
|
+
def text(b):
|
|
261
|
+
s = b.decode("utf-8", "replace").replace("\r\n", "\n")
|
|
262
|
+
return s if len(s) <= MAX_OUTPUT else "…(earlier output cut)\n" + s[-MAX_OUTPUT:]
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
"output": text(out),
|
|
266
|
+
"error": clean_traceback(text(err)),
|
|
267
|
+
"finished": finished,
|
|
268
|
+
"still_running": still_running,
|
|
269
|
+
"stopped": stopped,
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
def stop(self):
|
|
273
|
+
"""Stops a running program (Ctrl-C) and leaves the board at the normal REPL."""
|
|
274
|
+
self._raw()
|
|
275
|
+
|
|
276
|
+
def soft_reset(self):
|
|
277
|
+
"""Soft reset: clears the program's state and memory (boot.py runs, main.py does not)."""
|
|
278
|
+
self.t.enter_raw_repl(soft_reset=True)
|
|
279
|
+
self.in_raw = True
|
|
280
|
+
|
|
281
|
+
def watch(self, seconds):
|
|
282
|
+
"""Reads what a running program prints, for `seconds`, without stopping it."""
|
|
283
|
+
ser = self.t.serial
|
|
284
|
+
data = bytearray()
|
|
285
|
+
end = time.monotonic() + seconds
|
|
286
|
+
while time.monotonic() < end:
|
|
287
|
+
n = ser.in_waiting
|
|
288
|
+
if n:
|
|
289
|
+
data.extend(ser.read(n))
|
|
290
|
+
else:
|
|
291
|
+
time.sleep(0.02)
|
|
292
|
+
self.leave_running = True
|
|
293
|
+
return data.decode("utf-8", "replace").replace("\r\n", "\n")[-MAX_OUTPUT:]
|
|
294
|
+
|
|
295
|
+
def info(self):
|
|
296
|
+
return parse_info(self.exec_quiet(info_code()))
|
|
297
|
+
|
|
298
|
+
def board_sha256(self, path):
|
|
299
|
+
"""Hex SHA-256 of a board file, None if missing, "" if the board can't hash."""
|
|
300
|
+
self._raw()
|
|
301
|
+
try:
|
|
302
|
+
if not self.t.fs_exists(path):
|
|
303
|
+
return None
|
|
304
|
+
return self.t.fs_hashfile(path, "sha256").hex()
|
|
305
|
+
except Exception as e:
|
|
306
|
+
if "hashlib" in str(e) or "sha256" in str(e) or "AttributeError" in str(e):
|
|
307
|
+
return ""
|
|
308
|
+
raise
|
|
309
|
+
|
|
310
|
+
def put(self, local_path, device_path, board_sha=False):
|
|
311
|
+
"""Uploads one file unless the board already has the same bytes. The board copy
|
|
312
|
+
is checked by hash afterwards. Returns "uploaded" or "unchanged".
|
|
313
|
+
board_sha: the board file's hash when the caller already knows it (None = missing)."""
|
|
314
|
+
with open(local_path, "rb") as f:
|
|
315
|
+
data = f.read()
|
|
316
|
+
want = hashlib.sha256(data).hexdigest()
|
|
317
|
+
have = self.board_sha256(device_path) if board_sha is False else board_sha
|
|
318
|
+
if have == want:
|
|
319
|
+
return "unchanged"
|
|
320
|
+
parent = device_path.rsplit("/", 1)[0]
|
|
321
|
+
if parent:
|
|
322
|
+
self.exec_quiet(make_dirs_code(parent))
|
|
323
|
+
self._raw()
|
|
324
|
+
self.t.fs_writefile(device_path, data, chunk_size=256)
|
|
325
|
+
after = self.board_sha256(device_path)
|
|
326
|
+
if after not in ("", want):
|
|
327
|
+
raise BoardError("Upload of %s to %s did not verify (board hash %s, expected %s)." % (local_path, device_path, after, want))
|
|
328
|
+
return "uploaded"
|
|
329
|
+
|
|
330
|
+
def walk(self, root="/"):
|
|
331
|
+
"""({board path: size} of every file under root, set of folders), in one exec."""
|
|
332
|
+
return parse_walk(self.exec_quiet(walk_code(root)))
|
|
333
|
+
|
|
334
|
+
def hashes(self, paths, batch=40):
|
|
335
|
+
"""{board path: sha256 | None (missing) | "" (no hashlib)}, a few execs for many files."""
|
|
336
|
+
out = {}
|
|
337
|
+
paths = list(paths)
|
|
338
|
+
for i in range(0, len(paths), batch):
|
|
339
|
+
out.update(parse_hashes(self.run(hashes_code(paths[i:i + batch]), timeout=60, stop_at_timeout=True)["output"]))
|
|
340
|
+
return out
|
|
341
|
+
|
|
342
|
+
def delete(self, path):
|
|
343
|
+
self._raw()
|
|
344
|
+
try:
|
|
345
|
+
self.t.fs_rmfile(path)
|
|
346
|
+
except OSError as e:
|
|
347
|
+
raise BoardError(_fs_error(path, e))
|
|
348
|
+
|
|
349
|
+
def listdir(self, path):
|
|
350
|
+
self._raw()
|
|
351
|
+
out = []
|
|
352
|
+
try:
|
|
353
|
+
entries = self.t.fs_listdir(path)
|
|
354
|
+
except OSError as e:
|
|
355
|
+
raise BoardError(_fs_error(path, e))
|
|
356
|
+
for e in entries:
|
|
357
|
+
name = getattr(e, "name", None) or e[0]
|
|
358
|
+
mode = e[1]
|
|
359
|
+
size = e[3] if len(e) > 3 else 0
|
|
360
|
+
out.append({"name": name, "dir": bool(mode & 0x4000), "size": 0 if mode & 0x4000 else size})
|
|
361
|
+
out.sort(key=lambda x: (not x["dir"], x["name"].lower()))
|
|
362
|
+
return out
|
|
363
|
+
|
|
364
|
+
def read_text(self, path, limit=MAX_OUTPUT):
|
|
365
|
+
self._raw()
|
|
366
|
+
try:
|
|
367
|
+
data = self.t.fs_readfile(path)
|
|
368
|
+
except OSError as e:
|
|
369
|
+
raise BoardError(_fs_error(path, e))
|
|
370
|
+
text = data.decode("utf-8", "replace")
|
|
371
|
+
return text if len(text) <= limit else text[:limit] + "\n…(cut at %d characters)" % limit
|
mpywb/cli.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""mpywb: run and sync MicroPython code on a board from the terminal.
|
|
2
|
+
|
|
3
|
+
mpywb ports serial ports, and which look like boards
|
|
4
|
+
mpywb info MicroPython version, chip, free memory and flash
|
|
5
|
+
mpywb run main.py [--timeout 10] upload if changed, run, print output/traceback
|
|
6
|
+
mpywb exec "print(1+1)" run a few lines on the board
|
|
7
|
+
mpywb output [--seconds 3] what a running program prints, without stopping it
|
|
8
|
+
mpywb stop | reset Ctrl-C | soft reset
|
|
9
|
+
mpywb put lib/ upload changed files (checked by SHA-256)
|
|
10
|
+
mpywb ls [/lib] | cat /boot.py look at the board's files
|
|
11
|
+
mpywb diff [main.py] what differs between the project and the board
|
|
12
|
+
mpywb sync [--delete] [--dry-run] make the board match the project (.mpyignore applies)
|
|
13
|
+
mpywb mcp MCP server on stdio (for Claude Code and other agents)
|
|
14
|
+
|
|
15
|
+
--port picks the board (else $MPYWB_PORT, else the only board plugged in).
|
|
16
|
+
Exit codes: 0 done, 1 the program raised an error, 2 the tool could not do it.
|
|
17
|
+
"""
|
|
18
|
+
import argparse
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main(argv=None):
|
|
25
|
+
ap = argparse.ArgumentParser(prog="mpywb", description="Run and sync MicroPython code on a board.", epilog=__doc__.split("\n\n", 1)[1], formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
26
|
+
ap.add_argument("--port", help="serial port (default: $MPYWB_PORT or the only board plugged in)")
|
|
27
|
+
ap.add_argument("--version", action="version", version="mpywb " + __version__)
|
|
28
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
29
|
+
sub.add_parser("ports")
|
|
30
|
+
sub.add_parser("info")
|
|
31
|
+
p = sub.add_parser("run")
|
|
32
|
+
p.add_argument("file")
|
|
33
|
+
p.add_argument("--timeout", type=float, default=10)
|
|
34
|
+
p.add_argument("--stop", action="store_true", help="stop the program at the timeout instead of leaving it running")
|
|
35
|
+
p.add_argument("--device-path")
|
|
36
|
+
p = sub.add_parser("exec")
|
|
37
|
+
p.add_argument("code")
|
|
38
|
+
p.add_argument("--timeout", type=float, default=10)
|
|
39
|
+
p = sub.add_parser("output")
|
|
40
|
+
p.add_argument("--seconds", type=float, default=3)
|
|
41
|
+
sub.add_parser("stop")
|
|
42
|
+
sub.add_parser("reset")
|
|
43
|
+
p = sub.add_parser("put")
|
|
44
|
+
p.add_argument("path")
|
|
45
|
+
p.add_argument("--device-path")
|
|
46
|
+
p = sub.add_parser("ls")
|
|
47
|
+
p.add_argument("path", nargs="?", default="/")
|
|
48
|
+
p = sub.add_parser("cat")
|
|
49
|
+
p.add_argument("path")
|
|
50
|
+
p = sub.add_parser("diff")
|
|
51
|
+
p.add_argument("path", nargs="?")
|
|
52
|
+
p = sub.add_parser("sync")
|
|
53
|
+
p.add_argument("--delete", action="store_true", help="also delete board files that are not in the project")
|
|
54
|
+
p.add_argument("--dry-run", action="store_true", help="only say what would change")
|
|
55
|
+
sub.add_parser("mcp")
|
|
56
|
+
sub.add_parser("hook-upload", help=argparse.SUPPRESS)
|
|
57
|
+
a = ap.parse_args(argv)
|
|
58
|
+
|
|
59
|
+
if a.cmd == "hook-upload":
|
|
60
|
+
return _hook_upload()
|
|
61
|
+
if a.cmd == "mcp":
|
|
62
|
+
from .mcp_server import serve
|
|
63
|
+
serve()
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
from . import tools
|
|
67
|
+
from .board import BoardError
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
rc = 0
|
|
71
|
+
if a.cmd == "ports":
|
|
72
|
+
text = tools.tool_list_ports()
|
|
73
|
+
elif a.cmd == "info":
|
|
74
|
+
text = tools.tool_board_info(a.port)
|
|
75
|
+
elif a.cmd == "run":
|
|
76
|
+
text, r = tools.tool_run_file(a.file, a.port, a.timeout, a.stop, a.device_path)
|
|
77
|
+
rc = 1 if r["error"].strip() and not r["stopped"] else 0
|
|
78
|
+
elif a.cmd == "exec":
|
|
79
|
+
text, r = tools.tool_run_code(a.code, a.port, a.timeout)
|
|
80
|
+
rc = 1 if r["error"].strip() and not r["stopped"] else 0
|
|
81
|
+
elif a.cmd == "output":
|
|
82
|
+
text = tools.tool_read_output(a.port, a.seconds)
|
|
83
|
+
elif a.cmd == "stop":
|
|
84
|
+
text = tools.tool_stop(a.port)
|
|
85
|
+
elif a.cmd == "reset":
|
|
86
|
+
text = tools.tool_soft_reset(a.port)
|
|
87
|
+
elif a.cmd == "put":
|
|
88
|
+
text = tools.tool_upload(a.path, a.port, a.device_path)
|
|
89
|
+
elif a.cmd == "diff":
|
|
90
|
+
text = tools.tool_diff(a.path, a.port)
|
|
91
|
+
elif a.cmd == "sync":
|
|
92
|
+
text = tools.tool_sync(a.port, a.delete, a.dry_run)
|
|
93
|
+
elif a.cmd == "ls":
|
|
94
|
+
text = tools.tool_list_files(a.path, a.port)
|
|
95
|
+
else:
|
|
96
|
+
text = tools.tool_read_file(a.path, a.port)
|
|
97
|
+
except (BoardError, RuntimeError) as e:
|
|
98
|
+
print("mpywb: %s" % e, file=sys.stderr)
|
|
99
|
+
return 2
|
|
100
|
+
print(text)
|
|
101
|
+
return rc
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _hook_upload():
|
|
105
|
+
"""Claude Code PostToolUse hook (Edit/Write): uploads the edited file. Never fails the
|
|
106
|
+
tool call: problems become a note for Claude, and non-board projects are left alone."""
|
|
107
|
+
import json
|
|
108
|
+
|
|
109
|
+
from . import tools
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
event = json.load(sys.stdin)
|
|
113
|
+
except ValueError:
|
|
114
|
+
return 0
|
|
115
|
+
try:
|
|
116
|
+
note = tools.hook_upload(event)
|
|
117
|
+
except Exception as e: # never break Claude's edit because of the board
|
|
118
|
+
note = "Auto-upload skipped: %s" % e
|
|
119
|
+
if note:
|
|
120
|
+
print(json.dumps({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": note}}))
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
if __name__ == "__main__":
|
|
125
|
+
sys.exit(main())
|