aprs
Encode and decode APRS packets.
APRSFrame is an AX.25 UI frame whose information field is decoded into a
typed report: PositionReport, ObjectReport, ItemReport,
StatusReport or Message. Anything else stays an InformationField.
Decoding
APRS-IS sends packets as TNC2 text; a TNC sends AX.25 bytes. Both decode to the same frame:
>>> import aprs
>>> frame = aprs.APRSFrame.from_str(
... "KF7HVM-9>APZ069,WIDE1-1:!4610.00N/12255.00W>090/025/A=000500 on the road"
... )
>>> str(frame.source), str(frame.destination), [str(p) for p in frame.path]
('KF7HVM-9', 'APZ069', ['WIDE1-1'])
>>> aprs.APRSFrame.from_bytes(bytes(frame)) == frame
True
Read the report's fields directly. Coordinates are decimal degrees:
>>> report = frame.info
>>> type(report).__name__
'PositionReport'
>>> round(float(report.lat), 4), round(float(report.long), 4)
(46.1667, -122.9167)
>>> report.symbol_code, report.altitude_ft
(b'>', 500)
>>> report.data_ext
CourseSpeed(course=90, speed=25)
Messages carry the addressee, text and message number:
>>> msg = aprs.APRSFrame.from_str("KF7HVM>APZ069::N0CALL :hello there{42").info
>>> msg.addressee, msg.text, msg.number
(b'N0CALL', b'hello there', b'42')
Encoding
Build a report and wrap it in a frame with APRSFrame.ui:
>>> beacon = aprs.PositionReport(
... raw=b"",
... data=b"",
... data_type=aprs.DataType.POSITION_W_O_TIMESTAMP_MSG,
... position=aprs.Position(lat=46.1, long=-122.9, symbol_code=b"-"),
... comment=b"Home station",
... )
>>> str(aprs.APRSFrame.ui("APZ069", "N0CALL", ["WIDE1-1"], bytes(beacon)))
'N0CALL>APZ069,WIDE1-1:=4606.00N/12254.00W-Home station'
Connections
Connect to APRS-IS with create_aprsis_connection (async) or TCP
(sync), or to a TNC with create_tcp_connection, create_serial_connection,
TCPKISS or SerialKISS. All of them yield APRSFrame objects. The
examples/ directory in the repository has runnable scripts.
Based on the original aprs module by Greg Albrecht W2GMD
(https://github.com/ampledata/aprs), Apache License 2.0.
1r"""Encode and decode APRS packets. 2 3``APRSFrame`` is an AX.25 UI frame whose information field is decoded into a 4typed report: ``PositionReport``, ``ObjectReport``, ``ItemReport``, 5``StatusReport`` or ``Message``. Anything else stays an ``InformationField``. 6 7Decoding 8======== 9 10APRS-IS sends packets as TNC2 text; a TNC sends AX.25 bytes. Both decode to 11the same frame: 12 13>>> import aprs 14>>> frame = aprs.APRSFrame.from_str( 15... "KF7HVM-9>APZ069,WIDE1-1:!4610.00N/12255.00W>090/025/A=000500 on the road" 16... ) 17>>> str(frame.source), str(frame.destination), [str(p) for p in frame.path] 18('KF7HVM-9', 'APZ069', ['WIDE1-1']) 19>>> aprs.APRSFrame.from_bytes(bytes(frame)) == frame 20True 21 22Read the report's fields directly. Coordinates are decimal degrees: 23 24>>> report = frame.info 25>>> type(report).__name__ 26'PositionReport' 27>>> round(float(report.lat), 4), round(float(report.long), 4) 28(46.1667, -122.9167) 29>>> report.symbol_code, report.altitude_ft 30(b'>', 500) 31>>> report.data_ext 32CourseSpeed(course=90, speed=25) 33 34Messages carry the addressee, text and message number: 35 36>>> msg = aprs.APRSFrame.from_str("KF7HVM>APZ069::N0CALL :hello there{42").info 37>>> msg.addressee, msg.text, msg.number 38(b'N0CALL', b'hello there', b'42') 39 40Encoding 41======== 42 43Build a report and wrap it in a frame with ``APRSFrame.ui``: 44 45>>> beacon = aprs.PositionReport( 46... raw=b"", 47... data=b"", 48... data_type=aprs.DataType.POSITION_W_O_TIMESTAMP_MSG, 49... position=aprs.Position(lat=46.1, long=-122.9, symbol_code=b"-"), 50... comment=b"Home station", 51... ) 52>>> str(aprs.APRSFrame.ui("APZ069", "N0CALL", ["WIDE1-1"], bytes(beacon))) 53'N0CALL>APZ069,WIDE1-1:=4606.00N/12254.00W-Home station' 54 55Connections 56=========== 57 58Connect to APRS-IS with ``create_aprsis_connection`` (async) or ``TCP`` 59(sync), or to a TNC with ``create_tcp_connection``, ``create_serial_connection``, 60``TCPKISS`` or ``SerialKISS``. All of them yield ``APRSFrame`` objects. The 61``examples/`` directory in the repository has runnable scripts. 62 63Based on the original ``aprs`` module by Greg Albrecht W2GMD 64(https://github.com/ampledata/aprs), Apache License 2.0. 65""" 66 67from importlib.metadata import version 68 69from . import decimaldegrees, geo_util, position, timestamp 70from .aprsis import TCP, APRSISProtocol, create_aprsis_connection 71from .classes import ( 72 APRSFrame, 73 DataType, 74 DataTypeError, 75 InformationField, 76 ItemReport, 77 Message, 78 ObjectReport, 79 PositionReport, 80 StatusReport, 81) 82from .constants import ( 83 APRSIS_FILTER_PORT, 84 APRSIS_HTTP_HEADERS, 85 APRSIS_RX_PORT, 86 APRSIS_SERVERS, 87 APRSIS_URL, 88 DEFAULT_TOCALL, 89 PositionFormat, 90 TimestampFormat, 91 timestamp_formats_map, 92) 93from .data_ext import ( 94 DFS, 95 PHG, 96 RNG, 97 AreaObject, 98 CourseSpeed, 99 DataExt, 100) 101from .kiss import TCPKISS, SerialKISS, create_serial_connection, create_tcp_connection 102from .position import Position 103from .timestamp import Timestamp 104 105__author__ = "Greg Albrecht W2GMD <oss@undef.net>" 106__copyright__ = "Copyright 2017 Greg Albrecht and Contributors" 107__license__ = "Apache License, Version 2.0" 108__distribution__ = "aprs3" 109__version__ = version(__distribution__) 110__all__ = [ 111 "APRSFrame", 112 "APRSIS_HTTP_HEADERS", 113 "APRSIS_SERVERS", 114 "APRSIS_FILTER_PORT", 115 "APRSIS_RX_PORT", 116 "APRSIS_URL", 117 "APRSISProtocol", 118 "AreaObject", 119 "CourseSpeed", 120 "create_aprsis_connection", 121 "create_serial_connection", 122 "create_tcp_connection", 123 "DataExt", 124 "DataType", 125 "DataTypeError", 126 "decimaldegrees", 127 "DEFAULT_TOCALL", 128 "DFS", 129 "geo_util", 130 "ItemReport", 131 "InformationField", 132 "Message", 133 "ObjectReport", 134 "PHG", 135 "position", 136 "Position", 137 "PositionFormat", 138 "PositionReport", 139 "RNG", 140 "SerialKISS", 141 "StatusReport", 142 "TCP", 143 "TCPKISS", 144 "timestamp", 145 "Timestamp", 146 "TimestampFormat", 147 "timestamp_formats_map", 148 "__author__", 149 "__copyright__", 150 "__license__", 151 "__distribution__", 152 "__version__", 153]
400@define(frozen=True, slots=True) 401class APRSFrame(Frame): 402 # Narrower than Frame.info (bytes); bytes(info) is still the AX.25 info. 403 # ty doesn't yet apply attrs converters (it sees the default, b""). 404 info: InformationField = field( # ty: ignore[incompatible-attribute-override, invalid-assignment] 405 default=b"", converter=InformationField.from_any 406 )
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('command_response', __attr_converter_command_response(command_response)) 48 _setattr('info', __attr_converter_info(info)) 49 if _config._run_validators is True: 50 __attr_validator_pid(self, __attr_pid, self.pid)
Method generated by attrs for class APRSFrame.
41@define 42class APRSISProtocol(TNC2Protocol): 43 """Protocol for logging into APRS-IS servers (TNC2).""" 44 45 decoder: GenericDecoder[Frame] = field(factory=APRSDecode) 46 47 def login(self, user: str, passcode: str, command: str) -> None: 48 # pylint: disable=import-outside-toplevel 49 # avoid circular import 50 from . import __distribution__, __version__ 51 52 # pylint: enable=import-outside-toplevel 53 54 self._connected_transport().write( 55 f"user {user} pass {passcode} vers {__distribution__} {__version__} {command}\r\n".encode( 56 "ascii" 57 ), 58 )
Protocol for logging into APRS-IS servers (TNC2).
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 APRSISProtocol.
47 def login(self, user: str, passcode: str, command: str) -> None: 48 # pylint: disable=import-outside-toplevel 49 # avoid circular import 50 from . import __distribution__, __version__ 51 52 # pylint: enable=import-outside-toplevel 53 54 self._connected_transport().write( 55 f"user {user} pass {passcode} vers {__distribution__} {__version__} {command}\r\n".encode( 56 "ascii" 57 ), 58 )
180@define(frozen=True, slots=True) 181class AreaObject(DataExt): 182 """ 183 Tyy/Cxx 184 """ 185 186 t: bytes = field(default=b"") 187 c: bytes = field(default=b"") 188 189 @classmethod 190 def try_parse(cls, raw: bytes) -> bool: 191 """Return True if this subclass might be able to parse raw bytes.""" 192 return re.match(rb"T../C..", raw[:7]) is not None 193 194 @classmethod 195 def from_bytes(cls, raw: bytes) -> "AreaObject": 196 if not re.match(rb"T../C..", raw[:7]): 197 raise ValueError(f"{raw!r} is not an Area Object extension field") 198 return cls( 199 t=raw[1:3], 200 c=raw[5:7], 201 ) 202 203 def __bytes__(self) -> bytes: 204 return b"T% 2b/C% 2b" % (self.t[:2], self.c[:2])
Tyy/Cxx
30def __init__(self, t=attr_dict['t'].default, c=attr_dict['c'].default): 31 _setattr = _cached_setattr_get(self) 32 _setattr('t', t) 33 _setattr('c', c)
Method generated by attrs for class AreaObject.
189 @classmethod 190 def try_parse(cls, raw: bytes) -> bool: 191 """Return True if this subclass might be able to parse raw bytes.""" 192 return re.match(rb"T../C..", raw[:7]) is not None
Return True if this subclass might be able to parse raw bytes.
53@define(frozen=True, slots=True) 54class CourseSpeed(DataExt): 55 course: int = field(default=0, validator=_valid_course) 56 speed: float = field(default=0) 57 """Knots: whole knots from text, a float from compressed cs bytes.""" 58 59 @classmethod 60 def try_parse(cls, raw: bytes) -> bool: 61 """Return True if this subclass might be able to parse raw bytes.""" 62 return re.match(rb"[0-9]{3}/", raw[:4]) is not None 63 64 @classmethod 65 def from_bytes(cls, raw: bytes) -> "CourseSpeed": 66 course, slash, speed = raw[:7].partition(b"/") 67 if not slash or len(course) != len(speed): 68 raise ValueError(f"{raw!r} is not a Course/Speed extension field") 69 return cls( 70 course=int(course.decode("ascii")), 71 speed=int(speed.decode("ascii")), 72 ) 73 74 def __bytes__(self) -> bytes: 75 return b"%03d/%03d" % (self.course, (self.speed % 1000))
Helper class that provides a standard way to create an ABC using inheritance.
30def __init__(self, course=attr_dict['course'].default, speed=attr_dict['speed'].default): 31 _setattr = _cached_setattr_get(self) 32 _setattr('course', course) 33 _setattr('speed', speed) 34 if _config._run_validators is True: 35 __attr_validator_course(self, __attr_course, self.course)
Method generated by attrs for class CourseSpeed.
59 @classmethod 60 def try_parse(cls, raw: bytes) -> bool: 61 """Return True if this subclass might be able to parse raw bytes.""" 62 return re.match(rb"[0-9]{3}/", raw[:4]) is not None
Return True if this subclass might be able to parse raw bytes.
64 @classmethod 65 def from_bytes(cls, raw: bytes) -> "CourseSpeed": 66 course, slash, speed = raw[:7].partition(b"/") 67 if not slash or len(course) != len(speed): 68 raise ValueError(f"{raw!r} is not a Course/Speed extension field") 69 return cls( 70 course=int(course.decode("ascii")), 71 speed=int(speed.decode("ascii")), 72 )
77async def create_aprsis_connection( # pylint: disable=too-many-arguments 78 host: str = APRSIS_SERVERS[0], 79 port: int = APRSIS_FILTER_PORT, 80 user: str = DEFAULT_MYCALL, 81 passcode: str = "-1", 82 command: str = "", 83 protocol_kwargs: dict[str, Any] | None = None, 84 loop: asyncio.AbstractEventLoop | None = None, 85 create_connection_kwargs: dict[str, Any] | None = None, 86) -> tuple[asyncio.BaseTransport, APRSISProtocol]: 87 """ 88 Establish an async APRS-IS connection. 89 90 :param host: the APRS-IS host to connect to 91 :param port: the TCP port to connect to (14580 is usually a good choice) 92 :param user: callsign of the user to authenticate 93 :param passcode: APRS-IS passcode associated with the callsign 94 :param command: initial command to send after connecting 95 :param protocol_kwargs: These kwargs are passed directly to APRSISProtocol 96 :param loop: override the asyncio event loop (default: the running loop) 97 :param create_connection_kwargs: These kwargs are passed directly to 98 loop.create_connection 99 :return: (TCPTransport, APRSISProtocol) 100 """ 101 if loop is None: 102 loop = asyncio.get_running_loop() 103 protocol: APRSISProtocol 104 transport, protocol = await loop.create_connection( 105 host=host, 106 port=port, 107 **_handle_kwargs( 108 protocol_kwargs=protocol_kwargs, 109 create_connection_kwargs=create_connection_kwargs, 110 ), 111 ) 112 await protocol.connection_future 113 protocol.login(user, passcode, command) 114 return transport, protocol
Establish an async APRS-IS connection.
Parameters
- host: the APRS-IS host to connect to
- port: the TCP port to connect to (14580 is usually a good choice)
- user: callsign of the user to authenticate
- passcode: APRS-IS passcode associated with the callsign
- command: initial command to send after connecting
- protocol_kwargs: These kwargs are passed directly to APRSISProtocol
- loop: override the asyncio event loop (default: the running loop)
- create_connection_kwargs: These kwargs are passed directly to loop.create_connection
Returns
(TCPTransport, APRSISProtocol)
45async def create_serial_connection(*args, protocol_kwargs=None, **kwargs): 46 if protocol_kwargs is None: 47 protocol_kwargs = {} 48 protocol_kwargs["decoder"] = protocol_kwargs.pop("decoder", APRSDecode()) 49 return await kiss.create_serial_connection( 50 *args, protocol_kwargs=protocol_kwargs, **kwargs 51 )
36async def create_tcp_connection(*args, protocol_kwargs=None, **kwargs): 37 if protocol_kwargs is None: 38 protocol_kwargs = {} 39 protocol_kwargs["decoder"] = protocol_kwargs.pop("decoder", APRSDecode()) 40 return await kiss.create_tcp_connection( 41 *args, protocol_kwargs=protocol_kwargs, **kwargs 42 )
18@define(frozen=True, slots=True) 19class DataExt(ABC): 20 @classmethod 21 @abstractmethod 22 def try_parse(cls, raw: bytes) -> bool: 23 """Return True if this subclass might be able to parse raw bytes.""" 24 25 @classmethod 26 def from_bytes(cls, raw: bytes) -> Union["DataExt", bytes]: 27 for subcls in attrs_subclasses(cls): 28 if subcls.try_parse(raw): 29 try: 30 return subcls.from_bytes(raw[:7]) 31 except ValueError: 32 pass 33 return b"" 34 35 @classmethod 36 def split_parse(cls, raw: bytes) -> tuple[Union["DataExt", bytes], bytes]: 37 parsed = cls.from_bytes(raw) 38 if parsed: 39 return parsed, raw[7:] 40 return b"", raw 41 42 @abstractmethod 43 def __bytes__(self) -> bytes: 44 """Serialize the data extension as bytes."""
Helper class that provides a standard way to create an ABC using inheritance.
20 @classmethod 21 @abstractmethod 22 def try_parse(cls, raw: bytes) -> bool: 23 """Return True if this subclass might be able to parse raw bytes."""
Return True if this subclass might be able to parse raw bytes.
23class DataType(enum.Enum): 24 """APRS101.PDF p. 27""" 25 26 CURRENT_MIC_E_DATA = b"\x1c" 27 OLD_MIC_E_DATA = b"\x1d" 28 POSITION_W_O_TIMESTAMP = b"!" 29 PEET_BROS_U_II = b"#" 30 RAW_GPS_DATA = b"$" 31 AGRELO_DFJR = b"%" 32 OLD_MIC_E_DATA_2 = b"'" 33 ITEM = b")" 34 PEET_BROS_U_II_2 = b"*" 35 INVALID_DATA = b"," 36 POSITION_W_TIMESTAMP_NO_MSG = b"/" 37 MESSAGE = b":" 38 OBJECT = b";" 39 STATION_CAPABILITIES = b"<" 40 POSITION_W_O_TIMESTAMP_MSG = b"=" 41 STATUS = b">" 42 QUERY = b"?" 43 POSITION_W_TIMESTAMP_MSG = b"@" 44 TELEMETRY_DATA = b"T" 45 MAIDENHEAD_GRID_LOCATOR_BEACON = b"[" 46 WEATHER_REPORT_W_O_POSITION = b"_" 47 CURRENT_MIC_E_DATA_2 = b"`" 48 USER_DEFINED = b"{" 49 THIRD_PARTY_TRAFFIC = b"}"
APRS101.PDF p. 27
Inappropriate argument value (of correct type).
138@define(frozen=True, slots=True) 139class DFS(DataExt): 140 """ 141 DFSshgd 142 """ 143 144 strength_s: int = field(default=0) 145 height_ft: int = field(default=0) 146 gain_db: int = field(default=0) 147 directivity: int = field(default=0) 148 149 @classmethod 150 def try_parse(cls, raw: bytes) -> bool: 151 """Return True if this subclass might be able to parse raw bytes.""" 152 return raw.startswith(b"DFS") 153 154 @classmethod 155 def from_bytes(cls, raw: bytes) -> "DFS": 156 if not raw.startswith(b"DFS"): 157 raise ValueError(f"{raw!r} is not a DFS extension field") 158 strength_code, height_code, gain_code, directivity_code = raw[3:7] 159 zero_byte = ord(b"0") 160 return cls( 161 strength_s=int(strength_code - zero_byte), 162 height_ft=10 * (2 ** int(height_code - zero_byte)), 163 gain_db=int(gain_code - zero_byte), 164 directivity=int(directivity_code - zero_byte) * 45, 165 ) 166 167 def __bytes__(self) -> bytes: 168 strength_code = bytes([ord(b"0") + self.strength_s]) 169 height_code = bytes([ord(b"0") + int(round(math.log2(self.height_ft / 10)))]) 170 gain_code = self.gain_db % 10 171 directivity_code = int(round(self.directivity / 45)) % 10 172 return b"DFS%b%b%d%d" % ( 173 strength_code, 174 height_code, 175 gain_code, 176 directivity_code, 177 )
DFSshgd
34def __init__(self, strength_s=attr_dict['strength_s'].default, height_ft=attr_dict['height_ft'].default, gain_db=attr_dict['gain_db'].default, directivity=attr_dict['directivity'].default): 35 _setattr = _cached_setattr_get(self) 36 _setattr('strength_s', strength_s) 37 _setattr('height_ft', height_ft) 38 _setattr('gain_db', gain_db) 39 _setattr('directivity', directivity)
Method generated by attrs for class DFS.
149 @classmethod 150 def try_parse(cls, raw: bytes) -> bool: 151 """Return True if this subclass might be able to parse raw bytes.""" 152 return raw.startswith(b"DFS")
Return True if this subclass might be able to parse raw bytes.
154 @classmethod 155 def from_bytes(cls, raw: bytes) -> "DFS": 156 if not raw.startswith(b"DFS"): 157 raise ValueError(f"{raw!r} is not a DFS extension field") 158 strength_code, height_code, gain_code, directivity_code = raw[3:7] 159 zero_byte = ord(b"0") 160 return cls( 161 strength_s=int(strength_code - zero_byte), 162 height_ft=10 * (2 ** int(height_code - zero_byte)), 163 gain_db=int(gain_code - zero_byte), 164 directivity=int(directivity_code - zero_byte) * 45, 165 )
351@define(frozen=True, slots=True) 352class ItemReport(InformationField, PositionMixin): 353 name: bytes = field(default=None) 354 killed: bool = field(default=False) 355 _position: Position | None = field(default=None, alias="position") 356 357 __data_type__ = [DataType.ITEM] 358 359 @classmethod 360 def from_bytes(cls, raw: bytes) -> "ItemReport": 361 data_type = DataType(raw[0:1]) 362 if data_type not in cls.__data_type__: 363 raise DataTypeError( 364 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 365 ) 366 # APRS101 p59: the name (3-9 characters) can't contain "!" or "_", 367 # so the first of either ends it; the comment may contain both 368 match = re.search(rb"[!_]", raw[1:]) 369 if match is None: 370 raise ValueError(f"{raw!r}: item name is not terminated by '!' or '_'") 371 name = raw[1 : 1 + match.start()] 372 status = match.group() 373 remainder = raw[2 + match.start() :] 374 name = name.strip() 375 killed = status == b"_" 376 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 377 return cls( 378 raw=raw, 379 data_type=data_type, 380 data=data, 381 comment=comment, 382 name=name, 383 killed=killed, 384 position=position, 385 ) 386 387 def __bytes__(self) -> bytes: 388 return b"".join( 389 [ 390 self._data_type_id(), 391 self.name, 392 b"_" if self.killed else b"!", 393 bytes(_required(self._position, "position")), 394 self.format_altitude(), 395 self.comment, 396 ], 397 )
Class for APRS 'Information' Field.
40def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default, name=attr_dict['name'].default, killed=attr_dict['killed'].default, position=attr_dict['_position'].default): 41 _setattr = _cached_setattr_get(self) 42 _setattr('raw', raw) 43 _setattr('data_type', data_type) 44 _setattr('data', data) 45 _setattr('comment', comment) 46 _setattr('name', name) 47 _setattr('killed', killed) 48 _setattr('_position', position)
Method generated by attrs for class ItemReport.
359 @classmethod 360 def from_bytes(cls, raw: bytes) -> "ItemReport": 361 data_type = DataType(raw[0:1]) 362 if data_type not in cls.__data_type__: 363 raise DataTypeError( 364 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 365 ) 366 # APRS101 p59: the name (3-9 characters) can't contain "!" or "_", 367 # so the first of either ends it; the comment may contain both 368 match = re.search(rb"[!_]", raw[1:]) 369 if match is None: 370 raise ValueError(f"{raw!r}: item name is not terminated by '!' or '_'") 371 name = raw[1 : 1 + match.start()] 372 status = match.group() 373 remainder = raw[2 + match.start() :] 374 name = name.strip() 375 killed = status == b"_" 376 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 377 return cls( 378 raw=raw, 379 data_type=data_type, 380 data=data, 381 comment=comment, 382 name=name, 383 killed=killed, 384 position=position, 385 )
Inherited Members
77@define(frozen=True, slots=True) 78class InformationField: 79 """ 80 Class for APRS 'Information' Field. 81 """ 82 83 raw: bytes 84 data_type: DataType | None 85 """None when the first byte isn't a known APRS data type identifier.""" 86 data: bytes 87 comment: bytes = field(default=b"") 88 89 __data_type__: ClassVar[list[DataType]] = [] 90 """The data types a subclass decodes.""" 91 92 @classmethod 93 @lru_cache(len(DataType.__members__)) 94 def _find_handler(cls, data_type: DataType) -> type["InformationField"] | None: 95 for subcls in attrs_subclasses(cls): 96 if data_type in subcls.__data_type__: 97 return subcls 98 return None 99 100 @classmethod 101 def from_bytes(cls, raw: bytes) -> "InformationField": 102 try: 103 data_type = DataType(raw[0:1]) 104 except ValueError: 105 # free text, an empty info field, or an unused identifier 106 # (APRS101 p17): keep the raw bytes so the frame still decodes 107 data_type = None 108 handler = None if data_type is None else cls._find_handler(data_type) 109 if (handler is None or data_type == DataType.OBJECT) and ( 110 data_type not in MIC_E_DATA_TYPES 111 ): 112 x1j_header, found_data_type, data = raw.partition(b"!") 113 if found_data_type and len(x1j_header) <= 40: 114 # special case in APRS101 p32: a position after up to 40 115 # characters of other text (e.g. a TNC beacon header) 116 try: 117 report = PositionReport.from_bytes(found_data_type + data) 118 return attr.evolve(report, raw=raw, prefix=x1j_header) 119 except ValueError: 120 pass # just a "!" in some other kind of packet 121 if handler is None: 122 return cls( 123 raw=raw, 124 data_type=data_type, 125 data=b"", 126 comment=raw if data_type is None else raw[1:], 127 ) 128 return handler.from_bytes(raw) 129 130 @classmethod 131 def from_frame(cls, f: Frame) -> "InformationField": 132 return cls.from_bytes(f.info) 133 134 @classmethod 135 def from_any(cls, obj: Any) -> "InformationField": 136 if isinstance(obj, cls): 137 return obj 138 if isinstance(obj, Frame): 139 return cls.from_frame(obj) 140 return cls.from_bytes(obj) 141 142 def __bytes__(self) -> bytes: 143 return self.raw 144 145 def _data_type_id(self) -> bytes: 146 """The data type identifier byte, for encoding.""" 147 if self.data_type is None: 148 raise ValueError(f"{type(self).__name__} has no data type to encode") 149 return self.data_type.value
Class for APRS 'Information' Field.
34def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default): 35 _setattr = _cached_setattr_get(self) 36 _setattr('raw', raw) 37 _setattr('data_type', data_type) 38 _setattr('data', data) 39 _setattr('comment', comment)
Method generated by attrs for class InformationField.
100 @classmethod 101 def from_bytes(cls, raw: bytes) -> "InformationField": 102 try: 103 data_type = DataType(raw[0:1]) 104 except ValueError: 105 # free text, an empty info field, or an unused identifier 106 # (APRS101 p17): keep the raw bytes so the frame still decodes 107 data_type = None 108 handler = None if data_type is None else cls._find_handler(data_type) 109 if (handler is None or data_type == DataType.OBJECT) and ( 110 data_type not in MIC_E_DATA_TYPES 111 ): 112 x1j_header, found_data_type, data = raw.partition(b"!") 113 if found_data_type and len(x1j_header) <= 40: 114 # special case in APRS101 p32: a position after up to 40 115 # characters of other text (e.g. a TNC beacon header) 116 try: 117 report = PositionReport.from_bytes(found_data_type + data) 118 return attr.evolve(report, raw=raw, prefix=x1j_header) 119 except ValueError: 120 pass # just a "!" in some other kind of packet 121 if handler is None: 122 return cls( 123 raw=raw, 124 data_type=data_type, 125 data=b"", 126 comment=raw if data_type is None else raw[1:], 127 ) 128 return handler.from_bytes(raw)
215@define(frozen=True, slots=True) 216class Message(InformationField): 217 addressee: bytes = field(default=b"") 218 text: bytes = field(default=b"") 219 number: bytes | None = field(default=None) 220 221 __data_type__ = [DataType.MESSAGE] 222 223 @classmethod 224 def from_bytes(cls, raw: bytes) -> "Message": 225 data_type = DataType(raw[0:1]) 226 if data_type not in cls.__data_type__: 227 raise DataTypeError( 228 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 229 ) 230 data = raw[1:] 231 end_of_addressee = data[9:10] 232 if end_of_addressee != DataType.MESSAGE.value: 233 raise ValueError( 234 f"Expecting {DataType.MESSAGE.value!r} at index 9 of {data!r}", 235 ) 236 init_kwargs = dict(addressee=data[:9].strip()) 237 text = data[10:] 238 match = MESSAGE_NUMBER.search(text) 239 if match is not None: 240 text, init_kwargs["number"] = text[: match.start()], match.group(1) 241 return cls( 242 raw=raw, 243 data_type=data_type, 244 data=data, 245 text=text, 246 **init_kwargs, 247 ) 248 249 def __bytes__(self): 250 return b"".join( 251 [ 252 DataType.MESSAGE.value, 253 self.addressee.ljust(9), # pylint: disable=no-member 254 DataType.MESSAGE.value, 255 # no truncation: the spec's 67 character limit applies to 256 # chat text, but telemetry PARM/UNIT/EQNS/BITS headers are 257 # carried as messages and may be longer 258 self.text, 259 b"" if self.number is None else b"{%s" % self.number, 260 ], 261 )
Class for APRS 'Information' Field.
40def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default, addressee=attr_dict['addressee'].default, text=attr_dict['text'].default, number=attr_dict['number'].default): 41 _setattr = _cached_setattr_get(self) 42 _setattr('raw', raw) 43 _setattr('data_type', data_type) 44 _setattr('data', data) 45 _setattr('comment', comment) 46 _setattr('addressee', addressee) 47 _setattr('text', text) 48 _setattr('number', number)
Method generated by attrs for class Message.
223 @classmethod 224 def from_bytes(cls, raw: bytes) -> "Message": 225 data_type = DataType(raw[0:1]) 226 if data_type not in cls.__data_type__: 227 raise DataTypeError( 228 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 229 ) 230 data = raw[1:] 231 end_of_addressee = data[9:10] 232 if end_of_addressee != DataType.MESSAGE.value: 233 raise ValueError( 234 f"Expecting {DataType.MESSAGE.value!r} at index 9 of {data!r}", 235 ) 236 init_kwargs = dict(addressee=data[:9].strip()) 237 text = data[10:] 238 match = MESSAGE_NUMBER.search(text) 239 if match is not None: 240 text, init_kwargs["number"] = text[: match.start()], match.group(1) 241 return cls( 242 raw=raw, 243 data_type=data_type, 244 data=data, 245 text=text, 246 **init_kwargs, 247 )
306@define(frozen=True, slots=True) 307class ObjectReport(InformationField, TimestampMixin, PositionMixin): 308 name: bytes = field(default=None) 309 killed: bool = field(default=False) 310 _timestamp: Timestamp | None = field(default=None, alias="timestamp") 311 _position: Position | None = field(default=None, alias="position") 312 313 __data_type__ = [DataType.OBJECT] 314 315 @classmethod 316 def from_bytes(cls, raw: bytes) -> "ObjectReport": 317 data_type = DataType(raw[0:1]) 318 if data_type not in cls.__data_type__: 319 raise DataTypeError( 320 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 321 ) 322 name = raw[1:10].strip() 323 killed = raw[10:11] == b"_" 324 timestamp, remainder = Timestamp.from_bytes(raw[11:18]), raw[18:] 325 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 326 return cls( 327 raw=raw, 328 data_type=data_type, 329 data=data, 330 comment=comment, 331 name=name, 332 killed=killed, 333 timestamp=timestamp, 334 position=position, 335 ) 336 337 def __bytes__(self) -> bytes: 338 return b"".join( 339 [ 340 self._data_type_id(), 341 self.name.ljust(9), # pylint: disable=no-member 342 b"_" if self.killed else b"*", 343 bytes(self._timestamp) if self._timestamp else b"", 344 bytes(self._position) if self._position else b"", 345 self.format_altitude(), 346 self.comment, 347 ], 348 )
Class for APRS 'Information' Field.
42def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default, name=attr_dict['name'].default, killed=attr_dict['killed'].default, timestamp=attr_dict['_timestamp'].default, position=attr_dict['_position'].default): 43 _setattr = _cached_setattr_get(self) 44 _setattr('raw', raw) 45 _setattr('data_type', data_type) 46 _setattr('data', data) 47 _setattr('comment', comment) 48 _setattr('name', name) 49 _setattr('killed', killed) 50 _setattr('_timestamp', timestamp) 51 _setattr('_position', position)
Method generated by attrs for class ObjectReport.
315 @classmethod 316 def from_bytes(cls, raw: bytes) -> "ObjectReport": 317 data_type = DataType(raw[0:1]) 318 if data_type not in cls.__data_type__: 319 raise DataTypeError( 320 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 321 ) 322 name = raw[1:10].strip() 323 killed = raw[10:11] == b"_" 324 timestamp, remainder = Timestamp.from_bytes(raw[11:18]), raw[18:] 325 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 326 return cls( 327 raw=raw, 328 data_type=data_type, 329 data=data, 330 comment=comment, 331 name=name, 332 killed=killed, 333 timestamp=timestamp, 334 position=position, 335 )
78@define(frozen=True, slots=True) 79class PHG(DataExt): 80 """ 81 PHGphgd 82 """ 83 84 power_w: int = field(default=0) 85 height_ft: int = field(default=0) 86 gain_db: int = field(default=0) 87 directivity: int = field(default=0) 88 89 @classmethod 90 def try_parse(cls, raw: bytes) -> bool: 91 """Return True if this subclass might be able to parse raw bytes.""" 92 return raw.startswith(b"PHG") 93 94 @classmethod 95 def from_bytes(cls, raw: bytes) -> "PHG": 96 if not raw.startswith(b"PHG"): 97 raise ValueError(f"{raw!r} is not a PHG extension field") 98 power_code, height_code, gain_code, directivity_code = raw[3:7] 99 zero_byte = ord(b"0") 100 return cls( 101 power_w=int(power_code - zero_byte) ** 2, 102 height_ft=10 * (2 ** int(height_code - zero_byte)), 103 gain_db=int(gain_code - zero_byte), 104 directivity=int(directivity_code - zero_byte) * 45, 105 ) 106 107 def __bytes__(self) -> bytes: 108 power_code = int(round(math.sqrt(self.power_w))) % 10 109 height_code = bytes([ord(b"0") + int(round(math.log2(self.height_ft / 10)))]) 110 gain_code = self.gain_db % 10 111 directivity_code = int(round(self.directivity / 45)) % 10 112 return b"PHG%d%b%d%d" % (power_code, height_code, gain_code, directivity_code)
PHGphgd
34def __init__(self, power_w=attr_dict['power_w'].default, height_ft=attr_dict['height_ft'].default, gain_db=attr_dict['gain_db'].default, directivity=attr_dict['directivity'].default): 35 _setattr = _cached_setattr_get(self) 36 _setattr('power_w', power_w) 37 _setattr('height_ft', height_ft) 38 _setattr('gain_db', gain_db) 39 _setattr('directivity', directivity)
Method generated by attrs for class PHG.
89 @classmethod 90 def try_parse(cls, raw: bytes) -> bool: 91 """Return True if this subclass might be able to parse raw bytes.""" 92 return raw.startswith(b"PHG")
Return True if this subclass might be able to parse raw bytes.
94 @classmethod 95 def from_bytes(cls, raw: bytes) -> "PHG": 96 if not raw.startswith(b"PHG"): 97 raise ValueError(f"{raw!r} is not a PHG extension field") 98 power_code, height_code, gain_code, directivity_code = raw[3:7] 99 zero_byte = ord(b"0") 100 return cls( 101 power_w=int(power_code - zero_byte) ** 2, 102 height_ft=10 * (2 ** int(height_code - zero_byte)), 103 gain_db=int(gain_code - zero_byte), 104 directivity=int(directivity_code - zero_byte) * 45, 105 )
234@define(frozen=True, slots=True) 235class Position: 236 """Represents a position including any data extension.""" 237 238 position_format: PositionFormat = field(default=PositionFormat.Uncompressed) 239 lat: float | Decimal = field(default=0.0, validator=_in_range(90)) 240 """Decimal when decoded from uncompressed text (exact), float otherwise.""" 241 sym_table_id: bytes = field(default=b"/") 242 long: float | Decimal = field(default=0.0, validator=_in_range(180)) 243 symbol_code: bytes = field(default=b"-") 244 altitude_ft: float | None = field(default=None) 245 """Whole feet from "/A=", a float from compressed cs bytes.""" 246 data_ext: bytes | DataExt = field(default=b"") 247 ambiguity: int = field(default=0) 248 """Uncompressed only: how many trailing digits are blanked (0-4).""" 249 long_ambiguity: int | None = field(default=None) 250 """ 251 Uncompressed only: blanked longitude digits, when they differ from the 252 latitude's; None means the same as ambiguity. 253 """ 254 compression_type: int | None = field(default=None) 255 """Compressed only: the type byte (minus 33); None picks a default.""" 256 ignored_cs: bytes | None = field(default=None) 257 """Compressed only: cs bytes starting with a space, which carry no data.""" 258 259 @classmethod 260 def from_bytes_with_data_and_remainder( 261 cls, raw: bytes 262 ) -> tuple["Position", bytes, bytes]: 263 """ 264 Create a Position from raw packet bytes. 265 266 :return: a Position and remaining bytes, which may be any unparsed 267 extended data or comments. 268 """ 269 try: 270 ( 271 position_format, 272 position, 273 ) = PositionFormat.Uncompressed, decode_position_uncompressed(raw[:19]) 274 data, remainder = raw[:19], raw[19:] 275 except ValueError: 276 try: 277 ( 278 position_format, 279 position, 280 ) = PositionFormat.Compressed, decode_position_compressed(raw[:13]) 281 data, remainder = raw[:13], raw[13:] 282 except ValueError: # pylint: disable=try-except-raise 283 # eventually we may try to decode other position types here 284 raise 285 # try to decode extended data; a compressed position carries 286 # course/speed or range in its cs bytes (APRS101 p36), so text after 287 # it (e.g. an igate's PHG) stays in the comment 288 data_ext = b"" 289 if position_format is PositionFormat.Uncompressed: 290 data_ext, remainder = DataExt.split_parse(remainder) 291 # try to find the altitude comment 292 alt_match = ALTITUDE_REX.search(remainder) 293 if alt_match and "altitude_ft" not in position: 294 # a compressed altitude (in cs) takes precedence 295 position["altitude_ft"] = int(alt_match.group(1)) 296 return ( 297 cls( 298 position_format=position_format, 299 data_ext=data_ext or position.pop("data_ext", b""), 300 **position, 301 ), 302 data, 303 remainder, 304 ) 305 306 def __bytes__(self) -> bytes: 307 if self.position_format is PositionFormat.Uncompressed: 308 return b"".join( 309 [ 310 encode_position_uncompressed( 311 self.lat, 312 self.long, 313 self.sym_table_id, 314 self.symbol_code, 315 ambiguity=self.ambiguity, 316 long_ambiguity=self.long_ambiguity, 317 ), 318 bytes(self.data_ext), 319 ] 320 ) 321 if self.position_format is PositionFormat.Compressed: 322 return encode_position_compressed( 323 self.lat, 324 self.long, 325 self.sym_table_id, 326 self.symbol_code, 327 data_ext=self.data_ext, 328 altitude_ft=self.altitude_ft, 329 compression_type=self.compression_type, 330 ignored_cs=self.ignored_cs, 331 ) 332 raise ValueError(f"Unknown position format: {self.position_format!r}")
Represents a position including any data extension.
48def __init__(self, position_format=attr_dict['position_format'].default, lat=attr_dict['lat'].default, sym_table_id=attr_dict['sym_table_id'].default, long=attr_dict['long'].default, symbol_code=attr_dict['symbol_code'].default, altitude_ft=attr_dict['altitude_ft'].default, data_ext=attr_dict['data_ext'].default, ambiguity=attr_dict['ambiguity'].default, long_ambiguity=attr_dict['long_ambiguity'].default, compression_type=attr_dict['compression_type'].default, ignored_cs=attr_dict['ignored_cs'].default): 49 _setattr = _cached_setattr_get(self) 50 _setattr('position_format', position_format) 51 _setattr('lat', lat) 52 _setattr('sym_table_id', sym_table_id) 53 _setattr('long', long) 54 _setattr('symbol_code', symbol_code) 55 _setattr('altitude_ft', altitude_ft) 56 _setattr('data_ext', data_ext) 57 _setattr('ambiguity', ambiguity) 58 _setattr('long_ambiguity', long_ambiguity) 59 _setattr('compression_type', compression_type) 60 _setattr('ignored_cs', ignored_cs) 61 if _config._run_validators is True: 62 __attr_validator_lat(self, __attr_lat, self.lat) 63 __attr_validator_long(self, __attr_long, self.long)
Method generated by attrs for class Position.
Uncompressed only: blanked longitude digits, when they differ from the latitude's; None means the same as ambiguity.
259 @classmethod 260 def from_bytes_with_data_and_remainder( 261 cls, raw: bytes 262 ) -> tuple["Position", bytes, bytes]: 263 """ 264 Create a Position from raw packet bytes. 265 266 :return: a Position and remaining bytes, which may be any unparsed 267 extended data or comments. 268 """ 269 try: 270 ( 271 position_format, 272 position, 273 ) = PositionFormat.Uncompressed, decode_position_uncompressed(raw[:19]) 274 data, remainder = raw[:19], raw[19:] 275 except ValueError: 276 try: 277 ( 278 position_format, 279 position, 280 ) = PositionFormat.Compressed, decode_position_compressed(raw[:13]) 281 data, remainder = raw[:13], raw[13:] 282 except ValueError: # pylint: disable=try-except-raise 283 # eventually we may try to decode other position types here 284 raise 285 # try to decode extended data; a compressed position carries 286 # course/speed or range in its cs bytes (APRS101 p36), so text after 287 # it (e.g. an igate's PHG) stays in the comment 288 data_ext = b"" 289 if position_format is PositionFormat.Uncompressed: 290 data_ext, remainder = DataExt.split_parse(remainder) 291 # try to find the altitude comment 292 alt_match = ALTITUDE_REX.search(remainder) 293 if alt_match and "altitude_ft" not in position: 294 # a compressed altitude (in cs) takes precedence 295 position["altitude_ft"] = int(alt_match.group(1)) 296 return ( 297 cls( 298 position_format=position_format, 299 data_ext=data_ext or position.pop("data_ext", b""), 300 **position, 301 ), 302 data, 303 remainder, 304 )
Create a Position from raw packet bytes.
Returns
a Position and remaining bytes, which may be any unparsed extended data or comments.
152@define(frozen=True, slots=True) 153class PositionReport(InformationField, TimestampMixin, PositionMixin): 154 _timestamp: Timestamp | None = field(default=None, alias="timestamp") 155 _position: Position | None = field(default=None, alias="position") 156 prefix: bytes = field(default=b"") 157 """Text before the "!" of a position that doesn't start the info field.""" 158 159 __data_type__ = [ 160 DataType.POSITION_W_O_TIMESTAMP, 161 DataType.POSITION_W_O_TIMESTAMP_MSG, 162 DataType.POSITION_W_TIMESTAMP_MSG, 163 DataType.POSITION_W_TIMESTAMP_NO_MSG, 164 ] 165 166 @classmethod 167 def from_bytes(cls, raw: bytes) -> "PositionReport": 168 data_type = DataType(raw[0:1]) 169 if data_type not in cls.__data_type__: 170 raise DataTypeError( 171 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 172 ) 173 timestamp, remainder = None, raw[1:] 174 if data_type in [ 175 DataType.POSITION_W_TIMESTAMP_MSG, 176 DataType.POSITION_W_TIMESTAMP_NO_MSG, 177 ]: 178 timestamp, remainder = Timestamp.from_bytes(remainder[:7]), remainder[7:] 179 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 180 return cls( 181 raw=raw, 182 data_type=data_type, 183 data=data, 184 timestamp=timestamp, 185 position=position, 186 comment=comment, 187 ) 188 189 def __bytes__(self) -> bytes: 190 return b"".join( 191 [ 192 self.prefix, 193 self._data_type_id(), 194 bytes(_required(self._timestamp, "timestamp")) 195 if self.data_type 196 in [ 197 DataType.POSITION_W_TIMESTAMP_MSG, 198 DataType.POSITION_W_TIMESTAMP_NO_MSG, 199 ] 200 else b"", 201 bytes(_required(self._position, "position")), 202 self.format_altitude(), 203 self.comment, 204 ], 205 )
Class for APRS 'Information' Field.
40def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default, timestamp=attr_dict['_timestamp'].default, position=attr_dict['_position'].default, prefix=attr_dict['prefix'].default): 41 _setattr = _cached_setattr_get(self) 42 _setattr('raw', raw) 43 _setattr('data_type', data_type) 44 _setattr('data', data) 45 _setattr('comment', comment) 46 _setattr('_timestamp', timestamp) 47 _setattr('_position', position) 48 _setattr('prefix', prefix)
Method generated by attrs for class PositionReport.
166 @classmethod 167 def from_bytes(cls, raw: bytes) -> "PositionReport": 168 data_type = DataType(raw[0:1]) 169 if data_type not in cls.__data_type__: 170 raise DataTypeError( 171 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 172 ) 173 timestamp, remainder = None, raw[1:] 174 if data_type in [ 175 DataType.POSITION_W_TIMESTAMP_MSG, 176 DataType.POSITION_W_TIMESTAMP_NO_MSG, 177 ]: 178 timestamp, remainder = Timestamp.from_bytes(remainder[:7]), remainder[7:] 179 position, data, comment = Position.from_bytes_with_data_and_remainder(remainder) 180 return cls( 181 raw=raw, 182 data_type=data_type, 183 data=data, 184 timestamp=timestamp, 185 position=position, 186 comment=comment, 187 )
115@define(frozen=True, slots=True) 116class RNG(DataExt): 117 """ 118 RNGrrrr 119 """ 120 121 range: int = field(default=0) 122 123 @classmethod 124 def try_parse(cls, raw: bytes) -> bool: 125 """Return True if this subclass might be able to parse raw bytes.""" 126 return raw.startswith(b"RNG") 127 128 @classmethod 129 def from_bytes(cls, raw: bytes) -> "RNG": 130 if not raw.startswith(b"RNG"): 131 raise ValueError(f"{raw!r} is not a RNG extension field") 132 return cls(range=int(raw[3:7])) 133 134 def __bytes__(self) -> bytes: 135 return b"RNG%04d" % (self.range % 10000)
RNGrrrr
28def __init__(self, range=attr_dict['range'].default): 29 _setattr = _cached_setattr_get(self) 30 _setattr('range', range)
Method generated by attrs for class RNG.
KISS Serial Class.
264@define(frozen=True, slots=True) 265class StatusReport(InformationField, TimestampMixin): 266 status: bytes = field(default=b"") 267 _timestamp: Timestamp | None = field(default=None, alias="timestamp") 268 269 __data_type__ = [DataType.STATUS] 270 271 @classmethod 272 def from_bytes(cls, raw: bytes) -> "StatusReport": 273 data_type = DataType(raw[0:1]) 274 if data_type not in cls.__data_type__: 275 raise DataTypeError( 276 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 277 ) 278 timestamp, data = None, raw[1:] 279 try: 280 timestamp, data = Timestamp.from_bytes(data[:7]), data[7:] 281 if timestamp.timestamp_format != TimestampFormat.DayHoursMinutesZulu: 282 # APRS101 p. 80: Note: The timestamp can only be in DHM zulu format. 283 timestamp = attr.evolve( 284 timestamp, timestamp_format=TimestampFormat.DayHoursMinutesZulu 285 ) 286 except ValueError: 287 pass 288 return cls( 289 raw=raw, 290 data_type=data_type, 291 data=data, 292 timestamp=timestamp, 293 status=data, 294 ) 295 296 def __bytes__(self): 297 return b"".join( 298 [ 299 DataType.STATUS.value, 300 bytes(self._timestamp) if self._timestamp else b"", 301 self.status, 302 ], 303 )
Class for APRS 'Information' Field.
38def __init__(self, raw, data_type, data, comment=attr_dict['comment'].default, status=attr_dict['status'].default, timestamp=attr_dict['_timestamp'].default): 39 _setattr = _cached_setattr_get(self) 40 _setattr('raw', raw) 41 _setattr('data_type', data_type) 42 _setattr('data', data) 43 _setattr('comment', comment) 44 _setattr('status', status) 45 _setattr('_timestamp', timestamp)
Method generated by attrs for class StatusReport.
271 @classmethod 272 def from_bytes(cls, raw: bytes) -> "StatusReport": 273 data_type = DataType(raw[0:1]) 274 if data_type not in cls.__data_type__: 275 raise DataTypeError( 276 f"{data_type!r} cannot be handled by {cls!r} (expecting {cls.__data_type__!r})", 277 ) 278 timestamp, data = None, raw[1:] 279 try: 280 timestamp, data = Timestamp.from_bytes(data[:7]), data[7:] 281 if timestamp.timestamp_format != TimestampFormat.DayHoursMinutesZulu: 282 # APRS101 p. 80: Note: The timestamp can only be in DHM zulu format. 283 timestamp = attr.evolve( 284 timestamp, timestamp_format=TimestampFormat.DayHoursMinutesZulu 285 ) 286 except ValueError: 287 pass 288 return cls( 289 raw=raw, 290 data_type=data_type, 291 data=data, 292 timestamp=timestamp, 293 status=data, 294 )
Inherited Members
117class TCP(SyncFrameDecode[APRSFrame]): 118 """APRSIS-over-TCP.""" 119 120 def __init__(self, *args, **kwargs) -> None: 121 super().__init__() 122 self.args = args 123 self.kwargs = kwargs 124 125 def stop(self) -> None: 126 """ 127 Close the connection and let the event loop finish closing it. 128 129 asyncio transports release the socket on the next loop iteration 130 after close(), and this class's loop only runs inside its calls, so 131 the server would otherwise see the connection stay open. 132 """ 133 if self._protocol is None or self._protocol.transport is None: 134 return 135 transport = self._protocol.transport 136 if transport.is_closing(): 137 return # already stopped (e.g. stop() and then __del__) 138 transport.close() 139 loop = self.loop 140 if loop is None or loop.is_running() or loop.is_closed(): 141 return 142 try: 143 asyncio.get_running_loop() 144 except RuntimeError: 145 loop.run_until_complete(asyncio.sleep(0)) 146 # else: stop() (or __del__) ran inside another loop's coroutine; this 147 # loop can't run here, and finishes closing the next time it runs 148 149 def start(self, **kwargs: Any) -> None: 150 """ 151 Open the APRS-IS connection and start decoding packets. 152 """ 153 _, self.protocol = self.loop.run_until_complete( 154 create_aprsis_connection(*self.args, **self.kwargs), 155 ) 156 self.loop.run_until_complete(self.protocol.connection_future)
APRSIS-over-TCP.
120 def __init__(self, *args, **kwargs) -> None: 121 super().__init__() 122 self.args = args 123 self.kwargs = kwargs
Method generated by attrs for class SyncFrameDecode.
125 def stop(self) -> None: 126 """ 127 Close the connection and let the event loop finish closing it. 128 129 asyncio transports release the socket on the next loop iteration 130 after close(), and this class's loop only runs inside its calls, so 131 the server would otherwise see the connection stay open. 132 """ 133 if self._protocol is None or self._protocol.transport is None: 134 return 135 transport = self._protocol.transport 136 if transport.is_closing(): 137 return # already stopped (e.g. stop() and then __del__) 138 transport.close() 139 loop = self.loop 140 if loop is None or loop.is_running() or loop.is_closed(): 141 return 142 try: 143 asyncio.get_running_loop() 144 except RuntimeError: 145 loop.run_until_complete(asyncio.sleep(0)) 146 # else: stop() (or __del__) ran inside another loop's coroutine; this 147 # loop can't run here, and finishes closing the next time it runs
Close the connection and let the event loop finish closing it.
asyncio transports release the socket on the next loop iteration after close(), and this class's loop only runs inside its calls, so the server would otherwise see the connection stay open.
149 def start(self, **kwargs: Any) -> None: 150 """ 151 Open the APRS-IS connection and start decoding packets. 152 """ 153 _, self.protocol = self.loop.run_until_complete( 154 create_aprsis_connection(*self.args, **self.kwargs), 155 ) 156 self.loop.run_until_complete(self.protocol.connection_future)
Open the APRS-IS connection and start decoding packets.
KISS TCP Class.
96@define(frozen=True, slots=True) 97class Timestamp: 98 """Represents a timestamp for an APRS information field.""" 99 100 timestamp_format: TimestampFormat = field(default=TimestampFormat.DayHoursMinutesZulu) 101 timestamp: datetime = field(factory=utcnow_tz) 102 103 @classmethod 104 def from_bytes(cls, raw: bytes) -> "Timestamp": 105 """ 106 Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp. 107 108 Raises ValueError if ``raw`` does not start with a valid timestamp. 109 """ 110 indicator = raw[6:7] 111 if indicator.isdigit(): 112 return cls( 113 TimestampFormat.MonthDayHoursMinutesZulu, decode_timestamp_mdhm(raw) 114 ) 115 ts_format = TimestampFormat(indicator) 116 if ts_format == TimestampFormat.HoursMinutesSecondsZulu: 117 return cls(ts_format, decode_timestamp_hms(raw)) 118 if ts_format == TimestampFormat.MonthDayHoursMinutesZulu: 119 raise ValueError(f"Timestamp too short: {raw!r}") 120 return cls(ts_format, decode_timestamp_dhm(raw)) 121 122 def __bytes__(self) -> bytes: 123 # pylint: disable=no-member 124 return ( 125 self.timestamp.strftime(self.timestamp_format_string).encode("ascii") 126 + self.timestamp_format.value 127 ) 128 # pylint: enable=no-member 129 130 @property 131 def timestamp_format_string(self): 132 return timestamp_formats_map[self.timestamp_format]
Represents a timestamp for an APRS information field.
30def __init__(self, timestamp_format=attr_dict['timestamp_format'].default, timestamp=NOTHING): 31 _setattr = _cached_setattr_get(self) 32 _setattr('timestamp_format', timestamp_format) 33 if timestamp is not NOTHING: 34 _setattr('timestamp', timestamp) 35 else: 36 _setattr('timestamp', __attr_factory_timestamp())
Method generated by attrs for class Timestamp.
103 @classmethod 104 def from_bytes(cls, raw: bytes) -> "Timestamp": 105 """ 106 Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp. 107 108 Raises ValueError if ``raw`` does not start with a valid timestamp. 109 """ 110 indicator = raw[6:7] 111 if indicator.isdigit(): 112 return cls( 113 TimestampFormat.MonthDayHoursMinutesZulu, decode_timestamp_mdhm(raw) 114 ) 115 ts_format = TimestampFormat(indicator) 116 if ts_format == TimestampFormat.HoursMinutesSecondsZulu: 117 return cls(ts_format, decode_timestamp_hms(raw)) 118 if ts_format == TimestampFormat.MonthDayHoursMinutesZulu: 119 raise ValueError(f"Timestamp too short: {raw!r}") 120 return cls(ts_format, decode_timestamp_dhm(raw))
Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp.
Raises ValueError if raw does not start with a valid timestamp.
26class TimestampFormat(enum.Enum): 27 DayHoursMinutesLocal = b"/" 28 DayHoursMinutesZulu = b"z" 29 HoursMinutesSecondsZulu = b"h" 30 MonthDayHoursMinutesZulu = b""