boardemul 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.
- boardemul/__init__.py +14 -0
- boardemul/__main__.py +19 -0
- boardemul/build.py +76 -0
- boardemul/cli.py +80 -0
- boardemul/lab.py +364 -0
- boardemul/launcher.py +124 -0
- boardemul/pytest_plugin.py +36 -0
- boardemul-0.1.0.dist-info/METADATA +417 -0
- boardemul-0.1.0.dist-info/RECORD +99 -0
- boardemul-0.1.0.dist-info/WHEEL +5 -0
- boardemul-0.1.0.dist-info/entry_points.txt +5 -0
- boardemul-0.1.0.dist-info/licenses/LICENSE +201 -0
- boardemul-0.1.0.dist-info/licenses/NOTICE +19 -0
- boardemul-0.1.0.dist-info/top_level.txt +3 -0
- emu/aes.py +264 -0
- emu/app.py +722 -0
- emu/board.py +509 -0
- emu/board_tdeck.py +498 -0
- emu/bus.py +303 -0
- emu/ccmp.py +127 -0
- emu/chooser.py +803 -0
- emu/device.py +806 -0
- emu/devices/air.py +276 -0
- emu/devices/backlight.py +132 -0
- emu/devices/bhi260ap.py +309 -0
- emu/devices/epaper.py +161 -0
- emu/devices/es7210.py +77 -0
- emu/devices/gps.py +441 -0
- emu/devices/i2c_devices.py +469 -0
- emu/devices/lcd.py +336 -0
- emu/devices/ledc.py +204 -0
- emu/devices/lora.py +194 -0
- emu/devices/modem.py +74 -0
- emu/devices/sdcard.py +320 -0
- emu/devices/spi_trace.py +57 -0
- emu/devices/sx1262.py +892 -0
- emu/devices/tdeck_i2c.py +421 -0
- emu/devices/tdeck_trackball.py +80 -0
- emu/devices/usb_otg.py +468 -0
- emu/devices/wifi_ap.py +1603 -0
- emu/dhcp.py +117 -0
- emu/dns.py +126 -0
- emu/face.py +146 -0
- emu/factory.py +77 -0
- emu/font.py +170 -0
- emu/guest_clock.py +141 -0
- emu/home.py +43 -0
- emu/i2c_link.py +144 -0
- emu/inputs.py +128 -0
- emu/local_mirror.py +126 -0
- emu/max_face.py +280 -0
- emu/peripherals/adc.py +100 -0
- emu/peripherals/gpio.py +113 -0
- emu/peripherals/i2c.py +35 -0
- emu/png.py +109 -0
- emu/raster.py +233 -0
- emu/run.py +921 -0
- emu/sdimage.py +153 -0
- emu/serial_input.py +151 -0
- emu/serial_link.py +120 -0
- emu/skin.py +346 -0
- emu/spi_link.py +273 -0
- emu/tcp.py +516 -0
- emu/tdeck_face.py +269 -0
- emu/uplink.py +476 -0
- emu/version.py +8 -0
- emu/web/index.html +1320 -0
- emu/web.py +901 -0
- emu/wpa2.py +277 -0
- tools/air_between_containers.py +88 -0
- tools/analyse_trace.py +115 -0
- tools/app_symbols.py +125 -0
- tools/bench_bus.py +137 -0
- tools/ble_central.py +593 -0
- tools/ble_crypto.py +247 -0
- tools/bp_count.py +125 -0
- tools/device.py +338 -0
- tools/disas_rom.py +211 -0
- tools/doctor.py +205 -0
- tools/dump_final.py +92 -0
- tools/dump_mic.py +113 -0
- tools/fetch_firmware.py +154 -0
- tools/find_ble_advertising.py +103 -0
- tools/firmware_manifest.toml +117 -0
- tools/hot_before.py +103 -0
- tools/image_to_elf.py +150 -0
- tools/make_configured_fs.py +195 -0
- tools/make_viewer.py +236 -0
- tools/mesh_api.py +413 -0
- tools/mkflash.py +407 -0
- tools/msg4_branch.py +100 -0
- tools/ring_state.py +177 -0
- tools/rom_overrides.py +73 -0
- tools/rom_symbols.py +55 -0
- tools/rsp.py +126 -0
- tools/sample_report.py +115 -0
- tools/tone.py +95 -0
- tools/trace_diff.py +124 -0
- tools/trace_rx_frame.py +211 -0
boardemul/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""BoardEmul: run and test ESP32-S3 firmware without the board.
|
|
4
|
+
|
|
5
|
+
`python -m boardemul` (or `boardemul`) opens the page; `boardemul test`
|
|
6
|
+
runs a build and a test command (ADR 0182). From Python, a `Lab` makes and
|
|
7
|
+
drives devices.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from boardemul.build import Build, BuildError
|
|
11
|
+
from boardemul.lab import Device, Lab, LabError, Screen, Serial, Shot, Timeout
|
|
12
|
+
|
|
13
|
+
__all__ = ["Build", "BuildError", "Device", "Lab", "LabError", "Screen", "Serial",
|
|
14
|
+
"Shot", "Timeout"]
|
boardemul/__main__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""`boardemul test ...` runs a build and a test (ADR 0182); anything else is
|
|
4
|
+
the launcher's (ADR 0159)."""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv: list[str] | None = None) -> int:
|
|
10
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
11
|
+
if argv[:1] == ["test"]:
|
|
12
|
+
from boardemul.cli import test
|
|
13
|
+
return test(argv[1:])
|
|
14
|
+
from boardemul.launcher import main as launch
|
|
15
|
+
return launch(argv)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
if __name__ == "__main__":
|
|
19
|
+
sys.exit(main())
|
boardemul/build.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""A Build: what a firmware project produces for one board (ADR 0182).
|
|
4
|
+
|
|
5
|
+
Read from a PlatformIO build folder (`.pio/build/ENV`): `firmware.bin` is
|
|
6
|
+
the application, and a filesystem image beside it -- `littlefs.bin`,
|
|
7
|
+
`spiffs.bin` or `fatfs.bin` -- goes at the offset of the first filesystem
|
|
8
|
+
data partition in `partitions.bin`, read as ESP-IDF writes that table:
|
|
9
|
+
32-byte entries starting 0xAA 0x50, then type, subtype, offset and size.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import struct
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
APPLICATION = "firmware.bin"
|
|
19
|
+
FILESYSTEMS = ("littlefs.bin", "spiffs.bin", "fatfs.bin")
|
|
20
|
+
PARTITIONS = "partitions.bin"
|
|
21
|
+
|
|
22
|
+
ENTRY = struct.Struct("<2sBBII16sI")
|
|
23
|
+
ENTRY_MAGIC = b"\xaa\x50"
|
|
24
|
+
TYPE_DATA = 0x01
|
|
25
|
+
# fat, spiffs, littlefs (esp_partition.h); Arduino's LittleFS images often
|
|
26
|
+
# go in a partition still typed spiffs, so all three count.
|
|
27
|
+
FILESYSTEM_SUBTYPES = (0x81, 0x82, 0x83)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BuildError(ValueError):
|
|
31
|
+
"""A folder that is not a build this can place on a board."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Build:
|
|
36
|
+
application: Path
|
|
37
|
+
filesystem: Path | None = None
|
|
38
|
+
filesystem_offset: int | None = None
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_dir(cls, folder: str | Path) -> "Build":
|
|
42
|
+
folder = Path(folder)
|
|
43
|
+
application = folder / APPLICATION
|
|
44
|
+
if not application.is_file():
|
|
45
|
+
raise BuildError(f"no {APPLICATION} in {folder}")
|
|
46
|
+
filesystem = next((folder / n for n in FILESYSTEMS if (folder / n).is_file()), None)
|
|
47
|
+
if filesystem is None:
|
|
48
|
+
return cls(application)
|
|
49
|
+
table = folder / PARTITIONS
|
|
50
|
+
if not table.is_file():
|
|
51
|
+
raise BuildError(f"{filesystem.name} is in {folder} but no {PARTITIONS} "
|
|
52
|
+
"says where it goes")
|
|
53
|
+
offset = filesystem_offset(table.read_bytes())
|
|
54
|
+
if offset is None:
|
|
55
|
+
raise BuildError(f"{PARTITIONS} in {folder} has no filesystem partition "
|
|
56
|
+
f"for {filesystem.name}")
|
|
57
|
+
return cls(application, filesystem, offset)
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def overlays(self) -> tuple[str, ...]:
|
|
61
|
+
"""The filesystem as the emulator's overlay spec, if there is one."""
|
|
62
|
+
if self.filesystem is None:
|
|
63
|
+
return ()
|
|
64
|
+
return (f"0x{self.filesystem_offset:x}={self.filesystem}",)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def filesystem_offset(table: bytes) -> int | None:
|
|
68
|
+
"""The offset of the first filesystem data partition in a partition
|
|
69
|
+
table, or None."""
|
|
70
|
+
for at in range(0, len(table) - ENTRY.size + 1, ENTRY.size):
|
|
71
|
+
magic, kind, subtype, offset, _size, _label, _flags = ENTRY.unpack_from(table, at)
|
|
72
|
+
if magic != ENTRY_MAGIC:
|
|
73
|
+
break
|
|
74
|
+
if kind == TYPE_DATA and subtype in FILESYSTEM_SUBTYPES:
|
|
75
|
+
return offset
|
|
76
|
+
return None
|
boardemul/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""`boardemul test`: run a build on one device or several, run a test
|
|
4
|
+
command against them, and answer with its exit status (ADR 0182).
|
|
5
|
+
|
|
6
|
+
boardemul test --build .pio/build/t-deck --board tdeck --devices 2 \\
|
|
7
|
+
-- python -m pytest tests/
|
|
8
|
+
|
|
9
|
+
The command finds the page in BOARDEMUL_URL and the devices' names, comma
|
|
10
|
+
separated, in BOARDEMUL_DEVICES; `boardemul.Lab()` uses the first on its
|
|
11
|
+
own. Each device's logs are kept in --logs when the command ends.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import os
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from boardemul.build import Build, BuildError
|
|
23
|
+
from boardemul.lab import Lab, LabError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test(argv: list[str]) -> int:
|
|
27
|
+
if "--" not in argv:
|
|
28
|
+
print("boardemul test: give the test command after --", file=sys.stderr)
|
|
29
|
+
return 2
|
|
30
|
+
cut = argv.index("--")
|
|
31
|
+
own, command = argv[:cut], argv[cut + 1:]
|
|
32
|
+
ap = argparse.ArgumentParser(prog="boardemul test")
|
|
33
|
+
ap.add_argument("--build", required=True,
|
|
34
|
+
help="the build folder: firmware.bin, and its filesystem and "
|
|
35
|
+
"partitions.bin if it has one (a PlatformIO .pio/build/ENV)")
|
|
36
|
+
ap.add_argument("--board", default="tdeck", help="tdeck or tdeck-max")
|
|
37
|
+
ap.add_argument("--devices", type=int, default=1,
|
|
38
|
+
help="how many devices run the build; more than one share an air")
|
|
39
|
+
ap.add_argument("--name", default="dut", help="the devices' name, numbered if several")
|
|
40
|
+
ap.add_argument("--air", default="boardemul-test",
|
|
41
|
+
help="the LoRa air several devices share")
|
|
42
|
+
ap.add_argument("--setting", action="append", default=[],
|
|
43
|
+
help="a run setting for every device, as the page takes them "
|
|
44
|
+
"(repeat: --setting=--host-clock)")
|
|
45
|
+
ap.add_argument("--logs", default="boardemul-logs",
|
|
46
|
+
help="where each device's logs are kept")
|
|
47
|
+
args = ap.parse_args(own)
|
|
48
|
+
if not command:
|
|
49
|
+
print("boardemul test: no test command after --", file=sys.stderr)
|
|
50
|
+
return 2
|
|
51
|
+
try:
|
|
52
|
+
build = Build.from_dir(args.build)
|
|
53
|
+
except BuildError as exc:
|
|
54
|
+
print(f"boardemul test: {exc}", file=sys.stderr)
|
|
55
|
+
return 2
|
|
56
|
+
|
|
57
|
+
names = ([args.name] if args.devices == 1
|
|
58
|
+
else [f"{args.name}{i}" for i in range(1, args.devices + 1)])
|
|
59
|
+
with Lab() as lab:
|
|
60
|
+
try:
|
|
61
|
+
devices = [lab.device(n, build, board=args.board, settings=tuple(args.setting))
|
|
62
|
+
for n in names]
|
|
63
|
+
for device in devices:
|
|
64
|
+
device.start(air=args.air if len(devices) > 1 else None)
|
|
65
|
+
except LabError as exc:
|
|
66
|
+
print(f"boardemul test: {exc}", file=sys.stderr)
|
|
67
|
+
return 2
|
|
68
|
+
env = dict(os.environ, BOARDEMUL_URL=lab.url, BOARDEMUL_DEVICES=",".join(names))
|
|
69
|
+
try:
|
|
70
|
+
status = subprocess.run(command, env=env).returncode
|
|
71
|
+
finally:
|
|
72
|
+
logs = Path(args.logs)
|
|
73
|
+
logs.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
for device in devices:
|
|
75
|
+
device.stop()
|
|
76
|
+
try:
|
|
77
|
+
device.save_logs(logs / f"{device.name}.zip")
|
|
78
|
+
except LabError:
|
|
79
|
+
pass
|
|
80
|
+
return status
|
boardemul/lab.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Test firmware on emulated boards, from Python (ADR 0182).
|
|
4
|
+
|
|
5
|
+
from boardemul import Lab
|
|
6
|
+
|
|
7
|
+
with Lab() as lab:
|
|
8
|
+
node = lab.device("node", build=".pio/build/t-deck", board="tdeck")
|
|
9
|
+
node.start()
|
|
10
|
+
node.serial("usb").expect(r"Booted", timeout=120)
|
|
11
|
+
node.tap(120, 80)
|
|
12
|
+
assert node.screen.wait(lambda shot: shot.pixel(2, 2) != (0, 0, 0), 60)
|
|
13
|
+
|
|
14
|
+
A Lab is a BoardEmul page -- the one at BOARDEMUL_URL, or one it starts --
|
|
15
|
+
and the devices it made there. Everything goes through the page's HTTP API;
|
|
16
|
+
nothing here imports the emulator. Timeouts are wall seconds.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import socket
|
|
25
|
+
import struct
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
import urllib.error
|
|
30
|
+
import urllib.parse
|
|
31
|
+
import urllib.request
|
|
32
|
+
import zlib
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
from boardemul.build import Build
|
|
36
|
+
|
|
37
|
+
SERIAL_PORTS = ("uart", "usb", "otg")
|
|
38
|
+
START_TIMEOUT = 300.0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class LabError(RuntimeError):
|
|
42
|
+
"""The page refused a request, or never answered."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Timeout(LabError):
|
|
46
|
+
"""What a test waited for did not come in time."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# -- the page's API -----------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Api:
|
|
53
|
+
def __init__(self, url: str):
|
|
54
|
+
self.url = url.rstrip("/")
|
|
55
|
+
|
|
56
|
+
def call(self, method: str, path: str, body=None, raw: bytes | None = None,
|
|
57
|
+
timeout: float = 60.0):
|
|
58
|
+
"""JSON in and out; or raw bytes in, with `raw`. Returns (status,
|
|
59
|
+
parsed body or bytes, headers)."""
|
|
60
|
+
data, headers = None, {}
|
|
61
|
+
if raw is not None:
|
|
62
|
+
data, headers["Content-Type"] = raw, "application/octet-stream"
|
|
63
|
+
elif body is not None:
|
|
64
|
+
data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
|
|
65
|
+
request = urllib.request.Request(self.url + path, data=data, method=method,
|
|
66
|
+
headers=headers)
|
|
67
|
+
try:
|
|
68
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
69
|
+
payload, status, hdrs = response.read(), response.status, dict(response.headers)
|
|
70
|
+
except urllib.error.HTTPError as exc:
|
|
71
|
+
payload, status, hdrs = exc.read(), exc.code, dict(exc.headers)
|
|
72
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
73
|
+
raise LabError(f"{method} {path}: {exc}") from exc
|
|
74
|
+
if hdrs.get("Content-Type", "").startswith("application/json"):
|
|
75
|
+
payload = json.loads(payload or b"null")
|
|
76
|
+
return status, payload, hdrs
|
|
77
|
+
|
|
78
|
+
def ok(self, method: str, path: str, body=None, raw: bytes | None = None):
|
|
79
|
+
status, payload, _h = self.call(method, path, body, raw)
|
|
80
|
+
if status >= 300:
|
|
81
|
+
error = payload.get("error") if isinstance(payload, dict) else payload
|
|
82
|
+
raise LabError(f"{method} {path}: {status} {error}")
|
|
83
|
+
return payload
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _free_port() -> int:
|
|
87
|
+
with socket.socket() as sock:
|
|
88
|
+
sock.bind(("127.0.0.1", 0))
|
|
89
|
+
return sock.getsockname()[1]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# -- the lab ------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Lab:
|
|
96
|
+
"""A page, and the devices made on it."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, url: str | None = None, start_timeout: float = START_TIMEOUT):
|
|
99
|
+
self._server: subprocess.Popen | None = None
|
|
100
|
+
url = url or os.environ.get("BOARDEMUL_URL")
|
|
101
|
+
if not url:
|
|
102
|
+
port = _free_port()
|
|
103
|
+
url = f"http://127.0.0.1:{port}"
|
|
104
|
+
self._server = subprocess.Popen(
|
|
105
|
+
[sys.executable, "-m", "boardemul", "--port", str(port), "--no-open"],
|
|
106
|
+
cwd=Path(__file__).resolve().parent.parent,
|
|
107
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
|
108
|
+
self.api = Api(url)
|
|
109
|
+
self.url = url
|
|
110
|
+
self.devices: dict[str, Device] = {}
|
|
111
|
+
self._wait_ready(start_timeout)
|
|
112
|
+
|
|
113
|
+
def _wait_ready(self, timeout: float) -> None:
|
|
114
|
+
deadline = time.monotonic() + timeout
|
|
115
|
+
while time.monotonic() < deadline:
|
|
116
|
+
if self._server is not None and self._server.poll() is not None:
|
|
117
|
+
raise LabError("the page stopped while starting: run `python "
|
|
118
|
+
"boardemul.py --check` to see what this machine lacks")
|
|
119
|
+
try:
|
|
120
|
+
status, _p, _h = self.api.call("GET", "/api/version", timeout=5)
|
|
121
|
+
if status == 200:
|
|
122
|
+
return
|
|
123
|
+
except LabError:
|
|
124
|
+
pass
|
|
125
|
+
time.sleep(0.5)
|
|
126
|
+
raise Timeout(f"no page answered at {self.url} in {timeout:.0f} s")
|
|
127
|
+
|
|
128
|
+
def device(self, name: str, build: str | Path | Build, board: str = "tdeck",
|
|
129
|
+
settings: tuple[str, ...] = ()) -> "Device":
|
|
130
|
+
"""A device made from `build`, replacing one of that name."""
|
|
131
|
+
build = build if isinstance(build, Build) else Build.from_dir(build)
|
|
132
|
+
existing = {d["name"] for d in self.api.ok("GET", "/api/devices")["devices"]}
|
|
133
|
+
if name in existing:
|
|
134
|
+
self.api.call("POST", f"/api/devices/{_q(name)}/stop", {})
|
|
135
|
+
self.api.ok("POST", f"/api/devices/{_q(name)}/remove", {})
|
|
136
|
+
application = self._upload(build.application)
|
|
137
|
+
overlays = []
|
|
138
|
+
if build.filesystem is not None:
|
|
139
|
+
path = self._upload(build.filesystem)
|
|
140
|
+
overlays.append(f"0x{build.filesystem_offset:x}={path}")
|
|
141
|
+
made = self.api.ok("POST", "/api/devices", {"name": name, "board": board,
|
|
142
|
+
"firmware": application,
|
|
143
|
+
"overlays": overlays})
|
|
144
|
+
if settings:
|
|
145
|
+
# Beside what a device is made with (it restarts after a panic,
|
|
146
|
+
# ADR 0145), not instead of it.
|
|
147
|
+
kept = list(made.get("settings", [])) + [s for s in settings
|
|
148
|
+
if s not in made.get("settings", [])]
|
|
149
|
+
self.api.ok("POST", f"/api/devices/{_q(name)}/settings", {"settings": kept})
|
|
150
|
+
device = Device(self, name)
|
|
151
|
+
self.devices[name] = device
|
|
152
|
+
return device
|
|
153
|
+
|
|
154
|
+
def _upload(self, path: Path) -> str:
|
|
155
|
+
reply = self.api.ok("POST", f"/api/firmware?name={_q(path.name)}",
|
|
156
|
+
raw=Path(path).read_bytes())
|
|
157
|
+
return reply["path"]
|
|
158
|
+
|
|
159
|
+
def close(self) -> None:
|
|
160
|
+
for device in self.devices.values():
|
|
161
|
+
try:
|
|
162
|
+
device.stop()
|
|
163
|
+
except LabError:
|
|
164
|
+
pass
|
|
165
|
+
if self._server is not None:
|
|
166
|
+
self._server.terminate()
|
|
167
|
+
try:
|
|
168
|
+
self._server.wait(timeout=30)
|
|
169
|
+
except subprocess.TimeoutExpired:
|
|
170
|
+
self._server.kill()
|
|
171
|
+
self._server = None
|
|
172
|
+
|
|
173
|
+
def __enter__(self) -> "Lab":
|
|
174
|
+
return self
|
|
175
|
+
|
|
176
|
+
def __exit__(self, *_exc) -> None:
|
|
177
|
+
self.close()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _q(text: str) -> str:
|
|
181
|
+
return urllib.parse.quote(text, safe="")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# -- a device -----------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class Device:
|
|
188
|
+
def __init__(self, lab: Lab, name: str):
|
|
189
|
+
self.lab, self.name = lab, name
|
|
190
|
+
self.screen = Screen(self)
|
|
191
|
+
self._serial: dict[str, Serial] = {}
|
|
192
|
+
|
|
193
|
+
def start(self, air: str | None = None, args: tuple[str, ...] = ()) -> None:
|
|
194
|
+
"""Run it; devices started on the same air hear each other's LoRa
|
|
195
|
+
radios."""
|
|
196
|
+
extra = list(args) + (["--air", air] if air else [])
|
|
197
|
+
self.lab.api.ok("POST", f"/api/devices/{_q(self.name)}/start", {"args": extra})
|
|
198
|
+
self._serial.clear()
|
|
199
|
+
|
|
200
|
+
def stop(self) -> None:
|
|
201
|
+
self.lab.api.call("POST", f"/api/devices/{_q(self.name)}/stop", {})
|
|
202
|
+
|
|
203
|
+
def serial(self, port: str = "uart") -> "Serial":
|
|
204
|
+
if port not in SERIAL_PORTS:
|
|
205
|
+
raise ValueError(f"a serial port is one of {', '.join(SERIAL_PORTS)}")
|
|
206
|
+
return self._serial.setdefault(port, Serial(self, port))
|
|
207
|
+
|
|
208
|
+
def _input(self, *events: dict) -> None:
|
|
209
|
+
self.lab.api.ok("POST", f"/api/runs/{_q(self.name)}/input",
|
|
210
|
+
{"events": list(events)})
|
|
211
|
+
|
|
212
|
+
def tap(self, x: int, y: int, hold: float = 0.3) -> None:
|
|
213
|
+
self._input({"type": "touch", "x": int(x), "y": int(y), "down": True})
|
|
214
|
+
time.sleep(hold)
|
|
215
|
+
self._input({"type": "touch", "down": False})
|
|
216
|
+
|
|
217
|
+
def key(self, name: str, hold: float = 0.15) -> None:
|
|
218
|
+
self._input({"type": "key", "key": name, "down": True})
|
|
219
|
+
time.sleep(hold)
|
|
220
|
+
self._input({"type": "key", "key": name, "down": False})
|
|
221
|
+
|
|
222
|
+
def type(self, text: str) -> None:
|
|
223
|
+
self._input({"type": "text", "text": text})
|
|
224
|
+
|
|
225
|
+
def save_logs(self, path: str | Path) -> Path:
|
|
226
|
+
"""The device's latest run's logs, as one zip (ADR 0163)."""
|
|
227
|
+
status, body, _h = self.lab.api.call("GET", f"/api/devices/{_q(self.name)}/logs.zip")
|
|
228
|
+
if status != 200:
|
|
229
|
+
raise LabError(f"no logs for {self.name}: {status}")
|
|
230
|
+
path = Path(path)
|
|
231
|
+
path.write_bytes(body)
|
|
232
|
+
return path
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class Serial:
|
|
236
|
+
"""One serial port of a running device: its lines, and what to send it."""
|
|
237
|
+
|
|
238
|
+
def __init__(self, device: Device, port: str):
|
|
239
|
+
self.device, self.port = device, port
|
|
240
|
+
self.seen = 0 # lines already looked at by expect()
|
|
241
|
+
|
|
242
|
+
def lines(self) -> list[str]:
|
|
243
|
+
"""Every line the port has carried in this run."""
|
|
244
|
+
reply = self.device.lab.api.ok(
|
|
245
|
+
"GET", f"/api/runs/{_q(self.device.name)}/uart?port={self.port}&after=0")
|
|
246
|
+
return reply["lines"]
|
|
247
|
+
|
|
248
|
+
def send(self, text: str) -> None:
|
|
249
|
+
self.device._input({"type": "serial", "port": self.port, "text": text})
|
|
250
|
+
|
|
251
|
+
def expect(self, pattern: str, timeout: float = 60.0) -> re.Match:
|
|
252
|
+
"""The first line after the last one matched that matches `pattern`."""
|
|
253
|
+
wanted = re.compile(pattern)
|
|
254
|
+
deadline = time.monotonic() + timeout
|
|
255
|
+
while True:
|
|
256
|
+
reply = self.device.lab.api.ok(
|
|
257
|
+
"GET", f"/api/runs/{_q(self.device.name)}/uart"
|
|
258
|
+
f"?port={self.port}&after={self.seen}")
|
|
259
|
+
for line in reply["lines"]:
|
|
260
|
+
self.seen += 1
|
|
261
|
+
found = wanted.search(line)
|
|
262
|
+
if found:
|
|
263
|
+
return found
|
|
264
|
+
if time.monotonic() >= deadline:
|
|
265
|
+
raise Timeout(f"{self.device.name} {self.port}: no line matching "
|
|
266
|
+
f"{pattern!r} in {timeout:.0f} s")
|
|
267
|
+
time.sleep(0.25)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class Shot:
|
|
271
|
+
"""One frame of a device's screen."""
|
|
272
|
+
|
|
273
|
+
def __init__(self, png: bytes):
|
|
274
|
+
self.png = png
|
|
275
|
+
self.width, self.height, self.channels, self.data = decode_png(png)
|
|
276
|
+
|
|
277
|
+
def pixel(self, x: int, y: int) -> tuple[int, ...]:
|
|
278
|
+
at = (y * self.width + x) * self.channels
|
|
279
|
+
value = tuple(self.data[at:at + self.channels])
|
|
280
|
+
return value * 3 if self.channels == 1 else value
|
|
281
|
+
|
|
282
|
+
def same_as(self, other: "Shot | bytes | str | Path", tolerance: int = 0) -> bool:
|
|
283
|
+
"""Whether two frames match, each channel within `tolerance`."""
|
|
284
|
+
if isinstance(other, (str, Path)):
|
|
285
|
+
other = Path(other).read_bytes()
|
|
286
|
+
if isinstance(other, bytes):
|
|
287
|
+
other = Shot(other)
|
|
288
|
+
if (self.width, self.height, self.channels) != (other.width, other.height,
|
|
289
|
+
other.channels):
|
|
290
|
+
return False
|
|
291
|
+
return all(abs(a - b) <= tolerance for a, b in zip(self.data, other.data))
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class Screen:
|
|
295
|
+
def __init__(self, device: Device):
|
|
296
|
+
self.device = device
|
|
297
|
+
|
|
298
|
+
def shot(self, newer_than: int = 0) -> tuple[Shot | None, int]:
|
|
299
|
+
"""The latest frame newer than `newer_than` (the page's own stamp),
|
|
300
|
+
waiting up to a quarter-minute; (None, newer_than) if none came."""
|
|
301
|
+
status, body, headers = self.device.lab.api.call(
|
|
302
|
+
"GET", f"/api/runs/{_q(self.device.name)}/frame?since={newer_than}", timeout=30)
|
|
303
|
+
if status == 204:
|
|
304
|
+
return None, newer_than
|
|
305
|
+
if status != 200:
|
|
306
|
+
raise LabError(f"{self.device.name}: no screen ({status})")
|
|
307
|
+
return Shot(body), int(headers.get("X-Frame-Mtime", newer_than))
|
|
308
|
+
|
|
309
|
+
def wait(self, predicate, timeout: float = 60.0) -> Shot:
|
|
310
|
+
"""The first frame `predicate(shot)` is true of."""
|
|
311
|
+
deadline = time.monotonic() + timeout
|
|
312
|
+
stamp = 0
|
|
313
|
+
while time.monotonic() < deadline:
|
|
314
|
+
shot, stamp = self.shot(stamp)
|
|
315
|
+
if shot is not None and predicate(shot):
|
|
316
|
+
return shot
|
|
317
|
+
raise Timeout(f"{self.device.name}: no frame as wanted in {timeout:.0f} s")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
# -- PNG, as the emulator writes it --------------------------------------------
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def decode_png(data: bytes) -> tuple[int, int, int, bytes]:
|
|
324
|
+
"""Width, height, channels and pixel bytes of an 8-bit greyscale or RGB
|
|
325
|
+
PNG, unfiltered by each row's filter type."""
|
|
326
|
+
if data[:8] != b"\x89PNG\r\n\x1a\n":
|
|
327
|
+
raise LabError("not a PNG")
|
|
328
|
+
at, idat, width = 8, b"", 0
|
|
329
|
+
while at < len(data):
|
|
330
|
+
length, kind = struct.unpack(">I4s", data[at:at + 8])
|
|
331
|
+
chunk = data[at + 8:at + 8 + length]
|
|
332
|
+
if kind == b"IHDR":
|
|
333
|
+
width, height, depth, colour = struct.unpack(">IIBB", chunk[:10])
|
|
334
|
+
if depth != 8 or colour not in (0, 2):
|
|
335
|
+
raise LabError("only 8-bit greyscale or RGB PNGs")
|
|
336
|
+
channels = 1 if colour == 0 else 3
|
|
337
|
+
elif kind == b"IDAT":
|
|
338
|
+
idat += chunk
|
|
339
|
+
at += 12 + length
|
|
340
|
+
raw = zlib.decompress(idat)
|
|
341
|
+
stride = width * channels
|
|
342
|
+
out = bytearray()
|
|
343
|
+
previous = bytearray(stride)
|
|
344
|
+
for row in range(height):
|
|
345
|
+
start = row * (stride + 1)
|
|
346
|
+
kind, line = raw[start], bytearray(raw[start + 1:start + 1 + stride])
|
|
347
|
+
for i in range(stride):
|
|
348
|
+
left = line[i - channels] if i >= channels else 0
|
|
349
|
+
up = previous[i]
|
|
350
|
+
corner = previous[i - channels] if i >= channels else 0
|
|
351
|
+
if kind == 1:
|
|
352
|
+
line[i] = (line[i] + left) & 0xFF
|
|
353
|
+
elif kind == 2:
|
|
354
|
+
line[i] = (line[i] + up) & 0xFF
|
|
355
|
+
elif kind == 3:
|
|
356
|
+
line[i] = (line[i] + (left + up) // 2) & 0xFF
|
|
357
|
+
elif kind == 4:
|
|
358
|
+
p = left + up - corner
|
|
359
|
+
pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner)
|
|
360
|
+
pred = left if pa <= pb and pa <= pc else up if pb <= pc else corner
|
|
361
|
+
line[i] = (line[i] + pred) & 0xFF
|
|
362
|
+
out += line
|
|
363
|
+
previous = line
|
|
364
|
+
return width, height, channels, bytes(out)
|
boardemul/launcher.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 Prolific Lab
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Start BoardEmul: one command, from a clone (ADR 0159).
|
|
5
|
+
|
|
6
|
+
python boardemul.py # check, build what is missing, open the page
|
|
7
|
+
python boardemul.py --check # say what this machine lacks, and stop
|
|
8
|
+
python boardemul.py --port 8420 --no-open
|
|
9
|
+
|
|
10
|
+
On a host whose runs go into a container (Windows; ADR 0140), it uses the
|
|
11
|
+
runtime image, which carries QEMU already built, and builds that image the
|
|
12
|
+
first time. On a host that runs natively and has QEMU built, it uses that.
|
|
13
|
+
It fetches the vendor firmware the manifest pins, then serves the page.
|
|
14
|
+
|
|
15
|
+
Developers keep ADR 0147's commands: the development image, tools/build_qemu.sh
|
|
16
|
+
and tools/fetch_firmware.py, which this calls too.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import os
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
28
|
+
sys.path.insert(0, str(REPO_ROOT))
|
|
29
|
+
|
|
30
|
+
from tools.doctor import PUBLISHED_IMAGE, RUNTIME_IMAGE # noqa: E402
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def say(text: str) -> None:
|
|
34
|
+
print(f"boardemul: {text}", flush=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def build_runtime_image(why: str) -> bool:
|
|
38
|
+
from tools import doctor
|
|
39
|
+
say(f"building the {RUNTIME_IMAGE} image ({why}): it compiles QEMU, which "
|
|
40
|
+
"takes ten to thirty minutes and downloads its sources from GitHub")
|
|
41
|
+
done = subprocess.run(["docker", "build", "-t", RUNTIME_IMAGE,
|
|
42
|
+
"--build-arg", f"BOARDEMUL_SOURCES={doctor.sources_digest()}",
|
|
43
|
+
"-f", "docker/runtime/Dockerfile", "."], cwd=REPO_ROOT)
|
|
44
|
+
return done.returncode == 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def pull_runtime_image() -> bool:
|
|
48
|
+
"""An installed BoardEmul runs the image CI published for its version
|
|
49
|
+
(ADR 0183)."""
|
|
50
|
+
say(f"pulling the {PUBLISHED_IMAGE} image, which carries QEMU")
|
|
51
|
+
return subprocess.run(["docker", "pull", PUBLISHED_IMAGE]).returncode == 0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main(argv: list[str] | None = None) -> int:
|
|
55
|
+
ap = argparse.ArgumentParser(description=__doc__,
|
|
56
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
57
|
+
ap.add_argument("--version", action="store_true", help="say the version, and stop")
|
|
58
|
+
ap.add_argument("--check", action="store_true",
|
|
59
|
+
help="say what this machine lacks, and stop")
|
|
60
|
+
ap.add_argument("--port", type=int, default=8420)
|
|
61
|
+
ap.add_argument("--no-open", action="store_true", help="do not open a browser tab")
|
|
62
|
+
args = ap.parse_args(argv)
|
|
63
|
+
from emu.version import VERSION
|
|
64
|
+
if args.version:
|
|
65
|
+
print(f"BoardEmul {VERSION}")
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
if sys.version_info < (3, 11):
|
|
69
|
+
say(f"Python {sys.version.split()[0]} is too old: install Python 3.12")
|
|
70
|
+
return 1
|
|
71
|
+
|
|
72
|
+
from emu import device as device_folder
|
|
73
|
+
from tools import doctor, fetch_firmware
|
|
74
|
+
|
|
75
|
+
# Runs go into the runtime image unless the host runs them natively with
|
|
76
|
+
# a QEMU of its own (ADR 0159).
|
|
77
|
+
native = device_folder.runs_natively()
|
|
78
|
+
if not native and not os.environ.get("BOARDEMUL_IMAGE"):
|
|
79
|
+
os.environ["BOARDEMUL_IMAGE"] = RUNTIME_IMAGE
|
|
80
|
+
image = os.environ.get("BOARDEMUL_IMAGE", device_folder.DEFAULT_IMAGE)
|
|
81
|
+
|
|
82
|
+
findings = doctor.diagnose()
|
|
83
|
+
blocking = [f for f in findings if f.level == doctor.ERROR]
|
|
84
|
+
if args.check:
|
|
85
|
+
doctor.main([])
|
|
86
|
+
return 1 if blocking else 0
|
|
87
|
+
|
|
88
|
+
for f in blocking:
|
|
89
|
+
if f.what == "Build image" and image == RUNTIME_IMAGE:
|
|
90
|
+
if image == PUBLISHED_IMAGE:
|
|
91
|
+
if not pull_runtime_image():
|
|
92
|
+
say("the image did not arrive; Docker's output above says why")
|
|
93
|
+
return 1
|
|
94
|
+
continue
|
|
95
|
+
why = ("its QEMU sources have changed since it was built"
|
|
96
|
+
if "other QEMU sources" in f.detail else "once")
|
|
97
|
+
if not build_runtime_image(why):
|
|
98
|
+
say("the image did not build; its output above says why")
|
|
99
|
+
return 1
|
|
100
|
+
elif f.what.startswith("Firmware"):
|
|
101
|
+
continue # fetched below
|
|
102
|
+
else:
|
|
103
|
+
say(f"{f.what}: {f.detail}" + (f" -- fix: {f.fix}" if f.fix else ""))
|
|
104
|
+
return 1
|
|
105
|
+
|
|
106
|
+
missing = [e["name"] for e in fetch_firmware.load()
|
|
107
|
+
if fetch_firmware.state(e) == "missing"]
|
|
108
|
+
if missing:
|
|
109
|
+
say(f"fetching {len(missing)} pinned firmware image(s)")
|
|
110
|
+
fetch_firmware.main([arg for name in missing for arg in ("--only", name)])
|
|
111
|
+
|
|
112
|
+
still = [f for f in doctor.diagnose() if f.level == doctor.ERROR]
|
|
113
|
+
if still:
|
|
114
|
+
for f in still:
|
|
115
|
+
say(f"{f.what}: {f.detail}" + (f" -- fix: {f.fix}" if f.fix else ""))
|
|
116
|
+
return 1
|
|
117
|
+
|
|
118
|
+
say(f"ready; runs start {'on this host' if native else 'in ' + image}")
|
|
119
|
+
from emu import web
|
|
120
|
+
return web.main(["--port", str(args.port)] + (["--no-open"] if args.no_open else []))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
sys.exit(main())
|