Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/device/base.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2023 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Low level device base class."""
9
10 from abc import ABC, abstractmethod
11 from types import TracebackType
12 from typing import TYPE_CHECKING, Optional, Type
13
14 if TYPE_CHECKING:
15 from typing_extensions import Self
16
17
18 class DeviceBase(ABC):
19 """Device base class."""
20
21 def __enter__(self) -> "Self":
22 self.open()
23 return self
24
25 def __exit__(
26 self,
27 exception_type: Optional[Type[Exception]] = None,
28 exception_value: Optional[Exception] = None,
29 traceback: Optional[TracebackType] = None,
30 ) -> None:
31 self.close()
32
33 @property
34 @abstractmethod
35 def is_opened(self) -> bool:
36 """Indicates whether interface is open."""
37
38 @abstractmethod
39 def open(self) -> None:
40 """Open the interface."""
41
42 @abstractmethod
43 def close(self) -> None:
44 """Close the interface."""
45
46 @abstractmethod
47 def read(self, length: int, timeout: Optional[int] = None) -> bytes:
48 """Read data from the device.
49
50 :param length: Length of data to be read
51 :param timeout: Read timeout to be applied
52 """
53
54 @abstractmethod
55 def write(self, data: bytes, timeout: Optional[int] = None) -> None:
56 """Write data to the device.
57
58 :param data: Data to be written
59 :param timeout: Read timeout to be applied
60 """
61
62 @property
63 @abstractmethod
64 def timeout(self) -> int:
65 """Timeout property."""
66
67 @timeout.setter
68 @abstractmethod
69 def timeout(self, value: int) -> None:
70 """Timeout property setter."""
71
72 @abstractmethod
73 def __str__(self) -> str:
74 """Return string containing information about the interface."""