Skip to content

Commit 209509d

Browse files
committed
chore: formatting
Signed-off-by: Jos Verlinde <[email protected]>
1 parent 79e8e14 commit 209509d

File tree

10 files changed

+100
-37
lines changed

10 files changed

+100
-37
lines changed

src/mptool/mptool/common.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ def micropython_versions(minver: str = "v1.9.2"):
8787
g = Github()
8888
_ = 1 / 0
8989
repo = g.get_repo("micropython/micropython")
90-
versions = [tag.name for tag in repo.get_tags() if parse(tag.name) >= parse(minver)]
90+
versions = [
91+
tag.name for tag in repo.get_tags() if parse(tag.name) >= parse(minver)
92+
]
9193
except Exception:
9294
versions = [
9395
"v9.99.9-preview",

src/mptool/mptool/downloader.py

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ def firmware_list(board_url: str, base_url: str, ext: str) -> List[str]:
7777
tags = soup.findAll(
7878
"a",
7979
recursive=True,
80-
attrs={"href": re.compile(r"^/resources/firmware/.*\." + ext.lstrip(".") + "$")},
80+
attrs={
81+
"href": re.compile(r"^/resources/firmware/.*\." + ext.lstrip(".") + "$")
82+
},
8183
)
8284
if "?" in base_url:
8385
base_url = base_url.split("?")[0]
@@ -92,7 +94,9 @@ def firmware_list(board_url: str, base_url: str, ext: str) -> List[str]:
9294
# boards we are interested in ( this avoids getting a lot of boards we don't care about)
9395
# The first run takes ~60 seconds to run for 4 ports , all boards
9496
# so it makes sense to cache the results and skip boards as soon as possible
95-
def get_boards(fw_types: Dict[str, str], board_list: List[str], clean: bool) -> List[FirmwareInfo]:
97+
def get_boards(
98+
fw_types: Dict[str, str], board_list: List[str], clean: bool
99+
) -> List[FirmwareInfo]:
96100
board_urls: List[FirmwareInfo] = []
97101
for port in fw_types:
98102
download_page_url = f"{MICROPYTHON_ORG_URL}download/?port={port}"
@@ -103,7 +107,9 @@ def get_boards(fw_types: Dict[str, str], board_list: List[str], clean: bool) ->
103107
for board in _urls:
104108
board["port"] = port
105109

106-
for board in track(_urls, description="Checking download pages", transient=True):
110+
for board in track(
111+
_urls, description="Checking download pages", transient=True
112+
):
107113
# add a board to the list for each firmware found
108114
firmwares = firmware_list(board["url"], MICROPYTHON_ORG_URL, fw_types[port])
109115
for _url in firmwares:
@@ -124,7 +130,11 @@ def get_boards(fw_types: Dict[str, str], board_list: List[str], clean: bool) ->
124130
# remove hash from firmware name
125131
fname = re.sub(RE_HASH, ".", fname)
126132
board["filename"] = fname
127-
board["variant"] = board["filename"].split("-v")[0] if "-v" in board["filename"] else ""
133+
board["variant"] = (
134+
board["filename"].split("-v")[0]
135+
if "-v" in board["filename"]
136+
else ""
137+
)
128138
board_urls.append(board.copy())
129139
return board_urls
130140

@@ -161,7 +171,9 @@ def download_firmwares(
161171

162172
firmware_folder.mkdir(exist_ok=True)
163173

164-
with open(firmware_folder / "firmware.jsonl", "a", encoding="utf-8", buffering=1) as f_jsonl:
174+
with open(
175+
firmware_folder / "firmware.jsonl", "a", encoding="utf-8", buffering=1
176+
) as f_jsonl:
165177
for board in unique_boards:
166178
filename = firmware_folder / board["port"] / board["filename"]
167179
filename.parent.mkdir(exist_ok=True)
@@ -185,16 +197,21 @@ def download_firmwares(
185197
log.info(f"Downloaded {downloaded} firmwares, skipped {skipped} existing files.")
186198

187199

188-
def get_firmware_list(board_list: List[str], version_list: List[str], preview: bool, clean: bool):
200+
def get_firmware_list(
201+
board_list: List[str], version_list: List[str], preview: bool, clean: bool
202+
):
189203
log.trace("Checking MicroPython download pages")
190204

191-
board_urls = sorted(get_boards(PORT_FWTYPES, board_list, clean), key=key_fw_variant_ver)
205+
board_urls = sorted(
206+
get_boards(PORT_FWTYPES, board_list, clean), key=key_fw_variant_ver
207+
)
192208

193209
log.debug(f"Total {len(board_urls)} firmwares")
194210
relevant = [
195211
board
196212
for board in board_urls
197-
if board["board"] in board_list and (board["version"] in version_list or board["preview"] and preview)
213+
if board["board"] in board_list
214+
and (board["version"] in version_list or board["preview"] and preview)
198215
# and b["port"] in ["esp32", "rp2"]
199216
]
200217
log.debug(f"Matching firmwares: {len(relevant)}")
@@ -208,7 +225,10 @@ def get_firmware_list(board_list: List[str], version_list: List[str], preview: b
208225
return unique_boards
209226

210227

211-
@cli.command("download", help="Download MicroPython firmware for specific ports, boards and versions.")
228+
@cli.command(
229+
"download",
230+
help="Download MicroPython firmware for specific ports, boards and versions.",
231+
)
212232
@click.option(
213233
"--destination",
214234
"-d",
@@ -247,13 +267,19 @@ def get_firmware_list(board_list: List[str], version_list: List[str], preview: b
247267
help="""Force download of firmware even if it already exists.""",
248268
show_default=True,
249269
)
250-
def download(destination: Path, boards: List[str], versions: List[str], force: bool, clean: bool):
270+
def download(
271+
destination: Path, boards: List[str], versions: List[str], force: bool, clean: bool
272+
):
251273
versions = list(versions)
252274
# preview is not a version, it is an option to include preview versions
253275
preview = "preview" in versions
254276
versions = [v for v in versions if v != "preview"]
255277

256278
boards = list(boards) or DEFAULT_BOARDS
257-
versions = [clean_version(v, drop_v=True) for v in versions] # remove leading v from version
279+
versions = [
280+
clean_version(v, drop_v=True) for v in versions
281+
] # remove leading v from version
258282
destination.mkdir(exist_ok=True)
259-
download_firmwares(destination, boards, versions, preview=preview, force=force, clean=clean)
283+
download_firmwares(
284+
destination, boards, versions, preview=preview, force=force, clean=clean
285+
)

src/mptool/mptool/flash_esp.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,13 @@
1414
from stubber.bulk.mpremoteboard import MPRemoteBoard
1515

1616

17-
def flash_esp(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True) -> Optional[MPRemoteBoard]:
17+
def flash_esp(
18+
mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True
19+
) -> Optional[MPRemoteBoard]:
1820
if mcu.port not in ["esp32", "esp8266"] or mcu.board in ["ARDUINO_NANO_ESP32"]:
19-
log.error(f"esptool not supported for {mcu.port} {mcu.board} on {mcu.serialport}")
21+
log.error(
22+
f"esptool not supported for {mcu.port} {mcu.board} on {mcu.serialport}"
23+
)
2024
return None
2125

2226
log.info(f"Flashing {fw_file} on {mcu.board} on {mcu.serialport}")
@@ -27,7 +31,9 @@ def flash_esp(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True) -> Optio
2731
# baud_rate = str(115_200)
2832
cmds: List[List[str]] = []
2933
if erase:
30-
cmds.append(f"esptool --chip {mcu.cpu} --port {mcu.serialport} erase_flash".split())
34+
cmds.append(
35+
f"esptool --chip {mcu.cpu} --port {mcu.serialport} erase_flash".split()
36+
)
3137

3238
if mcu.cpu.upper() in ("ESP32", "ESP32S2"):
3339
start_addr = "0x1000"

src/mptool/mptool/flash_stm32.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ def get_stm32_start_address(fw_file: Path):
3333
return ""
3434

3535

36-
def flash_stm32(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True) -> Optional[MPRemoteBoard]:
36+
def flash_stm32(
37+
mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True
38+
) -> Optional[MPRemoteBoard]:
3739
"""
3840
Flash STM32 devices using STM32CubeProgrammer CLI
3941
- Enter bootloader mode
@@ -93,12 +95,16 @@ def flash_stm32(mcu: MPRemoteBoard, fw_file: Path, *, erase: bool = True) -> Opt
9395
"--erase",
9496
"all",
9597
]
96-
results = subprocess.run(cmd, capture_output=True, text=True).stdout.splitlines()
98+
results = subprocess.run(
99+
cmd, capture_output=True, text=True
100+
).stdout.splitlines()
97101
results = [strip_ansi(line) for line in results]
98102
log.info("Flashing")
99103
start_address = get_stm32_start_address(fw_file)
100104

101-
log.trace(f"STM32_Programmer_CLI --connect port=USB1 --write {str(fw_file)} --go {start_address}")
105+
log.trace(
106+
f"STM32_Programmer_CLI --connect port=USB1 --write {str(fw_file)} --go {start_address}"
107+
)
102108
cmd = [
103109
STM32_CLI,
104110
"--connect",

src/mptool/mptool/flash_uf2.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
from .flash_uf2_windows import wait_for_UF2_windows
1818

1919

20-
def flash_uf2(mcu: MPRemoteBoard, fw_file: Path, erase: bool) -> Optional[MPRemoteBoard]:
20+
def flash_uf2(
21+
mcu: MPRemoteBoard, fw_file: Path, erase: bool
22+
) -> Optional[MPRemoteBoard]:
2123
"""
2224
Flash .UF2 devices via bootloader and filecopy
2325
- mpremote bootloader
@@ -47,7 +49,11 @@ def flash_uf2(mcu: MPRemoteBoard, fw_file: Path, erase: bool) -> Optional[MPRemo
4749
log.error(f"OS {sys.platform} not supported")
4850
return None
4951

50-
if not destination or not destination.exists() or not (destination / "INFO_UF2.TXT").exists():
52+
if (
53+
not destination
54+
or not destination.exists()
55+
or not (destination / "INFO_UF2.TXT").exists()
56+
):
5157
log.error("Board is not in bootloader mode")
5258
return None
5359

src/mptool/mptool/flash_uf2_linux.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,20 @@
88
from typing import List
99
from .uf2_boardid import get_board_id
1010

11-
glb_dismount_me : List[UF2Disk] = []
11+
glb_dismount_me: List[UF2Disk] = []
12+
1213

1314
class UF2Disk:
1415
"""Info to support mounting and unmounting of UF2 drives on linux"""
16+
1517
device_path: str
1618
label: str
1719
mountpoint: str
1820

1921
def __repr__(self):
2022
return repr(self.__dict__)
2123

24+
2225
def get_uf2_drives():
2326
"""
2427
Get a list of all the (un)mounted UF2 drives
@@ -31,7 +34,7 @@ def get_uf2_drives():
3134

3235
myblkd = BlkDiskInfo()
3336
filters = {
34-
'tran': 'usb',
37+
"tran": "usb",
3538
}
3639
usb_disks = myblkd.get_disks(filters)
3740
for disk in usb_disks:
@@ -44,9 +47,16 @@ def get_uf2_drives():
4447
uf2.device_path = "/dev/" + uf2_part["name"]
4548
uf2.label = uf2_part["label"]
4649
uf2.mountpoint = uf2_part["mountpoint"]
47-
yield uf2
48-
elif disk["type"] == "disk" and disk.get("children") and len(disk.get("children")) > 0:
49-
if disk.get("children")[0]["type"] == "part" and disk.get("children")[0]["fstype"] == "vfat":
50+
yield uf2
51+
elif (
52+
disk["type"] == "disk"
53+
and disk.get("children")
54+
and len(disk.get("children")) > 0
55+
):
56+
if (
57+
disk.get("children")[0]["type"] == "part"
58+
and disk.get("children")[0]["fstype"] == "vfat"
59+
):
5060
uf2_part = disk.get("children")[0]
5161
# print( json.dumps(uf2_part, indent=4))
5262
uf2 = UF2Disk()
@@ -65,12 +75,13 @@ def pmount(disk: UF2Disk):
6575
if not disk.label:
6676
disk.label = "UF2BOOT"
6777
disk.mountpoint = f"/media/{disk.label}"
68-
subprocess.run(["pmount",disk.device_path, disk.mountpoint ])
78+
subprocess.run(["pmount", disk.device_path, disk.mountpoint])
6979
log.info(f"Mounted {disk.label} at {disk.mountpoint}")
7080
glb_dismount_me.append(disk)
7181
else:
7282
log.warning(f"{disk.label} already mounted at {disk.mountpoint}")
7383

84+
7485
def pumount(disk: UF2Disk):
7586
"""
7687
Unmount a UF2 drive
@@ -79,18 +90,20 @@ def pumount(disk: UF2Disk):
7990
log.error("pumount only works on Linux")
8091
return
8192
if disk.mountpoint:
82-
subprocess.run(["pumount", disk.mountpoint]) # ), f"/media/{disk.label}"])
93+
subprocess.run(["pumount", disk.mountpoint]) # ), f"/media/{disk.label}"])
8394
log.info(f"Unmounted {disk.label} from {disk.mountpoint}")
8495
disk.mountpoint = f""
8596
else:
8697
log.warning(f"{disk.label} already dismounted")
8798

99+
88100
def dismount_uf2():
89101
global glb_dismount_me
90102
for disk in glb_dismount_me:
91103
pumount(disk)
92104
glb_dismount_me = []
93105

106+
94107
def wait_for_UF2_linux():
95108
destination = ""
96109
wait = 10
@@ -102,9 +115,9 @@ def wait_for_UF2_linux():
102115
pmount(drive)
103116
time.sleep(1)
104117
if Path(drive.mountpoint, "INFO_UF2.TXT").exists():
105-
board_id = get_board_id(Path(drive.mountpoint)) # type: ignore
118+
board_id = get_board_id(Path(drive.mountpoint)) # type: ignore
106119
destination = Path(drive.mountpoint)
107120
break
108121
time.sleep(1)
109122
wait -= 1
110-
return destination
123+
return destination

src/mptool/mptool/flash_uf2_windows.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from loguru import logger as log
66
from .uf2_boardid import get_board_id
77

8+
89
def wait_for_UF2_windows():
910
destination = ""
1011
wait = 10
@@ -13,9 +14,9 @@ def wait_for_UF2_windows():
1314
drives = [drive.device for drive in psutil.disk_partitions()]
1415
for drive in drives:
1516
if Path(drive, "INFO_UF2.TXT").exists():
16-
board_id = get_board_id(Path(drive)) # type: ignore
17+
board_id = get_board_id(Path(drive)) # type: ignore
1718
destination = Path(drive)
1819
break
1920
time.sleep(1)
2021
wait -= 1
21-
return destination
22+
return destination

src/mptool/mptool/logger.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ def set_loglevel(loglevel: str):
3030
log.remove()
3131
except ValueError:
3232
pass
33-
log.add(console.print, level=loglevel.upper(), colorize=False, format=_log_formatter)
33+
log.add(
34+
console.print, level=loglevel.upper(), colorize=False, format=_log_formatter
35+
)
3436

3537
# log.add(
3638
# console.print,

src/mptool/mptool/uf2_boardid.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from pathlib import Path
22
from loguru import logger as log
33

4-
def get_board_id(path:Path):
4+
5+
def get_board_id(path: Path):
56
# Option : read Board-ID from INFO_UF2.TXT
67
board_id = "Unknown"
7-
with open(path / "INFO_UF2.TXT") as f:
8+
with open(path / "INFO_UF2.TXT") as f:
89
data = f.readlines()
910
for line in data:
1011
if line.startswith("Board-ID"):
1112
board_id = line[9:].strip()
1213
log.trace(f"Found Board-ID={board_id}")
13-
return board_id
14+
return board_id

src/mptool/tests/test_sort.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@
1414
# fws = flasher.find_firmware(fw_folder=fw_folder, port="samd", board="SEEED_WIO_TERMINAL",preview=True)
1515
# assert len(fws) > 0
1616
# assert fws[0]["board"] == "SEEED_WIO_TERMINAL"
17-
# assert int(fws[-1]["build"]) == 155
17+
# assert int(fws[-1]["build"]) == 155

0 commit comments

Comments
 (0)