smpclient 1.3.2__tar.gz → 3.0.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.
Files changed (26) hide show
  1. {smpclient-1.3.2 → smpclient-3.0.0}/PKG-INFO +11 -5
  2. {smpclient-1.3.2 → smpclient-3.0.0}/README.md +5 -1
  3. {smpclient-1.3.2 → smpclient-3.0.0}/pyproject.toml +48 -7
  4. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/__init__.py +65 -15
  5. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/extensions/intercreate.py +1 -1
  6. smpclient-3.0.0/smpclient/generics.py +57 -0
  7. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/mcuboot.py +2 -0
  8. smpclient-3.0.0/smpclient/requests/image_management.py +22 -0
  9. smpclient-3.0.0/smpclient/requests/os_management.py +42 -0
  10. smpclient-3.0.0/smpclient/requests/shell_management.py +10 -0
  11. smpclient-3.0.0/smpclient/requests/user/intercreate.py +10 -0
  12. smpclient-3.0.0/smpclient/transport/__init__.py +50 -0
  13. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/transport/ble.py +46 -14
  14. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/transport/serial.py +31 -5
  15. smpclient-1.3.2/smpclient/generics.py +0 -83
  16. smpclient-1.3.2/smpclient/requests/image_management.py +0 -28
  17. smpclient-1.3.2/smpclient/requests/os_management.py +0 -24
  18. smpclient-1.3.2/smpclient/requests/shell_management.py +0 -20
  19. smpclient-1.3.2/smpclient/requests/user/intercreate.py +0 -20
  20. smpclient-1.3.2/smpclient/transport/__init__.py +0 -28
  21. {smpclient-1.3.2 → smpclient-3.0.0}/LICENSE +0 -0
  22. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/exceptions.py +0 -0
  23. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/extensions/__init__.py +0 -0
  24. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/py.typed +0 -0
  25. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/requests/__init__.py +0 -0
  26. {smpclient-1.3.2 → smpclient-3.0.0}/smpclient/requests/user/__init__.py +0 -0
@@ -1,20 +1,22 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: smpclient
3
- Version: 1.3.2
3
+ Version: 3.0.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
7
7
  Author-email: jphutchins@gmail.com
8
- Requires-Python: >=3.10,<3.13
8
+ Requires-Python: >=3.8.1,<3.13
9
9
  Classifier: License :: OSI Approved :: Apache Software License
10
10
  Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
11
12
  Classifier: Programming Language :: Python :: 3.10
12
13
  Classifier: Programming Language :: Python :: 3.11
13
14
  Classifier: Programming Language :: Python :: 3.12
14
- Requires-Dist: bleak (>=0.21.1,<0.22.0)
15
+ Requires-Dist: async-timeout (>=4.0.3,<5.0.0) ; python_version < "3.11"
16
+ Requires-Dist: bleak (>=0.22.1,<0.23.0)
15
17
  Requires-Dist: intelhex (>=2.3.0,<3.0.0)
16
18
  Requires-Dist: pyserial (>=3.5,<4.0)
17
- Requires-Dist: smp (>=0.3.4,<0.4.0)
19
+ Requires-Dist: smp (>=1.0.3,<2.0.0)
18
20
  Description-Content-Type: text/markdown
19
21
 
20
22
  # Simple Management Protocol (SMP) Client
@@ -54,12 +56,16 @@ If you'd like an SMP CLI application instead of a library, then you should try
54
56
  ```
55
57
  poetry add -G dev <my_dev_dependency>
56
58
  ```
59
+ 7. run tests for all supported python versions:
60
+ ```
61
+ tox
62
+ ```
57
63
 
58
64
  ## Development Environment Setup
59
65
 
60
66
  ### Install Dependencies
61
67
 
62
- - python >=3.10, <3.13
68
+ - python >=3.8, <3.13
63
69
  - poetry: https://python-poetry.org/docs/#installation
64
70
 
65
71
  ### Create the venv
@@ -35,12 +35,16 @@ If you'd like an SMP CLI application instead of a library, then you should try
35
35
  ```
36
36
  poetry add -G dev <my_dev_dependency>
37
37
  ```
38
+ 7. run tests for all supported python versions:
39
+ ```
40
+ tox
41
+ ```
38
42
 
39
43
  ## Development Environment Setup
40
44
 
41
45
  ### Install Dependencies
42
46
 
43
- - python >=3.10, <3.13
47
+ - python >=3.8, <3.13
44
48
  - poetry: https://python-poetry.org/docs/#installation
45
49
 
46
50
  ### Create the venv
@@ -19,12 +19,12 @@ mcuimg = "smpclient.mcuboot:mcuimg"
19
19
  source = "git-tag"
20
20
 
21
21
  [tool.poetry.dependencies]
22
- python = ">=3.10, <3.13"
22
+ python = ">=3.8.1, <3.13"
23
23
  pyserial = "^3.5"
24
- smp = "^0.3.4"
24
+ smp = "^1.0.3"
25
25
  intelhex = "^2.3.0"
26
- bleak = "^0.21.1"
27
-
26
+ bleak = "^0.22.1"
27
+ async-timeout = { version = "^4.0.3", python = "<3.11" }
28
28
 
29
29
  [tool.poetry.group.dev.dependencies]
30
30
  pytest = "^7.4.3"
@@ -36,21 +36,62 @@ mypy = "^1.7.0"
36
36
  mypy-extensions = "^1.0.0"
