smpclient 3.1.0__tar.gz → 3.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: smpclient
3
- Version: 3.1.0
3
+ Version: 3.2.0
4
4
  Summary: Simple Management Protocol (SMP) Client for remotely managing MCU firmware
5
5
  License: Apache-2.0
6
6
  Author: J.P. Hutchins
@@ -84,11 +84,27 @@ class SMPClient:
84
84
  upgrade: bool = False,
85
85
  first_timeout_s: float = 40.000,
86
86
  subsequent_timeout_s: float = 2.500,
87
+ use_sha: bool = True,
87
88
  ) -> AsyncIterator[int]:
88
- """Iteratively upload an `image` to `slot`, yielding the offset."""
89
-
90
- if self._transport.max_unencoded_size < 23:
91
- raise Exception("Upload requires an MTU >=23.")
89
+ """Iteratively upload an `image` to `slot`, yielding the offset.
90
+
91
+ Parameters:
92
+ - `image`: the `bytes` to upload
93
+ - `slot`: the slot to upload to (0 for default)
94
+ - `upgrade`: `True` to mark the image as confirmed. This is unsafe and
95
+ can cause a boot-loop that could brick the device. This setting
96
+ should be left at the default `False` and the image should be
97
+ confirmed from within the upgraded application. Zephyr provides
98
+ [boot_write_img_confirmed()](https://docs.zephyrproject.org/apidoc/latest/group__mcuboot__api.html#ga95ccc9e1c7460fec16b9ce9ac8ad7a72)
99
+ for this purpose.
100
+ - `first_timeout_s`: the timeout for the first `ImageUploadWrite` request
101
+ - `subsequent_timeout_s`: the timeout for subsequent `ImageUploadWrite` requests
102
+ - `use_sha`: `True` to include the SHA256 hash of the image in the first
103
+ packet.
104
+ - Zephyr's SMP server will fail with `MGMT_ERR.EINVAL` if the
105
+ MTU is too small to include both the SHA256 and the first 32-bytes
106
+ of the image. Increase the MTU or set `use_sha=False` in this case.
107
+ """
92
108
 
