| 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 |
"""Protocol base.""" |
| 9 |
|
| 10 |
from abc import ABC, abstractmethod |
| 11 |
from types import TracebackType |
| 12 |
from typing import TYPE_CHECKING, Optional, Type, Union |
| 13 |
|
| 14 |
from ....utils.interfaces.commands import CmdPacketBase, CmdResponseBase |
| 15 |
from ....utils.interfaces.device.base import DeviceBase |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from typing_extensions import Self |
| 19 |
|
| 20 |
|
| 21 |
class ProtocolBase(ABC): |
| 22 |
"""Protocol base class.""" |
| 23 |
|
| 24 |
device: DeviceBase |
| 25 |
identifier: str |
| 26 |
|
| 27 |
def __init__(self, device: DeviceBase) -> None: |
| 28 |
"""Initialize the MbootSerialProtocol object. |
| 29 |
|
| 30 |
:param device: The device instance |
| 31 |
""" |
| 32 |
self.device = device |
| 33 |
|
| 34 |
def __str__(self) -> str: |
| 35 |
return f"identifier='{self.identifier}', device={self.device}" |
| 36 |
|
| 37 |
def __enter__(self) -> "Self": |
| 38 |
self.open() |
| 39 |
return self |
| 40 |
|
| 41 |
def __exit__( |
| 42 |
self, |
| 43 |
exception_type: Optional[Type[Exception]] = None, |
| 44 |
exception_value: Optional[Exception] = None, |
| 45 |
traceback: Optional[TracebackType] = None, |
| 46 |
) -> None: |
| 47 |
self.close() |
| 48 |
|
| 49 |
@abstractmethod |
| 50 |
def open(self) -> None: |
| 51 |
"""Open the interface.""" |
| 52 |
|
| 53 |
@abstractmethod |
| 54 |
def close(self) -> None: |
| 55 |
"""Close the interface.""" |
| 56 |
|
| 57 |
@property |
| 58 |
@abstractmethod |
| 59 |
def is_opened(self) -> bool: |
| 60 |
"""Indicates whether interface is open.""" |
| 61 |
|
| 62 |
@abstractmethod |
| 63 |
def write_command(self, packet: CmdPacketBase) -> None: |
| 64 |
"""Write command to the device. |
| 65 |
|
| 66 |
:param packet: Command packet to be sent |
| 67 |
""" |
| 68 |
|
| 69 |
@abstractmethod |
| 70 |
def write_data(self, data: bytes) -> None: |
| 71 |
"""Write data to the device. |
| 72 |
|
| 73 |
:param data: Data to be send |
| 74 |
""" |
| 75 |
|
| 76 |
@abstractmethod |
| 77 |
def read(self, length: Optional[int] = None) -> Union[CmdResponseBase, bytes]: |
| 78 |
"""Read data from device. |
| 79 |
|
| 80 |
:return: read data |
| 81 |
""" |