37
37
  pytest-asyncio = "^0.23.2"
38
38
  types-pyserial = "^3.5.0.11"
39
+ tox = "^4.15.0"
39
40
 
40
41
  [tool.black]
41
42
  line-length = 100
42
- skip-string-normalization = 1
43
+ skip-string-normalization = true
44
+ extend-exclude = "dutfirmware|.venv|tests/fixtures|.tox"
43
45
 
44
46
  [tool.isort]
45
47
  profile = "black"
46
48
  line_length = 100
47
49
  multi_line_output = 3
50
+ skip = [
51
+ ".venv",
52
+ "dutfirmware",
53
+ ".tox",
54
+ ]
48
55
 
49
56
  [tool.mypy]
50
57
  disallow_untyped_defs = true
51
- exclude = ['.venv']
58
+ exclude = ['.venv', 'dutfirmware', '.tox']
52
59
 
53
60
  [tool.pytest.ini_options]
61
+ norecursedirs = "dutfirmware/*"
54
62
  filterwarnings = [
55
63
  "ignore:The --rsyncdir:DeprecationWarning",
56
- ]
64
+ ]
65
+
66
+ [tool.tox]
67
+ legacy_tox_ini = """
68
+ [tox]
69
+ min_version = 4.15
70
+ env_list =
71
+ py38
72
+ py39
73
+ py310
74
+ py311
75
+ py312
76
+
77
+ [testenv]
78
+ allowlist_externals =
79
+ poetry
80
+ black
81
+ isort
82
+ flake8
83
+ mypy
84
+ coverage
85
+ commands =
86
+ poetry install
87
+ black --check .
88
+ isort --check-only .
89
+ flake8 .
90
+ mypy .
91
+ coverage erase
92
+ pytest --cov --maxfail=1
93
+ """
94
+
95
+ [build-system]
96
+ requires = ["poetry-core>=1.0.0"]
97
+ build-backend = "poetry.core.masonry.api"
@@ -1,17 +1,30 @@
1
1
  """Simple Management Protocol (SMP) Client."""
2
2
 
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
3
7
  from hashlib import sha256
4
- from typing import AsyncIterator, Final, Tuple, cast
8
+ from types import TracebackType
9
+ from typing import AsyncIterator, Final, Tuple, Type, cast
5
10
 
6
11
  from pydantic import ValidationError
7
12
  from smp import header as smpheader
8
13
  from smp import message as smpmsg
9
14
 
10
15
  from smpclient.exceptions import SMPBadSequence, SMPUploadError
11
- from smpclient.generics import SMPRequest, TEr0, TEr1, TErr, TRep, error, flatten_error, success
16
+ from smpclient.generics import SMPRequest, TEr0, TEr1, TRep, error, success
12
17
  from smpclient.requests.image_management import ImageUploadWrite
18
+ from smpclient.requests.os_management import MCUMgrParametersRead
13
19
  from smpclient.transport import SMPTransport
14
20
 
21
+ try:
22
+ from asyncio import timeout # type: ignore
23
+ except ImportError: # backport for Python3.10 and below
24
+ from async_timeout import timeout # type: ignore
25
+
26
+ logger = logging.getLogger(__name__)
27
+
15
28
 
16
29
  class SMPClient:
17
30
  def __init__(self, transport: SMPTransport, address: str):
@@ -19,15 +32,16 @@ class SMPClient:
19
32
  self._transport: Final = transport
20
33
  self._address: Final = address
21
34
 
22
- async def connect(self) -> None:
35
+ async def connect(self, timeout_s: float = 5.0) -> None:
23
36
  """Connect to the SMP server."""
24
- await self._transport.connect(self._address)
37
+ await self._transport.connect(self._address, timeout_s)
38
+ await self._initialize()
25
39
 
26
40
  async def disconnect(self) -> None:
27
41
  """Disconnect from the SMP server."""
28
42
  await self._transport.disconnect()
29
43
 
30
- async def request(self, request: SMPRequest[TRep, TEr0, TEr1, TErr]) -> TRep | TErr:
44
+ async def request(self, request: SMPRequest[TRep, TEr0, TEr1]) -> TRep | TEr0 | TEr1:
31
45
  """Make an `SMPRequest` to the SMP server."""
32
46
 
33
47
  frame = await self._transport.send_and_receive(request.BYTES)
@@ -38,13 +52,22 @@ class SMPClient:
38
52
  raise SMPBadSequence("Bad sequence")
39
53
 
40
54
  try:
41
- return request.Response.loads(frame) # type: ignore
55
+ return request._Response.loads(frame) # type: ignore
56
+ except ValidationError:
57
+ pass
58
+ try:
59
+ return request._ErrorV0.loads(frame)
42
60
  except ValidationError:
