| 1 | from __future__ import annotations |
| 2 | |
| 3 | import asyncio |
| 4 | import logging |
| 5 | from asyncio.transports import BaseTransport, WriteTransport |
| 6 | from typing import Any, Callable, cast |
| 7 | |
| 8 | _LOGGER = logging.getLogger(__name__) |
| 9 | |
| 10 | |
| 11 | class AIOLEDENETProtocol(asyncio.Protocol): |
| 12 | """A asyncio.Protocol implementing a wrapper around the LEDENET protocol.""" |
| 13 | |
| 14 | def __init__( |
| 15 | self, |
| 16 | data_received: Callable[[bytes], Any], |
| 17 | connection_lost: Callable[[Exception | None], Any], |
| 18 | ) -> None: |
| 19 | self._data_receive_callback = data_received |
| 20 | self._connection_lost_callback = connection_lost |
| 21 | self.transport: WriteTransport | None = None |
| 22 | |
| 23 | def connection_lost(self, exc: Exception | None) -> None: |
| 24 | """Handle connection lost.""" |
| 25 | _LOGGER.debug("%s: Connection lost: %s", self.peername, exc) |
| 26 | self.close() |
| 27 | self._connection_lost_callback(exc) |
| 28 | |
| 29 | def connection_made(self, transport: BaseTransport) -> None: |
| 30 | """Handle connection made.""" |
| 31 | self.transport = cast("WriteTransport", transport) |
| 32 | self.peername = transport.get_extra_info("peername") |
| 33 | |
| 34 | def write(self, data: bytes) -> None: |
| 35 | """Write data to the client.""" |
| 36 | assert self.transport is not None |
| 37 | if _LOGGER.isEnabledFor(logging.DEBUG): |
| 38 | _LOGGER.debug( |
| 39 | "%s => %s (%d)", |
| 40 | self.peername, |
| 41 | " ".join(f"0x{x:02X}" for x in data), |
| 42 | len(data), |
| 43 | ) |
| 44 | self.transport.write(data) |
| 45 | |
| 46 | def close(self) -> None: |
| 47 | """Remove the connection and close the transport.""" |
| 48 | assert self.transport is not None |
| 49 | self.transport.write_eof() |
| 50 | self.transport.close() |
| 51 | |
| 52 | def data_received(self, data: bytes) -> None: |
| 53 | """Process new data from the socket.""" |
| 54 | if _LOGGER.isEnabledFor(logging.DEBUG): |
| 55 | _LOGGER.debug( |
| 56 | "%s <= %s (%d)", |
| 57 | self.peername, |
| 58 | " ".join(f"0x{x:02X}" for x in data), |
| 59 | len(data), |
| 60 | ) |
| 61 | self._data_receive_callback(data) |