Edit on GitHub

base_aprs_client

APRS station behaviour for applications.

AsyncClient sends messages with acknowledgement and timer-driven retry, acks incoming messages addressed to mycall (once each, with reply-ack support), sends status and position reports, reconnects when the transport drops, and can log frames and run a delayed send queue with PacketStore. Client is its synchronous wrapper. APRSISSimulator is a local APRS-IS-like relay for testing without a radio.

 1"""APRS station behaviour for applications.
 2
 3``AsyncClient`` sends messages with acknowledgement and timer-driven retry,
 4acks incoming messages addressed to ``mycall`` (once each, with reply-ack
 5support), sends status and position reports, reconnects when the transport
 6drops, and can log frames and run a delayed send queue with ``PacketStore``.
 7``Client`` is its synchronous wrapper. ``APRSISSimulator`` is a local
 8APRS-IS-like relay for testing without a radio.
 9"""
10
11from importlib.metadata import version
12
13from .aio import AsyncClient, NotConnected, ReconnectPolicy
14from .client import Client, MessageAckFuture
15from .common import MaximumRetryExceeded, MessageRejected, OverflowDisposition
16from .simulator import APRSISSimulator
17
18__author__ = "Masen Furer KF7HVM <kf7hvm@0x26.net>"
19__copyright__ = "Copyright 2022 Masen Furer and Contributors"
20__license__ = "Apache License, Version 2.0"
21__distribution__ = "base-aprs-client"
22__version__ = version(__distribution__)
23__all__ = [
24    "APRSISSimulator",
25    "AsyncClient",
26    "Client",
27    "MaximumRetryExceeded",
28    "MessageAckFuture",
29    "MessageRejected",
30    "NotConnected",
31    "OverflowDisposition",
32    "ReconnectPolicy",
33    "__distribution__",
34    "__version__",
35]
@attrs.define(eq=False)
class APRSISSimulator:
 18@attrs.define(eq=False)
 19class APRSISSimulator:
 20    """
 21    Miniature APRS-IS-like server for testing.
 22
 23    Every TNC2 line received from one client is relayed verbatim to every
 24    other connected client. Login lines (``user ...``) are acknowledged with
 25    a ``# logresp`` comment and are never relayed. Lines beginning with ``#``
 26    are treated as client comments and dropped.
 27
 28    The server runs its own event loop in a background thread so it can be
 29    used from synchronous test code::
 30
 31        from aprs import TCP
 32        from base_aprs_client import APRSISSimulator, Client
 33
 34        with APRSISSimulator() as sim:
 35            with TCP(host=sim.host, port=sim.port) as t1, \\
 36                    TCP(host=sim.host, port=sim.port) as t2:
 37                client1 = Client("N0CALL-1", t1)
 38                client2 = Client("N0CALL-2", t2)
 39                client1.send_status("Foobar")
 40                print(client2.read(min_frames=1))
 41
 42    Pass ``port=0`` (the default) to bind an ephemeral port; the bound port
 43    is available as ``.port`` once the server is started.
 44    """
 45
 46    host: str = attrs.field(default="127.0.0.1")
 47    port: int = attrs.field(default=0)
 48    received: list[tuple[tuple[str, int], bytes]] = attrs.field(factory=list)
 49    """Every relayed line, with the peer address that sent it."""
 50
 51    _writers: list[asyncio.StreamWriter] = attrs.field(factory=list, init=False)
 52    _loop: asyncio.AbstractEventLoop | None = attrs.field(default=None, init=False)
 53    _server: asyncio.AbstractServer | None = attrs.field(default=None, init=False)
 54    _thread: threading.Thread | None = attrs.field(default=None, init=False)
 55    _started: threading.Event = attrs.field(factory=threading.Event, init=False)
 56    _stopped: asyncio.Event | None = attrs.field(default=None, init=False)
 57    _error: BaseException | None = attrs.field(default=None, init=False)
 58
 59    def _broadcast(self, sender: asyncio.StreamWriter | None, line: bytes) -> None:
 60        for writer in list(self._writers):
 61            if writer is sender or writer.is_closing():
 62                continue
 63            writer.write(line)
 64
 65    async def _handle_client(
 66        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
 67    ) -> None:
 68        addr = writer.get_extra_info("peername")
 69        writer.write(SERVER_BANNER)
 70        while True:
 71            line = await reader.readline()
 72            if not line:  # EOF
 73                break
 74            # APRS-IS only strips the line terminator; trailing spaces are
 75            # significant (e.g. in message text).
 76            stripped = line.rstrip(b"\r\n")
 77            if not stripped.strip():
 78                continue
 79            if stripped.startswith(b"user "):
 80                username = stripped.split()[1].decode("latin1", "replace")
 81                logger.info("%r logs in as %s", addr, username)
 82                writer.write(
 83                    b"# logresp %s verified, server SIMULATOR\r\n"
 84                    % username.encode("latin1", "replace")
 85                )
 86                continue
 87            if stripped.startswith(b"#"):
 88                continue
 89            # normalize line endings to CRLF, as APRS-IS does
 90            out = stripped + b"\r\n"
 91            self.received.append((addr, out))
 92            self._broadcast(writer, out)
 93            await writer.drain()
 94
 95    async def _handle_connection(
 96        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
 97    ) -> None:
 98        if self._stopped is not None and self._stopped.is_set():
 99            # accepted just as the server stopped: don't keep it open
100            writer.close()
101            return
102        self._writers.append(writer)
103        try:
104            await self._handle_client(reader, writer)
105        except (ConnectionError, asyncio.IncompleteReadError):
106            pass
107        except Exception:  # pylint: disable=broad-except
108            logger.exception("Exception handling connection")
109        finally:
110            self._writers.remove(writer)
111            writer.close()
112
113    async def _run(self) -> None:
114        self._stopped = asyncio.Event()
115        self._server = await asyncio.start_server(
116            self._handle_connection,
117            self.host,
118            self.port,
119        )
120        self.port = self._server.sockets[0].getsockname()[1]
121        logger.info("Serving on %s:%s", self.host, self.port)
122        self._started.set()
123        async with self._server:
124            await self._stopped.wait()
125            self._server.close()  # stop accepting before closing connections
126            for writer in list(self._writers):
127                writer.close()
128            # let every connection handler finish, including any accepted
129            # just now that hasn't started: Python 3.11 doesn't wait for them
130            # and would leave those sockets open when the loop closes
131            handlers = asyncio.all_tasks() - {asyncio.current_task()}
132            await asyncio.gather(*handlers, return_exceptions=True)
133            await asyncio.sleep(0)  # transports finish closing
134
135    def _thread_main(self) -> None:
136        self._loop = asyncio.new_event_loop()
137        try:
138            self._loop.run_until_complete(self._run())
139        except BaseException as exc:  # pylint: disable=broad-except
140            self._error = exc
141            self._started.set()
142        finally:
143            self._loop.close()
144
145    def start(self) -> "APRSISSimulator":
146        """Start the server thread and block until it is accepting connections."""
147        self._thread = threading.Thread(
148            target=self._thread_main, name="APRSISSimulator", daemon=True
149        )
150        self._thread.start()
151        if not self._started.wait(SERVER_BRINGUP_TIMEOUT):
152            raise TimeoutError("APRSISSimulator did not start")
153        if self._error is not None:
154            raise self._error
155        return self
156
157    @property
158    def n_clients(self) -> int:
159        """Number of currently connected clients."""
160        return len(self._writers)
161
162    def wait_for_clients(self, n: int, timeout: float = SERVER_BRINGUP_TIMEOUT) -> None:
163        """Block until at least ``n`` clients are connected."""
164        deadline = time.monotonic() + timeout
165        while self.n_clients < n:
166            if time.monotonic() > deadline:
167                raise TimeoutError(f"Only {self.n_clients} of {n} clients connected")
168            time.sleep(0.01)
169
170    def close(self) -> None:
171        """Stop the server and wait for its thread to exit."""
172        if self._loop is not None and self._stopped is not None:
173            try:
174                self._loop.call_soon_threadsafe(self._stopped.set)
175            except RuntimeError:
176                pass  # loop already closed
177        if self._thread is not None:
178            self._thread.join(SERVER_BRINGUP_TIMEOUT)
179
180    def __enter__(self) -> "APRSISSimulator":
181        return self.start()
182
183    def __exit__(self, exc_type, exc_value, exc_tb) -> None:
184        self.close()

Miniature APRS-IS-like server for testing.

Every TNC2 line received from one client is relayed verbatim to every other connected client. Login lines (user ...) are acknowledged with a # logresp comment and are never relayed. Lines beginning with # are treated as client comments and dropped.

The server runs its own event loop in a background thread so it can be used from synchronous test code::

from aprs import TCP
from base_aprs_client import APRSISSimulator, Client

with APRSISSimulator() as sim:
    with TCP(host=sim.host, port=sim.port) as t1, \
            TCP(host=sim.host, port=sim.port) as t2:
        client1 = Client("N0CALL-1", t1)
        client2 = Client("N0CALL-2", t2)
        client1.send_status("Foobar")
        print(client2.read(min_frames=1))

