Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/protocol/bulk_protocol.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2023-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Mboot bulk implementation."""
9
10 import logging
11 from struct import pack, unpack_from
12 from typing import Optional, Union
13
14 from nitrokey.trussed._bootloader.lpc55_upload.exceptions import SPSDKAttributeError
15
16 from ...mboot.commands import CmdResponse, parse_cmd_response
17 from ...mboot.exceptions import McuBootConnectionError, McuBootDataAbortError
18 from ...mboot.protocol.base import MbootProtocolBase
19 from ...utils.exceptions import SPSDKTimeoutError
20 from ...utils.interfaces.commands import CmdPacketBase
21 from ...utils.spsdk_enum import SpsdkEnum
22
23
24 class ReportId(SpsdkEnum):
25 """Report ID enum."""
26
27 CMD_OUT = (0x01, "CMD_OUT")
28 CMD_IN = (0x03, "CMD_IN")
29 DATA_OUT = (0x02, "DATA_OUT")
30 DATA_IN = (0x04, "DATA_IN")
31
32
33 logger = logging.getLogger(__name__)
34
35
36 class MbootBulkProtocol(MbootProtocolBase):
37 """Mboot Bulk protocol."""
38
39 def open(self) -> None:
40 """Open the interface."""
41 self.device.open()
42
43 def close(self) -> None:
44 """Close the interface."""
45 self.device.close()
46
47 @property
48 def is_opened(self) -> bool:
49 """Indicates whether interface is open."""
50 return self.device.is_opened
51
52 def write_data(self, data: bytes) -> None:
53 """Encapsulate data into frames and send them to device.
54
55 :param data: Data to be sent
56 """
57 frame = self._create_frame(data, ReportId.DATA_OUT)
58 if self.allow_abort:
59 try:
60 abort_data = self.device.read(1024, timeout=10)
61 logger.debug(f"Read {len(abort_data)} bytes of abort data")
62 except Exception as e:
63 raise McuBootConnectionError(str(e)) from e
64 if abort_data:
65 logger.debug(f"{', '.join(f'{b:02X}' for b in abort_data)}")
66 raise McuBootDataAbortError()
67 self.device.write(frame)
68
69 def write_command(self, packet: CmdPacketBase) -> None:
70 """Encapsulate command into frames and send them to device.
71
72 :param packet: Command packet object to be sent
73 :raises SPSDKAttributeError: Command packed contains no data to be sent
74 """
75 data = packet.to_bytes(padding=False)
76 if not data:
77 raise SPSDKAttributeError("Incorrect packet type")
78 frame = self._create_frame(data, ReportId.CMD_OUT)
79 self.device.write(frame)
80
81 def read(self, length: Optional[int] = None) -> Union[CmdResponse, bytes]:
82 """Read data from device.
83
84 :return: read data
85 :raises SPSDKTimeoutError: Timeout occurred
86 """
87 data = self.device.read(1024)
88 if not data:
89 logger.error("Cannot read from HID device")
90 raise SPSDKTimeoutError()
91 return self._parse_frame(bytes(data))
92
93 def _create_frame(self, data: bytes, report_id: ReportId) -> bytes:
94 """Encode the USB packet.
95
96 :param report_id: ID of the report (see: HID_REPORT)
97 :param data: Data to send
98 :return: Encoded bytes and length of the final report frame
99 """
100 raw_data = pack("<2BH", report_id.tag, 0x00, len(data))
101 raw_data += data
102 logger.debug(f"OUT[{len(raw_data)}]: {', '.join(f'{b:02X}' for b in raw_data)}")
103 return raw_data
104
105 @staticmethod
106 def _parse_frame(raw_data: bytes) -> Union[CmdResponse, bytes]:
107 """Decodes the data read on USB interface.
108
109 :param raw_data: Data received
110 :return: CmdResponse object or data read
111 :raises McuBootDataAbortError: Transaction aborted by target
112 """
113 logger.debug(f"IN [{len(raw_data)}]: {', '.join(f'{b:02X}' for b in raw_data)}")
114 report_id, _, plen = unpack_from("<2BH", raw_data)
115 if plen == 0:
116 raise McuBootDataAbortError()
117 data = raw_data[4 : 4 + plen]
118 if report_id == ReportId.CMD_IN:
119 return parse_cmd_response(data)
120 return data