93
109
  response = await self.request(
94
110
  self._maximize_packet(
@@ -97,7 +113,7 @@ class SMPClient:
97
113
  data=b"",
98
114
  image=slot,
99
115
  len=len(image),
100
- sha=sha256(image).digest(),
116
+ sha=sha256(image).digest() if use_sha else None,
101
117
  upgrade=upgrade,
102
118
  ),
103
119
  image,
@@ -14,7 +14,7 @@ from serial import Serial, SerialException
14
14
  from smp import packet as smppacket
15
15
  from typing_extensions import override
16
16
 
17
- from smpclient.transport import SMPTransport
17
+ from smpclient.transport import SMPTransport, SMPTransportDisconnected
18
18
 
19
19
  logger = logging.getLogger(__name__)
20
20
 
@@ -68,7 +68,9 @@ class SMPSerialTransport(SMPTransport):
68
68
 
69
69
  def __init__(
70
70
  self,
71
- mtu: int = 4096,
71
+ max_smp_encoded_frame_size: int = 256,
72
+ line_length: int = 128,
73
+ line_buffers: int = 2,
72
74
  baudrate: int = 115200,
73
75
  bytesize: int = 8,
74
76
  parity: str = "N",
@@ -79,9 +81,42 @@ class SMPSerialTransport(SMPTransport):
79
81
  write_timeout: float | None = None,
80
82
  dsrdtr: bool = False,
81
83
  inter_byte_timeout: float | None = None,
82
- exclusive: float | None = None,
84
+ exclusive: bool | None = None,
83
85
  ) -> None:
84
- self._mtu: Final = mtu
86
+ """Initialize the serial transport.
87
+
88
+ Parameters:
89
+ - `max_smp_encoded_frame_size`: The maximum size of an encoded SMP
90
+ frame. The SMP server needs to have a buffer large enough to
91
+ receive the encoded frame packets and to store the decoded frame.
92
+ - `line_length`: The maximum SMP packet size.
93
+ - `line_buffers`: The number of line buffers in the serial buffer.
94
+ - `baudrate`: The baudrate of the serial connection. OK to ignore for
95
+ USB CDC ACM.
96
+ - `bytesize`: The number of data bits.
97
+ - `parity`: The parity setting.
98
+ - `stopbits`: The number of stop bits.
99
+ - `timeout`: The read timeout.
100
+ - `xonxoff`: Enable software flow control.
101
+ - `rtscts`: Enable hardware (RTS/CTS) flow control.
102
+ - `write_timeout`: The write timeout.
103
+ - `dsrdtr`: Enable hardware (DSR/DTR) flow control.
104
+ - `inter_byte_timeout`: The inter-byte timeout.
105
+ - `exclusive`: The exclusive access timeout.
106
+
107
+ """
108
+ if max_smp_encoded_frame_size < line_length * line_buffers:
109
+ logger.error(
110
+ f"{max_smp_encoded_frame_size=} is less than {line_length=} * {line_buffers=}!"
111
+ )
112
+ elif max_smp_encoded_frame_size != line_length * line_buffers:
113
+ logger.warning(
114
+ f"{max_smp_encoded_frame_size=} is not equal to {line_length=} * {line_buffers=}!"
115
+ )
116
+
117
+ self._max_smp_encoded_frame_size: Final = max_smp_encoded_frame_size
118
+ self._line_length: Final = line_length
119
+ self._line_buffers: Final = line_buffers
85
120
  self._conn: Final = Serial(
86
121
  baudrate=baudrate,
87
122
  bytesize=bytesize,
@@ -125,18 +160,24 @@ class SMPSerialTransport(SMPTransport):
125
160
 
126
161
  @override
127
162
  async def send(self, data: bytes) -> None:
163
+ if len(data) > self.max_unencoded_size:
164
+ raise ValueError(
165
+ f"Data size {len(data)} exceeds maximum unencoded size {self.max_unencoded_size}"
166
+ )
128
167
  logger.debug(f"Sending {len(data)} bytes")
129
- for packet in smppacket.encode(data, line_length=self.mtu):
130
- if len(packet) > self.mtu: # pragma: no cover
131
- raise Exception(
132
- f"Encoded packet size {len(packet)} exceeds {self.mtu=}, this is a bug!"
133
- )
134
- self._conn.write(packet)
135
- logger.debug(f"Writing encoded packet of size {len(packet)}B; {self.mtu=}")
136
-
137
- # fake async until I get around to replacing pyserial
138
- while self._conn.out_waiting > 0:
139
- await asyncio.sleep(SMPSerialTransport._POLLING_INTERVAL_S)
168
+ try:
169
+ for packet in smppacket.encode(data, line_length=self._line_length):
170
+ self._conn.write(packet)
171
+ logger.debug(f"Writing encoded packet of size {len(packet)}B; {self._line_length=}")
172
+
173
+ # fake async until I get around to replacing pyserial
174
+ while self._conn.out_waiting > 0:
175
+ await asyncio.sleep(SMPSerialTransport._POLLING_INTERVAL_S)
176
+ except SerialException as e:
177
+ logger.error(f"Failed to send {len(data)} bytes: {e}")
178
+ raise SMPTransportDisconnected(
179
+ f"{self.__class__.__name__} disconnected from {self._conn.port}"
180
+ )
140
181
 
141
182
  logger.debug(f"Sent {len(data)} bytes")
142
183
 
@@ -153,6 +194,11 @@ class SMPSerialTransport(SMPTransport):
153
194
  except StopIteration as e:
154
195
  logger.debug(f"Finished receiving {len(e.value)} byte response")
155
196
  return e.value
197
+ except SerialException as e:
198
+ logger.error(f"Failed to receive response: {e}")
199
+ raise SMPTransportDisconnected(
200
+ f"{self.__class__.__name__} disconnected from {self._conn.port}"
201
+ )
156
202
 
157
203
  async def _readuntil(self) -> bytes:
158
204
  """Read `bytes` until the `delimiter` then return the `bytes` including the `delimiter`."""
@@ -257,32 +303,23 @@ class SMPSerialTransport(SMPTransport):
257
303
  @override
258
304
  @property
259
305
  def mtu(self) -> int:
260
- return self._mtu
306
+ return self._max_smp_encoded_frame_size
261
307
 
262
308
  @override
263
309
  @cached_property
264
310
  def max_unencoded_size(self) -> int:
265
- """The serial transport encodes each packet instead of sending SMP messages as raw bytes.
266
-
267
- The worst case size of an encoded SMP packet is:
268
- ```
269
- base64_cost(
270
- len(smp_message) + len(frame_length) + len(frame_crc16)
271
- ) + len(delimiter) + len(line_ending)
272
- ```
273
- This simplifies to:
274
- ```
275
- base64_cost(len(smp_message) + 4) + 3
276
- ```
277
-
278
- This property specifies the maximum size of an SMP message before it has been encoded for
279
- the serial transport.
280
- """
311
+ """The serial transport encodes each packet instead of sending SMP messages as raw bytes."""
281
312
 
313
+ # For each packet, AKA line_buffer, include the cost of the base64
314
+ # encoded frame_length and CRC16 and the start/continue delimiter.
315
+ # Add to that the cost of the stop delimiter.
282
316
  packet_framing_size: Final = (
283
317
  _base64_cost(smppacket.FRAME_LENGTH_STRUCT.size + smppacket.CRC16_STRUCT.size)
284
318
  + smppacket.DELIMITER_SIZE
285
- + len(smppacket.CR)
286
- )
319
+ ) * self._line_buffers + len(smppacket.CR)
287
320
 
321
+ # Get the number of unencoded bytes that can fit in self.mtu and
322
+ # subtract the cost of framing the separate packets.
323
+ # This is the maximum number of unencoded bytes that can be received by
324
+ # the SMP server with this transport configuration.
288
325
  return _base64_max(self.mtu) - packet_framing_size
File without changes
File without changes
File without changes
File without changes