Pass port=0 (the default) to bind an ephemeral port; the bound port is available as .port once the server is started.

APRSISSimulator( host: str = '127.0.0.1', port: int = 0, received: list[tuple[tuple[str, int], bytes]] = NOTHING)
17def __init__(self, host=attr_dict['host'].default, port=attr_dict['port'].default, received=NOTHING):
18    self.host = host
19    self.port = port
20    if received is not NOTHING:
21        self.received = received
22    else:
23        self.received = __attr_factory_received()
24    self._writers = __attr_factory__writers()
25    self._loop = attr_dict['_loop'].default
26    self._server = attr_dict['_server'].default
27    self._thread = attr_dict['_thread'].default
28    self._started = __attr_factory__started()
29    self._stopped = attr_dict['_stopped'].default
30    self._error = attr_dict['_error'].default

Method generated by attrs for class APRSISSimulator.

host: str
port: int
received: list[tuple[tuple[str, int], bytes]]

Every relayed line, with the peer address that sent it.

def start(self) -> APRSISSimulator:
145    def start(self) -> "APRSISSimulator":
146        """Start the server thread and block until it is accepting connections."""
147        self._thread = threading.Thread(
148            target=self._thread_main, name="APRSISSimulator", daemon=True
149        )
150        self._thread.start()
151        if not self._started.wait(SERVER_BRINGUP_TIMEOUT):
152            raise TimeoutError("APRSISSimulator did not start")
153        if self._error is not None:
154            raise self._error
155        return self

Start the server thread and block until it is accepting connections.

n_clients: int
157    @property
158    def n_clients(self) -> int:
159        """Number of currently connected clients."""
160        return len(self._writers)

Number of currently connected clients.

def wait_for_clients(self, n: int, timeout: float = 10) -> None:
162    def wait_for_clients(self, n: int, timeout: float = SERVER_BRINGUP_TIMEOUT) -> None:
163        """Block until at least ``n`` clients are connected."""
164        deadline = time.monotonic() + timeout
165        while self.n_clients < n:
166            if time.monotonic() > deadline:
167                raise TimeoutError(f"Only {self.n_clients} of {n} clients connected")
168            time.sleep(0.01)

Block until at least n clients are connected.

def close(self) -> None:
170    def close(self) -> None:
171        """Stop the server and wait for its thread to exit."""
172        if self._loop is not None and self._stopped is not None:
173            try:
174                self._loop.call_soon_threadsafe(self._stopped.set)
175            except RuntimeError:
176                pass  # loop already closed
177        if self._thread is not None:
178            self._thread.join(SERVER_BRINGUP_TIMEOUT)

Stop the server and wait for its thread to exit.

