ax253
AX.25 frames and the TNC2 text format.
ax253 encodes and decodes the AX.25 UI frames that APRS and other packet
radio applications send. It is the bottom layer of kiss3 (KISS TNCs) and
aprs3 (APRS), and does no I/O of its own beyond the asyncio protocols.
Frames
A frame parses from TNC2 monitor text, the format APRS-IS and most TNCs print:
>>> from ax253 import Frame
>>> frame = Frame.from_str("N0CALL-7>APRS,WIDE1-1*,WIDE2-1:>On the air")
>>> frame.source
Address(callsign=b'N0CALL', ssid=7, digi=False)
>>> [str(p) for p in frame.path]
['WIDE1-1*', 'WIDE2-1']
>>> frame.info
b'>On the air'
bytes(frame) is the AX.25 encoding a KISS TNC sends over the air, and
Frame.from_bytes reads it back:
>>> raw = bytes(frame)
>>> raw[:7]
b'\x82\xa0\xa4\xa6@@`'
>>> print(Frame.from_bytes(raw))
N0CALL-7>APRS,WIDE1-1*,WIDE2-1:>On the air
Frame.ui builds a new UI frame; the * convention marks digipeaters
that have already repeated it:
>>> print(Frame.ui("APRS", "N0CALL", path=["WIDE1-1"], info=b">hello"))
N0CALL>APRS,WIDE1-1:>hello
Addresses
>>> from ax253 import Address
>>> address = Address.from_str("N0CALL-7")
>>> address.callsign, address.ssid
(b'N0CALL', 7)
>>> str(address)
'N0CALL-7'
Streams
AX25BytestreamDecoder (HDLC-framed bytes) and TNC2Decode (text
lines) turn a byte stream into frames, keeping partial input between
calls:
>>> from ax253 import TNC2Decode
>>> decoder = TNC2Decode()
>>> [str(f) for f in decoder.update(b"N0CALL>APRS:>one\r\nN0CALL>AP")]
['N0CALL>APRS:>one']
>>> [str(f) for f in decoder.update(b"RS:>two\r\n")]
['N0CALL>APRS:>two']
FrameDecodeProtocol wraps a decoder as an asyncio protocol, with an async
read(); SyncFrameDecode is the base of the blocking transports in
kiss3 and aprs3.
1r""" 2AX.25 frames and the TNC2 text format. 3 4``ax253`` encodes and decodes the AX.25 UI frames that APRS and other packet 5radio applications send. It is the bottom layer of `kiss3`_ (KISS TNCs) and 6`aprs3`_ (APRS), and does no I/O of its own beyond the asyncio protocols. 7 8.. _kiss3: https://github.com/python-aprs/kiss3 9.. _aprs3: https://github.com/python-aprs/aprs3 10 11Frames 12====== 13 14A frame parses from TNC2 monitor text, the format APRS-IS and most TNCs 15print: 16 17>>> from ax253 import Frame 18>>> frame = Frame.from_str("N0CALL-7>APRS,WIDE1-1*,WIDE2-1:>On the air") 19>>> frame.source 20Address(callsign=b'N0CALL', ssid=7, digi=False) 21>>> [str(p) for p in frame.path] 22['WIDE1-1*', 'WIDE2-1'] 23>>> frame.info 24b'>On the air' 25 26``bytes(frame)`` is the AX.25 encoding a KISS TNC sends over the air, and 27``Frame.from_bytes`` reads it back: 28 29>>> raw = bytes(frame) 30>>> raw[:7] 31b'\x82\xa0\xa4\xa6@@`' 32>>> print(Frame.from_bytes(raw)) 33N0CALL-7>APRS,WIDE1-1*,WIDE2-1:>On the air 34 35``Frame.ui`` builds a new UI frame; the ``*`` convention marks digipeaters 36that have already repeated it: 37 38>>> print(Frame.ui("APRS", "N0CALL", path=["WIDE1-1"], info=b">hello")) 39N0CALL>APRS,WIDE1-1:>hello 40 41Addresses 42========= 43 44>>> from ax253 import Address 45>>> address = Address.from_str("N0CALL-7") 46>>> address.callsign, address.ssid 47(b'N0CALL', 7) 48>>> str(address) 49'N0CALL-7' 50 51Streams 52======= 53 54``AX25BytestreamDecoder`` (HDLC-framed bytes) and ``TNC2Decode`` (text 55lines) turn a byte stream into frames, keeping partial input between 56calls: 57 58>>> from ax253 import TNC2Decode 59>>> decoder = TNC2Decode() 60>>> [str(f) for f in decoder.update(b"N0CALL>APRS:>one\r\nN0CALL>AP")] 61['N0CALL>APRS:>one'] 62>>> [str(f) for f in decoder.update(b"RS:>two\r\n")] 63['N0CALL>APRS:>two'] 64 65``FrameDecodeProtocol`` wraps a decoder as an asyncio protocol, with an async 66``read()``; ``SyncFrameDecode`` is the base of the blocking transports in 67kiss3 and aprs3. 68""" 69 70from importlib.metadata import version 71 72from .address import Address 73from .decode import FrameDecodeProtocol, GenericDecoder, SyncFrameDecode 74from .frame import AX25BytestreamDecoder, Control, Frame, FrameType 75from .tnc2 import TNC2Decode, TNC2Protocol 76 77__author__ = "Masen Furer KF7HVM <kf7hvm@0x26.net>" 78__copyright__ = "Copyright 2022 Masen Furer and Contributors" 79__license__ = "Apache License, Version 2.0" 80__distribution__ = "ax253" 81__version__ = version(__distribution__) 82__all__ = [ 83 "Address", 84 "AX25BytestreamDecoder", 85 "Control", 86 "Frame", 87 "FrameDecodeProtocol", 88 "FrameType", 89 "GenericDecoder", 90 "SyncFrameDecode", 91 "TNC2Decode", 92 "TNC2Protocol", 93 "__distribution__", 94 "__version__", 95]
37@define(slots=True, frozen=True) 38class Address: 39 """A source, destination, or path entry in an AX.25 frame.""" 40 41 callsign: bytes = field(validator=valid_callsign) 42 """ 43 The callsign associated with the address, case preserved. 44 45 For APRS-IS addresses whose SSID is not a number 0-15 (e.g. "KJ4ABC-B"), 46 the whole text is kept here and ``ssid`` is 0. 47 """ 48 ssid: int = field(default=0, converter=int, validator=valid_ssid) 49 """The ssid (0-15) extension of the callsign.""" 50 digi: bool = field(default=False, converter=bool) 51 """If true, indicates that this address has digipeated the packet.""" 52 # The high order bit of HLDC; True indicates end of address information. 53 a7_hldc: bool = field(default=False, converter=bool, repr=False) 54 55 @classmethod 56 def from_bytes(cls, ax25_address: bytes, **kwargs: Any) -> Self: 57 """Create an address from ax25 bytes.""" 58 if len(ax25_address) != 7: 59 raise ValueError(f"ax25 address must be 7 bytes, got {len(ax25_address)}") 60 callsign = bytes(b >> 1 for b in ax25_address[:6]).rstrip() 61 ssid = (ax25_address[6] >> 1) & 0x0F 62 a7 = bitarray() 63 a7.frombytes(ax25_address[6:7]) 64 c_or_h = a7[0] 65 r = a7[1:3] # noqa: F841 66 hldc = a7[7] 67 init_kwargs: dict[str, Any] = dict( 68 callsign=callsign, 69 ssid=ssid, 70 # For digipeater addresses bit 7 is the H ("has been repeated") 71 # bit, set on *every* digipeater that has relayed the frame, not 72 # only the last address. For destination/source it is the C 73 # (command/response) bit instead; Frame.from_bytes overrides it. 74 digi=c_or_h, 75 a7_hldc=hldc, 76 ) 77 if kwargs: 78 init_kwargs.update(kwargs) 79 return cls(**init_kwargs) 80 81 @classmethod 82 def from_str( 83 cls, 84 address_spec: str, 85 a7_hldc: bool = False, 86 **kwargs: Any, 87 ) -> Self: 88 """Create an address from a string (TNC2 format).""" 89 digi = "*" in address_spec 90 address = address_spec.strip("*") 91 callsign_str, found, ssid_str = address.partition("-") 92 if ssid_str in AX25_SSIDS: 93 callsign, ssid = callsign_str.encode("latin1"), int(ssid_str) 94 elif not found: 95 callsign, ssid = callsign_str.encode("latin1"), 0 96 else: 97 # not representable in AX.25 (e.g. "KJ4ABC-B", "N0CALL-16", 98 # "N0CALL-01"): keep the text verbatim 99 callsign, ssid = address.encode("latin1"), 0 100 init_kwargs: dict[str, Any] = dict( 101 callsign=callsign, 102 ssid=ssid, 103 digi=digi, 104 a7_hldc=a7_hldc, 105 ) 106 if kwargs: 107 init_kwargs.update(**kwargs) 108 return cls(**init_kwargs) 109 110 @classmethod 111 def from_any( 112 cls, 113 address: Union["Address", bytes, str], 114 **kwargs: Any, 115 ) -> "Address": 116 """Create an address from any supported value.""" 117 if isinstance(address, cls): 118 if kwargs: 119 address = address.evolve(**kwargs) 120 return address 121 elif isinstance(address, bytes): 122 return cls.from_bytes(address, **kwargs) 123 return cls.from_str(str(address), **kwargs) 124 125 def __str__(self) -> str: 126 """Encode address as TNC2 string.""" 127 return "".join( 128 [ 129 self.callsign.decode("latin1"), 130 # Append SSID if non-zero 131 "-%d" % self.ssid if self.ssid else "", 132 # If callsign was digipeated, append '*'. 133 "*" if self.digi else "", 134 ] 135 ) 136 137 def __bytes__(self) -> bytes: 138 """Encode address as ax25 bytes.""" 139 callsign = self.callsign.upper() 140 if not AX25_CALLSIGN_REX.match(callsign): 141 raise ValueError( 142 f"Cannot encode {self.callsign!r} as an AX.25 address: callsign must be 1-6 " 143 "letters or digits" 144 ) 145 callsign = bytes(b << 1 for b in callsign.ljust(6)) 146 a7 = bitarray() 147 a7.frombytes(bytes([self.ssid << 1])) 148 a7[0] = self.digi 149 a7[1:3] = True # r 150 a7[7] = self.a7_hldc 151 return callsign + a7.tobytes() 152 153 def evolve(self, **kwargs) -> "Address": 154 """Create a new Address by applying kwargs to this Address.""" 155 return attr.evolve(self, **kwargs)
A source, destination, or path entry in an AX.25 frame.
34def __init__(self, callsign, ssid=attr_dict['ssid'].default, digi=attr_dict['digi'].default, a7_hldc=attr_dict['a7_hldc'].default): 35 _setattr = _cached_setattr_get(self) 36 _setattr('callsign', callsign) 37 _setattr('ssid', __attr_converter_ssid(ssid)) 38 _setattr('digi', __attr_converter_digi(digi)) 39 _setattr('a7_hldc', __attr_converter_a7_hldc(a7_hldc)) 40 if _config._run_validators is True: 41 __attr_validator_callsign(self, __attr_callsign, self.callsign) 42 __attr_validator_ssid(self, __attr_ssid, self.ssid)
Method generated by attrs for class Address.
The callsign associated with the address, case preserved.
For APRS-IS addresses whose SSID is not a number 0-15 (e.g. "KJ4ABC-B"),
the whole text is kept here and ssid is 0.
55 @classmethod 56 def from_bytes(cls, ax25_address: bytes, **kwargs: Any) -> Self: 57 """Create an address from ax25 bytes.""" 58 if len(ax25_address) != 7: 59 raise ValueError(f"ax25 address must be 7 bytes, got {len(ax25_address)}") 60 callsign = bytes(b >> 1 for b in ax25_address[:6]).rstrip() 61 ssid = (ax25_address[6] >> 1) & 0x0F 62 a7 = bitarray() 63 a7.frombytes(ax25_address[6:7]) 64 c_or_h = a7[0] 65 r = a7[1:3] # noqa: F841 66 hldc = a7[7] 67 init_kwargs: dict[str, Any] = dict( 68 callsign=callsign, 69 ssid=ssid, 70 # For digipeater addresses bit 7 is the H ("has been repeated") 71 # bit, set on *every* digipeater that has relayed the frame, not 72 # only the last address. For destination/source it is the C 73 # (command/response) bit instead; Frame.from_bytes overrides it. 74 digi=c_or_h, 75 a7_hldc=hldc, 76 ) 77 if kwargs: 78 init_kwargs.update(kwargs) 79 return cls(**init_kwargs)
Create an address from ax25 bytes.
81 @classmethod 82 def from_str( 83 cls, 84 address_spec: str, 85 a7_hldc: bool = False, 86 **kwargs: Any, 87 ) -> Self: 88 """Create an address from a string (TNC2 format).""" 89 digi = "*" in address_spec 90 address = address_spec.strip("*") 91 callsign_str, found, ssid_str = address.partition("-") 92 if ssid_str in AX25_SSIDS: 93 callsign, ssid = callsign_str.encode("latin1"), int(ssid_str) 94 elif not found: 95 callsign, ssid = callsign_str.encode("latin1"), 0 96 else: 97 # not representable in AX.25 (e.g. "KJ4ABC-B", "N0CALL-16", 98 # "N0CALL-01"): keep the text verbatim 99 callsign, ssid = address.encode("latin1"), 0 100 init_kwargs: dict[str, Any] = dict( 101 callsign=callsign, 102 ssid=ssid, 103 digi=digi, 104 a7_hldc=a7_hldc, 105 ) 106 if kwargs: 107 init_kwargs.update(**kwargs) 108 return cls(**init_kwargs)
Create an address from a string (TNC2 format).
110 @classmethod 111 def from_any( 112 cls, 113 address: Union["Address", bytes, str], 114 **kwargs: Any, 115 ) -> "Address": 116 """Create an address from any supported value.""" 117 if isinstance(address, cls): 118 if kwargs: 119 address = address.evolve(**kwargs) 120 return address 121 elif isinstance(address, bytes): 122 return cls.from_bytes(address, **kwargs) 123 return cls.from_str(str(address), **kwargs)
Create an address from any supported value.
303@define 304class AX25BytestreamDecoder(GenericDecoder[Frame]): 305 """ 306 Decode a byte stream of AX25_FLAG (0x7E) delimited frames, each followed 307 by its 2-byte FCS. 308 309 The stream carries no escaping, so 0x7E may also occur inside a frame 310 (e.g. "~" in the info field, or in the FCS). When the bytes up to a flag 311 fail the FCS check, later flags are tried as the end of the same frame 312 before the bytes are dropped as corrupt. 313 """ 314 315 _last_pframe: bytes = field(default=b"", init=False) 316 317 @staticmethod 318 def decode_frames(frame: bytes) -> Iterable[Frame]: 319 """ 320 Decode a single deframed byte chunk. 321 322 :param frame: should represent a single higher level frame to 323 decode in some way. 324 """ 325 if frame: 326 yield Frame.from_bytes(frame) 327 328 @staticmethod 329 def _check(segment: bytes) -> bytes | None: 330 """The frame bytes of ``segment`` (frame + FCS) if its FCS matches.""" 331 if len(segment) < MIN_FRAME_WITH_FCS: 332 return None 333 payload, fcs = segment[:-2], segment[-2:] 334 # check the FCS over the bytes as received 335 if FCS.from_bytes(payload).digest() != fcs: 336 return None 337 return payload 338 339 def _decode_payload(self, payload: bytes) -> Iterable[Frame]: 340 try: 341 yield from self.decode_frames(payload) 342 except ValueError: 343 _logger.debug("Dropping undecodable frame %r", payload, exc_info=True) 344 345 @staticmethod 346 def _skip_flags(data: bytes, ix: int) -> int: 347 while ix < len(data) and data[ix] == AX25_FLAG: 348 ix += 1 349 return ix 350 351 def update(self, new_data: bytes) -> Iterable[Frame]: 352 """ 353 Decode the next sequence of bytes from the stream. 354 355 :param new_data: the next bytes from the stream 356 :return: an iterable of decoded frames 357 """ 358 data, self._last_pframe = self._last_pframe + new_data, b"" 359 start = self._skip_flags(data, 0) 360 while start < len(data): 361 end = data.find(AX25_FLAG, start) 362 if end < 0: 363 break # frame not finished yet 364 payload = self._check(data[start:end]) 365 if payload is not None: 366 yield from self._decode_payload(payload) 367 start = self._skip_flags(data, end) 368 continue 369 # Not a valid frame up to this flag. Either the flag byte belongs 370 # to the frame, or the frame is corrupt. 371 next_start = self._skip_flags(data, end) 372 next_end = data.find(AX25_FLAG, next_start) 373 later_end = end 374 resolved = False 375 while True: 376 later_end = data.find(AX25_FLAG, later_end + 1) 377 if later_end < 0 or later_end - start > MAX_FRAME_WITH_FCS: 378 break 379 payload = self._check(data[start:later_end]) 380 if payload is not None: 381 yield from self._decode_payload(payload) 382 start = self._skip_flags(data, later_end) 383 resolved = True 384 break 385 if later_end == next_end and self._check(data[next_start:next_end]): 386 break # the next frame is whole: this one was corrupt 387 if resolved: 388 continue 389 if ( 390 later_end < 0 391 and len(data) - start <= MAX_FRAME_WITH_FCS 392 and (next_end < 0 or not self._check(data[next_start:next_end])) 393 ): 394 break # a later flag may still complete this frame 395 _logger.debug("Dropping frame with bad FCS: %r", data[start:end]) 396 start = next_start 397 self._last_pframe = data[start:] 398 399 def flush(self) -> Iterable[Frame]: 400 """ 401 Call when the stream is closing to decode any final buffered bytes. 402 403 Buffered bytes are decoded only if they end in a valid FCS. 404 """ 405 buffered, self._last_pframe = self._last_pframe, b"" 406 payload = self._check(buffered) 407 if payload is not None: 408 yield from self._decode_payload(payload) 409 elif buffered: 410 _logger.debug("Dropping unterminated frame %r", buffered)
Decode a byte stream of AX25_FLAG (0x7E) delimited frames, each followed by its 2-byte FCS.
The stream carries no escaping, so 0x7E may also occur inside a frame (e.g. "~" in the info field, or in the FCS). When the bytes up to a flag fail the FCS check, later flags are tried as the end of the same frame before the bytes are dropped as corrupt.
317 @staticmethod 318 def decode_frames(frame: bytes) -> Iterable[Frame]: 319 """ 320 Decode a single deframed byte chunk. 321 322 :param frame: should represent a single higher level frame to 323 decode in some way. 324 """ 325 if frame: 326 yield Frame.from_bytes(frame)
Decode a single deframed byte chunk.
Parameters
- frame: should represent a single higher level frame to decode in some way.
351 def update(self, new_data: bytes) -> Iterable[Frame]: 352 """ 353 Decode the next sequence of bytes from the stream. 354 355 :param new_data: the next bytes from the stream 356 :return: an iterable of decoded frames 357 """ 358 data, self._last_pframe = self._last_pframe + new_data, b"" 359 start = self._skip_flags(data, 0) 360 while start < len(data): 361 end = data.find(AX25_FLAG, start) 362 if end < 0: 363 break # frame not finished yet 364 payload = self._check(data[start:end]) 365 if payload is not None: 366 yield from self._decode_payload(payload) 367 start = self._skip_flags(data, end) 368 continue 369 # Not a valid frame up to this flag. Either the flag byte belongs 370 # to the frame, or the frame is corrupt. 371 next_start = self._skip_flags(data, end) 372 next_end = data.find(AX25_FLAG, next_start) 373 later_end = end 374 resolved = False 375 while True: 376 later_end = data.find(AX25_FLAG, later_end + 1) 377 if later_end < 0 or later_end - start > MAX_FRAME_WITH_FCS: 378 break 379 payload = self._check(data[start:later_end]) 380 if payload is not None: 381 yield from self._decode_payload(payload) 382 start = self._skip_flags(data, later_end) 383 resolved = True 384 break 385 if later_end == next_end and self._check(data[next_start:next_end]): 386 break # the next frame is whole: this one was corrupt 387 if resolved: 388 continue 389 if ( 390 later_end < 0 391 and len(data) - start <= MAX_FRAME_WITH_FCS 392 and (next_end < 0 or not self._check(data[next_start:next_end])) 393 ): 394 break # a later flag may still complete this frame 395 _logger.debug("Dropping frame with bad FCS: %r", data[start:end]) 396 start = next_start 397 self._last_pframe = data[start:]
Decode the next sequence of bytes from the stream.
Parameters
- new_data: the next bytes from the stream
Returns
an iterable of decoded frames
399 def flush(self) -> Iterable[Frame]: 400 """ 401 Call when the stream is closing to decode any final buffered bytes. 402 403 Buffered bytes are decoded only if they end in a valid FCS. 404 """ 405 buffered, self._last_pframe = self._last_pframe, b"" 406 payload = self._check(buffered) 407 if payload is not None: 408 yield from self._decode_payload(payload) 409 elif buffered: 410 _logger.debug("Dropping unterminated frame %r", buffered)
Call when the stream is closing to decode any final buffered bytes.
Buffered bytes are decoded only if they end in a valid FCS.
81@define(frozen=True, slots=True) 82class Control: 83 """The Frame control byte, indicates FrameType and PID""" 84 85 v: bytes = field( 86 validator=util.valid_length(1, 1, validators.instance_of(bytes)), 87 converter=bytes_from_int, 88 ) 89 90 @property 91 def bv(self) -> bitarray: 92 bv = bitarray() 93 bv.frombytes(self.v) 94 return bv 95 96 @property 97 def ftype(self) -> FrameType: 98 """The FrameType associated with this Control byte.""" 99 return FrameType.from_control_byte(self.v[0]) 100 101 @classmethod 102 def from_any(cls, obj: Any) -> "Control": 103 if isinstance(obj, cls): 104 return obj 105 return Control(obj) 106 107 @property 108 def n_r(self) -> int: 109 return self.v[0] >> 5 110 111 @property 112 def n_s(self) -> int: 113 return (self.v[0] & 0x0F) >> 1 114 115 @property 116 def p_f(self) -> bool: 117 """The Poll/Final bit (0x10 in modulo-8 control fields).""" 118 return bool(self.v[0] & 0x10) 119 120 def __bytes__(self) -> bytes: 121 return self.v
The Frame control byte, indicates FrameType and PID
28def __init__(self, v): 29 _setattr = _cached_setattr_get(self) 30 _setattr('v', __attr_converter_v(v)) 31 if _config._run_validators is True: 32 __attr_validator_v(self, __attr_v, self.v)
Method generated by attrs for class Control.
96 @property 97 def ftype(self) -> FrameType: 98 """The FrameType associated with this Control byte.""" 99 return FrameType.from_control_byte(self.v[0])
The FrameType associated with this Control byte.
137@define(frozen=True, slots=True) 138class Frame: 139 """ 140 An AX.25 Frame. 141 """ 142 143 # how large the `control` field is: 1 byte for UN frames 144 CONTROL_SIZE = 1 145 146 destination: Address 147 source: Address 148 path: Sequence[Address] 149 control: Control = field( 150 default=Control(UI_CONTROL_FIELD), converter=Control.from_any 151 ) 152 pid: bytes | None = field( 153 default=NO_PROTOCOL_ID, 154 validator=validators.optional( 155 util.valid_length(1, 1, validators.instance_of(bytes)), 156 ), 157 converter=converters.optional(bytes_from_int), 158 ) 159 info: bytes = field(default=b"", converter=bytes_or_encode_utf8) 160 command_response: tuple[bool, bool] = field( 161 default=(False, False), 162 converter=lambda v: (bool(v[0]), bool(v[1])), 163 kw_only=True, 164 ) 165 """ 166 The AX.25 v2 command/response (C) bits of the destination and source 167 addresses, kept so a decoded frame re-encodes to the same bytes. 168 ``(True, False)`` is a command, ``(False, True)`` a response; both equal 169 means a v1 frame. Not shown in TNC2 text. 170 """ 171 172 @classmethod 173 def ui( 174 cls, 175 destination: Address | str, 176 source: Address | str, 177 path: Sequence[Address | str] | None = None, 178 info: bytes | SupportsBytes | str = b"", 179 ) -> Self: 180 """ 181 Create a UI frame with the given information. 182 183 Path entries follow the TNC2 monitor convention: a ``*`` marks the 184 last digipeater that has repeated the frame, and every digipeater 185 before it is implicitly repeated too. Their H bits are all set. 186 """ 187 path_addresses = [Address.from_any(p) for p in path or []] 188 last_repeated = max( 189 (ix for ix, p in enumerate(path_addresses) if p.digi), default=-1 190 ) 191 last_ix = len(path_addresses) - 1 192 return cls( 193 destination=Address.from_any(destination, digi=False, a7_hldc=False), 194 source=Address.from_any(source, digi=False, a7_hldc=not path_addresses), 195 path=[ 196 p.evolve(digi=ix <= last_repeated, a7_hldc=ix == last_ix) 197 for ix, p in enumerate(path_addresses) 198 ], 199 info=info, 200 ) 201 202 @classmethod 203 def from_bytes(cls, ax25_bytes: bytes) -> Self: 204 """ 205 Decode the frame from AX.25 bytes. 206 """ 207 # bit 7 of the destination/source SSID byte is the C (command/response) 208 # bit, not a has-been-repeated flag. Dire Wolf sets it on both. 209 destination = Address.from_bytes(ax25_bytes[:7], digi=False) 210 source = last_address = Address.from_bytes(ax25_bytes[7:14], digi=False) 211 path = [] 212 path_start = 14 213 while not last_address.a7_hldc: 214 if len(path) == MAX_DIGIPEATERS: 215 raise ValueError( 216 f"AX.25 allows at most {MAX_DIGIPEATERS} digipeater addresses" 217 ) 218 last_address = Address.from_bytes(ax25_bytes[path_start : path_start + 7]) 219 path.append(last_address) 220 path_start += 7 221 info_start = control_end = path_start + cls.CONTROL_SIZE 222 control = Control(ax25_bytes[path_start:control_end]) 223 if control.ftype in (FrameType.I, FrameType.U_UI): 224 info_start += 1 225 pid = ax25_bytes[control_end:info_start] 226 else: 227 pid = None 228 return cls( 229 destination=destination, 230 source=source, 231 path=path, 232 control=control, 233 pid=pid, 234 info=ax25_bytes[info_start:], 235 command_response=(bool(ax25_bytes[6] & 0x80), bool(ax25_bytes[13] & 0x80)), 236 ) 237 238 def __bytes__(self) -> bytes: 239 """Encode the frame as AX.25.""" 240 if len(self.path) > MAX_DIGIPEATERS: 241 raise ValueError( 242 f"Cannot encode {len(self.path)} digipeaters as AX.25 (at most " 243 f"{MAX_DIGIPEATERS}); TNC2 text has no such limit" 244 ) 245 dest_c, src_c = self.command_response 246 encoded_frame = [ 247 bytes(self.destination.evolve(digi=dest_c or self.destination.digi)), 248 bytes(self.source.evolve(digi=src_c or self.source.digi)), 249 *(bytes(p) for p in self.path), 250 bytes(self.control), 251 ] 252 if self.control.ftype in (FrameType.I, FrameType.U_UI) and self.pid is not None: 253 encoded_frame.append(self.pid) 254 encoded_frame.append(bytes(self.info)) 255 return b"".join(encoded_frame) 256 257 @classmethod 258 def from_str(cls, ax25_text: str) -> Self: 259 """ 260 Decode the frame from TNC2 monitor format. 261 262 TNC2 text from the stream decoders holds the info bytes decoded as 263 Latin-1, so they are encoded back the same way. Text that can't be 264 Latin-1 (typed by a user, e.g. "€") is encoded as UTF-8, the usual 265 encoding on APRS-IS. 266 """ 267 source_text, gt, rem = ax25_text.partition(">") 268 address_field, colon, info_text = rem.partition(":") 269 destination_text, *paths_text = address_field.split(",") 270 return cls.ui( 271 destination=destination_text, 272 source=source_text, 273 path=paths_text, 274 info=_encode_info_text(info_text), 275 ) 276 277 def __str__(self) -> str: 278 """ 279 Serialize the frame as TNC2 monitor format. 280 281 Only the last digipeater with its H bit set is marked with ``*``. 282 """ 283 path = list(self.path or []) 284 last_repeated = max((ix for ix, p in enumerate(path) if p.digi), default=-1) 285 full_path = [ 286 str(self.destination.evolve(digi=False)), 287 *(str(p.evolve(digi=ix == last_repeated)) for ix, p in enumerate(path)), 288 ] 289 return "%s>%s:%s" % ( 290 str(self.source.evolve(digi=False)), 291 ",".join(full_path), 292 bytes(self.info).decode("latin1"), 293 )
An AX.25 Frame.
40def __init__(self, destination, source, path, control=attr_dict['control'].default, pid=attr_dict['pid'].default, info=attr_dict['info'].default, *, command_response=attr_dict['command_response'].default): 41 _setattr = _cached_setattr_get(self) 42 _setattr('destination', destination) 43 _setattr('source', source) 44 _setattr('path', path) 45 _setattr('control', __attr_converter_control(control)) 46 _setattr('pid', __attr_converter_pid(pid)) 47 _setattr('info', __attr_converter_info(info)) 48 _setattr('command_response', __attr_converter_command_response(command_response)) 49 if _config._run_validators is True: 50 __attr_validator_pid(self, __attr_pid, self.pid)
Method generated by attrs for class Frame.
The AX.25 v2 command/response (C) bits of the destination and source
addresses, kept so a decoded frame re-encodes to the same bytes.
(True, False) is a command, (False, True) a response; both equal
means a v1 frame. Not shown in TNC2 text.
172 @classmethod 173 def ui( 174 cls, 175 destination: Address | str, 176 source: Address | str, 177 path: Sequence[Address | str] | None = None, 178 info: bytes | SupportsBytes | str = b"", 179 ) -> Self: 180 """ 181 Create a UI frame with the given information. 182 183 Path entries follow the TNC2 monitor convention: a ``*`` marks the 184 last digipeater that has repeated the frame, and every digipeater 185 before it is implicitly repeated too. Their H bits are all set. 186 """ 187 path_addresses = [Address.from_any(p) for p in path or []] 188 last_repeated = max( 189 (ix for ix, p in enumerate(path_addresses) if p.digi), default=-1 190 ) 191 last_ix = len(path_addresses) - 1 192 return cls( 193 destination=Address.from_any(destination, digi=False, a7_hldc=False), 194 source=Address.from_any(source, digi=False, a7_hldc=not path_addresses), 195 path=[ 196 p.evolve(digi=ix <= last_repeated, a7_hldc=ix == last_ix) 197 for ix, p in enumerate(path_addresses) 198 ], 199 info=info, 200 )
Create a UI frame with the given information.
Path entries follow the TNC2 monitor convention: a * marks the
last digipeater that has repeated the frame, and every digipeater
before it is implicitly repeated too. Their H bits are all set.
202 @classmethod 203 def from_bytes(cls, ax25_bytes: bytes) -> Self: 204 """ 205 Decode the frame from AX.25 bytes. 206 """ 207 # bit 7 of the destination/source SSID byte is the C (command/response) 208 # bit, not a has-been-repeated flag. Dire Wolf sets it on both. 209 destination = Address.from_bytes(ax25_bytes[:7], digi=False) 210 source = last_address = Address.from_bytes(ax25_bytes[7:14], digi=False) 211 path = [] 212 path_start = 14 213 while not last_address.a7_hldc: 214 if len(path) == MAX_DIGIPEATERS: 215 raise ValueError( 216 f"AX.25 allows at most {MAX_DIGIPEATERS} digipeater addresses" 217 ) 218 last_address = Address.from_bytes(ax25_bytes[path_start : path_start + 7]) 219 path.append(last_address) 220 path_start += 7 221 info_start = control_end = path_start + cls.CONTROL_SIZE 222 control = Control(ax25_bytes[path_start:control_end]) 223 if control.ftype in (FrameType.I, FrameType.U_UI): 224 info_start += 1 225 pid = ax25_bytes[control_end:info_start] 226 else: 227 pid = None 228 return cls( 229 destination=destination, 230 source=source, 231 path=path, 232 control=control, 233 pid=pid, 234 info=ax25_bytes[info_start:], 235 command_response=(bool(ax25_bytes[6] & 0x80), bool(ax25_bytes[13] & 0x80)), 236 )
Decode the frame from AX.25 bytes.
257 @classmethod 258 def from_str(cls, ax25_text: str) -> Self: 259 """ 260 Decode the frame from TNC2 monitor format. 261 262 TNC2 text from the stream decoders holds the info bytes decoded as 263 Latin-1, so they are encoded back the same way. Text that can't be 264 Latin-1 (typed by a user, e.g. "€") is encoded as UTF-8, the usual 265 encoding on APRS-IS. 266 """ 267 source_text, gt, rem = ax25_text.partition(">") 268 address_field, colon, info_text = rem.partition(":") 269 destination_text, *paths_text = address_field.split(",") 270 return cls.ui( 271 destination=destination_text, 272 source=source_text, 273 path=paths_text, 274 info=_encode_info_text(info_text), 275 )
Decode the frame from TNC2 monitor format.
TNC2 text from the stream decoders holds the info bytes decoded as Latin-1, so they are encoded back the same way. Text that can't be Latin-1 (typed by a user, e.g. "€") is encoded as UTF-8, the usual encoding on APRS-IS.
66@define 67class FrameDecodeProtocol(asyncio.Protocol, Generic[_T]): 68 """Protocol which uses a GenericDecoder to split the stream into frames.""" 69 70 transport: asyncio.Transport | None = field(default=None) 71 decoder: GenericDecoder[_T] = field(factory=GenericDecoder) 72 frames: asyncio.Queue = field(factory=asyncio.Queue, init=False) 73 connection_future: asyncio.Future = field( 74 factory=asyncio.Future, 75 init=False, 76 ) 77 max_queued_frames: int | None = field( 78 default=DEFAULT_MAX_QUEUED_FRAMES, 79 kw_only=True, 80 ) 81 """ 82 Most decoded frames kept waiting to be read. When full, the oldest frame 83 is dropped to make room (and counted in `dropped_frames`). None means 84 no limit. 85 """ 86 dropped_frames: int = field(default=0, init=False) 87 """Number of frames dropped because nobody read them in time.""" 88 89 def _queue_frame(self, frame: _T) -> None: 90 self.frame_decoded(frame) 91 limit = self.max_queued_frames 92 if limit is not None: 93 while self.frames.qsize() >= max(limit, 1): 94 try: 95 self.frames.get_nowait() 96 except asyncio.QueueEmpty: # pragma: no cover 97 break 98 self.dropped_frames += 1 99 if self.dropped_frames == 1 or self.dropped_frames % 1000 == 0: 100 log.warning( 101 "Receive queue full (%d frames): dropped %d oldest " 102 "frame(s) so far. Read frames more often or raise " 103 "max_queued_frames.", 104 limit, 105 self.dropped_frames, 106 ) 107 self.frames.put_nowait(frame) 108 109 def connection_made(self, transport: asyncio.BaseTransport) -> None: 110 """ 111 asyncio callback when connection is established. 112 113 Because this protocol exposes higher-level read/write operations that 114 require the transport, an awaitable `connection_future` is completed for consumers 115 who depend on an active connection. 116 """ 117 # the stream transports this protocol is used with are full Transports 118 self.transport = cast(asyncio.Transport, transport) 119 self.connection_future.set_result(self.transport) 120 121 def frame_decoded(self, frame: _T) -> None: 122 """Subclasses may override this function to handle new frame.""" 123 pass 124 125 def data_received(self, data: bytes) -> None: 126 """Pass data off to decoder instance and put frames on the queue.""" 127 for frame in self.decoder.update(data): 128 self._queue_frame(frame) 129 130 def connection_lost(self, exc: Exception | None) -> None: 131 """asyncio callback when connection is lost.""" 132 for frame in self.decoder.flush(): 133 self._queue_frame(frame) 134 self.frames.put_nowait(EOF) 135 136 async def read( 137 self, 138 n_frames: int | None = None, 139 callback: Callable[[_T], None] | None = None, 140 ) -> AsyncIterable[_T]: 141 """ 142 Iterate through decoded frames. 143 144 If n_frames is specified, exit after yielding that number of frames. 145 """ 146 if n_frames is None: 147 n_frames = -1 148 transport = await self.connection_future 149 while (not transport.is_closing() or not self.frames.empty()) and n_frames: 150 frame = await self.frames.get() 151 if frame is EOF: 152 break 153 if callback is not None: 154 callback(frame) 155 yield frame 156 n_frames -= 1 157 158 def read_frames( 159 self, 160 n_frames: int | None = -1, 161 callback: Callable[[_T], None] | None = None, 162 loop: asyncio.AbstractEventLoop | None = None, 163 ) -> Sequence[_T]: 164 """Blocking read of the given number of frames.""" 165 if loop is None: 166 loop = asyncio.get_event_loop() 167 168 if n_frames is not None and n_frames < 0: 169 n_frames = self.frames.qsize() 170 171 async def _(): 172 return [f async for f in self.read(n_frames=n_frames, callback=callback)] 173 174 return loop.run_until_complete(_()) 175 176 def write(self, frame: SupportsBytes) -> None: 177 """ 178 Write serialized frame to the underlying transport. 179 180 :param frame: Frame to write. 181 """ 182 self._connected_transport().write(bytes(frame)) 183 184 def _connected_transport(self) -> asyncio.Transport: 185 if self.transport is None: 186 raise ConnectionError("not connected: the transport isn't open yet") 187 return self.transport
Protocol which uses a GenericDecoder to split the stream into frames.
28def __init__(self, transport=attr_dict['transport'].default, decoder=NOTHING, *, max_queued_frames=attr_dict['max_queued_frames'].default): 29 self.transport = transport 30 if decoder is not NOTHING: 31 self.decoder = decoder 32 else: 33 self.decoder = __attr_factory_decoder() 34 self.frames = __attr_factory_frames() 35 self.connection_future = __attr_factory_connection_future() 36 self.max_queued_frames = max_queued_frames 37 self.dropped_frames = attr_dict['dropped_frames'].default
Method generated by attrs for class FrameDecodeProtocol.
Most decoded frames kept waiting to be read. When full, the oldest frame
is dropped to make room (and counted in dropped_frames). None means
no limit.
109 def connection_made(self, transport: asyncio.BaseTransport) -> None: 110 """ 111 asyncio callback when connection is established. 112 113 Because this protocol exposes higher-level read/write operations that 114 require the transport, an awaitable `connection_future` is completed for consumers 115 who depend on an active connection. 116 """ 117 # the stream transports this protocol is used with are full Transports 118 self.transport = cast(asyncio.Transport, transport) 119 self.connection_future.set_result(self.transport)
asyncio callback when connection is established.
Because this protocol exposes higher-level read/write operations that
require the transport, an awaitable connection_future is completed for consumers
who depend on an active connection.
121 def frame_decoded(self, frame: _T) -> None: 122 """Subclasses may override this function to handle new frame.""" 123 pass
Subclasses may override this function to handle new frame.
130 def connection_lost(self, exc: Exception | None) -> None: 131 """asyncio callback when connection is lost.""" 132 for frame in self.decoder.flush(): 133 self._queue_frame(frame) 134 self.frames.put_nowait(EOF)
asyncio callback when connection is lost.
136 async def read( 137 self, 138 n_frames: int | None = None, 139 callback: Callable[[_T], None] | None = None, 140 ) -> AsyncIterable[_T]: 141 """ 142 Iterate through decoded frames. 143 144 If n_frames is specified, exit after yielding that number of frames. 145 """ 146 if n_frames is None: 147 n_frames = -1 148 transport = await self.connection_future 149 while (not transport.is_closing() or not self.frames.empty()) and n_frames: 150 frame = await self.frames.get() 151 if frame is EOF: 152 break 153 if callback is not None: 154 callback(frame) 155 yield frame 156 n_frames -= 1
Iterate through decoded frames.
If n_frames is specified, exit after yielding that number of frames.
158 def read_frames( 159 self, 160 n_frames: int | None = -1, 161 callback: Callable[[_T], None] | None = None, 162 loop: asyncio.AbstractEventLoop | None = None, 163 ) -> Sequence[_T]: 164 """Blocking read of the given number of frames.""" 165 if loop is None: 166 loop = asyncio.get_event_loop() 167 168 if n_frames is not None and n_frames < 0: 169 n_frames = self.frames.qsize() 170 171 async def _(): 172 return [f async for f in self.read(n_frames=n_frames, callback=callback)] 173 174 return loop.run_until_complete(_())
Blocking read of the given number of frames.
176 def write(self, frame: SupportsBytes) -> None: 177 """ 178 Write serialized frame to the underlying transport. 179 180 :param frame: Frame to write. 181 """ 182 self._connected_transport().write(bytes(frame))
Write serialized frame to the underlying transport.
Parameters
- frame: Frame to write.
35class FrameType(enum.Enum): 36 """ 37 Determines the type of the packet based on the control field. 38 """ 39 40 U_TEST = 0xE3 41 U_XID = 0xAF 42 U_FRMR = 0x87 43 U_SABME = 0x6F 44 U_UA = 0x63 45 U_DISC = 0x43 46 U_SABM = 0x2F 47 U_DM = 0xF 48 S_SREJ = 0xD 49 S_REJ = 0x9 50 S_RNR = 0x5 51 U_UI = 0x3 52 S_RR = 0x1 53 I = 0x0 # noqa: E741 54 55 @classmethod 56 def from_control_byte(cls, control: int) -> "FrameType": 57 """ 58 Classify a (modulo-8) control byte, ignoring the P/F, N(S) and N(R) bits. 59 60 :raises ValueError: for a U-frame control byte that isn't a defined 61 AX.25 command or response. 62 """ 63 if control & 0x01 == 0: 64 return cls.I 65 if control & 0x03 == 0x01: 66 return cls(control & 0x0F) # RR, RNR, REJ, SREJ 67 try: 68 return cls(control & ~0x10 & 0xFF) # U frame without the P/F bit 69 except ValueError: 70 raise ValueError( 71 f"Cannot interpret control byte {control:#04x} as a valid AX.25 frame type." 72 ) from None
Determines the type of the packet based on the control field.
55 @classmethod 56 def from_control_byte(cls, control: int) -> "FrameType": 57 """ 58 Classify a (modulo-8) control byte, ignoring the P/F, N(S) and N(R) bits. 59 60 :raises ValueError: for a U-frame control byte that isn't a defined 61 AX.25 command or response. 62 """ 63 if control & 0x01 == 0: 64 return cls.I 65 if control & 0x03 == 0x01: 66 return cls(control & 0x0F) # RR, RNR, REJ, SREJ 67 try: 68 return cls(control & ~0x10 & 0xFF) # U frame without the P/F bit 69 except ValueError: 70 raise ValueError( 71 f"Cannot interpret control byte {control:#04x} as a valid AX.25 frame type." 72 ) from None
Classify a (modulo-8) control byte, ignoring the P/F, N(S) and N(R) bits.
Raises
- ValueError: for a U-frame control byte that isn't a defined AX.25 command or response.
36@define 37class GenericDecoder(Generic[_T]): 38 """Generic stateful decoder.""" 39 40 @staticmethod 41 def decode_frames(frame: bytes) -> Iterable[_T]: 42 """ 43 Decode a single deframed byte chunk. 44 45 :param frame: should represent a single higher level frame to 46 decode in some way. 47 """ 48 yield cast(_T, frame) 49 50 def update(self, new_data: bytes) -> Iterable[_T]: 51 """ 52 Decode the next sequence of bytes from the stream. 53 54 :param new_data: the next bytes from the stream 55 :return: an iterable of decoded frames 56 """ 57 yield cast(_T, new_data) 58 59 def flush(self) -> Iterable[_T]: 60 """Call when the stream is closing to decode any final buffered bytes.""" 61 if None: 62 yield 63 return
Generic stateful decoder.
40 @staticmethod 41 def decode_frames(frame: bytes) -> Iterable[_T]: 42 """ 43 Decode a single deframed byte chunk. 44 45 :param frame: should represent a single higher level frame to 46 decode in some way. 47 """ 48 yield cast(_T, frame)
Decode a single deframed byte chunk.
Parameters
- frame: should represent a single higher level frame to decode in some way.
50 def update(self, new_data: bytes) -> Iterable[_T]: 51 """ 52 Decode the next sequence of bytes from the stream. 53 54 :param new_data: the next bytes from the stream 55 :return: an iterable of decoded frames 56 """ 57 yield cast(_T, new_data)
Decode the next sequence of bytes from the stream.
Parameters
- new_data: the next bytes from the stream
Returns
an iterable of decoded frames
190@define 191class SyncFrameDecode(abc.ABC, Generic[_T]): 192 """ 193 Synchronous wrapper over FrameDecodeProtocol. 194 195 It is recommended to use this class as a contextmanager for automatic 196 start/stop functionality. 197 """ 198 199 _protocol: FrameDecodeProtocol[_T] | None = field(default=None) 200 """The connected protocol (access via .protocol property).""" 201 202 _loop: asyncio.AbstractEventLoop | None = field(default=None, init=False, repr=False) 203 """This instance's event loop (access via .loop property).""" 204 205 _owns_loop: bool = field(default=False, init=False, repr=False) 206 """True when the loop was created here and should be closed with us.""" 207 208 @property 209 def loop(self) -> asyncio.AbstractEventLoop: 210 """ 211 Get the event loop that this instance runs its connection on. 212 213 Each instance gets its own loop, so instances can be used from 214 different threads at the same time. Inside a running loop, that 215 loop is used instead. A loop created here is closed when the 216 instance is garbage collected. 217 """ 218 if self._loop is None or self._loop.is_closed(): 219 try: 220 self._loop = asyncio.get_running_loop() 221 self._owns_loop = False 222 except RuntimeError: 223 self._loop = asyncio.new_event_loop() 224 self._owns_loop = True 225 # as before: code in this thread that calls get_event_loop() 226 # (e.g. constructing a protocol outside a coroutine) finds it 227 asyncio.set_event_loop(self._loop) 228 return self._loop 229 230 def _close_loop(self) -> None: 231 """Close the event loop if this instance created it.""" 232 loop, self._loop = self._loop, None 233 if self._owns_loop and loop is not None and not loop.is_running(): 234 loop.close() 235 self._owns_loop = False 236 237 @property 238 def protocol(self) -> FrameDecodeProtocol[_T]: 239 if self._protocol is None: 240 raise OSError( 241 "Underlying connection is not active. Hint: did you call start()?", 242 ) 243 return self._protocol 244 245 @property 246 def connected(self) -> bool: 247 """ 248 True while the connection is open. 249 250 Becomes False after stop(), or once the peer closes the connection 251 or the device goes away (a blocking read() then returns early with 252 whatever frames were left). Frames already received can still be 253 read after that. A TCP peer that vanishes without closing (cable 254 pulled, host crashed) is only noticed once a write fails or TCP 255 keepalive gives up. 256 """ 257 protocol = self._protocol 258 if protocol is None or protocol.transport is None: 259 return False 260 return not protocol.transport.is_closing() 261 262 @protocol.setter 263 def protocol(self, p) -> None: 264 if not isinstance(p, FrameDecodeProtocol): 265 raise ValueError( 266 f"Protocol must be a subclass of {FrameDecodeProtocol!r}, got {p!r}", 267 ) 268 self._protocol = p 269 270 def __enter__(self) -> "SyncFrameDecode": 271 self.start() 272 return self 273 274 def __exit__( 275 self, 276 exc_type: type[BaseException] | None, 277 exc: BaseException | None, 278 traceback: TracebackType | None, 279 ) -> bool | None: 280 return self.stop() 281 282 def __del__(self) -> None: 283 # a destructor must never raise, even on an object whose __init__ 284 # or start() failed part way (or during interpreter shutdown) 285 try: 286 self.stop() 287 except Exception: # pylint: disable=broad-except 288 pass 289 try: 290 self._close_loop() 291 except Exception: # pylint: disable=broad-except 292 pass 293 294 @abc.abstractmethod 295 def start(self, **kwargs: Any) -> None: 296 """ 297 Method is responsible for establishing the connection and assigning self.protocol. 298 299 If self.protocol isn't assigned, the SyncFrameDecode is considered closed. 300 """ 301 302 @abc.abstractmethod 303 def stop(self) -> None: 304 """ 305 Method is responsible for closing the transport. 306 """ 307 308 def read( 309 self, 310 callback: Callable[[_T], None] | None = None, 311 min_frames: int | None = -1, 312 ) -> Sequence[_T]: 313 """ 314 Read frames from underlying protocol. 315 316 :param callback: optional function is called after each frame is decoded. 317 The callback will be fired for already-decoded frames immediately, 318 and then for any frames that are decoded while blocked. 319 :param min_frames: block until this minimum number of frames are available. 320 if -1 (default), return all buffered frames without blocking 321 if None, read until EOF is seen (device closed) 322 :return: List of frames 323 """ 324 return list( 325 self.protocol.read_frames( 326 n_frames=min_frames, 327 callback=callback, 328 loop=self.loop, 329 ) 330 ) 331 332 def write(self, frame: SupportsBytes) -> None: 333 """ 334 Writes frame to KISS interface. 335 336 :param frame: Frame to write. 337 """ 338 self.protocol.write(frame)
Synchronous wrapper over FrameDecodeProtocol.
It is recommended to use this class as a contextmanager for automatic start/stop functionality.
25def __init__(self, protocol=attr_dict['_protocol'].default): 26 self._protocol = protocol 27 self._loop = attr_dict['_loop'].default 28 self._owns_loop = attr_dict['_owns_loop'].default
Method generated by attrs for class SyncFrameDecode.
208 @property 209 def loop(self) -> asyncio.AbstractEventLoop: 210 """ 211 Get the event loop that this instance runs its connection on. 212 213 Each instance gets its own loop, so instances can be used from 214 different threads at the same time. Inside a running loop, that 215 loop is used instead. A loop created here is closed when the 216 instance is garbage collected. 217 """ 218 if self._loop is None or self._loop.is_closed(): 219 try: 220 self._loop = asyncio.get_running_loop() 221 self._owns_loop = False 222 except RuntimeError: 223 self._loop = asyncio.new_event_loop() 224 self._owns_loop = True 225 # as before: code in this thread that calls get_event_loop() 226 # (e.g. constructing a protocol outside a coroutine) finds it 227 asyncio.set_event_loop(self._loop) 228 return self._loop
Get the event loop that this instance runs its connection on.
Each instance gets its own loop, so instances can be used from different threads at the same time. Inside a running loop, that loop is used instead. A loop created here is closed when the instance is garbage collected.
245 @property 246 def connected(self) -> bool: 247 """ 248 True while the connection is open. 249 250 Becomes False after stop(), or once the peer closes the connection 251 or the device goes away (a blocking read() then returns early with 252 whatever frames were left). Frames already received can still be 253 read after that. A TCP peer that vanishes without closing (cable 254 pulled, host crashed) is only noticed once a write fails or TCP 255 keepalive gives up. 256 """ 257 protocol = self._protocol 258 if protocol is None or protocol.transport is None: 259 return False 260 return not protocol.transport.is_closing()
True while the connection is open.
Becomes False after stop(), or once the peer closes the connection or the device goes away (a blocking read() then returns early with whatever frames were left). Frames already received can still be read after that. A TCP peer that vanishes without closing (cable pulled, host crashed) is only noticed once a write fails or TCP keepalive gives up.
294 @abc.abstractmethod 295 def start(self, **kwargs: Any) -> None: 296 """ 297 Method is responsible for establishing the connection and assigning self.protocol. 298 299 If self.protocol isn't assigned, the SyncFrameDecode is considered closed. 300 """
Method is responsible for establishing the connection and assigning self.protocol.
If self.protocol isn't assigned, the SyncFrameDecode is considered closed.
302 @abc.abstractmethod 303 def stop(self) -> None: 304 """ 305 Method is responsible for closing the transport. 306 """
Method is responsible for closing the transport.
308 def read( 309 self, 310 callback: Callable[[_T], None] | None = None, 311 min_frames: int | None = -1, 312 ) -> Sequence[_T]: 313 """ 314 Read frames from underlying protocol. 315 316 :param callback: optional function is called after each frame is decoded. 317 The callback will be fired for already-decoded frames immediately, 318 and then for any frames that are decoded while blocked. 319 :param min_frames: block until this minimum number of frames are available. 320 if -1 (default), return all buffered frames without blocking 321 if None, read until EOF is seen (device closed) 322 :return: List of frames 323 """ 324 return list( 325 self.protocol.read_frames( 326 n_frames=min_frames, 327 callback=callback, 328 loop=self.loop, 329 ) 330 )
Read frames from underlying protocol.
Parameters
- callback: optional function is called after each frame is decoded. The callback will be fired for already-decoded frames immediately, and then for any frames that are decoded while blocked.
- min_frames: block until this minimum number of frames are available. if -1 (default), return all buffered frames without blocking if None, read until EOF is seen (device closed)
Returns
List of frames
21@define 22class TNC2Decode(GenericDecoder[Frame]): 23 """ 24 Decode packets in CR-LF delimited TNC2 monitor format. 25 26 Example: SENDER>DEST,PATH:data for the packet 27 28 Lines may be split across any number of ``update()`` calls (TCP delivers 29 a byte stream, not lines); an incomplete trailing line is buffered until 30 its terminator arrives, or until ``flush()``. 31 """ 32 33 _buffer: bytes = field(default=b"", init=False, repr=False) 34 35 @staticmethod 36 def decode_frames(frame: bytes) -> Iterable[Frame]: 37 try: 38 yield Frame.from_str(frame.decode("latin1")) 39 except Exception: 40 log.debug("Ignore frame decode error %r", frame, exc_info=True) 41 42 def _decode_line(self, packet: bytes) -> Iterable[Frame]: 43 if packet.strip().startswith(b"#"): 44 log.debug(packet) # log comment 45 return 46 if packet: 47 yield from self.decode_frames(packet) 48 49 def update(self, new_data: bytes) -> Iterable[Frame]: 50 data = self._buffer + new_data 51 lines = data.splitlines(keepends=True) 52 self._buffer = b"" 53 if lines and not lines[-1].endswith((b"\n", b"\r")): 54 self._buffer = lines.pop() 55 elif data.endswith(b"\r"): 56 # CR may be the first half of a CRLF split across reads; the 57 # LF will arrive as an empty line and be ignored 58 pass 59 for line in lines: 60 yield from self._decode_line(line.rstrip(b"\r\n")) 61 62 def flush(self) -> Iterable[Frame]: 63 buffered, self._buffer = self._buffer, b"" 64 yield from self._decode_line(buffered)
Decode packets in CR-LF delimited TNC2 monitor format.
Example: SENDER>DEST,PATH:data for the packet
Lines may be split across any number of update() calls (TCP delivers
a byte stream, not lines); an incomplete trailing line is buffered until
its terminator arrives, or until flush().
35 @staticmethod 36 def decode_frames(frame: bytes) -> Iterable[Frame]: 37 try: 38 yield Frame.from_str(frame.decode("latin1")) 39 except Exception: 40 log.debug("Ignore frame decode error %r", frame, exc_info=True)
Decode a single deframed byte chunk.
Parameters
- frame: should represent a single higher level frame to decode in some way.
49 def update(self, new_data: bytes) -> Iterable[Frame]: 50 data = self._buffer + new_data 51 lines = data.splitlines(keepends=True) 52 self._buffer = b"" 53 if lines and not lines[-1].endswith((b"\n", b"\r")): 54 self._buffer = lines.pop() 55 elif data.endswith(b"\r"): 56 # CR may be the first half of a CRLF split across reads; the 57 # LF will arrive as an empty line and be ignored 58 pass 59 for line in lines: 60 yield from self._decode_line(line.rstrip(b"\r\n"))
Decode the next sequence of bytes from the stream.
Parameters
- new_data: the next bytes from the stream
Returns
an iterable of decoded frames
67@define 68class TNC2Protocol(FrameDecodeProtocol[Frame]): 69 """Protocol for decoding a stream of TNC2 format packets.""" 70 71 decoder: GenericDecoder[Frame] = field(factory=TNC2Decode) 72 73 def write(self, frame: SupportsBytes) -> None: 74 """Write the frame to the transport as a TNC2 line.""" 75 self._connected_transport().write(str(frame).encode("latin1") + b"\r\n")
Protocol for decoding a stream of TNC2 format packets.
28def __init__(self, transport=attr_dict['transport'].default, decoder=NOTHING, *, max_queued_frames=attr_dict['max_queued_frames'].default): 29 self.transport = transport 30 self.frames = __attr_factory_frames() 31 self.connection_future = __attr_factory_connection_future() 32 self.max_queued_frames = max_queued_frames 33 self.dropped_frames = attr_dict['dropped_frames'].default 34 if decoder is not NOTHING: 35 self.decoder = decoder 36 else: 37 self.decoder = __attr_factory_decoder()
Method generated by attrs for class TNC2Protocol.