picoforge 0.0.4__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.
- picoforge/__init__.py +1 -0
- picoforge/__main__.py +3 -0
- picoforge/cli.py +94 -0
- picoforge/device.py +286 -0
- picoforge/monitor.py +436 -0
- picoforge/protocol.py +687 -0
- picoforge/web/css/dashboard.css +259 -0
- picoforge/web/favicon.svg +5 -0
- picoforge/web/index.html +208 -0
- picoforge/web/js/app.mjs +377 -0
- picoforge/web/js/dashboard.mjs +294 -0
- picoforge/web.py +201 -0
- picoforge-0.0.4.dist-info/METADATA +82 -0
- picoforge-0.0.4.dist-info/RECORD +18 -0
- picoforge-0.0.4.dist-info/WHEEL +5 -0
- picoforge-0.0.4.dist-info/entry_points.txt +2 -0
- picoforge-0.0.4.dist-info/licenses/LICENSE +28 -0
- picoforge-0.0.4.dist-info/top_level.txt +1 -0
picoforge/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""PicoForge host tools."""
|
picoforge/__main__.py
ADDED
picoforge/cli.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""CLI for PicoForge HID status and its local dashboard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from .device import PicoForgeHid
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
13
|
+
parser = argparse.ArgumentParser(prog="picoforge")
|
|
14
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
15
|
+
status = commands.add_parser("status", help="read hardware and runtime status")
|
|
16
|
+
web = commands.add_parser("web", help="serve the local status dashboard")
|
|
17
|
+
reboot = commands.add_parser("reboot", help="reboot the selected board")
|
|
18
|
+
reboot.add_argument("--confirm", action="store_true", required=True,
|
|
19
|
+
help="confirm that the board should reboot")
|
|
20
|
+
for command in (status, web, reboot):
|
|
21
|
+
selection = command.add_mutually_exclusive_group()
|
|
22
|
+
selection.add_argument("--serial", help="select a board by USB serial number")
|
|
23
|
+
selection.add_argument("--device-path", help="select a HID path")
|
|
24
|
+
web.add_argument("--port", type=int, default=5000)
|
|
25
|
+
return parser.parse_args(argv)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: list[str] | None = None) -> int:
|
|
29
|
+
args = parse_args(argv)
|
|
30
|
+
try:
|
|
31
|
+
if args.command == "web":
|
|
32
|
+
if not 1 <= args.port <= 65535:
|
|
33
|
+
raise ValueError("port must be between 1 and 65535")
|
|
34
|
+
from .web import run_server
|
|
35
|
+
|
|
36
|
+
run_server(args.port, args.serial, args.device_path)
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
with PicoForgeHid(args.serial, args.device_path) as device:
|
|
40
|
+
if args.command == "reboot":
|
|
41
|
+
device.read_info()
|
|
42
|
+
result = device.reboot()
|
|
43
|
+
print(json.dumps({"control_result": result}, sort_keys=True))
|
|
44
|
+
return 0 if result["status"] == "completed" else 1
|
|
45
|
+
info = device.read_info()
|
|
46
|
+
if not info.get("supported", True):
|
|
47
|
+
print(json.dumps({
|
|
48
|
+
"connected": True,
|
|
49
|
+
"hardware": info,
|
|
50
|
+
"settings": None,
|
|
51
|
+
"board_configuration": None,
|
|
52
|
+
"runtime": None,
|
|
53
|
+
"memory": None,
|
|
54
|
+
"msc": None,
|
|
55
|
+
"self_test": None,
|
|
56
|
+
}, sort_keys=True))
|
|
57
|
+
return 1
|
|
58
|
+
configuration = device.read_configuration()
|
|
59
|
+
settings = {
|
|
60
|
+
"system_clock_mhz": configuration["system_clock_mhz"],
|
|
61
|
+
"sdcard_profile": configuration["sdcard_profile"],
|
|
62
|
+
}
|
|
63
|
+
runtime = None
|
|
64
|
+
memory = None
|
|
65
|
+
self_test = None
|
|
66
|
+
self_test_expected = info["self_test_supported"]
|
|
67
|
+
for _ in range(16):
|
|
68
|
+
item = device.read_input_report(timeout_ms=1500)
|
|
69
|
+
if item is None:
|
|
70
|
+
continue
|
|
71
|
+
if item["kind"] == "runtime":
|
|
72
|
+
runtime = item["data"]
|
|
73
|
+
elif item["kind"] == "memory":
|
|
74
|
+
memory = item["data"]
|
|
75
|
+
elif item["kind"] == "self_test":
|
|
76
|
+
self_test = item["data"]
|
|
77
|
+
if runtime is not None and memory is not None and (
|
|
78
|
+
self_test is not None or not self_test_expected
|
|
79
|
+
):
|
|
80
|
+
break
|
|
81
|
+
print(json.dumps({
|
|
82
|
+
"connected": True,
|
|
83
|
+
"hardware": info,
|
|
84
|
+
"settings": settings,
|
|
85
|
+
"board_configuration": configuration,
|
|
86
|
+
"runtime": runtime,
|
|
87
|
+
"memory": memory,
|
|
88
|
+
"msc": memory["msc"] if memory is not None else None,
|
|
89
|
+
"self_test": self_test,
|
|
90
|
+
}, sort_keys=True))
|
|
91
|
+
return 0
|
|
92
|
+
except (OSError, RuntimeError, ValueError) as error:
|
|
93
|
+
print(f"error: {error}", file=sys.stderr)
|
|
94
|
+
return 1
|
picoforge/device.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""HIDAPI transport for PicoForge's vendor-defined status interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from math import ceil
|
|
6
|
+
from time import monotonic, sleep
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .protocol import (
|
|
10
|
+
CAP_LED,
|
|
11
|
+
CAP_REBOOT,
|
|
12
|
+
CAP_SAVE_SETTINGS,
|
|
13
|
+
CAP_SELF_TEST,
|
|
14
|
+
CONFIGURATION_FEATURE_SIZE,
|
|
15
|
+
CONFIGURATION_REPORT_ID,
|
|
16
|
+
CONTROL_FEATURE_SIZE,
|
|
17
|
+
CONTROL_REPORT_ID,
|
|
18
|
+
IDENTITY_FEATURE_SIZE,
|
|
19
|
+
IDENTITY_REPORT_ID,
|
|
20
|
+
STORAGE_INPUT_SIZE,
|
|
21
|
+
STORAGE_REPORT_ID,
|
|
22
|
+
TELEMETRY_INPUT_SIZE,
|
|
23
|
+
TELEMETRY_REPORT_ID,
|
|
24
|
+
SELF_TEST_REPORT_ID,
|
|
25
|
+
SELF_TEST_INPUT_SIZE,
|
|
26
|
+
build_control_command_report,
|
|
27
|
+
build_settings_command_report,
|
|
28
|
+
build_led_command_report,
|
|
29
|
+
build_msc_command_report,
|
|
30
|
+
build_self_test_command_report,
|
|
31
|
+
parse_device_identity_report,
|
|
32
|
+
parse_storage_report,
|
|
33
|
+
parse_board_configuration_report,
|
|
34
|
+
parse_control_result_report,
|
|
35
|
+
parse_self_test_status_report,
|
|
36
|
+
parse_telemetry_report,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
VENDOR_ID = 0xCAFE
|
|
40
|
+
PRODUCT_ID = 0x4011
|
|
41
|
+
PRODUCT_IDS = {0x4011, 0x4012}
|
|
42
|
+
USAGE_PAGE = 0xFF00
|
|
43
|
+
USAGE = 0x0001
|
|
44
|
+
PRODUCT_STRING = "PicoForge CDC + HID"
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
import hid
|
|
48
|
+
except ImportError as error: # Import only when a hardware connection is requested.
|
|
49
|
+
hid = None
|
|
50
|
+
HID_IMPORT_ERROR = error
|
|
51
|
+
else:
|
|
52
|
+
HID_IMPORT_ERROR = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _require_hid() -> Any:
|
|
56
|
+
if hid is None:
|
|
57
|
+
raise RuntimeError("HIDAPI is missing; install host/python with 'pip install -e host/python'") from HID_IMPORT_ERROR
|
|
58
|
+
return hid
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _path_string(path: Any) -> str:
|
|
62
|
+
if isinstance(path, bytes):
|
|
63
|
+
return path.decode("utf-8", errors="surrogateescape")
|
|
64
|
+
return str(path or "")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _matches_vendor_collection(info: dict[str, Any]) -> bool:
|
|
68
|
+
usage_page = info.get("usage_page")
|
|
69
|
+
usage = info.get("usage")
|
|
70
|
+
if usage_page not in (None, 0) and usage not in (None, 0):
|
|
71
|
+
return usage_page == USAGE_PAGE and usage == USAGE
|
|
72
|
+
product_string = info.get("product_string")
|
|
73
|
+
if product_string:
|
|
74
|
+
return product_string in (PRODUCT_STRING, "PicoForge CDC + HID + MSC")
|
|
75
|
+
# enumerate() is already restricted to our VID/PID; some HIDAPI backends
|
|
76
|
+
# leave usage and string metadata empty when the device is not readable.
|
|
77
|
+
return True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _matching_devices() -> list[dict[str, Any]]:
|
|
81
|
+
devices = _require_hid().enumerate(VENDOR_ID, 0)
|
|
82
|
+
return [info for info in devices
|
|
83
|
+
if info.get("product_id") in PRODUCT_IDS and _matches_vendor_collection(info)]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def enumerate_devices() -> list[dict[str, str | None]]:
|
|
87
|
+
"""Return board identity metadata without opening a HID connection."""
|
|
88
|
+
return [{
|
|
89
|
+
"product_name": info.get("product_string") or "PicoForge",
|
|
90
|
+
"serial_number": info.get("serial_number") or None,
|
|
91
|
+
"device_path": _path_string(info.get("path")),
|
|
92
|
+
} for info in _matching_devices()]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _select_device(serial_number: str | None, device_path: str | None) -> dict[str, Any]:
|
|
96
|
+
if serial_number is not None and device_path is not None:
|
|
97
|
+
raise ValueError("--serial and --device-path cannot be used together")
|
|
98
|
+
matches = _matching_devices()
|
|
99
|
+
if serial_number is not None:
|
|
100
|
+
matches = [info for info in matches if info.get("serial_number") == serial_number]
|
|
101
|
+
if device_path is not None:
|
|
102
|
+
matches = [info for info in matches if _path_string(info.get("path")) == device_path]
|
|
103
|
+
if not matches:
|
|
104
|
+
raise RuntimeError("PicoForge HID interface not found; check the USB connection and HID permissions")
|
|
105
|
+
if len(matches) != 1:
|
|
106
|
+
raise RuntimeError("multiple PicoForge HID interfaces matched; select one with --serial or --device-path")
|
|
107
|
+
return matches[0]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class PicoForgeHid:
|
|
111
|
+
"""Own one PicoForge HID connection and expose decoded reports."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, serial_number: str | None = None, device_path: str | None = None) -> None:
|
|
114
|
+
info = _select_device(serial_number, device_path)
|
|
115
|
+
device = _require_hid().device()
|
|
116
|
+
try:
|
|
117
|
+
device.open_path(info["path"])
|
|
118
|
+
except OSError as error:
|
|
119
|
+
raise RuntimeError(
|
|
120
|
+
"failed to open PicoForge HID interface; check device permissions "
|
|
121
|
+
"(Linux setup: see host/python/README.md)"
|
|
122
|
+
) from error
|
|
123
|
+
self._device = device
|
|
124
|
+
self.closed = False
|
|
125
|
+
self._expected_serial_number = info.get("serial_number")
|
|
126
|
+
self.identity: dict[str, object] | None = None
|
|
127
|
+
self.configuration: dict[str, object] | None = None
|
|
128
|
+
self._transaction_id = 0
|
|
129
|
+
self.last_command_result: dict[str, object] | None = None
|
|
130
|
+
self._command_uncertain = False
|
|
131
|
+
|
|
132
|
+
def read_info(self) -> dict[str, object]:
|
|
133
|
+
self._require_open()
|
|
134
|
+
report = self._device.get_feature_report(IDENTITY_REPORT_ID, IDENTITY_FEATURE_SIZE)
|
|
135
|
+
self.identity = parse_device_identity_report(report)
|
|
136
|
+
if (self._expected_serial_number and self.identity.get("supported")
|
|
137
|
+
and str(self._expected_serial_number).upper() != self.identity["serial_number"]):
|
|
138
|
+
raise ValueError("HID identity UID disagrees with the USB serial string")
|
|
139
|
+
return self.identity
|
|
140
|
+
|
|
141
|
+
def read_configuration(self) -> dict[str, object]:
|
|
142
|
+
self._require_open()
|
|
143
|
+
identity = self.identity or self.read_info()
|
|
144
|
+
if not identity.get("supported"):
|
|
145
|
+
raise RuntimeError(f"unsupported product: {identity['product_name']}")
|
|
146
|
+
report = self._device.get_feature_report(CONFIGURATION_REPORT_ID, CONFIGURATION_FEATURE_SIZE)
|
|
147
|
+
self.configuration = parse_board_configuration_report(report, identity)
|
|
148
|
+
return self.configuration
|
|
149
|
+
|
|
150
|
+
def read_settings(self) -> dict[str, int]:
|
|
151
|
+
configuration = self.read_configuration()
|
|
152
|
+
return {
|
|
153
|
+
"system_clock_mhz": configuration["system_clock_mhz"],
|
|
154
|
+
"sdcard_profile": configuration["sdcard_profile"],
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
def read_status(self, timeout_ms: int = 250) -> dict[str, object] | None:
|
|
158
|
+
"""Consume non-status input reports while waiting up to timeout_ms for status."""
|
|
159
|
+
if timeout_ms < 0:
|
|
160
|
+
raise ValueError("timeout_ms must not be negative")
|
|
161
|
+
deadline = monotonic() + timeout_ms / 1000
|
|
162
|
+
remaining_ms = timeout_ms
|
|
163
|
+
while True:
|
|
164
|
+
item = self.read_input_report(remaining_ms)
|
|
165
|
+
if item is None:
|
|
166
|
+
return None
|
|
167
|
+
if item["kind"] == "runtime":
|
|
168
|
+
return item["data"]
|
|
169
|
+
remaining_ms = ceil((deadline - monotonic()) * 1000)
|
|
170
|
+
if remaining_ms <= 0:
|
|
171
|
+
return None
|
|
172
|
+
|
|
173
|
+
def read_input_report(self, timeout_ms: int = 250) -> dict[str, object] | None:
|
|
174
|
+
if timeout_ms < 0:
|
|
175
|
+
raise ValueError("timeout_ms must not be negative")
|
|
176
|
+
self._require_open()
|
|
177
|
+
report = self._device.read(
|
|
178
|
+
max(TELEMETRY_INPUT_SIZE, STORAGE_INPUT_SIZE, SELF_TEST_INPUT_SIZE), timeout_ms
|
|
179
|
+
)
|
|
180
|
+
if not report:
|
|
181
|
+
return None
|
|
182
|
+
identity = self.identity or self.read_info()
|
|
183
|
+
if not identity.get("supported"):
|
|
184
|
+
raise RuntimeError(f"unsupported product: {identity['product_name']}")
|
|
185
|
+
if report[0] == STORAGE_REPORT_ID:
|
|
186
|
+
data = parse_storage_report(report, identity)
|
|
187
|
+
return {"kind": "memory", "data": data}
|
|
188
|
+
if report[0] == SELF_TEST_REPORT_ID:
|
|
189
|
+
if not identity["self_test_supported"]:
|
|
190
|
+
raise ValueError("device published self-test status without advertising capability bit 5")
|
|
191
|
+
return {"kind": "self_test", "data": parse_self_test_status_report(report)}
|
|
192
|
+
if report[0] == TELEMETRY_REPORT_ID:
|
|
193
|
+
return {"kind": "runtime", "data": parse_telemetry_report(report, identity)}
|
|
194
|
+
raise ValueError(f"unexpected HID Input report ID {report[0]}")
|
|
195
|
+
|
|
196
|
+
def set_led(self, on: bool) -> dict[str, object]:
|
|
197
|
+
self._require_open()
|
|
198
|
+
identity = self.identity or self.read_info()
|
|
199
|
+
if not identity["capabilities"] & CAP_LED:
|
|
200
|
+
raise RuntimeError("board identification LED is unavailable")
|
|
201
|
+
return self._execute_control(build_led_command_report(on, self._next_transaction_id()), 1)
|
|
202
|
+
|
|
203
|
+
def set_settings(self, settings: dict[str, object]) -> dict[str, object]:
|
|
204
|
+
self._require_open()
|
|
205
|
+
identity = self.identity or self.read_info()
|
|
206
|
+
if not identity["capabilities"] & CAP_SAVE_SETTINGS:
|
|
207
|
+
raise RuntimeError("persistent settings are unavailable on this firmware")
|
|
208
|
+
command = build_settings_command_report(settings, self._next_transaction_id())
|
|
209
|
+
result = self._execute_control(command, 6)
|
|
210
|
+
if result["status"] != "completed":
|
|
211
|
+
raise RuntimeError(f"settings command {result['status']}: {result['error']}")
|
|
212
|
+
saved = result["saved_settings"]
|
|
213
|
+
if saved != settings:
|
|
214
|
+
raise RuntimeError("firmware did not confirm the selected boot settings")
|
|
215
|
+
return saved
|
|
216
|
+
|
|
217
|
+
def reboot(self) -> dict[str, object]:
|
|
218
|
+
self._require_open()
|
|
219
|
+
identity = self.identity or self.read_info()
|
|
220
|
+
if not identity["capabilities"] & CAP_REBOOT:
|
|
221
|
+
raise RuntimeError("standalone reboot is unavailable on this firmware")
|
|
222
|
+
command = build_control_command_report(self._next_transaction_id(), 2, flags=1)
|
|
223
|
+
return self._execute_control(command, 2)
|
|
224
|
+
|
|
225
|
+
def set_msc(self, enable: bool, *, force: bool = False) -> dict[str, object]:
|
|
226
|
+
self._require_open()
|
|
227
|
+
identity = self.identity or self.read_info()
|
|
228
|
+
if not identity["capabilities"] & (1 << 3 | 1 << 4):
|
|
229
|
+
raise RuntimeError("MSC control is unavailable without a selected storage transport")
|
|
230
|
+
return self._execute_control(
|
|
231
|
+
build_msc_command_report(enable, force=force, transaction_id=self._next_transaction_id()), 3
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def close(self) -> None:
|
|
235
|
+
if not self.closed:
|
|
236
|
+
self._device.close()
|
|
237
|
+
self.closed = True
|
|
238
|
+
|
|
239
|
+
def set_self_test(self, action: str, size_mib: int | None = None) -> dict[str, object]:
|
|
240
|
+
self._require_open()
|
|
241
|
+
identity = self.identity or self.read_info()
|
|
242
|
+
if not identity["capabilities"] & CAP_SELF_TEST:
|
|
243
|
+
raise RuntimeError("SD self-test is unavailable on this firmware")
|
|
244
|
+
command = build_self_test_command_report(action, size_mib, self._next_transaction_id())
|
|
245
|
+
return self._execute_control(command, 4)
|
|
246
|
+
|
|
247
|
+
def _next_transaction_id(self) -> int:
|
|
248
|
+
self._transaction_id = self._transaction_id % 255 + 1
|
|
249
|
+
return self._transaction_id
|
|
250
|
+
|
|
251
|
+
def _execute_control(self, command: bytes, opcode: int) -> dict[str, object]:
|
|
252
|
+
if self._command_uncertain:
|
|
253
|
+
raise RuntimeError("a prior HID command has an uncertain outcome; reconnect and inspect device state")
|
|
254
|
+
sent = self._device.send_feature_report(list(command))
|
|
255
|
+
if sent != len(command):
|
|
256
|
+
raise OSError(f"failed to send HID control opcode {opcode}")
|
|
257
|
+
transaction_id = command[2]
|
|
258
|
+
deadline = monotonic() + 5.0
|
|
259
|
+
while True:
|
|
260
|
+
try:
|
|
261
|
+
report = self._device.get_feature_report(CONTROL_REPORT_ID, CONTROL_FEATURE_SIZE)
|
|
262
|
+
result = parse_control_result_report(report, self.identity)
|
|
263
|
+
except (OSError, ValueError):
|
|
264
|
+
self._command_uncertain = True
|
|
265
|
+
raise
|
|
266
|
+
if result["transaction_id"] == transaction_id and result["opcode"] == opcode:
|
|
267
|
+
if result["status"] != "pending":
|
|
268
|
+
self.last_command_result = result
|
|
269
|
+
return result
|
|
270
|
+
if monotonic() >= deadline:
|
|
271
|
+
self._command_uncertain = True
|
|
272
|
+
raise TimeoutError(
|
|
273
|
+
f"timed out waiting for HID control transaction {transaction_id}; outcome is uncertain"
|
|
274
|
+
)
|
|
275
|
+
sleep(0.05)
|
|
276
|
+
|
|
277
|
+
def _require_open(self) -> None:
|
|
278
|
+
if self.closed:
|
|
279
|
+
raise RuntimeError("PicoForge HID connection is closed")
|
|
280
|
+
|
|
281
|
+
def __enter__(self) -> "PicoForgeHid":
|
|
282
|
+
self._require_open()
|
|
283
|
+
return self
|
|
284
|
+
|
|
285
|
+
def __exit__(self, *_: object) -> None:
|
|
286
|
+
self.close()
|