@attrs.define(eq=False)
class AsyncClient:
175@attrs.define(eq=False)
176class AsyncClient:
177    """
178    An APRS station on one connection.
179
180    Pass a ``connector`` (see ``aprsis_connector``, ``kiss_tcp_connector``,
181    ``kiss_serial_connector``) or use the ``aprsis``/``kiss_tcp``/
182    ``kiss_serial`` constructors. ``start()`` (or ``async with``) connects.
183    """
184
185    mycall: Address = attrs.field(converter=Address.from_any)
186    connector: Connector | None = attrs.field(default=None)
187    default_path: list[Address] = attrs.field(factory=list, converter=path_split)
188    destination: Address = attrs.field(default="APZ069", converter=Address.from_any)
189    store: "PacketStore | None" = attrs.field(default=None)
190    """Log every frame heard and sent, and transmit its queue (``schedule``)."""
191    reconnect: ReconnectPolicy | None = attrs.field(factory=ReconnectPolicy)
192    """How to reconnect when the connection drops; None to stop instead."""
193    retries: int = attrs.field(default=DEFAULT_MESSAGE_RETRY)
194    retry_period: float = attrs.field(default=DEFAULT_MESSAGE_RETRY_PERIOD)
195    duplicate_window: float = attrs.field(default=DEFAULT_DUPLICATE_WINDOW)
196    """Seconds to remember incoming messages, so each is delivered once (0: off)."""
197    reply_ack: bool = attrs.field(default=True)
198    """Number outgoing messages "{MM}" + reply-ack, advertising reply-ack support."""
199    next_message_sequence_number: int = attrs.field(
200        factory=lambda: random.randint(0, SEQ_NUM_MAX)
201    )
202    max_queued_frames: int = attrs.field(default=DEFAULT_MAX_QUEUED_FRAMES)
203    """Frames kept for ``recv``/``async for`` before the oldest are dropped."""
204
205    protocol: FrameDecodeProtocol | None = attrs.field(default=None, init=False)
206    outstanding: dict[bytes, OutstandingMessage] = attrs.field(factory=dict, init=False)
207    frame_handlers: list[FrameHandler] = attrs.field(factory=list, init=False)
208    message_handlers: list[MessageHandler] = attrs.field(factory=list, init=False)
209    connect_handlers: list[Callable[[FrameDecodeProtocol], t.Any]] = attrs.field(
210        factory=list, init=False
211    )
212    dropped_frames: int = attrs.field(default=0, init=False)
213
214    _frames: asyncio.Queue = attrs.field(init=False, default=None)
215    _connected: asyncio.Event = attrs.field(init=False, default=None)
216    _wakeup: asyncio.Event = attrs.field(init=False, default=None)
217    _tasks: set[asyncio.Task] = attrs.field(factory=set, init=False)
218    _seen: dict[tuple, float] = attrs.field(factory=dict, init=False)
219    _reply_ack_stations: set[str] = attrs.field(factory=set, init=False)
220    _pending_reply_acks: dict[str, bytes] = attrs.field(factory=dict, init=False)
221    _started: bool = attrs.field(default=False, init=False)
222    _closing: bool = attrs.field(default=False, init=False)
223
224    # -- constructors --
225
226    @classmethod
227    def aprsis(
228        cls,
229        mycall: str,
230        host: str = APRSIS_SERVERS[0],
231        port: int = APRSIS_FILTER_PORT,
232        passcode: str = "-1",
233        filter: str | None = None,
234        **kwargs: t.Any,
235    ) -> "AsyncClient":
236        connector = aprsis_connector(str(mycall), host, port, passcode, filter)
237        return cls(mycall=mycall, connector=connector, **kwargs)
238
239    @classmethod
240    def kiss_tcp(
241        cls,
242        mycall: str,
243        host: str,
244        port: int,
245        kiss_settings: dict | None = None,
246        **kwargs: t.Any,
247    ) -> "AsyncClient":
248        connector = kiss_tcp_connector(host, port, kiss_settings)
249        return cls(mycall=mycall, connector=connector, **kwargs)
250
251    @classmethod
252    def kiss_serial(
253        cls,
254        mycall: str,
255        port: str,
256        baudrate: int = 9600,
257        kiss_settings: dict | None = None,
258        **kwargs: t.Any,
259    ) -> "AsyncClient":
260        connector = kiss_serial_connector(port, baudrate, kiss_settings)
261        return cls(mycall=mycall, connector=connector, **kwargs)
262
263    # -- lifecycle --
264
265    async def start(self, protocol: FrameDecodeProtocol | None = None) -> "AsyncClient":
266        """
267        Connect (or use an already connected ``protocol``) and start the
268        receive loop, and the send-queue loop when there is a ``store``.
269        """
270        if self._started:
271            return self
272        self._frames = asyncio.Queue()
273        self._connected = asyncio.Event()
274        self._wakeup = asyncio.Event()
275        if protocol is None:
276            if self.connector is None:
277                raise ValueError("AsyncClient needs a connector or a protocol")
278            protocol = await self.connector()
279        self._started = True
280        self._set_protocol(protocol)
281        self._spawn(self._run_reader())
282        if self.store is not None:
283            await self.store.create_all()
284            self._spawn(self._run_sender())
285        return self
286
287    async def close(self) -> None:
288        """Stop the loops, cancel outstanding messages and close the connection."""
289        if self._closing:
290            return
291        self._closing = True
292        for om in list(self.outstanding.values()):
293            self._finish(om)
294            om.future.cancel()
295        tasks = [task for task in self._tasks if task is not asyncio.current_task()]
296        for task in tasks:
297            task.cancel()
298        await asyncio.gather(*tasks, return_exceptions=True)
299        if self.protocol is not None and self.protocol.transport is not None:
300            self.protocol.transport.close()
301            await asyncio.sleep(0)  # let the transport release the socket/port
302        if self._frames is not None:
303            self._frames.put_nowait(_CLOSED)
304
305    async def __aenter__(self) -> "AsyncClient":
306        return await self.start()
307
308    async def __aexit__(self, *exc_info: t.Any) -> None:
309        await self.close()
310
311    @property
312    def connected(self) -> bool:
313        return self._connected is not None and self._connected.is_set()
314
315    async def wait_connected(self, timeout: float | None = None) -> None:
316        await asyncio.wait_for(self._connected.wait(), timeout)
317
318    def _spawn(self, coro: t.Coroutine) -> asyncio.Task:
319        task = asyncio.ensure_future(coro)
320        self._tasks.add(task)
321        task.add_done_callback(self._task_done)
322        return task
323
324    def _task_done(self, task: asyncio.Task) -> None:
325        self._tasks.discard(task)
326        if not task.cancelled() and task.exception() is not None:
327            logger.error("Background task failed", exc_info=task.exception())
328
329    def _set_protocol(self, protocol: FrameDecodeProtocol) -> None:
330        self.protocol = protocol
331        self._connected.set()
332        self._wakeup.set()
333        for handler in self.connect_handlers:
334            self._call_handler(handler, protocol)
335
336    # -- receiving --
337
338    async def _run_reader(self) -> None:
339        try:
340            while True:
341                protocol = self.protocol
342                assert protocol is not None
343                async for frame in protocol.read():
344                    await self._handle_frame(frame)
345                self._connected.clear()
346                if self._closing:
347                    return
348                logger.warning("%s: connection lost", self.mycall)
349                if not await self._reconnect():
350                    return
351        finally:
352            self._connected.clear()
353            if self._frames is not None:
354                self._frames.put_nowait(_CLOSED)
355
356    async def _reconnect(self) -> bool:
357        if self.reconnect is None or self.connector is None:
358            return False
359        for delay in self.reconnect.delays():
360            await asyncio.sleep(delay)
361            if self._closing:
362                return False
363            try:
364                protocol = await self.connector()
365            except OSError as exc:
366                logger.warning("%s: reconnect failed: %s", self.mycall, exc)
367                continue
368            logger.info("%s: reconnected", self.mycall)
369            self._set_protocol(protocol)
370            return True
371        logger.error("%s: giving up reconnecting", self.mycall)
372        return False
373
374    async def _handle_frame(self, frame: APRSFrame) -> None:
375        if not isinstance(frame, APRSFrame):
376            return
377        if self.store is not None:
378            try:
379                await self.store.record_received(frame)
380            except Exception:  # pylint: disable=broad-except
381                logger.exception("Could not log received frame %s", frame)
382        info = frame.info
383        to_me = isinstance(info, Message) and _same_station(
384            info.addressee.decode("latin1"), str(self.mycall)
385        )
386        if to_me and not self._handle_message(t.cast(Message, info), frame):
387            return  # duplicate
388        self._deliver(frame, to_me)
389
390    def _handle_message(self, message: Message, frame: APRSFrame) -> bool:
391        """Ack, resolve outstanding messages; False if ``message`` is a duplicate."""
392        source = str(frame.source)
393        if message.number:
394            number, reply_ack_capable, acked = parse_number(message.number)
395            if reply_ack_capable:
396                self._reply_ack_stations.add(source.upper())
397                self._pending_reply_acks[source.upper()] = number
398            if acked:
399                self._resolve(acked, frame, rejected=False)
400            self._send_ack(frame.source, number, reply_ack_capable)
401            key: tuple = (source.upper(), number)
402        else:
403            ack = parse_ack(message.text)
404            if ack is not None:
405                kind, number = ack
406                self._resolve(number, frame, rejected=kind == b"rej")
407            key = (source.upper(), message.text)
408        return not self._is_duplicate(key)
409
410    def _is_duplicate(self, key: tuple) -> bool:
411        if self.duplicate_window <= 0:
412            return False
413        now = asyncio.get_running_loop().time()
414        horizon = now - self.duplicate_window
415        for old in [k for k, seen in self._seen.items() if seen < horizon]:
416            del self._seen[old]
417        if key in self._seen:
418            return True
419        self._seen[key] = now
420        return False
421
422    def _deliver(self, frame: APRSFrame, to_me: bool) -> None:
423        if self.max_queued_frames and self._frames.qsize() >= self.max_queued_frames:
424            self._frames.get_nowait()
425            self.dropped_frames += 1
426        self._frames.put_nowait(frame)
427        for handler in self.frame_handlers:
428            self._call_handler(handler, frame)
429        if to_me:
430            for handler in self.message_handlers:
431                self._call_handler(handler, frame.info, frame)
432
433    def _call_handler(self, handler: Callable, *args: t.Any) -> None:
434        try:
435            result = handler(*args)
436            if inspect.isawaitable(result):
437                self._spawn(t.cast(t.Coroutine, result))
438        except Exception:  # pylint: disable=broad-except
439            logger.exception("Handler %r failed", handler)
440
441    def on_frame(self, handler: FrameHandler) -> FrameHandler:
442        """Call ``handler(frame)`` (or await it) for every frame delivered."""
443        self.frame_handlers.append(handler)
444        return handler
445
446    def on_message(self, handler: MessageHandler) -> MessageHandler:
447        """Call ``handler(message, frame)`` for each message to ``mycall``, once."""
448        self.message_handlers.append(handler)
449        return handler
450
451    async def recv(self, timeout: float | None = None) -> APRSFrame:
452        """The next frame; raises EOFError once the client is closed."""
453        frame = await asyncio.wait_for(self._frames.get(), timeout)
454        if frame is _CLOSED:
455            self._frames.put_nowait(_CLOSED)  # wake other readers too
456            raise EOFError("client closed")
457        return frame
458
459    def recv_nowait(self) -> list[APRSFrame]:
460        """Every frame received so far and not yet returned."""
461        frames = []
462        while not self._frames.empty():
463            frame = self._frames.get_nowait()
464            if frame is _CLOSED:
465                self._frames.put_nowait(_CLOSED)
466                break
467            frames.append(frame)
468        return frames
469
470    async def __aiter__(self) -> AsyncIterator[APRSFrame]:
471        while True:
472            try:
473                yield await self.recv()
474            except EOFError:
475                return
476
477    # -- sending --
478
479    def prepare_frame(
480        self, info: InformationField, path: list[Address] | str | None = None
481    ) -> APRSFrame:
482        # ui() sets the AX.25 end-of-address bit, which KISS TNCs need
483        return APRSFrame.ui(
484            destination=self.destination,
485            source=self.mycall,
486            path=path_split(path) if path else self.default_path,
487            info=info,  # ty: ignore[invalid-argument-type]  # ui() is typed for bytes
488        )
489
490    def write(self, frame: APRSFrame, record: bool = True) -> None:
491        """Transmit ``frame`` now; raises NotConnected if the connection is down."""
492        if not self.connected or self.protocol is None:
493            raise NotConnected(f"{self.mycall} is not connected")
494        self.protocol.write(frame)
495        if record and self.store is not None:
496            self._spawn(self._record_sent(frame))
497
498    async def _record_sent(self, frame: APRSFrame) -> None:
499        assert self.store is not None
500        try:
501            await self.store.record_sent(frame)
502        except Exception:  # pylint: disable=broad-except
503            logger.exception("Could not log sent frame %s", frame)
504
505    def _burn_message_sequence_number(self) -> bytes:
506        number = b"%x" % self.next_message_sequence_number
507        self.next_message_sequence_number = (
508            self.next_message_sequence_number + 1
509        ) % SEQ_NUM_MAX
510        return number
511
512    def _message(self, recipient: str, text: str, number: bytes | None) -> Message:
513        return Message(
514            raw=b"",
515            data_type=DataType.MESSAGE,
516            data=b"",
517            addressee=str(recipient).encode("latin1"),
518            text=text.encode(),
519            number=number,
520        )
521
522    def _send_ack(self, recipient: Address, number: bytes, reply_ack: bool) -> None:
523        text = "ack" + number.decode("latin1") + ("}" if reply_ack else "")
524        try:
525            self.write(self.prepare_frame(self._message(str(recipient), text, None)))
526        except NotConnected:
527            logger.warning("Could not ack %s from %s: not connected", number, recipient)
528
529    def submit_message(
530        self,
531        recipient: str,
532        body: str,
533        ack: bool = False,
534        overflow: OverflowDisposition = OverflowDisposition.Truncate,
535        path: list[Address] | str | None = None,
536    ) -> list[asyncio.Future]:
537        """
538        Send ``body`` without waiting; one future per part.
539
540        Text over 67 bytes is cut (``Truncate``) or split on word boundaries
541        (``Continue``). With ``ack``, each future resolves to the ack frame,
542        or fails with MessageRejected or MaximumRetryExceeded. Without
543        ``ack``, the futures are already resolved to None.
544        """
545        return [
546            future
547            for future, _ in self._submit_parts(recipient, body, ack, overflow, path)
548        ]
549
550    def _submit_parts(
551        self,
552        recipient: str,
553        body: str,
554        ack: bool,
555        overflow: OverflowDisposition,
556        path: list[Address] | str | None,
557    ) -> list[tuple[asyncio.Future, Message]]:
558        if overflow == OverflowDisposition.Continue:
559            parts = split_message(body)
560        else:
561            parts = [truncate_message(body)]
562        return [self._submit_part(recipient, part, ack, path) for part in parts]
563
564    def _submit_part(
565        self, recipient: str, text: str, ack: bool, path: list[Address] | str | None
566    ) -> tuple[asyncio.Future, Message]:
567        future = asyncio.get_running_loop().create_future()
568        frame_path = path_split(path) if path else self.default_path
569        if not ack:
570            message = self._message(recipient, text, None)
571            self.write(self.prepare_frame(message, frame_path))
572            future.set_result(None)
573            return future, message
574        number = self._burn_message_sequence_number()
575        field = number
576        if self.reply_ack:
577            field = (
578                number + b"}" + self._pending_reply_acks.pop(str(recipient).upper(), b"")
579            )
580        message = self._message(recipient, text, field)
581        om = OutstandingMessage(
582            message=message,
583            path=frame_path,
584            future=future,
585            remaining_tries=self.retries,
586            period=self.retry_period,
587        )
588        self.outstanding[number] = om
589        try:
590            self.write(self.prepare_frame(message, frame_path))
591        except NotConnected:
592            logger.warning(
593                "%s: not connected; will retry message %s", self.mycall, number
594            )
595        om.timer = asyncio.get_running_loop().call_later(om.period, self._retry, number)
596        return future, message
597
598    async def send_message(
599        self,
600        recipient: str,
601        body: str,
602        ack: bool = False,
603        overflow: OverflowDisposition = OverflowDisposition.Truncate,
604        path: list[Address] | str | None = None,
605    ) -> list[APRSFrame | None]:
606        """
607        Send ``body`` and wait until every part is acked (with ``ack``).
608
609        Returns the ack frame for each part (None without ``ack``). Raises
610        MessageRejected or MaximumRetryExceeded.
611        """
612        futures = self.submit_message(recipient, body, ack, overflow, path)
613        return list(await asyncio.gather(*futures))
614
615    def _retry(self, number: bytes) -> None:
616        om = self.outstanding.get(number)
617        if om is None or om.future.done():
618            return
619        if om.remaining_tries <= 0:
620            self._finish(om)
621            om.future.set_exception(
622                MaximumRetryExceeded(f"{om.recipient} did not acknowledge {om.message}")
623            )
624            return
625        om.remaining_tries -= 1
626        try:
627            self.write(self.prepare_frame(om.message, om.path))
628        except NotConnected:
629            logger.warning(
630                "%s: not connected; message %s retry skipped", self.mycall, number
631            )
632        om.timer = asyncio.get_running_loop().call_later(om.period, self._retry, number)
633
634    def _finish(self, om: OutstandingMessage) -> None:
635        if om.timer is not None:
636            om.timer.cancel()
637        for number, value in list(self.outstanding.items()):
638            if value is om:
639                del self.outstanding[number]
640
641    def _resolve(self, number: bytes, frame: APRSFrame, rejected: bool) -> None:
642        om = self.outstanding.get(number)
643        if om is None or om.future.done():
644            return
645        if not _same_station(om.recipient, str(frame.source)):
646            return  # someone else's ack for the same number
647        self._finish(om)
648        if rejected:
649            om.future.set_exception(MessageRejected(frame))
650        else:
651            om.future.set_result(frame)
652
653    def send_status(
654        self, status: str, path: list[Address] | str | None = None
655    ) -> APRSFrame:
656        frame = self.prepare_frame(
657            StatusReport(
658                raw=b"", data_type=DataType.STATUS, data=b"", status=status.encode()
659            ),
660            path,
661        )
662        self.write(frame)
663        return frame
664
665    def send_position(
666        self, position: Position, path: list[Address] | str | None = None
667    ) -> APRSFrame:
668        frame = self.prepare_frame(
669            PositionReport(
670                raw=b"",
671                data_type=DataType.POSITION_W_O_TIMESTAMP_MSG,
672                data=b"",
673                position=position,
674            ),
675            path,
676        )
677        self.write(frame)
678        return frame
679
680    # -- delayed send queue --
681
682    async def schedule(
683        self,
684        frame: APRSFrame | InformationField,
685        delay: float = 0.0,
686        at: t.Any = None,
687        path: list[Address] | str | None = None,
688    ) -> "PacketRecord":
689        """
690        Queue ``frame`` (or an info field, framed from ``mycall``) in the
691        store, to be transmitted ``delay`` seconds from now or ``at``. The
692        queue survives restarts. Scheduled messages are not ack-tracked.
693        """
694        if self.store is None:
695            raise RuntimeError("schedule() needs a PacketStore (store=...)")
696        if not isinstance(frame, APRSFrame):
697            frame = self.prepare_frame(frame, path)
698        record = await self.store.schedule(frame, delay=delay, at=at)
699        if self._wakeup is not None:
700            self._wakeup.set()
701        return record
702
703    async def _run_sender(self) -> None:
704        from .store import utcnow  # the db extra is optional
705
706        store = self.store
707        assert store is not None
708        while not self._closing:
709            self._wakeup.clear()
710            timeout: float | None = None
711            try:
712                if self.connected:
713                    for record in await store.due():
714                        if not self.connected:
715                            break
716                        if not await store.claim(record):
717                            continue  # another sender took it
718                        try:
719                            self.write(record.frame, record=False)
720                        except Exception as exc:  # pylint: disable=broad-except
721                            await store.mark_error(record, str(exc))
722                    next_due = await store.next_due()
723                    if next_due is not None:
724                        timeout = max(0.0, (next_due - utcnow()).total_seconds())
725            except Exception:  # pylint: disable=broad-except
726                logger.exception("Send queue failed; retrying")
727                timeout = 1.0
728            with contextlib.suppress(TimeoutError):
729                await asyncio.wait_for(self._wakeup.wait(), timeout)

