Skip to content

Commit 8579db4

Browse files
committed
flash: improve exception message for reply mismatch
This changes the message to be human-readable instead of including the raw message data. Also add type hints while we are touching this class.
1 parent d49044b commit 8579db4

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

pybricksdev/flash.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import sys
1212
import zipfile
1313
from collections import namedtuple
14-
from typing import BinaryIO, Dict, Optional, Tuple, Union
14+
from typing import BinaryIO, Dict, List, Optional, Tuple, Union
1515

1616
import semver
1717
from tqdm.auto import tqdm
@@ -122,12 +122,12 @@ class BootloaderRequest:
122122

123123
def __init__(
124124
self,
125-
command,
126-
name,
127-
request_format,
128-
data_format,
129-
request_reply=True,
130-
write_with_response=True,
125+
command: BootloaderCommand,
126+
name: str,
127+
request_format: List[str],
128+
data_format: str,
129+
request_reply: bool = True,
130+
write_with_response: bool = True,
131131
):
132132
self.command = command
133133
self.ReplyClass = namedtuple(name, request_format)
@@ -137,17 +137,19 @@ def __init__(
137137
self.reply_len += 1
138138
self.write_with_response = write_with_response
139139

140-
def make_request(self, payload=None):
141-
request = bytearray((self.command,))
140+
def make_request(self, payload: Optional[bytes] = None) -> bytearray:
141+
request = bytearray([self.command])
142142
if payload is not None:
143143
request += payload
144144
return request
145145

146-
def parse_reply(self, reply):
146+
def parse_reply(self, reply) -> namedtuple:
147147
if reply[0] == self.command:
148148
return self.ReplyClass(*struct.unpack(self.data_format, reply[1:]))
149149
else:
150-
raise ValueError("Unknown message: {0}".format(reply))
150+
raise ValueError(
151+
f"Expecting reply to {self.command.name} but received {BootloaderCommand(reply[0]).name}"
152+
)
151153

152154

153155
class BootloaderConnection(BLERequestsConnection):

0 commit comments

Comments
 (0)