43
- return flatten_error( # type: ignore
44
- request.ErrorV0.loads(frame)
45
- if header.version == smpheader.Version.V0
46
- else request.ErrorV1.loads(frame)
61
+ pass
62
+ try:
63
+ return request._ErrorV1.loads(frame)
64
+ except ValidationError:
65
+ error_message = (
66
+ f"Response could not by parsed as one of {request._Response}, "
67
+ f"{request._ErrorV0}, or {request._ErrorV1}. {header=} {frame=}"
47
68
  )
69
+ logger.error(error_message)
70
+ raise ValidationError(error_message)
48
71
 
49
72
  async def upload(
50
73
  self, image: bytes, slot: int = 0, upgrade: bool = False
@@ -56,9 +79,9 @@ class SMPClient:
56
79
 
57
80
  response = await self.request(
58
81
  self._maximize_packet(
59
- ImageUploadWrite( # type: ignore
82
+ ImageUploadWrite(
60
83
  off=0,
61
- data=b'',
84
+ data=b"",
62
85
  image=slot,
63
86
  len=len(image),
64
87
  sha=sha256(image).digest(),
@@ -71,6 +94,8 @@ class SMPClient:
71
94
  if error(response):
72
95
  raise SMPUploadError(response)
73
96
  elif success(response):
97
+ if response.off is None:
98
+ raise SMPUploadError(f"No offset received: {response=}")
74
99
  yield response.off
75
100
  else: # pragma: no cover
76
101
  raise Exception("Unreachable")
@@ -78,11 +103,13 @@ class SMPClient:
78
103
  # send chunks until the SMP server reports that the offset is at the end of the image
79
104
  while response.off != len(image):
80
105
  response = await self.request(
81
- self._maximize_packet(ImageUploadWrite(off=response.off, data=b''), image)
106
+ self._maximize_packet(ImageUploadWrite(off=response.off, data=b""), image)
82
107
  )
83
108
  if error(response):
84
109
  raise SMPUploadError(response)
85
110
  elif success(response):
111
+ if response.off is None:
112
+ raise SMPUploadError(f"No offset received: {response=}")
86
113
  yield response.off
87
114
  else: # pragma: no cover
88
115
  raise Exception("Unreachable")
@@ -91,11 +118,18 @@ class SMPClient:
91
118
  def address(self) -> str:
92
119
  return self._address
93
120
 
94
- async def __aenter__(self) -> 'SMPClient':
121
+ async def __aenter__(self) -> "SMPClient":
95
122
  await self.connect()
96
123
  return self
97
124
 
98
- async def __aexit__(self) -> None:
125
+ async def __aexit__(
126
+ self,
127
+ exc_type: Type[BaseException] | None,
128
+ exc_value: BaseException | None,
129
+ traceback: TracebackType | None,
130
+ ) -> None:
131
+ if exc_value is not None:
132
+ logger.error(f"Exception in SMPClient: {exc_type=}, {exc_value=}, {traceback=}")
99
133
  await self.disconnect()
100
134
 
101
135
  @staticmethod
@@ -157,3 +191,19 @@ class SMPClient:
157
191
  sha=request.sha,
158
192
  upgrade=request.upgrade,
159
193
  )
194
+
195
+ async def _initialize(self) -> None:
196
+ """Gather initialization information from the SMP server."""
197
+
198
+ try:
199
+ async with timeout(2):
200
+ mcumgr_parameters = await self.request(MCUMgrParametersRead())
201
+ if success(mcumgr_parameters):
202
+ logger.debug(f"MCUMgr parameters: {mcumgr_parameters}")
203
+ self._transport.initialize(mcumgr_parameters.buf_size)
204
+ elif error(mcumgr_parameters):
205
+ logger.warning(f"Error reading MCUMgr parameters: {mcumgr_parameters}")
206
+ else:
207
+ raise Exception("Unreachable")
208
+ except asyncio.TimeoutError:
209
+ logger.warning("Timeout waiting for MCUMgr parameters")
@@ -17,7 +17,7 @@ class ICUploadClient(SMPClient):
17
17
  """Iteratively upload `data` to the SMP server, yielding the offset."""
18
18
 
19
19
  response = await self.request(
20
- ic.ImageUploadWrite(off=0, data=b'', image=image, len=len(data)) # type: ignore
20
+ ic.ImageUploadWrite(off=0, data=b'', image=image, len=len(data))
21
21
  )
22
22
 
23
23
  if error(response):
@@ -0,0 +1,57 @@
1
+ """Some Generic helpers for the SMP module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol, Type, TypeVar, Union
6
+
7
+ from smp import error as smperror
8
+ from smp import message as smpmessage
9
+ from typing_extensions import TypeGuard
10
+
11
+ TEr0 = TypeVar("TEr0", bound=smperror.ErrorV0)
12
+ TEr1 = TypeVar("TEr1", bound=smperror.ErrorV1)
13
+ TRep = TypeVar("TRep", bound=Union[smpmessage.ReadResponse, smpmessage.WriteResponse])
14
+
15
+
16
+ class SMPRequest(Protocol[TRep, TEr0, TEr1]):
17
+ """A `Protocol` that groups the expected response and errors with a request.
18
+
19
+ To use, inherit from an SMP Read or Write `Request` and define its expected
20
+ `Response`, `ErrorV0`, and `ErrorV1`.
21
+
22
+ Example:
23
+ ```python
24
+ class ImageStatesRead(smpimg.ImageStatesReadRequest):
25
+ _Response = smpimg.ImageStatesReadResponse
26
+ _ErrorV0 = smpimg.ImageManagementErrorV0
27
+ _ErrorV1 = smpimg.ImageManagementErrorV1
28
+ ```
29
+ """
30
+
31
+ _Response: Type[TRep]
32
+ _ErrorV0: Type[TEr0]
33
+ _ErrorV1: Type[TEr1]
34
+
35
+ @property
36
+ def BYTES(self) -> bytes: # pragma: no cover
37
+ ...
38
+
39
+
40
+ def error_v0(response: smperror.ErrorV0 | TEr1 | TRep) -> TypeGuard[smperror.ErrorV0]:
41
+ """`TypeGuard` that returns `True` if the `response` is an `ErrorV0`."""
42
+ return response.RESPONSE_TYPE == smpmessage.ResponseType.ERROR_V0
43
+
44
+
45
+ def error_v1(response: smperror.ErrorV0 | TEr1 | TRep) -> TypeGuard[TEr1]:
46
+ """`TypeGuard` that returns `True` if the `response` is an `ErrorV1`."""
47
+ return response.RESPONSE_TYPE == smpmessage.ResponseType.ERROR_V1
48
+
49
+
50
+ def error(response: smperror.ErrorV0 | TEr1 | TRep) -> TypeGuard[smperror.ErrorV0 | TEr1]:
51
+ """`TypeGuard` that returns `True` if the `response` is an `ErrorV0` or `ErrorV1`."""
52
+ return error_v0(response) or error_v1(response)
53
+
54
+
55
+ def success(response: smperror.ErrorV0 | TEr1 | TRep) -> TypeGuard[TRep]:
56
+ """`TypeGuard` that returns `True` if the `response` is a successful `Response`."""
57
+ return response.RESPONSE_TYPE == smpmessage.ResponseType.SUCCESS
@@ -3,6 +3,8 @@
3
3
  Specification: https://docs.mcuboot.com/design.html
4
4
  """
5
5
 
6
+ from __future__ import annotations
7
+
6
8
  import argparse
7
9
  import pathlib
8
10
  import struct
@@ -0,0 +1,22 @@
1
+ from smp import image_management as smpimg
2
+
3
+
4
+ class _ImageGroupBase:
5
+ _ErrorV0 = smpimg.ImageManagementErrorV0
6
+ _ErrorV1 = smpimg.ImageManagementErrorV1
7
+
8
+
9
+ class ImageStatesRead(smpimg.ImageStatesReadRequest, _ImageGroupBase):
10
+ _Response = smpimg.ImageStatesReadResponse
11
+
12
+
13
+ class ImageStatesWrite(smpimg.ImageStatesWriteRequest, _ImageGroupBase):
14
+ _Response = smpimg.ImageStatesWriteResponse
15
+
16
+
17
+ class ImageUploadWrite(smpimg.ImageUploadWriteRequest, _ImageGroupBase):
18
+ _Response = smpimg.ImageUploadProgressWriteResponse
19
+
20
+
21
+ class ImageErase(smpimg.ImageEraseRequest, _ImageGroupBase):
22
+ _Response = smpimg.ImageEraseResponse
@@ -0,0 +1,42 @@
1
+ from smp import os_management as smpos
2
+
3
+
4
+ class _OSGroupBase:
5
+ _ErrorV0 = smpos.OSManagementErrorV0
6
+ _ErrorV1 = smpos.OSManagementErrorV1
7
+
8
+
9
+ class EchoWrite(smpos.EchoWriteRequest, _OSGroupBase):
10
+ _Response = smpos.EchoWriteResponse
11
+
12
+
13
+ class ResetWrite(smpos.ResetWriteRequest, _OSGroupBase):
14
+ _Response = smpos.ResetWriteResponse
15
+
16
+
17
+ class TaskStatisticsRead(smpos.TaskStatisticsReadRequest, _OSGroupBase):
18
+ _Response = smpos.TaskStatisticsReadResponse
19
+
20
+
21
+ class MemoryPoolStatisticsRead(smpos.MemoryPoolStatisticsReadRequest, _OSGroupBase):
22
+ _Response = smpos.MemoryPoolStatisticsReadResponse
23
+
24
+
25
+ class DateTimeRead(smpos.DateTimeReadRequest, _OSGroupBase):
26
+ _Response = smpos.DateTimeReadResponse
27
+
28
+
29
+ class DateTimeWrite(smpos.DateTimeWriteRequest, _OSGroupBase):
30
+ _Response = smpos.DateTimeWriteResponse
31
+
32
+
33
+ class MCUMgrParametersRead(smpos.MCUMgrParametersReadRequest, _OSGroupBase):
34
+ _Response = smpos.MCUMgrParametersReadResponse
35
+
36
+
37
+ class OSApplicationInfoRead(smpos.OSApplicationInfoReadRequest, _OSGroupBase):
38
+ _Response = smpos.OSApplicationInfoReadResponse
39
+
40
+
41
+ class BootloaderInformationRead(smpos.BootloaderInformationReadRequest, _OSGroupBase):
42
+ _Response = smpos.BootloaderInformationReadResponse
@@ -0,0 +1,10 @@
1
+ from smp import shell_management as smpshell
2
+
3
+
4
+ class _ShellGroupBase:
5
+ _ErrorV0 = smpshell.ShellManagementErrorV0
6
+ _ErrorV1 = smpshell.ShellManagementErrorV1
7
+
8
+
9
+ class Execute(smpshell.ExecuteRequest, _ShellGroupBase):
10
+ _Response = smpshell.ExecuteResponse
@@ -0,0 +1,10 @@
1
+ from smp.user import intercreate as smpic
2
+
3
+
4
+ class _GroupBase:
5
+ _ErrorV0 = smpic.ErrorV0
6
+ _ErrorV1 = smpic.ErrorV1
7
+
8
+
9
+ class ImageUploadWrite(smpic.ImageUploadWriteRequest, _GroupBase):
10
+ _Response = smpic.ImageUploadWriteResponse
@@ -0,0 +1,50 @@
1
+ """Simple Management Protocol (SMP) Client Transport Protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol
6
+
7
+
8
+ class SMPTransport(Protocol):
9
+ _smp_server_transport_buffer_size: int | None = None
10
+ """The SMP server transport buffer size, in 8-bit bytes."""
11
+
12
+ async def connect(self, address: str, timeout_s: float) -> None: # pragma: no cover
13
+ """Connect the `SMPTransport`."""
14
+
15
+ async def disconnect(self) -> None: # pragma: no cover
16
+ """Disconnect the `SMPTransport`."""
17
+
18
+ async def send(self, data: bytes) -> None: # pragma: no cover
19
+ """Send the encoded `SMPRequest` `data`."""
20
+
21
+ async def receive(self) -> bytes: # pragma: no cover
22
+ """Receive the decoded `SMPResponse`."""
23
+
24
+ async def send_and_receive(self, data: bytes) -> bytes: # pragma: no cover
25
+ """Send the encoded `SMPRequest` `data` and receive the decoded `SMPResponse`."""
26
+
27
+ def initialize(self, smp_server_transport_buffer_size: int) -> None: # pragma: no cover
28
+ """Initialize the `SMPTransport` with the server transport buffer size."""
29
+ self._smp_server_transport_buffer_size = smp_server_transport_buffer_size
30
+
31
+ @property
32
+ def mtu(self) -> int: # pragma: no cover
33
+ """The Maximum Transmission Unit (MTU) in 8-bit bytes."""
34
+
35
+ @property
36
+ def max_unencoded_size(self) -> int: # pragma: no cover
37
+ """The maximum size of an unencoded message that can be sent, in 8-bit bytes."""
38
+
39
+ # There is a potential speedup in the future by taking advantage of the
40
+ # multiple buffers that are provided by the SMP server implementation.
41
+ # Generally, the idea is to send as many as buf_count messages BEFORE
42
+ # awaiting the response. This will allow the SMP server to buffer the
43
+ # new IO while waiting for flash writes to complete. It creates some
44
+ # complexity in both the client and server and it's debatable whether
45
+ # or not the speedup is worth the complexity. Specifically, if there is
46
+ # an error in some write, then some of the writes that have already been
47
+ # sent out are no longer valid. That is, the response to each
48
+ # concurrent write needs to be tracked very carefully!
49
+
50
+ return self._smp_server_transport_buffer_size or self.mtu
@@ -1,23 +1,28 @@
1
1
  """A Bluetooth Low Energy (BLE) SMPTransport."""
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  import asyncio
4
6
  import logging
7
+ import platform
5
8
  import re
6
- from typing import Final
9
+ from typing import Final, List
7
10
  from uuid import UUID
8
11
 
9
12
  from bleak import BleakClient, BleakGATTCharacteristic, BleakScanner
10
13
  from bleak.backends.device import BLEDevice
11
14
  from smp import header as smphdr
15
+ from typing_extensions import override
12
16
 
13
17
  from smpclient.exceptions import SMPClientException
18
+ from smpclient.transport import SMPTransport
14
19
 
15
20
  SMP_SERVICE_UUID: Final = UUID("8D53DC1D-1DB7-4CD3-868B-8A527460AA84")
16
21
  SMP_CHARACTERISTIC_UUID: Final = UUID("DA2E7828-FBCE-4E01-AE9E-261174997C48")
17
22
 
18
- MAC_ADDRESS_PATTERN: Final = re.compile(r'([0-9A-F]{2}[:]){5}[0-9A-F]{2}$', flags=re.IGNORECASE)
23
+ MAC_ADDRESS_PATTERN: Final = re.compile(r"([0-9A-F]{2}[:]){5}[0-9A-F]{2}$", flags=re.IGNORECASE)
19
24
  UUID_PATTERN: Final = re.compile(
20
- r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z',
25
+ r"^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z",
21
26
  flags=re.IGNORECASE,
22
27
  )
23
28
 
@@ -37,18 +42,19 @@ class SMPBLETransportNotSMPServer(SMPBLETransportException):
37
42
  logger = logging.getLogger(__name__)
38
43
 
39
44
 
40
- class SMPBLETransport:
45
+ class SMPBLETransport(SMPTransport):
41
46
  def __init__(self) -> None:
42
47
  self._buffer = bytearray()
43
48
  self._notify_condition = asyncio.Condition()
44
49
  logger.debug(f"Initialized {self.__class__.__name__}")
45
50
 
46
- async def connect(self, address: str) -> None:
51
+ @override
52
+ async def connect(self, address: str, timeout_s: float) -> None:
47
53
  logger.debug(f"Scanning for {address=}")
48
- device = (
49
- await BleakScanner.find_device_by_address(address) # type: ignore # upstream fix
54
+ device: BLEDevice | None = (
55
+ await BleakScanner.find_device_by_address(address, timeout=timeout_s)
50
56
  if MAC_ADDRESS_PATTERN.match(address) or UUID_PATTERN.match(address)
51
- else await BleakScanner.find_device_by_name(address) # type: ignore # upstream fix
57
+ else await BleakScanner.find_device_by_name(address)
52
58
  )
53
59
 
54
60
  if type(device) is BLEDevice:
@@ -64,21 +70,36 @@ class SMPBLETransport:
64
70
  if smp_characteristic is None:
65
71
  raise SMPBLETransportNotSMPServer("Missing the SMP characteristic UUID.")
66
72
  else:
73
+ logger.debug(f"Found SMP characteristic: {smp_characteristic=}")
74
+ logger.info(f"{smp_characteristic.max_write_without_response_size=}")
75
+ if (
76
+ platform.system() == "Windows"
77
+ and smp_characteristic.max_write_without_response_size == 20
78
+ ):
79
+ # https://github.com/hbldh/bleak/pull/1552#issuecomment-2105573291
80
+ logger.warning(
81
+ "The SMP characteristic MTU is 20 bytes, possibly a Windows bug, checking again"
82
+ )
83
+ await asyncio.sleep(2)
84
+ smp_characteristic._max_write_without_response_size = (
85
+ self._client._backend._session.max_pdu_size - 3 # type: ignore
86
+ )
87
+ logger.warning(f"{smp_characteristic.max_write_without_response_size=}")
88
+
67
89
  self._smp_characteristic = smp_characteristic
68
90
 
69
91
  logger.debug(f"Starting notify on {SMP_CHARACTERISTIC_UUID=}")
70
92
  await self._client.start_notify(SMP_CHARACTERISTIC_UUID, self._notify_callback)
71
93
  logger.debug(f"Started notify on {SMP_CHARACTERISTIC_UUID=}")
72
94
 
95
+ @override
73
96
  async def disconnect(self) -> None:
74
97
  logger.debug(f"Disonnecting from {self._client.address}")
75
98
  await self._client.disconnect()
76
99
  logger.debug(f"Disconnected from {self._client.address}")
77
100
 
101
+ @override
78
102
  async def send(self, data: bytes) -> None:
79
- # TODO: Unclear whether Bleak + SMP spec support transport-level fragmentation. We can
80
- # continue this manual fragmentation for now, but it is not ideal.
81
-
82
103
  logger.debug(f"Sending {len(data)} bytes, {self.mtu=}")
83
104
  for offset in range(0, len(data), self.mtu):
84
105
  await self._client.write_gatt_char(
@@ -86,6 +107,7 @@ class SMPBLETransport:
86
107
  )
87
108
  logger.debug(f"Sent {len(data)} bytes")
88
109
 
110
+ @override
89
111
  async def receive(self) -> bytes:
90
112
  # Note: self._buffer is mutated asynchronously by this method and self._notify_callback().
91
113
  # self._notify_condition is used to synchronize access to self._buffer.
@@ -128,10 +150,20 @@ class SMPBLETransport:
128
150
  await self.send(data)
129
151
  return await self.receive()
130
152
 
153
+ @override
131
154
  @property
132
155
  def mtu(self) -> int:
133
156
  return self._smp_characteristic.max_write_without_response_size
134
157
 
135
- @property
136
- def max_unencoded_size(self) -> int:
137
- return self.mtu
158
+ @staticmethod
159
+ async def scan(timeout: int = 5) -> List[BLEDevice]:
160
+ """Scan for BLE devices."""
161
+ logger.debug(f"Scanning for BLE devices for {timeout} seconds")
162
+ devices: Final = await BleakScanner(service_uuids=[str(SMP_SERVICE_UUID)]).discover(
163
+ timeout=timeout, return_adv=True
164
+ )
165
+ smp_servers: Final = [
166
+ d for d, a in devices.values() if SMP_SERVICE_UUID in {UUID(u) for u in a.service_uuids}
167
+ ]
168
+ logger.debug(f"Found {len(smp_servers)} SMP devices: {smp_servers=}")
169
+ return smp_servers
@@ -1,14 +1,20 @@
1
1
  """A serial SMPTransport."""
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  import asyncio
4
6
  import logging
5
7
  import math
8
+ import time
6
9
  from enum import IntEnum, unique
7
10
  from functools import cached_property
8
11
  from typing import Final
9
12
 
10
- from serial import Serial
13
+ from serial import Serial, SerialException
11
14
  from smp import packet as smppacket
15
+ from typing_extensions import override
16
+
17
+ from smpclient.transport import SMPTransport
12
18
 
13
19
  logger = logging.getLogger(__name__)
14
20
 
@@ -31,8 +37,9 @@ def _base64_max(size: int) -> int:
31
37
  return math.floor(3 / 4 * size) - 2
32
38
 
33
39
 
34
- class SMPSerialTransport:
40
+ class SMPSerialTransport(SMPTransport):
35
41
  _POLLING_INTERVAL_S = 0.005
42
+ _CONNECTION_RETRY_INTERVAL_S = 0.500
36
43
 
37
44
  class _ReadBuffer:
38
45
  """The state of the read buffer."""
@@ -91,17 +98,32 @@ class SMPSerialTransport:
91
98
  self._buffer = SMPSerialTransport._ReadBuffer()
92
99
  logger.debug(f"Initialized {self.__class__.__name__}")
93
100
 
94
- async def connect(self, address: str) -> None:
101
+ @override
102
+ async def connect(self, address: str, timeout_s: float) -> None:
95
103
  self._conn.port = address
96
104
  logger.debug(f"Connecting to {self._conn.port=}")
97
- self._conn.open()
98
- logger.debug(f"Connected to {self._conn.port=}")
105
+ start_time: Final = time.time()
106
+ while time.time() - start_time <= timeout_s:
107
+ try:
108
+ self._conn.open()
109
+ logger.debug(f"Connected to {self._conn.port=}")
110
+ return
111
+ except SerialException as e:
112
+ logger.debug(
113
+ f"Failed to connect to {self._conn.port=}: {e}, "
114
+ f"retrying in {SMPSerialTransport._CONNECTION_RETRY_INTERVAL_S} seconds"
115
+ )
116
+ await asyncio.sleep(SMPSerialTransport._CONNECTION_RETRY_INTERVAL_S)
117
+
118
+ raise TimeoutError(f"Failed to connect to {address=}")
99
119
 
120
+ @override
100
121
  async def disconnect(self) -> None:
101
122
  logger.debug(f"Disconnecting from {self._conn.port=}")
102
123
  self._conn.close()
103
124
  logger.debug(f"Disconnected from {self._conn.port=}")
104
125
 
126
+ @override
105
127
  async def send(self, data: bytes) -> None:
106
128
  logger.debug(f"Sending {len(data)} bytes")
107
129
  for packet in smppacket.encode(data, line_length=self.mtu):
@@ -118,6 +140,7 @@ class SMPSerialTransport:
118
140
 
119
141
  logger.debug(f"Sent {len(data)} bytes")
120
142
 
143
+ @override
121
144
  async def receive(self) -> bytes:
122
145
  decoder = smppacket.decode()
123
146
  next(decoder)
@@ -226,14 +249,17 @@ class SMPSerialTransport:
226
249
 
227
250
  return out
228
251
 
252
+ @override
229
253
  async def send_and_receive(self, data: bytes) -> bytes:
230
254
  await self.send(data)
231
255
  return await self.receive()
232
256
 
257
+ @override
233
258
  @property
234
259
  def mtu(self) -> int:
235
260
  return self._mtu
236
261
 
262
+ @override
237
263
  @cached_property
238
264
  def max_unencoded_size(self) -> int:
239
265
  """The serial transport encodes each packet instead of sending SMP messages as raw bytes.
@@ -1,83 +0,0 @@
1
- """Some Generic helpers for the SMP module."""
2
-
3
- from enum import IntEnum
4
- from typing import Protocol, Type, TypeGuard, TypeVar
5
-
6
- from smp import error as smperror
7
- from smp import header as smpheader
8
- from smp import message as smpmessage
9
-
10
- TErrEnum = TypeVar("TErrEnum", bound=IntEnum)
11
- TEr0 = TypeVar("TEr0", bound=smperror.ErrorV0)
12
- TEr1 = TypeVar("TEr1", bound=smperror.ErrorV1)
13
- TErr = TypeVar("TErr", bound='SMPError')
14
- TRep = TypeVar("TRep", bound=smpmessage.ReadResponse | smpmessage.WriteResponse)
15
-
16
-
17
- class SMPError(smperror.ErrorV0[TErrEnum]):
18
- """An abstraction on top of SMP that joins and flattens V0 and V1 `Error`s"""
19
-
20
- group: smpheader.GroupId | None = None
21
-
22
-
23
- def _is_ErrorV0(error: TEr0 | TEr1 | TRep) -> TypeGuard[TEr0]:
24
- return error.RESPONSE_TYPE == smpmessage.ResponseType.ERROR_V0
25
-
26
-
27
- def _is_ErrorV1(error: TEr0 | TEr1 | TRep) -> TypeGuard[TEr1]:
28
- return error.RESPONSE_TYPE == smpmessage.ResponseType.ERROR_V1
29
-
30
-
31
- def flatten_error(
32
- error: smperror.ErrorV0[TErrEnum] | smperror.ErrorV1[TErrEnum],
33
- ) -> SMPError[TErrEnum]:
34
- """Flatten a `Generic` `ErrorV0` or `ErrorV1` into a `Generic` `SMPError`."""
35
- if _is_ErrorV0(error):
36
- return SMPError(header=error.header, rc=error.rc, rsn=error.rsn)
37
- elif _is_ErrorV1(error):
38
- return SMPError(header=error.header, rc=error.err.rc, group=error.err.group)
39
- else:
40
- raise Exception(f"{error} is not an Error?")
41
-
42
-
43
- class SMPRequest(Protocol[TRep, TEr0, TEr1, TErr]):
44
- """A `Protocol` that groups the expected response and errors with a request.
45
-
46
- To use, inherit from an SMP Read or Write `Request` and define its expected
47
- `Response`, `ErrorV0`, `ErrorV1`, and `SMPError`.
48
-
49
- Example:
50
- ```python
51
- class ImageManagementError(SMPError[smpimg.IMG_MGMT_ERR]):
52
- _GROUP_ID = smpheader.GroupId.IMAGE_MANAGEMENT
53
-
54
-
55
- class ImageStatesRead(smpimg.ImageStatesReadRequest):
56
- Response = smpimg.ImageStatesReadResponse
57
- ErrorV0 = smpimg.ImageManagementError1
58
- ErrorV1 = smpimg.ImageManagementError2
59
- Error = ImageManagementError
60
- ```
61
- """
62
-
63
- Response: Type[TRep]
64
- ErrorV0: Type[TEr0]
65
- ErrorV1: Type[TEr1]
66
- Error: Type[TErr]
67
-
68
- @property
69
- def BYTES(self) -> bytes: # pragma: no cover
70
- ...
71
-
72
-
73
- def error(response: TErr | TRep) -> TypeGuard[TErr]:
74
- """`TypeGuard` that returns `True` if the `response` is an `Error` (including `SMPError`)."""
75
- return response.RESPONSE_TYPE in {
76
- smpmessage.ResponseType.ERROR_V0,
77
- smpmessage.ResponseType.ERROR_V1,
78
- }
79
-
80
-
81
- def success(response: TRep | TErr) -> TypeGuard[TRep]:
82
- """`TypeGuard` that returns `True` if the `response` is a successful `Response`."""
83
- return response.RESPONSE_TYPE == smpmessage.ResponseType.SUCCESS
@@ -1,28 +0,0 @@
1
- from typing import ClassVar
2
-
3
- from smp import header as smpheader
4
- from smp import image_management as smpimg
5
-
6
- from smpclient.generics import SMPError
7
-
8
-
9
- class ImageManagementError(SMPError[smpimg.IMG_MGMT_ERR]):
10
- _GROUP_ID = smpheader.GroupId.IMAGE_MANAGEMENT
11
-
12
-
13
- class _ImageGroupBase:
14
- ErrorV0 = smpimg.ImageManagementErrorV0
15
- ErrorV1 = smpimg.ImageManagementErrorV1
16
- Error = ImageManagementError
17
-
18
-
19
- class ImageStatesRead(smpimg.ImageStatesReadRequest, _ImageGroupBase):
20
- Response: ClassVar = smpimg.ImageStatesReadResponse
21
-
22
-
23
- class ImageStatesWrite(smpimg.ImageStatesWriteRequest, _ImageGroupBase):
24
- Response: ClassVar = smpimg.ImageStatesWriteResponse
25
-
26
-
27
- class ImageUploadWrite(smpimg.ImageUploadWriteRequest, _ImageGroupBase):
28
- Response: ClassVar = smpimg.ImageUploadProgressWriteResponse
@@ -1,24 +0,0 @@
1
- from typing import ClassVar
2
-
3
- from smp import header as smpheader
4
- from smp import os_management as smpos
5
-
6
- from smpclient.generics import SMPError
7
-
8
-
9
- class OSManagementError(SMPError[smpos.OS_MGMT_RET_RC]):
10
- _GROUP_ID = smpheader.GroupId.OS_MANAGEMENT
11
-
12
-
13
- class _OSGroupBase:
14
- ErrorV0 = smpos.OSManagementErrorV0
15
- ErrorV1 = smpos.OSManagementErrorV1
16
- Error = OSManagementError
17
-
18
-
19
- class EchoWrite(smpos.EchoWriteRequest, _OSGroupBase):
20
- Response: ClassVar = smpos.EchoWriteResponse
21
-
22
-
23
- class ResetWrite(smpos.ResetWriteRequest, _OSGroupBase):
24
- Response: ClassVar = smpos.ResetWriteResponse
@@ -1,20 +0,0 @@
1
- from typing import ClassVar
2
-
3
- from smp import header as smpheader
4
- from smp import shell_management as smpshell
5
-
6
- from smpclient.generics import SMPError
7
-
8
-
9
- class ShellManagementError(SMPError[smpshell.SHELL_MGMT_RET_RC]):
10
- _GROUP_ID = smpheader.GroupId.SHELL_MANAGEMENT
11
-
12
-
13
- class _ShellGroupBase:
14
- ErrorV0 = smpshell.ShellManagementErrorV0
15
- ErrorV1 = smpshell.ShellManagementErrorV1
16
- Error = ShellManagementError
17
-
18
-
19
- class Execute(smpshell.ExecuteRequest, _ShellGroupBase):
20
- Response: ClassVar = smpshell.ExecuteResponse
@@ -1,20 +0,0 @@
1
- from typing import ClassVar
2
-
3
- from smp import header as smpheader
4
- from smp.user import intercreate as smpic
5
-
6
- from smpclient.generics import SMPError
7
-
8
-
9
- class Error(SMPError[smpic.IC_MGMT_ERR]):
10
- _GROUP_ID = smpheader.GroupId.INTERCREATE
11
-
12
-
13
- class _GroupBase:
14
- ErrorV0 = smpic.ErrorV0
15
- ErrorV1 = smpic.ErrorV1
16
- Error = Error
17
-
18
-
19
- class ImageUploadWrite(smpic.ImageUploadWriteRequest, _GroupBase):
20
- Response: ClassVar = smpic.ImageUploadWriteResponse
@@ -1,28 +0,0 @@
1
- """Simple Management Protocol (SMP) Client Transport Protocol."""
2
-
3
- from typing import Protocol
4
-
5
-
6
- class SMPTransport(Protocol):
7
- async def connect(self, address: str) -> None: # pragma: no cover
8
- """Connect the `SMPTransport`."""
9
-
10
- async def disconnect(self) -> None: # pragma: no cover
11
- """Disconnect the `SMPTransport`."""
12
-
13
- async def send(self, data: bytes) -> None: # pragma: no cover
14
- """Send the encoded `SMPRequest` `data`."""
15
-
16
- async def receive(self) -> bytes: # pragma: no cover
17
- """Receive the decoded `SMPResponse`."""
18
-
19
- async def send_and_receive(self, data: bytes) -> bytes: # pragma: no cover
20
- """Send the encoded `SMPRequest` `data` and receive the decoded `SMPResponse`."""
21
-
22
- @property
23
- def mtu(self) -> int: # pragma: no cover
24
- """The Maximum Transmission Unit (MTU) in 8-bit bytes."""
25
-
26
- @property
27
- def max_unencoded_size(self) -> int: # pragma: no cover
28
- """The maximum size of an unencoded message that can be sent in one MTU, in 8-bit bytes."""
File without changes
File without changes