An APRS station on one connection.

Pass a connector (see aprsis_connector, kiss_tcp_connector, kiss_serial_connector) or use the aprsis/kiss_tcp/ kiss_serial constructors. start() (or async with) connects.

AsyncClient( mycall: Union[ax253.Address, bytes, str], connector: Callable[[], Awaitable[ax253.FrameDecodeProtocol]] | None = None, default_path=NOTHING, destination: Union[ax253.Address, bytes, str] = 'APZ069', store: 'PacketStore | None' = None, reconnect: ReconnectPolicy | None = NOTHING, retries: int = 3, retry_period: float = 10, duplicate_window: float = 30.0, reply_ack: bool = True, next_message_sequence_number: int = NOTHING, max_queued_frames: int = 10000)
17def __init__(self, mycall, connector=attr_dict['connector'].default, default_path=NOTHING, destination=attr_dict['destination'].default, store=attr_dict['store'].default, reconnect=NOTHING, retries=attr_dict['retries'].default, retry_period=attr_dict['retry_period'].default, duplicate_window=attr_dict['duplicate_window'].default, reply_ack=attr_dict['reply_ack'].default, next_message_sequence_number=NOTHING, max_queued_frames=attr_dict['max_queued_frames'].default):
18    _setattr = _cached_setattr_get(self)
19    _setattr('mycall', __attr_converter_mycall(mycall))
20    _setattr('connector', connector)
21    if default_path is not NOTHING:
22        _setattr('default_path', __attr_converter_default_path(default_path))
23    else:
24        _setattr('default_path', __attr_converter_default_path(__attr_factory_default_path()))
25    _setattr('destination', __attr_converter_destination(destination))
26    _setattr('store', store)
27    if reconnect is not NOTHING:
28        _setattr('reconnect', reconnect)
29    else:
30        _setattr('reconnect', __attr_factory_reconnect())
31    _setattr('retries', retries)
32    _setattr('retry_period', retry_period)
33    _setattr('duplicate_window', duplicate_window)
34    _setattr('reply_ack', reply_ack)
35    if next_message_sequence_number is not NOTHING:
36        _setattr('next_message_sequence_number', next_message_sequence_number)
37    else:
38        _setattr('next_message_sequence_number', __attr_factory_next_message_sequence_number())
39    _setattr('max_queued_frames', max_queued_frames)
40    _setattr('protocol', attr_dict['protocol'].default)
41    _setattr('outstanding', __attr_factory_outstanding())
42    _setattr('frame_handlers', __attr_factory_frame_handlers())
43    _setattr('message_handlers', __attr_factory_message_handlers())
44    _setattr('connect_handlers', __attr_factory_connect_handlers())
45    _setattr('dropped_frames', attr_dict['dropped_frames'].default)
46    _setattr('_frames', attr_dict['_frames'].default)
47    _setattr('_connected', attr_dict['_connected'].default)
48    _setattr('_wakeup', attr_dict['_wakeup'].default)
49    _setattr('_tasks', __attr_factory__tasks())
50    _setattr('_seen', __attr_factory__seen())
51    _setattr('_reply_ack_stations', __attr_factory__reply_ack_stations())
52    _setattr('_pending_reply_acks', __attr_factory__pending_reply_acks())
53    _setattr('_started', attr_dict['_started'].default)
54    _setattr('_closing', attr_dict['_closing'].default)

Method generated by attrs for class AsyncClient.

mycall: ax253.Address
connector: Callable[[], Awaitable[ax253.FrameDecodeProtocol]] | None
default_path: list[ax253.Address]
destination: ax253.Address
store: 'PacketStore | None'

Log every frame heard and sent, and transmit its queue (schedule).

reconnect: ReconnectPolicy | None

How to reconnect when the connection drops; None to stop instead.

