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.
mpywb/codegen.py ADDED
@@ -0,0 +1,177 @@
1
+ """MicroPython code sent to the board, and parsing of what it prints. No serial port
2
+ or mpremote needed, so it is unit-tested."""
3
+ import re
4
+
5
+ # The runner's own frame means nothing to the user: tracebacks start at their file
6
+ STDIN_FRAME = re.compile(r' File "<stdin>", line \d+, in <module>\r?\n')
7
+
8
+
9
+ def py_str(s):
10
+ """A Python string literal that MicroPython reads back as `s`."""
11
+ return repr(str(s))
12
+
13
+
14
+ def run_file_code(device_path, trace_name):
15
+ """Runs the board copy of a file as __main__ (like Thonny): not imported, so
16
+ `if __name__ == "__main__":` blocks run and a file named like a built-in module is
17
+ not shadowed. Compiled under `trace_name` so tracebacks name the project file."""
18
+ return "\n".join([
19
+ "_s = open(%s).read()" % py_str(device_path),
20
+ "try:",
21
+ " _c = compile(_s, %s, 'exec')" % py_str(trace_name),
22
+ "except NameError:",
23
+ " _c = _s",
24
+ "del _s",
25
+ "exec(_c, {'__name__': '__main__'})",
26
+ ])
27
+
28
+
29
+ def make_dirs_code(directory):
30
+ """Creates `directory` and missing parents; existing folders are left alone."""
31
+ return "\n".join([
32
+ "import os",
33
+ "_p = ''",
34
+ "for _d in %s.strip('/').split('/'):" % py_str(directory),
35
+ " if not _d: continue",
36
+ " _p += '/' + _d",
37
+ " try:",
38
+ " os.mkdir(_p)",
39
+ " except OSError:",
40
+ " pass",
41
+ ])
42
+
43
+
44
+ INFO_MARK = "MPYWB_INFO"
45
+
46
+
47
+ def info_code():
48
+ return "\n".join([
49
+ "import sys, os, gc",
50
+ "gc.collect()",
51
+ "try:",
52
+ " _m = os.uname().machine",
53
+ "except Exception:",
54
+ " _m = sys.platform",
55
+ "try:",
56
+ " _s = os.statvfs('/')",
57
+ " _fs = '%d %d' % (_s[0] * _s[2], _s[0] * _s[3])",
58
+ "except Exception:",
59
+ " _fs = '0 0'",
60
+ "print(%s, sys.implementation.name, '.'.join(str(x) for x in sys.implementation.version[:3]), gc.mem_free(), _fs, _m)" % py_str(INFO_MARK),
61
+ ])
62
+
63
+
64
+ def parse_info(out):
65
+ for line in out.splitlines():
66
+ if line.startswith(INFO_MARK + " "):
67
+ # MARK implementation version mem_free fs_total fs_free machine (may have spaces)
68
+ parts = line.split(" ", 6)
69
+ if len(parts) == 7:
70
+ return {
71
+ "implementation": parts[1],
72
+ "version": parts[2],
73
+ "free_memory_bytes": int(parts[3]),
74
+ "flash_total_bytes": int(parts[4]),
75
+ "flash_free_bytes": int(parts[5]),
76
+ "machine": parts[6].strip(),
77
+ }
78
+ raise ValueError("unexpected board answer: %r" % out[:200])
79
+
80
+
81
+ def clean_traceback(err):
82
+ return STDIN_FRAME.sub("", err)
83
+
84
+
85
+ def split_raw_output(data):
86
+ """Splits what the raw REPL sends after a command: stdout, \\x04, stderr, \\x04.
87
+ Returns (stdout, stderr, complete)."""
88
+ first = data.find(b"\x04")
89
+ if first < 0:
90
+ return data, b"", False
91
+ second = data.find(b"\x04", first + 1)
92
+ if second < 0:
93
+ return data[:first], data[first + 1:], False
94
+ return data[:first], data[first + 1:second], True
95
+
96
+
97
+ WALK_MARK = "MPYWB_WALK"
98
+
99
+
100
+ def walk_code(root="/"):
101
+ """Prints every folder and file under `root` on the board, with file sizes."""
102
+ r = "" if root in ("", "/") else "/" + root.strip("/")
103
+ return "\n".join([
104
+ "import os",
105
+ "def _w(p):",
106
+ " for e in os.ilistdir(p or '/'):",
107
+ " f = p + '/' + e[0]",
108
+ " if e[1] & 0x4000:",
109
+ " print(%s + ' D ' + f)" % py_str(WALK_MARK),
110
+ " _w(f)",
111
+ " else:",
112
+ " s = e[3] if len(e) > 3 and e[3] >= 0 else os.stat(f)[6]",
113
+ " print(%s + ' F ' + str(s) + ' ' + f)" % py_str(WALK_MARK),
114
+ "try:",
115
+ " _w(%s)" % py_str(r),
116
+ "except OSError:",
117
+ " pass",
118
+ ])
119
+
120
+
121
+ def parse_walk(out):
122
+ """{board path: size} for files, and the set of folders."""
123
+ files, dirs = {}, set()
124
+ for line in out.splitlines():
125
+ line = line.rstrip("\r")
126
+ if not line.startswith(WALK_MARK + " "):
127
+ continue
128
+ rest = line[len(WALK_MARK) + 1:]
129
+ if rest.startswith("D "):
130
+ dirs.add(rest[2:])
131
+ elif rest.startswith("F "):
132
+ size, _, path = rest[2:].partition(" ")
133
+ if size.isdigit() and path:
134
+ files[path] = int(size)
135
+ return files, dirs
136
+
137
+
138
+ HASH_MARK = "MPYWB_HASH"
139
+
140
+
141
+ def hashes_code(paths):
142
+ """Prints the SHA-256 of each board file: MPYWB_HASH:<sha|missing|nohash>:<path>."""
143
+ return "\n".join([
144
+ "try:",
145
+ " import hashlib, binascii",
146
+ "except ImportError:",
147
+ " hashlib = None",
148
+ "for _p in %s:" % repr([str(p) for p in paths]),
149
+ " try:",
150
+ " _f = open(_p, 'rb')",
151
+ " except OSError:",
152
+ " print(%s + ':missing:' + _p)" % py_str(HASH_MARK),
153
+ " continue",
154
+ " if hashlib is None or not hasattr(hashlib, 'sha256'):",
155
+ " _f.close()",
156
+ " print(%s + ':nohash:' + _p)" % py_str(HASH_MARK),
157
+ " continue",
158
+ " _h = hashlib.sha256()",
159
+ " while True:",
160
+ " _b = _f.read(512)",
161
+ " if not _b: break",
162
+ " _h.update(_b)",
163
+ " _f.close()",
164
+ " print(%s + ':' + binascii.hexlify(_h.digest()).decode() + ':' + _p)" % py_str(HASH_MARK),
165
+ ])
166
+
167
+
168
+ def parse_hashes(out):
169
+ """{board path: sha256 hex, None (missing) or "" (board can't hash)}."""
170
+ result = {}
171
+ for line in out.splitlines():
172
+ line = line.rstrip("\r")
173
+ if not line.startswith(HASH_MARK + ":"):
174
+ continue
175
+ value, _, path = line[len(HASH_MARK) + 1:].partition(":")
176
+ result[path] = None if value == "missing" else ("" if value == "nohash" else value.lower())
177
+ return result
mpywb/deps.py ADDED
@@ -0,0 +1,79 @@
1
+ """Makes mpremote (and pyserial) importable, installing them on first use.
2
+
3
+ They go into a folder of their own, never into the user's Python:
4
+ $CLAUDE_PLUGIN_DATA/pylib-<python version> when run by the Claude Code plugin
5
+ ~/.cache/mpy-workbench/pylib-<python version> otherwise
6
+ A recent enough mpremote already installed in the user's Python is used as is.
7
+ """
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+
13
+ MIN_MPREMOTE = (1, 26)
14
+ PACKAGES = ["mpremote>=1.26"]
15
+
16
+
17
+ def lib_dir():
18
+ base = os.environ.get("CLAUDE_PLUGIN_DATA") or os.path.join(os.path.expanduser("~"), ".cache", "mpy-workbench")
19
+ return os.path.join(base, "pylib-%d.%d" % sys.version_info[:2])
20
+
21
+
22
+ def _version_tuple(v):
23
+ out = []
24
+ for part in v.split(".")[:2]:
25
+ digits = "".join(ch for ch in part if ch.isdigit())
26
+ out.append(int(digits or 0))
27
+ return tuple(out)
28
+
29
+
30
+ def _usable():
31
+ try:
32
+ from importlib.metadata import version
33
+ import mpremote.transport_serial # noqa: F401
34
+ import serial.tools.list_ports # noqa: F401
35
+ return _version_tuple(version("mpremote")) >= MIN_MPREMOTE
36
+ except Exception:
37
+ return False
38
+
39
+
40
+ def _forget_modules():
41
+ for name in list(sys.modules):
42
+ if name == "mpremote" or name.startswith("mpremote.") or name == "serial" or name.startswith("serial."):
43
+ del sys.modules[name]
44
+
45
+
46
+ def _install(target, log):
47
+ os.makedirs(target, exist_ok=True)
48
+ uv = shutil.which("uv")
49
+ attempts = []
50
+ attempts.append([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--upgrade", "--target", target] + PACKAGES)
51
+ if uv:
52
+ attempts.append([uv, "pip", "install", "--quiet", "--python", sys.executable, "--target", target] + PACKAGES)
53
+ errors = []
54
+ for cmd in attempts:
55
+ log("mpy-workbench: installing %s into %s (first use only)..." % (", ".join(PACKAGES), target))
56
+ r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
57
+ if r.returncode == 0:
58
+ return
59
+ errors.append("%s: %s" % (os.path.basename(cmd[0]), (r.stderr or r.stdout).strip().splitlines()[-1:] or ["failed"]))
60
+ raise RuntimeError(
61
+ "Could not install mpremote automatically (%s). Install it yourself with: %s -m pip install -U mpremote"
62
+ % ("; ".join(str(e) for e in errors), sys.executable)
63
+ )
64
+
65
+
66
+ def ensure(log=lambda msg: print(msg, file=sys.stderr)):
67
+ """Makes `import mpremote` work. Raises RuntimeError with what to do if it can't."""
68
+ target = lib_dir()
69
+ if os.path.isdir(target) and target not in sys.path:
70
+ sys.path.insert(0, target)
71
+ _forget_modules()
72
+ if _usable():
73
+ return
74
+ _install(target, log)
75
+ if target not in sys.path:
76
+ sys.path.insert(0, target)
77
+ _forget_modules()
78
+ if not _usable():
79
+ raise RuntimeError("mpremote was installed into %s but can't be imported by %s" % (target, sys.executable))
mpywb/linkclient.py ADDED
@@ -0,0 +1,278 @@
1
+ """Uses the board through VS Code's MPY Workbench extension when it holds the port.
2
+
3
+ The extension keeps the port open in a "board link" process and shares it on 127.0.0.1
4
+ (see python/mpywb_link.py in the extension). LinkBoard offers the same methods as
5
+ board.Board, so the tools work the same whether the port is free or VS Code has it, and
6
+ VS Code's MPY Board terminal shows what the plugin runs.
7
+ """
8
+ import base64
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import queue
13
+ import re
14
+ import socket
15
+ import threading
16
+ import time
17
+
18
+ from .codegen import hashes_code, info_code, make_dirs_code, parse_hashes, parse_info, parse_walk, walk_code, clean_traceback
19
+
20
+ MAX_OUTPUT = 64 * 1024
21
+
22
+
23
+ def links_dir():
24
+ return os.path.join(os.path.expanduser("~"), ".mpy-workbench", "links")
25
+
26
+
27
+ def link_file(port):
28
+ """Same rule as link_file() in the extension's mpywb_link.py."""
29
+ name = re.sub(r"[^A-Za-z0-9._-]", "_", port).strip("_") or "port"
30
+ return os.path.join(links_dir(), name + "-" + hashlib.sha256(port.encode("utf-8")).hexdigest()[:8] + ".json")
31
+
32
+
33
+ def _alive(pid):
34
+ if os.name == "nt":
35
+ return True # checked by connecting
36
+ try:
37
+ os.kill(pid, 0)
38
+ return True
39
+ except ProcessLookupError:
40
+ return False
41
+ except OSError:
42
+ return True
43
+
44
+
45
+ def find_link(port):
46
+ """The shared link for `port` ({"tcp_port", "token", "pid"}), or None."""
47
+ if os.environ.get("MPYWB_USE_LINK") == "0":
48
+ return None
49
+ try:
50
+ with open(link_file(port), encoding="utf-8") as f:
51
+ info = json.load(f)
52
+ except (OSError, ValueError):
53
+ return None
54
+ if info.get("port") != port or not _alive(int(info.get("pid") or 0)):
55
+ return None
56
+ try:
57
+ socket.create_connection(("127.0.0.1", int(info["tcp_port"])), timeout=1).close()
58
+ except OSError:
59
+ return None
60
+ return info
61
+
62
+
63
+ class LinkError(Exception):
64
+ pass
65
+
66
+
67
+ class _Conn:
68
+ """One request to the link. A thread reads the answer lines, so waiting for the next
69
+ one can time out without breaking the connection."""
70
+
71
+ def __init__(self, info, request):
72
+ self.sock = socket.create_connection(("127.0.0.1", int(info["tcp_port"])), timeout=5)
73
+ self.sock.settimeout(None)
74
+ msg = dict(request, token=info["token"])
75
+ self.sock.sendall((json.dumps(msg) + "\n").encode("utf-8"))
76
+ self.lines = queue.Queue()
77
+ threading.Thread(target=self._read, daemon=True).start()
78
+
79
+ def _read(self):
80
+ try:
81
+ for line in self.sock.makefile("rb"):
82
+ self.lines.put(json.loads(line.decode("utf-8")))
83
+ except (OSError, ValueError):
84
+ pass
85
+ self.lines.put(None)
86
+
87
+ def next(self, timeout=None):
88
+ """The next message; None if `timeout` passed first. Raises if the link closed."""
89
+ try:
90
+ msg = self.lines.get(timeout=timeout)
91
+ except queue.Empty:
92
+ return None
93
+ if msg is None:
94
+ self.lines.put(None)
95
+ raise LinkError("VS Code's board link closed the connection")
96
+ return msg
97
+
98
+ def close(self):
99
+ try:
100
+ self.sock.shutdown(socket.SHUT_RDWR)
101
+ except OSError:
102
+ pass
103
+ try:
104
+ self.sock.close()
105
+ except OSError:
106
+ pass
107
+
108
+
109
+ class LinkBoard:
110
+ """board.Board's interface, through the extension's shared link."""
111
+
112
+ def __init__(self, port, info):
113
+ self.port = port
114
+ self.info_ = info
115
+
116
+ def __enter__(self):
117
+ return self
118
+
119
+ def __exit__(self, *exc):
120
+ pass
121
+
122
+ def close(self):
123
+ pass
124
+
125
+ def _call(self, request, timeout=120):
126
+ from .board import BoardError
127
+
128
+ c = _Conn(self.info_, request)
129
+ try:
130
+ end = time.monotonic() + timeout
131
+ while True:
132
+ msg = c.next(timeout=max(0.0, end - time.monotonic()))
133
+ if msg is None:
134
+ raise BoardError("VS Code's board link did not answer in %g s" % timeout)
135
+ if "rc" in msg:
136
+ return msg
137
+ except LinkError as e:
138
+ raise BoardError(str(e))
139
+ finally:
140
+ c.close()
141
+
142
+ def _args(self, args):
143
+ r = self._call({"op": "args", "args": args})
144
+ if r.get("rc"):
145
+ from .board import BoardError
146
+ raise BoardError((r.get("err") or r.get("stderr") or "failed").strip().replace("mpremote: ", ""))
147
+ return r.get("stdout", "")
148
+
149
+ # -- the Board interface -------------------------------------------------------
150
+
151
+ def stop(self):
152
+ self._call({"op": "stop"}, timeout=10)
153
+
154
+ def soft_reset(self):
155
+ self.stop()
156
+ self._args(["soft-reset"])
157
+
158
+ def exec_quiet(self, code):
159
+ return self._args(["exec", code])
160
+
161
+ def run(self, code, timeout=10.0, stop_at_timeout=False):
162
+ c = _Conn(self.info_, {"op": "run", "code": code, "soft_reset": False})
163
+ data = bytearray()
164
+ deadline = time.monotonic() + timeout
165
+ stopped = False
166
+ final = None
167
+ try:
168
+ while final is None:
169
+ msg = c.next(timeout=0.2)
170
+ if msg is not None:
171
+ if msg.get("ev") == "out":
172
+ data.extend(base64.b64decode(msg["data"]))
173
+ elif "rc" in msg:
174
+ final = msg
175
+ break
176
+ now = time.monotonic()
177
+ if now >= deadline and not stopped:
178
+ if not stop_at_timeout:
179
+ return self._result(bytes(data), "", False, True, False)
180
+ self._call({"op": "stop"}, timeout=10)
181
+ stopped = True
182
+ deadline = now + 5
183
+ elif now >= deadline and stopped:
184
+ from .board import BoardError
185
+ raise BoardError("The program did not stop after Ctrl-C. Reset the board (press its reset button).")
186
+ finally:
187
+ c.close()
188
+ err = final.get("err") or ""
189
+ if final.get("rc") and err and not data.decode("utf-8", "replace").strip() and "busy" in err:
190
+ from .board import BoardError
191
+ raise BoardError("VS Code is running a program on the board (%s). Stop it there, or let me stop it." % err)
192
+ out = bytes(data)
193
+ e = err.encode("utf-8")
194
+ if e and out.endswith(e):
195
+ out = out[: -len(e)]
196
+ return self._result(out, err, True, False, stopped)
197
+
198
+ @staticmethod
199
+ def _result(out, err, finished, still_running, stopped):
200
+ text = out.decode("utf-8", "replace").replace("\r\n", "\n")[-MAX_OUTPUT:]
201
+ return {"output": text, "error": clean_traceback(err.replace("\r\n", "\n")), "finished": finished,
202
+ "still_running": still_running, "stopped": stopped}
203
+
204
+ def watch(self, seconds):
205
+ c = _Conn(self.info_, {"op": "watch", "seconds": seconds})
206
+ data = bytearray()
207
+ end = time.monotonic() + seconds + 10
208
+ try:
209
+ while time.monotonic() < end:
210
+ msg = c.next(timeout=0.5)
211
+ if msg is None:
212
+ continue
213
+ if msg.get("ev") == "out":
214
+ data.extend(base64.b64decode(msg["data"]))
215
+ elif "rc" in msg:
216
+ break
217
+ finally:
218
+ c.close()
219
+ return data.decode("utf-8", "replace").replace("\r\n", "\n")[-MAX_OUTPUT:]
220
+
221
+ def info(self):
222
+ return parse_info(self.exec_quiet(info_code()))
223
+
224
+ def hashes(self, paths, batch=40):
225
+ out = {}
226
+ paths = list(paths)
227
+ for i in range(0, len(paths), batch):
228
+ out.update(parse_hashes(self.exec_quiet(hashes_code(paths[i:i + batch]))))
229
+ return out
230
+
231
+ def board_sha256(self, path):
232
+ return self.hashes([path]).get(path)
233
+
234
+ def walk(self, root="/"):
235
+ return parse_walk(self.exec_quiet(walk_code(root)))
236
+
237
+ def put(self, local_path, device_path, board_sha=False):
238
+ from .board import BoardError
239
+
240
+ with open(local_path, "rb") as f:
241
+ want = hashlib.sha256(f.read()).hexdigest()
242
+ have = self.board_sha256(device_path) if board_sha is False else board_sha
243
+ if have == want:
244
+ return "unchanged"
245
+ parent = device_path.rsplit("/", 1)[0]
246
+ if parent:
247
+ self.exec_quiet(make_dirs_code(parent))
248
+ self._args(["fs", "cp", "-f", local_path, ":" + device_path])
249
+ after = self.board_sha256(device_path)
250
+ if after not in ("", want):
251
+ raise BoardError("Upload of %s to %s did not verify (board hash %s, expected %s)." % (local_path, device_path, after, want))
252
+ return "uploaded"
253
+
254
+ def delete(self, path):
255
+ self._args(["fs", "rm", path])
256
+
257
+ def listdir(self, path):
258
+ from .board import BoardError
259
+
260
+ files, dirs = self.walk(path)
261
+ base = "" if path in ("", "/") else "/" + path.strip("/")
262
+ if base and not files and not dirs:
263
+ # empty folder, or no such folder: ask the board which
264
+ if "MISSING" in self.exec_quiet("import os\ntry:\n os.stat(%r)\nexcept OSError:\n print('MISSING')" % base):
265
+ raise BoardError("No such file or folder on the board: %s" % path)
266
+ out = []
267
+ for d in dirs:
268
+ if d.rsplit("/", 1)[0] == base:
269
+ out.append({"name": d.rsplit("/", 1)[1], "dir": True, "size": 0})
270
+ for f, size in files.items():
271
+ if f.rsplit("/", 1)[0] == base:
272
+ out.append({"name": f.rsplit("/", 1)[1], "dir": False, "size": size})
273
+ out.sort(key=lambda x: (not x["dir"], x["name"].lower()))
274
+ return out
275
+
276
+ def read_text(self, path, limit=MAX_OUTPUT):
277
+ text = self._args(["fs", "cat", path])
278
+ return text if len(text) <= limit else text[:limit] + "\n…(cut at %d characters)" % limit