|
| 1 | +import asyncio |
| 2 | +from abc import ABC, abstractmethod |
| 3 | +from typing import * |
| 4 | + |
| 5 | +from pubsub import pub |
| 6 | + |
| 7 | +from meshtastic.protobuf.mesh_pb2 import FromRadio, ToRadio |
| 8 | + |
| 9 | + |
| 10 | +class MeshConnection(ABC): |
| 11 | + """A client API connection to a meshtastic radio.""" |
| 12 | + |
| 13 | + def __init__(self): |
| 14 | + self._on_disconnect: asyncio.Event = asyncio.Event() |
| 15 | + |
| 16 | + @abstractmethod |
| 17 | + async def _send_bytes(self, msg: buffer): |
| 18 | + """Send bytes to the mesh device.""" |
| 19 | + pass |
| 20 | + |
| 21 | + @abstractmethod |
| 22 | + async def _recv_bytes(self) -> buffer: |
| 23 | + """Recieve bytes from the mesh device.""" |
| 24 | + pass |
| 25 | + |
| 26 | + @abstractmethod |
| 27 | + def close(self): |
| 28 | + """Close the connection""" |
| 29 | + pass |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + @abstractmethod |
| 33 | + async def get_available() -> AsyncGenerator[Any]: |
| 34 | + """Enumerate any mesh devices that can be connected to. |
| 35 | +
|
| 36 | + Generates values that can be passed to the concrete connection class's |
| 37 | + constructor.""" |
| 38 | + pass |
| 39 | + |
| 40 | + def __enter__(self): |
| 41 | + return self |
| 42 | + |
| 43 | + def __exit__(self, exc_type, exc_value, trace): |
| 44 | + self.close() |
| 45 | + |
| 46 | + async def send(self, message: ToRadio): |
| 47 | + """Send something to the connected device.""" |
| 48 | + msg_str: str = message.SerializeToString() |
| 49 | + await self._send_bytes(bytes(msg_str)) |
| 50 | + |
| 51 | + async def recv(self) -> FromRadio: |
| 52 | + """Recieve something from the connected device.""" |
| 53 | + msg_bytes: buffer = await self._recv_bytes() |
| 54 | + return FromRadio.FromString(str(msg_bytes)) |
| 55 | + |
| 56 | + async def listen(self) -> AsyncGenerator[FromRadio]: |
| 57 | + while True: |
| 58 | + yield await self.recv() |
0 commit comments