retries: int
retry_period: float
duplicate_window: float

Seconds to remember incoming messages, so each is delivered once (0: off).

reply_ack: bool

Number outgoing messages "{MM}" + reply-ack, advertising reply-ack support.

next_message_sequence_number: int
max_queued_frames: int

Frames kept for recv/async for before the oldest are dropped.

protocol: ax253.FrameDecodeProtocol | None
outstanding: dict[bytes, base_aprs_client.aio.OutstandingMessage]
frame_handlers: list[Callable[[aprs.APRSFrame], typing.Any]]
message_handlers: list[Callable[[aprs.Message, aprs.APRSFrame], typing.Any]]
connect_handlers: list[Callable[[ax253.FrameDecodeProtocol], typing.Any]]
dropped_frames: int
@classmethod
def aprsis( cls, mycall: str, host: str = 'rotate.aprs.net', port: int = 14580, passcode: str = '-1', filter: str | None = None, **kwargs: Any) -> AsyncClient:
226    @classmethod
227    def aprsis(
228        cls,
229        mycall: str,
230        host: str = APRSIS_SERVERS[0],
231        port: int = APRSIS_FILTER_PORT,
232        passcode: str = "-1",
233        filter: str | None = None,
234        **kwargs: t.Any,
235    ) -> "AsyncClient":
236        connector = aprsis_connector(str(mycall), host, port, passcode, filter)
237        return cls(mycall=mycall, connector=connector, **kwargs)
@classmethod
def kiss_tcp( cls, mycall: str, host: str, port: int, kiss_settings: dict | None = None, **kwargs: Any) -> AsyncClient:
239    @classmethod
240    def kiss_tcp(
241        cls,
242        mycall: str,
243        host: str,
244        port: int,
245        kiss_settings: dict | None = None,
246        **kwargs: t.Any,
247    ) -> "AsyncClient":
248        connector = kiss_tcp_connector(host, port, kiss_settings)
249        return cls(mycall=mycall, connector=connector, **kwargs)
@classmethod
def kiss_serial( cls, mycall: str, port: str, baudrate: int = 9600, kiss_settings: dict | None = None, **kwargs: Any) -> AsyncClient:
251    @classmethod
252    def kiss_serial(
253        cls,
254        mycall: str,
255        port: str,
256        baudrate: int = 9600,
257        kiss_settings: dict | None = None,
258        **kwargs: t.Any,
259    ) -> "AsyncClient":
260        connector = kiss_serial_connector(port, baudrate, kiss_settings)
261        return cls(mycall=mycall, connector=connector, **kwargs)
async def start( self, protocol: ax253.FrameDecodeProtocol | None = None) -> AsyncClient:
265    async def start(self, protocol: FrameDecodeProtocol | None = None) -> "AsyncClient":
266        """
267        Connect (or use an already connected ``protocol``) and start the
268        receive loop, and the send-queue loop when there is a ``store``.
269        """
270        if self._started:
271            return self
272        self._frames = asyncio.Queue()
273        self._connected = asyncio.Event()
274        self._wakeup = asyncio.Event()
275        if protocol is None:
276            if self.connector is None:
277                raise ValueError("AsyncClient needs a connector or a protocol")
278            protocol = await self.connector()
279        self._started = True
280        self._set_protocol(protocol)
281        self._spawn(self._run_reader())
282        if self.store is not None:
283            await self.store.create_all()
284            self._spawn(self._run_sender())
285        return self

Connect (or use an already connected protocol) and start the receive loop, and the send-queue loop when there is a store.

async def close(self) -> None:
287    async def close(self) -> None:
288        """Stop the loops, cancel outstanding messages and close the connection."""
289        if self._closing:
290            return
291        self._closing = True
292        for om in list(self.outstanding.values()):
293            self._finish(om)
294            om.future.cancel()
295        tasks = [task for task in self._tasks if task is not asyncio.current_task()]
296        for task in tasks:
297            task.cancel()
298        await asyncio.gather(*tasks, return_exceptions=True)
299        if self.protocol is not None and self.protocol.transport is not None:
300            self.protocol.transport.close()
301            await asyncio.sleep(0)  # let the transport release the socket/port
302        if self._frames is not None:
303            self._frames.put_nowait(_CLOSED)

Stop the loops, cancel outstanding messages and close the connection.

connected: bool
311    @property
312    def connected(self) -> bool:
313        return self._connected is not None and self._connected.is_set()
async def wait_connected(self, timeout: float | None = None) -> None:
315    async def wait_connected(self, timeout: float | None = None) -> None:
316        await asyncio.wait_for(self._connected.wait(), timeout)
def on_frame( self, handler: Callable[[aprs.APRSFrame], typing.Any]) -> Callable[[aprs.APRSFrame], typing.Any]:
441    def on_frame(self, handler: FrameHandler) -> FrameHandler:
442        """Call ``handler(frame)`` (or await it) for every frame delivered."""
443        self.frame_handlers.append(handler)
444        return handler

Call handler(frame) (or await it) for every frame delivered.

def on_message( self, handler: Callable[[aprs.Message, aprs.APRSFrame], typing.Any]) -> Callable[[aprs.Message, aprs.APRSFrame], typing.Any]:
446    def on_message(self, handler: MessageHandler) -> MessageHandler:
447        """Call ``handler(message, frame)`` for each message to ``mycall``, once."""
448        self.message_handlers.append(handler)
449        return handler

Call handler(message, frame) for each message to mycall, once.

async def recv(self, timeout: float | None = None) -> aprs.APRSFrame:
451    async def recv(self, timeout: float | None = None) -> APRSFrame:
452        """The next frame; raises EOFError once the client is closed."""
453        frame = await asyncio.wait_for(self._frames.get(), timeout)
454        if frame is _CLOSED:
455            self._frames.put_nowait(_CLOSED)  # wake other readers too
456            raise EOFError("client closed")
457        return frame

The next frame; raises EOFError once the client is closed.

def recv_nowait(self) -> list[aprs.APRSFrame]:
459    def recv_nowait(self) -> list[APRSFrame]:
460        """Every frame received so far and not yet returned."""
461        frames = []
462        while not self._frames.empty():
463            frame = self._frames.get_nowait()
464            if frame is _CLOSED:
465                self._frames.put_nowait(_CLOSED)
466                break
467            frames.append(frame)
468        return frames

Every frame received so far and not yet returned.

