micropython-stubber 1.24.1__py3-none-any.whl → 1.24.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.
- {micropython_stubber-1.24.1.dist-info → micropython_stubber-1.24.4.dist-info}/METADATA +9 -29
- micropython_stubber-1.24.4.dist-info/RECORD +107 -0
- {micropython_stubber-1.24.1.dist-info → micropython_stubber-1.24.4.dist-info}/WHEEL +1 -1
- stubber/__init__.py +1 -1
- stubber/board/createstubs.py +44 -38
- stubber/board/createstubs_db.py +17 -12
- stubber/board/createstubs_db_min.py +63 -63
- stubber/board/createstubs_db_mpy.mpy +0 -0
- stubber/board/createstubs_mem.py +17 -12
- stubber/board/createstubs_mem_min.py +99 -99
- stubber/board/createstubs_mem_mpy.mpy +0 -0
- stubber/board/createstubs_min.py +111 -112
- stubber/board/createstubs_mpy.mpy +0 -0
- stubber/board/modulelist.txt +27 -27
- stubber/codemod/board.py +1 -1
- stubber/codemod/enrich.py +13 -13
- stubber/codemod/merge_docstub.py +83 -53
- stubber/codemod/visitors/type_helpers.py +143 -41
- stubber/commands/enrich_folder_cmd.py +17 -17
- stubber/commands/get_docstubs_cmd.py +27 -9
- stubber/commands/get_frozen_cmd.py +1 -0
- stubber/commands/merge_cmd.py +2 -4
- stubber/merge_config.py +5 -36
- stubber/minify.py +3 -3
- stubber/modcat.py +118 -0
- stubber/publish/merge_docstubs.py +22 -5
- stubber/publish/stubpackage.py +33 -28
- stubber/rst/lookup.py +6 -23
- stubber/rst/reader.py +8 -13
- stubber/stubs_from_docs.py +2 -1
- stubber/tools/manifestfile.py +2 -1
- stubber/{cst_transformer.py → typing_collector.py} +36 -4
- micropython_stubber-1.24.1.dist-info/RECORD +0 -161
- mpflash/README.md +0 -220
- mpflash/libusb_flash.ipynb +0 -203
- mpflash/mpflash/__init__.py +0 -0
- mpflash/mpflash/add_firmware.py +0 -98
- mpflash/mpflash/ask_input.py +0 -236
- mpflash/mpflash/basicgit.py +0 -324
- mpflash/mpflash/bootloader/__init__.py +0 -2
- mpflash/mpflash/bootloader/activate.py +0 -60
- mpflash/mpflash/bootloader/detect.py +0 -82
- mpflash/mpflash/bootloader/manual.py +0 -101
- mpflash/mpflash/bootloader/micropython.py +0 -12
- mpflash/mpflash/bootloader/touch1200.py +0 -36
- mpflash/mpflash/cli_download.py +0 -129
- mpflash/mpflash/cli_flash.py +0 -224
- mpflash/mpflash/cli_group.py +0 -111
- mpflash/mpflash/cli_list.py +0 -87
- mpflash/mpflash/cli_main.py +0 -39
- mpflash/mpflash/common.py +0 -217
- mpflash/mpflash/config.py +0 -44
- mpflash/mpflash/connected.py +0 -96
- mpflash/mpflash/download.py +0 -364
- mpflash/mpflash/downloaded.py +0 -138
- mpflash/mpflash/errors.py +0 -9
- mpflash/mpflash/flash/__init__.py +0 -55
- mpflash/mpflash/flash/esp.py +0 -59
- mpflash/mpflash/flash/stm32.py +0 -19
- mpflash/mpflash/flash/stm32_dfu.py +0 -104
- mpflash/mpflash/flash/uf2/__init__.py +0 -88
- mpflash/mpflash/flash/uf2/boardid.py +0 -15
- mpflash/mpflash/flash/uf2/linux.py +0 -136
- mpflash/mpflash/flash/uf2/macos.py +0 -42
- mpflash/mpflash/flash/uf2/uf2disk.py +0 -12
- mpflash/mpflash/flash/uf2/windows.py +0 -43
- mpflash/mpflash/flash/worklist.py +0 -170
- mpflash/mpflash/list.py +0 -106
- mpflash/mpflash/logger.py +0 -41
- mpflash/mpflash/mpboard_id/__init__.py +0 -98
- mpflash/mpflash/mpboard_id/add_boards.py +0 -262
- mpflash/mpflash/mpboard_id/board.py +0 -37
- mpflash/mpflash/mpboard_id/board_id.py +0 -90
- mpflash/mpflash/mpboard_id/board_info.zip +0 -0
- mpflash/mpflash/mpboard_id/store.py +0 -48
- mpflash/mpflash/mpremoteboard/__init__.py +0 -271
- mpflash/mpflash/mpremoteboard/mpy_fw_info.py +0 -152
- mpflash/mpflash/mpremoteboard/runner.py +0 -140
- mpflash/mpflash/vendor/board_database.py +0 -185
- mpflash/mpflash/vendor/click_aliases.py +0 -91
- mpflash/mpflash/vendor/dfu.py +0 -165
- mpflash/mpflash/vendor/pydfu.py +0 -605
- mpflash/mpflash/vendor/readme.md +0 -12
- mpflash/mpflash/versions.py +0 -123
- mpflash/poetry.lock +0 -2603
- mpflash/pyproject.toml +0 -66
- mpflash/stm32_udev_rules.md +0 -63
- stubber/codemod/test_enrich.py +0 -87
- {micropython_stubber-1.24.1.dist-info → micropython_stubber-1.24.4.dist-info}/LICENSE +0 -0
- {micropython_stubber-1.24.1.dist-info → micropython_stubber-1.24.4.dist-info}/entry_points.txt +0 -0
mpflash/mpflash/download.py
DELETED
@@ -1,364 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Module to download MicroPython firmware for specific boards and versions.
|
3
|
-
Uses the micropython.org website to get the available versions and locations to download firmware files.
|
4
|
-
"""
|
5
|
-
|
6
|
-
import functools
|
7
|
-
import itertools
|
8
|
-
import re
|
9
|
-
from pathlib import Path
|
10
|
-
from typing import Dict, List, Optional
|
11
|
-
from urllib.parse import urljoin
|
12
|
-
|
13
|
-
# #########################################################################################################
|
14
|
-
# make sure that jsonlines does not mistake the MicroPython ujson for the CPython ujson
|
15
|
-
import jsonlines
|
16
|
-
import requests
|
17
|
-
from bs4 import BeautifulSoup
|
18
|
-
from loguru import logger as log
|
19
|
-
from rich.progress import track
|
20
|
-
|
21
|
-
from mpflash.common import PORT_FWTYPES, FWInfo
|
22
|
-
from mpflash.errors import MPFlashError
|
23
|
-
from mpflash.mpboard_id import get_known_ports
|
24
|
-
from mpflash.versions import clean_version
|
25
|
-
|
26
|
-
# avoid conflict with the ujson used by MicroPython
|
27
|
-
jsonlines.ujson = None # type: ignore
|
28
|
-
# #########################################################################################################
|
29
|
-
|
30
|
-
|
31
|
-
MICROPYTHON_ORG_URL = "https://micropython.org/"
|
32
|
-
|
33
|
-
# Regexes to remove dates and hashes in the filename that just get in the way
|
34
|
-
RE_DATE = r"(-\d{8}-)"
|
35
|
-
RE_HASH = r"(.g[0-9a-f]+\.)"
|
36
|
-
# regex to extract the version and the build from the firmware filename
|
37
|
-
# group 1 is the version, group 2 is the build
|
38
|
-
RE_VERSION_PREVIEW = r"v([\d\.]+)-?(?:preview\.)?(\d+)?\."
|
39
|
-
# 'RPI_PICO_W-v1.23.uf2'
|
40
|
-
# 'RPI_PICO_W-v1.23.0.uf2'
|
41
|
-
# 'RPI_PICO_W-v1.23.0-406.uf2'
|
42
|
-
# 'RPI_PICO_W-v1.23.0-preview.406.uf2'
|
43
|
-
# 'RPI_PICO_W-v1.23.0-preview.4.uf2'
|
44
|
-
# 'RPI_PICO_W-v1.23.0.uf2'
|
45
|
-
# 'https://micropython.org/resources/firmware/RPI_PICO_W-20240531-v1.24.0-preview.10.gc1a6b95bf.uf2'
|
46
|
-
# 'https://micropython.org/resources/firmware/RPI_PICO_W-20240531-v1.24.0-preview.10.uf2'
|
47
|
-
# 'RPI_PICO_W-v1.24.0-preview.10.gc1a6b95bf.uf2'
|
48
|
-
|
49
|
-
|
50
|
-
# use functools.lru_cache to avoid needing to download pages multiple times
|
51
|
-
@functools.lru_cache(maxsize=500)
|
52
|
-
def get_page(page_url: str) -> str:
|
53
|
-
"""Get the HTML of a page and return it as a string."""
|
54
|
-
response = requests.get(page_url)
|
55
|
-
return response.content.decode()
|
56
|
-
|
57
|
-
|
58
|
-
@functools.lru_cache(maxsize=500)
|
59
|
-
def get_board_urls(page_url: str) -> List[Dict[str, str]]:
|
60
|
-
"""
|
61
|
-
Get the urls to all the board pages listed on this page.
|
62
|
-
Assumes that all links to firmware have "class": "board-card"
|
63
|
-
|
64
|
-
Args:
|
65
|
-
page_url (str): The url of the page to get the board urls from.
|
66
|
-
|
67
|
-
Returns:
|
68
|
-
List[Dict[str, str]]: A list of dictionaries containing the board name and url.
|
69
|
-
|
70
|
-
"""
|
71
|
-
downloads_html = get_page(page_url)
|
72
|
-
soup = BeautifulSoup(downloads_html, "html.parser")
|
73
|
-
tags = soup.findAll("a", recursive=True, attrs={"class": "board-card"})
|
74
|
-
# assumes that all links are relative to the page url
|
75
|
-
boards = [tag.get("href") for tag in tags]
|
76
|
-
if "?" in page_url:
|
77
|
-
page_url = page_url.split("?")[0]
|
78
|
-
return [{"board": board, "url": page_url + board} for board in boards]
|
79
|
-
|
80
|
-
|
81
|
-
def board_firmware_urls(board_url: str, base_url: str, ext: str) -> List[str]:
|
82
|
-
"""
|
83
|
-
Get the urls to all the firmware files for a board.
|
84
|
-
Args:
|
85
|
-
page_url (str): The url of the page to get the board urls from.
|
86
|
-
??? base_url (str): The base url to join the relative urls to.
|
87
|
-
ext (str): The extension of the firmware files to get. (with or withouth leading .)
|
88
|
-
|
89
|
-
the urls are relative urls to the site root
|
90
|
-
|
91
|
-
"""
|
92
|
-
html = get_page(board_url)
|
93
|
-
soup = BeautifulSoup(html, "html.parser")
|
94
|
-
# get all the a tags:
|
95
|
-
# 1. that have a url that starts with `/resources/firmware/`
|
96
|
-
# 2. end with a matching extension for this port.
|
97
|
-
tags = soup.findAll(
|
98
|
-
"a",
|
99
|
-
recursive=True,
|
100
|
-
attrs={"href": re.compile(r"^/resources/firmware/.*\." + ext.lstrip(".") + "$")},
|
101
|
-
)
|
102
|
-
if "?" in base_url:
|
103
|
-
base_url = base_url.split("?")[0]
|
104
|
-
links: List = [urljoin(base_url, tag.get("href")) for tag in tags]
|
105
|
-
return links
|
106
|
-
|
107
|
-
|
108
|
-
# boards we are interested in ( this avoids getting a lot of boards we don't care about)
|
109
|
-
# The first run takes ~60 seconds to run for 4 ports , all boards
|
110
|
-
# so it makes sense to cache the results and skip boards as soon as possible
|
111
|
-
def get_boards(ports: List[str], boards: List[str], clean: bool) -> List[FWInfo]:
|
112
|
-
# sourcery skip: use-getitem-for-re-match-groups
|
113
|
-
"""
|
114
|
-
Retrieves a list of firmware information for the specified ports and boards.
|
115
|
-
|
116
|
-
Args:
|
117
|
-
ports (List[str]): The list of ports to check for firmware.
|
118
|
-
boards (List[str]): The list of boards to retrieve firmware information for.
|
119
|
-
clean (bool): A flag indicating whether to perform a clean retrieval.
|
120
|
-
|
121
|
-
Returns:
|
122
|
-
List[FWInfo]: A list of firmware information for the specified ports and boards.
|
123
|
-
|
124
|
-
"""
|
125
|
-
board_urls: List[FWInfo] = []
|
126
|
-
if ports is None:
|
127
|
-
ports = get_known_ports()
|
128
|
-
for port in ports:
|
129
|
-
download_page_url = f"{MICROPYTHON_ORG_URL}download/?port={port}"
|
130
|
-
urls = get_board_urls(download_page_url)
|
131
|
-
# filter out boards we don't care about
|
132
|
-
urls = [board for board in urls if board["board"] in boards]
|
133
|
-
# add the port to the board urls
|
134
|
-
for board in urls:
|
135
|
-
board["port"] = port
|
136
|
-
|
137
|
-
for board in track(
|
138
|
-
urls,
|
139
|
-
description=f"Checking {port} download pages",
|
140
|
-
transient=True,
|
141
|
-
refresh_per_second=1,
|
142
|
-
show_speed=False,
|
143
|
-
):
|
144
|
-
# add a board to the list for each firmware found
|
145
|
-
firmware_urls: List[str] = []
|
146
|
-
for ext in PORT_FWTYPES[port]:
|
147
|
-
firmware_urls += board_firmware_urls(board["url"], MICROPYTHON_ORG_URL, ext)
|
148
|
-
for _url in firmware_urls:
|
149
|
-
board["firmware"] = _url
|
150
|
-
fname = Path(board["firmware"]).name
|
151
|
-
if clean:
|
152
|
-
# remove date from firmware name
|
153
|
-
fname = re.sub(RE_DATE, "-", fname)
|
154
|
-
# remove hash from firmware name
|
155
|
-
fname = re.sub(RE_HASH, ".", fname)
|
156
|
-
fw_info = FWInfo(
|
157
|
-
filename=fname,
|
158
|
-
port=port,
|
159
|
-
board=board["board"],
|
160
|
-
preview="preview" in _url,
|
161
|
-
firmware=_url,
|
162
|
-
version="",
|
163
|
-
)
|
164
|
-
# board["firmware"] = _url
|
165
|
-
# board["preview"] = "preview" in _url # type: ignore
|
166
|
-
if ver_match := re.search(RE_VERSION_PREVIEW, _url):
|
167
|
-
fw_info.version = clean_version(ver_match.group(1))
|
168
|
-
fw_info.build = ver_match.group(2) or "0"
|
169
|
-
fw_info.preview = fw_info.build != "0"
|
170
|
-
# # else:
|
171
|
-
# # board.$1= ""
|
172
|
-
# if "preview." in fw_info.version:
|
173
|
-
# fw_info.build = fw_info.version.split("preview.")[-1]
|
174
|
-
# else:
|
175
|
-
# fw_info.build = "0"
|
176
|
-
|
177
|
-
fw_info.ext = Path(fw_info.firmware).suffix
|
178
|
-
fw_info.variant = fw_info.filename.split("-v")[0] if "-v" in fw_info.filename else ""
|
179
|
-
|
180
|
-
board_urls.append(fw_info)
|
181
|
-
return board_urls
|
182
|
-
|
183
|
-
|
184
|
-
def key_fw_ver_pre_ext_bld(x: FWInfo):
|
185
|
-
"sorting key for the retrieved board urls"
|
186
|
-
return x.variant, x.version, x.preview, x.ext, x.build
|
187
|
-
|
188
|
-
|
189
|
-
def key_fw_var_pre_ext(x: FWInfo):
|
190
|
-
"Grouping key for the retrieved board urls"
|
191
|
-
return x.variant, x.preview, x.ext
|
192
|
-
|
193
|
-
|
194
|
-
def download_firmwares(
|
195
|
-
firmware_folder: Path,
|
196
|
-
ports: List[str],
|
197
|
-
boards: List[str],
|
198
|
-
versions: Optional[List[str]] = None,
|
199
|
-
*,
|
200
|
-
force: bool = False,
|
201
|
-
clean: bool = True,
|
202
|
-
) -> int:
|
203
|
-
"""
|
204
|
-
Downloads firmware files based on the specified firmware folder, ports, boards, versions, force flag, and clean flag.
|
205
|
-
|
206
|
-
Args:
|
207
|
-
firmware_folder : The folder to save the downloaded firmware files.
|
208
|
-
ports : The list of ports to check for firmware.
|
209
|
-
boards : The list of boards to download firmware for.
|
210
|
-
versions : The list of versions to download firmware for.
|
211
|
-
force : A flag indicating whether to force the download even if the firmware file already exists.
|
212
|
-
clean : A flag indicating to clean the date from the firmware filename.
|
213
|
-
"""
|
214
|
-
skipped = downloaded = 0
|
215
|
-
versions = [] if versions is None else [clean_version(v) for v in versions]
|
216
|
-
# handle renamed boards
|
217
|
-
boards = add_renamed_boards(boards)
|
218
|
-
|
219
|
-
unique_boards = get_firmware_list(ports, boards, versions, clean)
|
220
|
-
|
221
|
-
for b in unique_boards:
|
222
|
-
log.debug(b.filename)
|
223
|
-
# relevant
|
224
|
-
|
225
|
-
log.info(f"Found {len(unique_boards)} relevant unique firmwares")
|
226
|
-
if not unique_boards:
|
227
|
-
log.error("No relevant firmwares could be found on https://micropython.org/download")
|
228
|
-
log.info(f"{versions=} {ports=} {boards=}")
|
229
|
-
log.info("Please check the website for the latest firmware files or try the preview version.")
|
230
|
-
return 0
|
231
|
-
|
232
|
-
firmware_folder.mkdir(exist_ok=True)
|
233
|
-
|
234
|
-
with jsonlines.open(firmware_folder / "firmware.jsonl", "a") as writer:
|
235
|
-
for board in unique_boards:
|
236
|
-
filename = firmware_folder / board.port / board.filename
|
237
|
-
filename.parent.mkdir(exist_ok=True)
|
238
|
-
if filename.exists() and not force:
|
239
|
-
skipped += 1
|
240
|
-
log.debug(f" {filename} already exists, skip download")
|
241
|
-
continue
|
242
|
-
log.info(f"Downloading {board.firmware}")
|
243
|
-
log.info(f" to {filename}")
|
244
|
-
try:
|
245
|
-
r = requests.get(board.firmware, allow_redirects=True)
|
246
|
-
with open(filename, "wb") as fw:
|
247
|
-
fw.write(r.content)
|
248
|
-
board.filename = str(filename.relative_to(firmware_folder))
|
249
|
-
except requests.RequestException as e:
|
250
|
-
log.exception(e)
|
251
|
-
continue
|
252
|
-
writer.write(board.to_dict())
|
253
|
-
downloaded += 1
|
254
|
-
# if downloaded > 0:
|
255
|
-
# clean_downloaded_firmwares(firmware_folder)
|
256
|
-
log.success(f"Downloaded {downloaded} firmwares, skipped {skipped} existing files.")
|
257
|
-
return downloaded + skipped
|
258
|
-
|
259
|
-
|
260
|
-
def get_firmware_list(ports: List[str], boards: List[str], versions: List[str], clean: bool):
|
261
|
-
"""
|
262
|
-
Retrieves a list of unique firmware information based on the specified ports, boards, versions, and clean flag.
|
263
|
-
|
264
|
-
Args:
|
265
|
-
ports : The list of ports to check for firmware.
|
266
|
-
boards : The list of boards to filter the firmware by.
|
267
|
-
versions : The list of versions to filter the firmware by.
|
268
|
-
clean : A flag indicating whether to perform a clean check.
|
269
|
-
|
270
|
-
Returns:
|
271
|
-
List[FWInfo]: A list of unique firmware information.
|
272
|
-
|
273
|
-
"""
|
274
|
-
|
275
|
-
log.trace("Checking MicroPython download pages")
|
276
|
-
preview = "preview" in versions
|
277
|
-
board_urls = sorted(get_boards(ports, boards, clean), key=key_fw_ver_pre_ext_bld)
|
278
|
-
|
279
|
-
log.debug(f"Total {len(board_urls)} firmwares")
|
280
|
-
|
281
|
-
relevant = [
|
282
|
-
board for board in board_urls if board.version in versions and board.build == "0" and board.board in boards and not board.preview
|
283
|
-
]
|
284
|
-
|
285
|
-
if preview:
|
286
|
-
relevant.extend([board for board in board_urls if board.board in boards and board.preview])
|
287
|
-
log.debug(f"Matching firmwares: {len(relevant)}")
|
288
|
-
# select the unique boards
|
289
|
-
unique_boards: List[FWInfo] = []
|
290
|
-
for _, g in itertools.groupby(relevant, key=key_fw_var_pre_ext):
|
291
|
-
# list is aleady sorted by build so we can just get the last item
|
292
|
-
sub_list = list(g)
|
293
|
-
unique_boards.append(sub_list[-1])
|
294
|
-
log.debug(f"Last preview only: {len(unique_boards)}")
|
295
|
-
return unique_boards
|
296
|
-
|
297
|
-
|
298
|
-
def download(
|
299
|
-
destination: Path,
|
300
|
-
ports: List[str],
|
301
|
-
boards: List[str],
|
302
|
-
versions: List[str],
|
303
|
-
force: bool,
|
304
|
-
clean: bool,
|
305
|
-
) -> int:
|
306
|
-
"""
|
307
|
-
Downloads firmware files based on the specified destination, ports, boards, versions, force flag, and clean flag.
|
308
|
-
|
309
|
-
Args:
|
310
|
-
destination : The destination folder to save the downloaded firmware files.
|
311
|
-
ports : The list of ports to check for firmware.
|
312
|
-
boards : The list of boards to download firmware for.
|
313
|
-
versions : The list of versions to download firmware for.
|
314
|
-
force : A flag indicating whether to force the download even if the firmware file already exists.
|
315
|
-
clean : A flag indicating whether to clean the date from the firmware filename.
|
316
|
-
|
317
|
-
Returns:
|
318
|
-
int: The number of downloaded firmware files.
|
319
|
-
|
320
|
-
Raises:
|
321
|
-
MPFlashError : If no boards are found or specified.
|
322
|
-
|
323
|
-
"""
|
324
|
-
if not boards:
|
325
|
-
log.critical("No boards found, please connect a board or specify boards to download firmware for.")
|
326
|
-
raise MPFlashError("No boards found")
|
327
|
-
|
328
|
-
try:
|
329
|
-
destination.mkdir(exist_ok=True, parents=True)
|
330
|
-
except (PermissionError, FileNotFoundError) as e:
|
331
|
-
log.critical(f"Could not create folder {destination}")
|
332
|
-
raise MPFlashError(f"Could not create folder {destination}") from e
|
333
|
-
try:
|
334
|
-
result = download_firmwares(destination, ports, boards, versions, force=force, clean=clean)
|
335
|
-
except requests.exceptions.RequestException as e:
|
336
|
-
log.exception(e)
|
337
|
-
raise MPFlashError("Could not connect to micropython.org") from e
|
338
|
-
|
339
|
-
return result
|
340
|
-
|
341
|
-
|
342
|
-
def add_renamed_boards(boards: List[str]) -> List[str]:
|
343
|
-
"""
|
344
|
-
Adds the renamed boards to the list of boards.
|
345
|
-
|
346
|
-
Args:
|
347
|
-
boards : The list of boards to add the renamed boards to.
|
348
|
-
|
349
|
-
Returns:
|
350
|
-
List[str]: The list of boards with the renamed boards added.
|
351
|
-
|
352
|
-
"""
|
353
|
-
renamed = {
|
354
|
-
"PICO": ["RPI_PICO"],
|
355
|
-
"PICO_W": ["RPI_PICO_W"],
|
356
|
-
"GENERIC": ["ESP32_GENERIC", "ESP8266_GENERIC"], # just add both of them
|
357
|
-
}
|
358
|
-
_boards = boards.copy()
|
359
|
-
for board in boards:
|
360
|
-
if board in renamed and renamed[board] not in boards:
|
361
|
-
_boards.extend(renamed[board])
|
362
|
-
if board != board.upper() and board.upper() not in boards:
|
363
|
-
_boards.append(board.upper())
|
364
|
-
return _boards
|
mpflash/mpflash/downloaded.py
DELETED
@@ -1,138 +0,0 @@
|
|
1
|
-
from pathlib import Path
|
2
|
-
from typing import Dict, List, Optional
|
3
|
-
|
4
|
-
import jsonlines
|
5
|
-
from loguru import logger as log
|
6
|
-
|
7
|
-
from mpflash.common import PORT_FWTYPES, FWInfo
|
8
|
-
from mpflash.versions import clean_version
|
9
|
-
|
10
|
-
from .config import config
|
11
|
-
|
12
|
-
|
13
|
-
# #########################################################################################################
|
14
|
-
def downloaded_firmwares(fw_folder: Path) -> List[FWInfo]:
|
15
|
-
"""Load a list of locally downloaded firmwares from the jsonl file"""
|
16
|
-
firmwares: List[FWInfo] = []
|
17
|
-
log.debug(f"Reading {fw_folder / 'firmware.jsonl' }")
|
18
|
-
try:
|
19
|
-
with jsonlines.open(fw_folder / "firmware.jsonl") as reader:
|
20
|
-
firmwares = [FWInfo.from_dict(item) for item in reader]
|
21
|
-
except FileNotFoundError:
|
22
|
-
log.error(f"No firmware.jsonl found in {fw_folder}")
|
23
|
-
except jsonlines.InvalidLineError as e:
|
24
|
-
log.error(f"Invalid firmware.jsonl found in {fw_folder} : {e}")
|
25
|
-
|
26
|
-
# sort by filename
|
27
|
-
firmwares.sort(key=lambda x: x.filename)
|
28
|
-
return firmwares
|
29
|
-
|
30
|
-
|
31
|
-
def clean_downloaded_firmwares(fw_folder: Path) -> None:
|
32
|
-
"""
|
33
|
-
Remove duplicate entries from the firmware.jsonl file, keeping the latest one
|
34
|
-
uniqueness is based on the filename
|
35
|
-
"""
|
36
|
-
firmwares = downloaded_firmwares(fw_folder)
|
37
|
-
if not firmwares:
|
38
|
-
return
|
39
|
-
# keep the latest entry
|
40
|
-
unique_fw = {fw.filename: fw for fw in firmwares}
|
41
|
-
with jsonlines.open(fw_folder / "firmware.jsonl", "w") as writer:
|
42
|
-
for fw in unique_fw.values():
|
43
|
-
writer.write(fw.to_dict())
|
44
|
-
log.info(f"Removed duplicate entries from firmware.jsonl in {fw_folder}")
|
45
|
-
|
46
|
-
|
47
|
-
def find_downloaded_firmware(
|
48
|
-
*,
|
49
|
-
board_id: str,
|
50
|
-
version: str = "", # v1.2.3
|
51
|
-
port: str = "",
|
52
|
-
variants: bool = False,
|
53
|
-
fw_folder: Optional[Path] = None,
|
54
|
-
trie: int = 1,
|
55
|
-
selector: Optional[Dict[str, str]] = None,
|
56
|
-
) -> List[FWInfo]:
|
57
|
-
if selector is None:
|
58
|
-
selector = {}
|
59
|
-
fw_folder = fw_folder or config.firmware_folder
|
60
|
-
# Use the information in firmwares.jsonl to find the firmware file
|
61
|
-
log.debug(f"{trie}] Looking for firmware for {board_id} {version} ")
|
62
|
-
fw_list = downloaded_firmwares(fw_folder)
|
63
|
-
if not fw_list:
|
64
|
-
log.error("No firmware files found. Please download the firmware first.")
|
65
|
-
return []
|
66
|
-
# filter by version
|
67
|
-
version = clean_version(version)
|
68
|
-
fw_list = filter_downloaded_fwlist(fw_list, board_id, version, port, variants, selector)
|
69
|
-
|
70
|
-
if not fw_list and trie < 3:
|
71
|
-
log.info(f"Try ({trie+1}) to find a firmware for the board {board_id}")
|
72
|
-
if trie == 1:
|
73
|
-
# ESP board naming conventions have changed by adding a PORT prefix
|
74
|
-
if port.startswith("esp") and not board_id.startswith(port.upper()):
|
75
|
-
board_id = f"{port.upper()}_{board_id}"
|
76
|
-
# RP2 board naming conventions have changed by adding a _RPI prefix
|
77
|
-
if port == "rp2" and not board_id.startswith("RPI_"):
|
78
|
-
board_id = f"RPI_{board_id}"
|
79
|
-
elif trie == 2:
|
80
|
-
board_id = board_id.replace("_", "-")
|
81
|
-
|
82
|
-
fw_list = find_downloaded_firmware(
|
83
|
-
fw_folder=fw_folder,
|
84
|
-
board_id=board_id,
|
85
|
-
version=version,
|
86
|
-
port=port,
|
87
|
-
trie=trie + 1,
|
88
|
-
selector=selector,
|
89
|
-
)
|
90
|
-
# hope we have a match now for the board
|
91
|
-
# sort by filename
|
92
|
-
fw_list.sort(key=lambda x: x.filename)
|
93
|
-
return fw_list
|
94
|
-
|
95
|
-
|
96
|
-
def filter_downloaded_fwlist(
|
97
|
-
fw_list: List[FWInfo],
|
98
|
-
board_id: str,
|
99
|
-
version: str, # v1.2.3
|
100
|
-
port: str,
|
101
|
-
# preview: bool,
|
102
|
-
variants: bool,
|
103
|
-
selector: dict,
|
104
|
-
) -> List[FWInfo]:
|
105
|
-
"""Filter the downloaded firmware list based on the provided parameters"""
|
106
|
-
if "preview" in version:
|
107
|
-
# never get a preview for an older version
|
108
|
-
fw_list = [fw for fw in fw_list if fw.preview]
|
109
|
-
else:
|
110
|
-
# older FWInfo version has no v1.2.3 prefix
|
111
|
-
either = [clean_version(version, drop_v=False), clean_version(version, drop_v=True)]
|
112
|
-
fw_list = [fw for fw in fw_list if fw.version in either]
|
113
|
-
log.trace(f"Filtering firmware for {version} : {len(fw_list)} found.")
|
114
|
-
# filter by port
|
115
|
-
if port:
|
116
|
-
fw_list = [
|
117
|
-
fw
|
118
|
-
for fw in fw_list
|
119
|
-
if fw.port == port and Path(fw.firmware).suffix in PORT_FWTYPES[port]
|
120
|
-
]
|
121
|
-
log.trace(f"Filtering firmware for {port} : {len(fw_list)} found.")
|
122
|
-
|
123
|
-
if board_id:
|
124
|
-
if variants:
|
125
|
-
# any variant of this board_id
|
126
|
-
fw_list = [fw for fw in fw_list if fw.board == board_id]
|
127
|
-
else:
|
128
|
-
# the firmware variant should match exactly the board_id
|
129
|
-
fw_list = [fw for fw in fw_list if fw.variant == board_id]
|
130
|
-
log.trace(f"Filtering firmware for {board_id} : {len(fw_list)} found.")
|
131
|
-
|
132
|
-
if selector and port in selector:
|
133
|
-
fw_list = [fw for fw in fw_list if fw.filename.endswith(selector[port])]
|
134
|
-
return fw_list
|
135
|
-
|
136
|
-
|
137
|
-
# #########################################################################################################
|
138
|
-
#
|
mpflash/mpflash/errors.py
DELETED
@@ -1,55 +0,0 @@
|
|
1
|
-
from pathlib import Path
|
2
|
-
|
3
|
-
from loguru import logger as log
|
4
|
-
|
5
|
-
from mpflash.bootloader import enter_bootloader
|
6
|
-
from mpflash.common import PORT_FWTYPES, BootloaderMethod
|
7
|
-
|
8
|
-
from .esp import flash_esp
|
9
|
-
from .stm32 import flash_stm32
|
10
|
-
from .uf2 import flash_uf2
|
11
|
-
from .worklist import WorkList
|
12
|
-
|
13
|
-
# #########################################################################################################
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
def flash_list(
|
18
|
-
todo: WorkList,
|
19
|
-
fw_folder: Path,
|
20
|
-
erase: bool,
|
21
|
-
bootloader: BootloaderMethod,
|
22
|
-
):
|
23
|
-
"""Flash a list of boards with the specified firmware."""
|
24
|
-
UF2_PORTS = [port for port, exts in PORT_FWTYPES.items() if ".uf2" in exts]
|
25
|
-
flashed = []
|
26
|
-
for mcu, fw_info in todo:
|
27
|
-
fw_file = fw_folder / fw_info.filename
|
28
|
-
if not fw_file.exists():
|
29
|
-
log.error(f"File {fw_file} does not exist, skipping {mcu.board} on {mcu.serialport}")
|
30
|
-
continue
|
31
|
-
log.info(f"Updating {mcu.board} on {mcu.serialport} to {fw_info.version}")
|
32
|
-
updated = None
|
33
|
-
try:
|
34
|
-
if mcu.port in UF2_PORTS and fw_file.suffix == ".uf2":
|
35
|
-
if not enter_bootloader(mcu, bootloader):
|
36
|
-
continue
|
37
|
-
updated = flash_uf2(mcu, fw_file=fw_file, erase=erase)
|
38
|
-
elif mcu.port in ["stm32"]:
|
39
|
-
if not enter_bootloader(mcu, bootloader):
|
40
|
-
continue
|
41
|
-
updated = flash_stm32(mcu, fw_file, erase=erase)
|
42
|
-
elif mcu.port in ["esp32", "esp8266"]:
|
43
|
-
# bootloader is handled by esptool for esp32/esp8266
|
44
|
-
updated = flash_esp(mcu, fw_file=fw_file, erase=erase)
|
45
|
-
else:
|
46
|
-
log.error(f"Don't (yet) know how to flash {mcu.port}-{mcu.board} on {mcu.serialport}")
|
47
|
-
except Exception as e:
|
48
|
-
log.error(f"Failed to flash {mcu.board} on {mcu.serialport}")
|
49
|
-
log.exception(e)
|
50
|
-
|
51
|
-
if updated:
|
52
|
-
flashed.append(updated)
|
53
|
-
else:
|
54
|
-
log.error(f"Failed to flash {mcu.board} on {mcu.serialport}")
|
55
|
-
return flashed
|
mpflash/mpflash/flash/esp.py
DELETED
@@ -1,59 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
# #########################################################################################################
|
3
|
-
# Flash ESP32 and ESP8266 via esptool
|
4
|
-
# #########################################################################################################
|
5
|
-
"""
|
6
|
-
|
7
|
-
from pathlib import Path
|
8
|
-
from typing import List, Optional
|
9
|
-
|
10
|
-
import esptool
|
11
|
-
from loguru import logger as log
|
12
|
-
|
13
|
-
from mpflash.mpboard_id import find_known_board
|
14
|
-
from mpflash.mpremoteboard import MPRemoteBoard
|
15
|
-
|
16
|
-
|
17
|
-
def flash_esp(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True) -> Optional[MPRemoteBoard]:
|
18
|
-
if mcu.port not in ["esp32", "esp8266"] or mcu.board.startswith("ARDUINO_"):
|
19
|
-
log.error(f"esptool not supported for {mcu.port} {mcu.board} on {mcu.serialport}")
|
20
|
-
return None
|
21
|
-
|
22
|
-
log.info(f"Flashing {fw_file} on {mcu.board} on {mcu.serialport}")
|
23
|
-
if not mcu.cpu:
|
24
|
-
# Lookup CPU based on the board name
|
25
|
-
mcu.cpu = find_known_board(mcu.board).cpu
|
26
|
-
|
27
|
-
cmds: List[List[str]] = []
|
28
|
-
if erase:
|
29
|
-
cmds.append(f"esptool --chip {mcu.cpu} --port {mcu.serialport} erase_flash".split())
|
30
|
-
|
31
|
-
if mcu.cpu.upper().startswith("ESP32"):
|
32
|
-
baud_rate = str(921_600)
|
33
|
-
if mcu.cpu.upper() in ("ESP32", "ESP32S2"):
|
34
|
-
start_addr = "0x1000"
|
35
|
-
elif mcu.cpu.upper() in ("ESP32S3", "ESP32C3"):
|
36
|
-
start_addr = "0x0"
|
37
|
-
cmds.append(
|
38
|
-
f"esptool --chip {mcu.cpu} --port {mcu.serialport} -b {baud_rate} write_flash --compress {start_addr}".split()
|
39
|
-
+ [str(fw_file)]
|
40
|
-
)
|
41
|
-
elif mcu.cpu.upper() == "ESP8266":
|
42
|
-
baud_rate = str(460_800)
|
43
|
-
start_addr = "0x0"
|
44
|
-
cmds.append(
|
45
|
-
f"esptool --chip {mcu.cpu} --port {mcu.serialport} -b {baud_rate} write_flash --flash_size=detect {start_addr}".split()
|
46
|
-
+ [str(fw_file)]
|
47
|
-
)
|
48
|
-
try:
|
49
|
-
for cmd in cmds:
|
50
|
-
log.info(f"Running {' '.join(cmd)} ")
|
51
|
-
esptool.main(cmd[1:])
|
52
|
-
except Exception as e:
|
53
|
-
log.error(f"Failed to flash {mcu.board} on {mcu.serialport} : {e}")
|
54
|
-
return None
|
55
|
-
|
56
|
-
log.info("Done flashing, resetting the board...")
|
57
|
-
mcu.wait_for_restart()
|
58
|
-
log.success(f"Flashed {mcu.serialport} to {mcu.board} {mcu.version}")
|
59
|
-
return mcu
|
mpflash/mpflash/flash/stm32.py
DELETED
@@ -1,19 +0,0 @@
|
|
1
|
-
"""Flash STM32 boards using pydfu"""
|
2
|
-
|
3
|
-
from pathlib import Path
|
4
|
-
|
5
|
-
from loguru import logger as log
|
6
|
-
|
7
|
-
from mpflash.mpremoteboard import MPRemoteBoard
|
8
|
-
|
9
|
-
# from .flash_stm32_cube import flash_stm32_cubecli
|
10
|
-
from .stm32_dfu import dfu_init, flash_stm32_dfu
|
11
|
-
|
12
|
-
|
13
|
-
def flash_stm32(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool):
|
14
|
-
# sourcery skip: lift-return-into-if
|
15
|
-
dfu_init()
|
16
|
-
if updated := flash_stm32_dfu(mcu, fw_file=fw_file, erase=erase):
|
17
|
-
mcu.wait_for_restart()
|
18
|
-
log.success(f"Flashed {mcu.version} to {mcu.board}")
|
19
|
-
return updated
|