def prepare_frame( self, info: aprs.InformationField, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
479    def prepare_frame(
480        self, info: InformationField, path: list[Address] | str | None = None
481    ) -> APRSFrame:
482        # ui() sets the AX.25 end-of-address bit, which KISS TNCs need
483        return APRSFrame.ui(
484            destination=self.destination,
485            source=self.mycall,
486            path=path_split(path) if path else self.default_path,
487            info=info,  # ty: ignore[invalid-argument-type]  # ui() is typed for bytes
488        )
def write(self, frame: aprs.APRSFrame, record: bool = True) -> None:
490    def write(self, frame: APRSFrame, record: bool = True) -> None:
491        """Transmit ``frame`` now; raises NotConnected if the connection is down."""
492        if not self.connected or self.protocol is None:
493            raise NotConnected(f"{self.mycall} is not connected")
494        self.protocol.write(frame)
495        if record and self.store is not None:
496            self._spawn(self._record_sent(frame))

Transmit frame now; raises NotConnected if the connection is down.

def submit_message( self, recipient: str, body: str, ack: bool = False, overflow: OverflowDisposition = <OverflowDisposition.Truncate: False>, path: list[ax253.Address] | str | None = None) -> list[_asyncio.Future]:
529    def submit_message(
530        self,
531        recipient: str,
532        body: str,
533        ack: bool = False,
534        overflow: OverflowDisposition = OverflowDisposition.Truncate,
535        path: list[Address] | str | None = None,
536    ) -> list[asyncio.Future]:
537        """
538        Send ``body`` without waiting; one future per part.
539
540        Text over 67 bytes is cut (``Truncate``) or split on word boundaries
541        (``Continue``). With ``ack``, each future resolves to the ack frame,
542        or fails with MessageRejected or MaximumRetryExceeded. Without
543        ``ack``, the futures are already resolved to None.
544        """
545        return [
546            future
547            for future, _ in self._submit_parts(recipient, body, ack, overflow, path)
548        ]

Send body without waiting; one future per part.

Text over 67 bytes is cut (Truncate) or split on word boundaries (Continue). With ack, each future resolves to the ack frame, or fails with MessageRejected or MaximumRetryExceeded. Without ack, the futures are already resolved to None.

async def send_message( self, recipient: str, body: str, ack: bool = False, overflow: OverflowDisposition = <OverflowDisposition.Truncate: False>, path: list[ax253.Address] | str | None = None) -> list[aprs.APRSFrame | None]:
598    async def send_message(
599        self,
600        recipient: str,
601        body: str,
602        ack: bool = False,
603        overflow: OverflowDisposition = OverflowDisposition.Truncate,
604        path: list[Address] | str | None = None,
605    ) -> list[APRSFrame | None]:
606        """
607        Send ``body`` and wait until every part is acked (with ``ack``).
608
609        Returns the ack frame for each part (None without ``ack``). Raises
610        MessageRejected or MaximumRetryExceeded.
611        """
612        futures = self.submit_message(recipient, body, ack, overflow, path)
613        return list(await asyncio.gather(*futures))

Send body and wait until every part is acked (with ack).

Returns the ack frame for each part (None without ack). Raises MessageRejected or MaximumRetryExceeded.

def send_status( self, status: str, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
653    def send_status(
654        self, status: str, path: list[Address] | str | None = None
655    ) -> APRSFrame:
656        frame = self.prepare_frame(
657            StatusReport(
658                raw=b"", data_type=DataType.STATUS, data=b"", status=status.encode()
659            ),
660            path,
661        )
662        self.write(frame)
663        return frame
def send_position( self, position: aprs.Position, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
665    def send_position(
666        self, position: Position, path: list[Address] | str | None = None
667    ) -> APRSFrame:
668        frame = self.prepare_frame(
669            PositionReport(
670                raw=b"",
671                data_type=DataType.POSITION_W_O_TIMESTAMP_MSG,
672                data=b"",
673                position=position,
674            ),
675            path,
676        )
677        self.write(frame)
678        return frame
async def schedule( self, frame: aprs.APRSFrame | aprs.InformationField, delay: float = 0.0, at: Any = None, path: list[ax253.Address] | str | None = None) -> 'PacketRecord':
682    async def schedule(
683        self,
684        frame: APRSFrame | InformationField,
685        delay: float = 0.0,
686        at: t.Any = None,
687        path: list[Address] | str | None = None,
688    ) -> "PacketRecord":
689        """
690        Queue ``frame`` (or an info field, framed from ``mycall``) in the
691        store, to be transmitted ``delay`` seconds from now or ``at``. The
692        queue survives restarts. Scheduled messages are not ack-tracked.
693        """
694        if self.store is None:
695            raise RuntimeError("schedule() needs a PacketStore (store=...)")
696        if not isinstance(frame, APRSFrame):
697            frame = self.prepare_frame(frame, path)
698        record = await self.store.schedule(frame, delay=delay, at=at)
699        if self._wakeup is not None:
700            self._wakeup.set()
701        return record

Queue frame (or an info field, framed from mycall) in the store, to be transmitted delay seconds from now or at. The queue survives restarts. Scheduled messages are not ack-tracked.

@attrs.define(eq=False)
class Client:
214@attrs.define(eq=False)
215class Client:
216    """
217    Sends messages with ack and retry, acks incoming messages addressed to
218    ``mycall``, and sends status and position reports.
219
220    Subclasses may override ``on_frame(frame)`` and ``on_message(message,
221    frame)``; they are called from ``read()`` for each frame it returns.
222    """
223
224    mycall: Address = attrs.field(converter=Address.from_any)
225    sync_frame_io: t.Any = attrs.field(default=None)
226    default_path: list[Address] = attrs.field(factory=list, converter=path_split)
227    destination: Address = attrs.field(default="APZ069", converter=Address.from_any)
228    _initial_sequence_number: int | None = attrs.field(
229        default=None, alias="next_message_sequence_number"
230    )
231    store: "PacketStore | None" = attrs.field(default=None, kw_only=True)
232    reconnect: ReconnectPolicy | None = attrs.field(factory=ReconnectPolicy, kw_only=True)
233    retries: int = attrs.field(default=DEFAULT_MESSAGE_RETRY, kw_only=True)
234    retry_period: float = attrs.field(default=DEFAULT_MESSAGE_RETRY_PERIOD, kw_only=True)
235    duplicate_window: float = attrs.field(default=DEFAULT_DUPLICATE_WINDOW, kw_only=True)
236    reply_ack: bool = attrs.field(default=True, kw_only=True)
237    connector: Connector | None = attrs.field(default=None, kw_only=True)
238
239    aclient: AsyncClient = attrs.field(init=False)
240    _runner: _Runner = attrs.field(init=False)
241
242    def __attrs_post_init__(self) -> None:
243        kwargs: dict[str, t.Any] = dict(
244            mycall=self.mycall,
245            default_path=self.default_path,
246            destination=self.destination,
247            store=self.store,
248            reconnect=self.reconnect,
249            retries=self.retries,
250            retry_period=self.retry_period,
251            duplicate_window=self.duplicate_window,
252            reply_ack=self.reply_ack,
253        )
254        if self._initial_sequence_number is not None:
255            kwargs["next_message_sequence_number"] = self._initial_sequence_number
256        protocol = None
257        if self.sync_frame_io is not None:
258            self._runner = _Runner(self.sync_frame_io.loop, threaded=False)
259            protocol = self.sync_frame_io.protocol
260            kwargs["connector"] = self.connector or _connector_for(self.sync_frame_io)
261        else:
262            if self.connector is None:
263                raise ValueError("Client needs a sync_frame_io or a connector")
264            self._runner = _Runner(asyncio.new_event_loop(), threaded=True)
265            kwargs["connector"] = self.connector
266        self.aclient = AsyncClient(**kwargs)
267        if self.sync_frame_io is not None:
268            # keep the transport's stop() pointed at the live connection
269            self.aclient.connect_handlers.append(self._adopt_protocol)
270        self._runner.run(self.aclient.start(protocol))
271
272    def _adopt_protocol(self, protocol: FrameDecodeProtocol) -> None:
273        self.sync_frame_io._protocol = protocol  # pylint: disable=protected-access
274
275    # -- constructors --
276
277    @classmethod
278    def aprsis(
279        cls,
280        mycall: str,
281        host: str = "rotate.aprs.net",
282        port: int = 14580,
283        passcode: str = "-1",
284        filter: str | None = None,
285        **kwargs: t.Any,
286    ) -> "Client":
287        """Connect to APRS-IS; the client runs on a background thread."""
288        connector = aprsis_connector(str(mycall), host, port, passcode, filter)
289        return cls(mycall=mycall, connector=connector, **kwargs)
290
291    @classmethod
292    def kiss_tcp(
293        cls,
294        mycall: str,
295        host: str,
296        port: int,
297        kiss_settings: dict | None = None,
298        **kwargs,
299    ) -> "Client":
300        """Connect to a KISS-over-TCP TNC; the client runs on a background thread."""
301        return cls(
302            mycall=mycall,
303            connector=kiss_tcp_connector(host, port, kiss_settings),
304            **kwargs,
305        )
306
307    @classmethod
308    def kiss_serial(
309        cls,
310        mycall: str,
311        port: str,
312        baudrate: int = 9600,
313        kiss_settings: dict | None = None,
314        **kwargs: t.Any,
315    ) -> "Client":
316        """Open a serial KISS TNC; the client runs on a background thread."""
317        return cls(
318            mycall=mycall,
319            connector=kiss_serial_connector(port, baudrate, kiss_settings),
320            **kwargs,
321        )
322
323    # -- lifecycle --
324
325    def close(self) -> None:
326        """Close the connection and stop the client."""
327        try:
328            self._runner.run(self.aclient.close())
329        finally:
330            self._runner.stop()
331
332    def __enter__(self) -> "Client":
333        return self
334
335    def __exit__(self, *exc_info: t.Any) -> None:
336        self.close()
337
338    @property
339    def connected(self) -> bool:
340        return self.aclient.connected
341
342    @property
343    def next_message_sequence_number(self) -> int:
344        """The number the next acked message will carry."""
345        return self.aclient.next_message_sequence_number
346
347    @property
348    def outstanding_messages(self) -> dict:
349        """Messages waiting for an ack, by message number."""
350        return self.aclient.outstanding
351
352    def poll(self, seconds: float = 0.0) -> None:
353        """Let the client's loop run for ``seconds`` (only needed with ``sync_frame_io``)."""
354        self._runner.run(asyncio.sleep(seconds))
355
356    # -- receiving --
357
358    def read(self, min_frames: int | None = -1) -> list[APRSFrame]:
359        """
360        Frames received since the last read, calling ``on_frame`` for each.
361
362        ``min_frames=-1`` returns what has arrived without waiting; a number
363        waits for at least that many; None reads until the client closes.
364        Duplicate messages are left out.
365        """
366
367        async def _read() -> list[APRSFrame]:
368            await asyncio.sleep(0)  # let pending input be decoded
369            frames = self.aclient.recv_nowait()
370            while min_frames is None or len(frames) < min_frames:
371                try:
372                    frames.append(await self.aclient.recv())
373                except EOFError:
374                    break
375                frames.extend(self.aclient.recv_nowait())
376            return frames
377
378        frames = self._runner.run(_read())
379        for frame in frames:
380            self.on_frame(frame)
381        return frames
382
383    def on_frame(self, frame: APRSFrame) -> None:
384        """Called by ``read()`` for every frame; calls ``on_message`` for ours."""
385        info = frame.info
386        if (
387            isinstance(info, Message)
388            and info.addressee.decode("latin1").strip().upper()
389            == str(self.mycall).upper()
390        ):
391            self.on_message(info, frame)
392
393    def on_message(self, message: Message, frame: APRSFrame) -> None:
394        """Called by ``read()`` for each message to ``mycall`` (acks included)."""
395
396    # -- sending --
397
398    def prepare_frame(
399        self, info: InformationField, path: list[Address] | str | None = None
400    ) -> APRSFrame:
401        return self.aclient.prepare_frame(info, path)
402
403    def write(self, frame: APRSFrame) -> None:
404        self._runner.call(self.aclient.write, frame)
405
406    def send_message(
407        self,
408        recipient: str,
409        body: str,
410        ack: bool = False,
411        overflow: OverflowDisposition = OverflowDisposition.Truncate,
412        path: list[Address] | str | None = None,
413    ) -> MessageAckFuture | list[MessageAckFuture | None] | None:
414        """
415        Send ``body`` to ``recipient`` without waiting for the ack.
416
417        Text over 67 bytes is cut (``Truncate``) or split on word boundaries
418        (``Continue``); a split message returns one result per part. With
419        ``ack``, each result is a MessageAckFuture.
420        """
421        submitted = self._runner.call(
422            self.aclient._submit_parts,  # pylint: disable=protected-access
423            str(recipient),
424            body,
425            ack,
426            overflow,
427            path,
428        )
429        results: list[MessageAckFuture | None] = [
430            MessageAckFuture(future, message, self._runner) if ack else None
431            for future, message in submitted
432        ]
433        if len(results) == 1:
434            return results[0]
435        return results
436
437    def send_status(
438        self, status: str, path: list[Address] | str | None = None
439    ) -> APRSFrame:
440        return self._runner.call(self.aclient.send_status, status, path)
441
442    def send_position(
443        self, position: Position, path: list[Address] | str | None = None
444    ) -> APRSFrame:
445        return self._runner.call(self.aclient.send_position, position, path)
446
447    def schedule(
448        self,
449        frame: APRSFrame | InformationField,
450        delay: float = 0.0,
451        at: t.Any = None,
452        path: list[Address] | str | None = None,
453    ) -> "PacketRecord":
454        """Queue ``frame`` in the store for later transmission (see AsyncClient)."""
455        return self._runner.run(self.aclient.schedule(frame, delay, at, path))

Sends messages with ack and retry, acks incoming messages addressed to mycall, and sends status and position reports.

Subclasses may override on_frame(frame) and on_message(message, frame); they are called from read() for each frame it returns.

Client( mycall: Union[ax253.Address, bytes, str], sync_frame_io: Any = None, default_path=NOTHING, destination: Union[ax253.Address, bytes, str] = 'APZ069', next_message_sequence_number: int | None = None, *, store: 'PacketStore | None' = None, reconnect: ReconnectPolicy | None = NOTHING, retries: int = 3, retry_period: float = 10, duplicate_window: float = 30.0, reply_ack: bool = True, connector: Callable[[], Awaitable[ax253.FrameDecodeProtocol]] | None = None)
17def __init__(self, mycall, sync_frame_io=attr_dict['sync_frame_io'].default, default_path=NOTHING, destination=attr_dict['destination'].default, next_message_sequence_number=attr_dict['_initial_sequence_number'].default, *, store=attr_dict['store'].default, reconnect=NOTHING, retries=attr_dict['retries'].default, retry_period=attr_dict['retry_period'].default, duplicate_window=attr_dict['duplicate_window'].default, reply_ack=attr_dict['reply_ack'].default, connector=attr_dict['connector'].default):
18    _setattr = _cached_setattr_get(self)
19    _setattr('mycall', __attr_converter_mycall(mycall))
20    _setattr('sync_frame_io', sync_frame_io)
21    if default_path is not NOTHING:
22        _setattr('default_path', __attr_converter_default_path(default_path))
23    else:
24        _setattr('default_path', __attr_converter_default_path(__attr_factory_default_path()))
25    _setattr('destination', __attr_converter_destination(destination))
26    _setattr('_initial_sequence_number', next_message_sequence_number)
27    _setattr('store', store)
28    if reconnect is not NOTHING:
29        _setattr('reconnect', reconnect)
30    else:
31        _setattr('reconnect', __attr_factory_reconnect())
32    _setattr('retries', retries)
33    _setattr('retry_period', retry_period)
34    _setattr('duplicate_window', duplicate_window)
35    _setattr('reply_ack', reply_ack)
36    _setattr('connector', connector)
37    self.__attrs_post_init__()

Method generated by attrs for class Client.

mycall: ax253.Address
sync_frame_io: Any
default_path: list[ax253.Address]
destination: ax253.Address
store: 'PacketStore | None'
reconnect: ReconnectPolicy | None
retries: int
retry_period: float
duplicate_window: float
reply_ack: bool
connector: Callable[[], Awaitable[ax253.FrameDecodeProtocol]] | None
aclient: AsyncClient
@classmethod
def aprsis( cls, mycall: str, host: str = 'rotate.aprs.net', port: int = 14580, passcode: str = '-1', filter: str | None = None, **kwargs: Any) -> Client:
277    @classmethod
278    def aprsis(
279        cls,
280        mycall: str,
281        host: str = "rotate.aprs.net",
282        port: int = 14580,
283        passcode: str = "-1",
284        filter: str | None = None,
285        **kwargs: t.Any,
286    ) -> "Client":
287        """Connect to APRS-IS; the client runs on a background thread."""
288        connector = aprsis_connector(str(mycall), host, port, passcode, filter)
289        return cls(mycall=mycall, connector=connector, **kwargs)

Connect to APRS-IS; the client runs on a background thread.

@classmethod
def kiss_tcp( cls, mycall: str, host: str, port: int, kiss_settings: dict | None = None, **kwargs) -> Client:
291    @classmethod
292    def kiss_tcp(
293        cls,
294        mycall: str,
295        host: str,
296        port: int,
297        kiss_settings: dict | None = None,
298        **kwargs,
299    ) -> "Client":
300        """Connect to a KISS-over-TCP TNC; the client runs on a background thread."""
301        return cls(
302            mycall=mycall,
303            connector=kiss_tcp_connector(host, port, kiss_settings),
304            **kwargs,
305        )

Connect to a KISS-over-TCP TNC; the client runs on a background thread.

@classmethod
def kiss_serial( cls, mycall: str, port: str, baudrate: int = 9600, kiss_settings: dict | None = None, **kwargs: Any) -> Client:
307    @classmethod
308    def kiss_serial(
309        cls,
310        mycall: str,
311        port: str,
312        baudrate: int = 9600,
313        kiss_settings: dict | None = None,
314        **kwargs: t.Any,
315    ) -> "Client":
316        """Open a serial KISS TNC; the client runs on a background thread."""
317        return cls(
318            mycall=mycall,
319            connector=kiss_serial_connector(port, baudrate, kiss_settings),
320            **kwargs,
321        )

Open a serial KISS TNC; the client runs on a background thread.

def close(self) -> None:
325    def close(self) -> None:
326        """Close the connection and stop the client."""
327        try:
328            self._runner.run(self.aclient.close())
329        finally:
330            self._runner.stop()

Close the connection and stop the client.

connected: bool
338    @property
339    def connected(self) -> bool:
340        return self.aclient.connected
next_message_sequence_number: int
342    @property
343    def next_message_sequence_number(self) -> int:
344        """The number the next acked message will carry."""
345        return self.aclient.next_message_sequence_number

The number the next acked message will carry.

outstanding_messages: dict
347    @property
348    def outstanding_messages(self) -> dict:
349        """Messages waiting for an ack, by message number."""
350        return self.aclient.outstanding

Messages waiting for an ack, by message number.

def poll(self, seconds: float = 0.0) -> None:
352    def poll(self, seconds: float = 0.0) -> None:
353        """Let the client's loop run for ``seconds`` (only needed with ``sync_frame_io``)."""
354        self._runner.run(asyncio.sleep(seconds))

Let the client's loop run for seconds (only needed with sync_frame_io).

def read(self, min_frames: int | None = -1) -> list[aprs.APRSFrame]:
358    def read(self, min_frames: int | None = -1) -> list[APRSFrame]:
359        """
360        Frames received since the last read, calling ``on_frame`` for each.
361
362        ``min_frames=-1`` returns what has arrived without waiting; a number
363        waits for at least that many; None reads until the client closes.
364        Duplicate messages are left out.
365        """
366
367        async def _read() -> list[APRSFrame]:
368            await asyncio.sleep(0)  # let pending input be decoded
369            frames = self.aclient.recv_nowait()
370            while min_frames is None or len(frames) < min_frames:
371                try:
372                    frames.append(await self.aclient.recv())
373                except EOFError:
374                    break
375                frames.extend(self.aclient.recv_nowait())
376            return frames
377
378        frames = self._runner.run(_read())
379        for frame in frames:
380            self.on_frame(frame)
381        return frames

Frames received since the last read, calling on_frame for each.

min_frames=-1 returns what has arrived without waiting; a number waits for at least that many; None reads until the client closes. Duplicate messages are left out.

def on_frame(self, frame: aprs.APRSFrame) -> None:
383    def on_frame(self, frame: APRSFrame) -> None:
384        """Called by ``read()`` for every frame; calls ``on_message`` for ours."""
385        info = frame.info
386        if (
387            isinstance(info, Message)
388            and info.addressee.decode("latin1").strip().upper()
389            == str(self.mycall).upper()
390        ):
391            self.on_message(info, frame)

Called by read() for every frame; calls on_message for ours.

def on_message( self, message: aprs.Message, frame: aprs.APRSFrame) -> None:
393    def on_message(self, message: Message, frame: APRSFrame) -> None:
394        """Called by ``read()`` for each message to ``mycall`` (acks included)."""

Called by read() for each message to mycall (acks included).

def prepare_frame( self, info: aprs.InformationField, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
398    def prepare_frame(
399        self, info: InformationField, path: list[Address] | str | None = None
400    ) -> APRSFrame:
401        return self.aclient.prepare_frame(info, path)
def write(self, frame: aprs.APRSFrame) -> None:
403    def write(self, frame: APRSFrame) -> None:
404        self._runner.call(self.aclient.write, frame)
def send_message( self, recipient: str, body: str, ack: bool = False, overflow: OverflowDisposition = <OverflowDisposition.Truncate: False>, path: list[ax253.Address] | str | None = None) -> MessageAckFuture | list[MessageAckFuture | None] | None:
406    def send_message(
407        self,
408        recipient: str,
409        body: str,
410        ack: bool = False,
411        overflow: OverflowDisposition = OverflowDisposition.Truncate,
412        path: list[Address] | str | None = None,
413    ) -> MessageAckFuture | list[MessageAckFuture | None] | None:
414        """
415        Send ``body`` to ``recipient`` without waiting for the ack.
416
417        Text over 67 bytes is cut (``Truncate``) or split on word boundaries
418        (``Continue``); a split message returns one result per part. With
419        ``ack``, each result is a MessageAckFuture.
420        """
421        submitted = self._runner.call(
422            self.aclient._submit_parts,  # pylint: disable=protected-access
423            str(recipient),
424            body,
425            ack,
426            overflow,
427            path,
428        )
429        results: list[MessageAckFuture | None] = [
430            MessageAckFuture(future, message, self._runner) if ack else None
431            for future, message in submitted
432        ]
433        if len(results) == 1:
434            return results[0]
435        return results

Send body to recipient without waiting for the ack.

Text over 67 bytes is cut (Truncate) or split on word boundaries (Continue); a split message returns one result per part. With ack, each result is a MessageAckFuture.

def send_status( self, status: str, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
437    def send_status(
438        self, status: str, path: list[Address] | str | None = None
439    ) -> APRSFrame:
440        return self._runner.call(self.aclient.send_status, status, path)
def send_position( self, position: aprs.Position, path: list[ax253.Address] | str | None = None) -> aprs.APRSFrame:
442    def send_position(
443        self, position: Position, path: list[Address] | str | None = None
444    ) -> APRSFrame:
445        return self._runner.call(self.aclient.send_position, position, path)
def schedule( self, frame: aprs.APRSFrame | aprs.InformationField, delay: float = 0.0, at: Any = None, path: list[ax253.Address] | str | None = None) -> 'PacketRecord':
447    def schedule(
448        self,
449        frame: APRSFrame | InformationField,
450        delay: float = 0.0,
451        at: t.Any = None,
452        path: list[Address] | str | None = None,
453    ) -> "PacketRecord":
454        """Queue ``frame`` in the store for later transmission (see AsyncClient)."""
455        return self._runner.run(self.aclient.schedule(frame, delay, at, path))

Queue frame in the store for later transmission (see AsyncClient).

class MaximumRetryExceeded(builtins.TimeoutError):
30class MaximumRetryExceeded(TimeoutError):
31    """The recipient did not ack a message after every retry."""

The recipient did not ack a message after every retry.

class MessageAckFuture:
160class MessageAckFuture:
161    """
162    The pending ack for one sent message.
163
164    ``result()`` blocks until the recipient acks (returning the ack frame),
165    rejects (raising MessageRejected) or every retry has timed out (raising
166    MaximumRetryExceeded); waiting keeps the client's loop running.
167    """
168
169    def __init__(self, future: asyncio.Future, message: Message, runner: _Runner) -> None:
170        self._future = future
171        self._runner = runner
172        self.message = message
173
174    def done(self) -> bool:
175        return self._future.done()
176
177    def _wait(self, timeout: float | None) -> None:
178        if not self._future.done():
179
180            async def _wait() -> None:
181                await asyncio.wait([self._future])
182
183            self._runner.run(_wait(), timeout)
184
185    def result(self, timeout: float | None = None) -> APRSFrame:
186        self._wait(timeout)
187        return self._future.result()
188
189    def exception(self, timeout: float | None = None) -> BaseException | None:
190        self._wait(timeout)
191        return self._future.exception()
192
193    def cancel(self) -> bool:
194        return self._runner.call(self._future.cancel)

The pending ack for one sent message.

result() blocks until the recipient acks (returning the ack frame), rejects (raising MessageRejected) or every retry has timed out (raising MaximumRetryExceeded); waiting keeps the client's loop running.

MessageAckFuture( future: _asyncio.Future, message: aprs.Message, runner: base_aprs_client.client._Runner)
169    def __init__(self, future: asyncio.Future, message: Message, runner: _Runner) -> None:
170        self._future = future
171        self._runner = runner
172        self.message = message
message
def done(self) -> bool:
174    def done(self) -> bool:
175        return self._future.done()
def result(self, timeout: float | None = None) -> aprs.APRSFrame:
185    def result(self, timeout: float | None = None) -> APRSFrame:
186        self._wait(timeout)
187        return self._future.result()
def exception(self, timeout: float | None = None) -> BaseException | None:
189    def exception(self, timeout: float | None = None) -> BaseException | None:
190        self._wait(timeout)
191        return self._future.exception()
def cancel(self) -> bool:
193    def cancel(self) -> bool:
194        return self._runner.call(self._future.cancel)
class MessageRejected(builtins.Exception):
34class MessageRejected(Exception):
35    """The recipient answered a message with "rej"."""
36
37    def __init__(self, frame: APRSFrame) -> None:
38        super().__init__(f"{frame.source} rejected the message: {frame}")
39        self.frame = frame

The recipient answered a message with "rej".

MessageRejected(frame: aprs.APRSFrame)
37    def __init__(self, frame: APRSFrame) -> None:
38        super().__init__(f"{frame.source} rejected the message: {frame}")
39        self.frame = frame
frame
class NotConnected(builtins.ConnectionError):
69class NotConnected(ConnectionError):
70    """The client has no open connection to write to."""

The client has no open connection to write to.

class OverflowDisposition(enum.Enum):
25class OverflowDisposition(Enum):
26    Truncate = False
27    Continue = True
Truncate = <OverflowDisposition.Truncate: False>
Continue = <OverflowDisposition.Continue: True>
@attrs.define
class ReconnectPolicy:
128@attrs.define
129class ReconnectPolicy:
130    """Exponential backoff with jitter between reconnect attempts."""
131
132    initial_delay: float = 1.0
133    max_delay: float = 60.0
134    factor: float = 2.0
135    jitter: float = 0.1
136    """Each delay is randomly varied by up to this fraction, up or down."""
137    max_attempts: int | None = None
138    """Give up after this many failed attempts in a row (None: never)."""
139
140    def delays(self) -> Iterator[float]:
141        delay = self.initial_delay
142        attempt = 0
143        while self.max_attempts is None or attempt < self.max_attempts:
144            attempt += 1
145            yield max(0.0, delay * (1 + random.uniform(-self.jitter, self.jitter)))
146            delay = min(self.max_delay, delay * self.factor)

Exponential backoff with jitter between reconnect attempts.

ReconnectPolicy( initial_delay: float = 1.0, max_delay: float = 60.0, factor: float = 2.0, jitter: float = 0.1, max_attempts: int | None = None)
27def __init__(self, initial_delay=attr_dict['initial_delay'].default, max_delay=attr_dict['max_delay'].default, factor=attr_dict['factor'].default, jitter=attr_dict['jitter'].default, max_attempts=attr_dict['max_attempts'].default):
28    self.initial_delay = initial_delay
29    self.max_delay = max_delay
30    self.factor = factor
31    self.jitter = jitter
32    self.max_attempts = max_attempts

Method generated by attrs for class ReconnectPolicy.

initial_delay: float
max_delay: float
factor: float
jitter: float

Each delay is randomly varied by up to this fraction, up or down.

max_attempts: int | None

Give up after this many failed attempts in a row (None: never).

def delays(self) -> Iterator[float]:
140    def delays(self) -> Iterator[float]:
141        delay = self.initial_delay
142        attempt = 0
143        while self.max_attempts is None or attempt < self.max_attempts:
144            attempt += 1
145            yield max(0.0, delay * (1 + random.uniform(-self.jitter, self.jitter)))
146            delay = min(self.max_delay, delay * self.factor)
__distribution__ = 'base-aprs-client'
__version__ = '0.1.dev39+gbc5bca4bc'