aprs.position
Represent various position formats
1"""Represent various position formats""" 2 3import math 4import re 5from decimal import Decimal 6from typing import TYPE_CHECKING 7 8from attrs import define, field 9 10from .base91 import from_decimal, to_decimal 11from .constants import PositionFormat 12from .data_ext import RNG, CourseSpeed, DataExt 13from .decimaldegrees import dm2decimal 14from .geo_util import ambiguate, deambiguate, dec2dm_lat, dec2dm_lng 15 16__author__ = "Masen Furer KF7HVM <kf7hvm@0x26.net>" 17__copyright__ = "Copyright 2022 Masen Furer and Contributors" 18__license__ = "Apache License, Version 2.0" 19 20 21POSITION_UNCOMPRESSED_SIGNATURE = tuple("0123456789") 22# APRS101 p26: "/A=aaaaaa", 6 digits, or "-" and 5 digits when negative 23ALTITUDE_REX = re.compile(rb"/A=(-[0-9]{5}|[0-9]{6})") 24# Minutes to add to an ambiguous position to place it in the middle of its box, 25# by ambiguity level (APRS101 p24: 1 to 4 trailing digits replaced by spaces) 26AMBIGUITY_CENTER_MINUTES = ( 27 Decimal(0), 28 Decimal("0.05"), 29 Decimal("0.5"), 30 Decimal(5), 31 Decimal(30), 32) 33 34 35def _decode_dm(text: str, degree_digits: int) -> Decimal: 36 """ 37 Decode "DDMM.mm" or "DDDMM.mm", where trailing digits may be blanked. 38 39 Blanked digits are centred in their range; digits that were sent are kept. 40 """ 41 unblanked = text.replace(" ", "0") 42 if not re.fullmatch(r"[0-9]{%d}[0-9]{2}\.[0-9]{2}" % degree_digits, unblanked): 43 raise ValueError(f"{text!r} is not a valid coordinate") 44 ambiguity = text.count(" ") 45 if ambiguity > 4 or ambiguate(unblanked.encode("ascii"), ambiguity) != text.encode( 46 "ascii" 47 ): 48 raise ValueError(f"{text!r}: only up to 4 trailing digits may be blanked") 49 degrees = int(unblanked[:degree_digits]) 50 minutes = Decimal(unblanked[degree_digits:]) 51 max_degrees = 90 if degree_digits == 2 else 180 52 if minutes >= 60 or degrees > max_degrees or (degrees == max_degrees and minutes): 53 raise ValueError(f"{text!r} is out of range") 54 return dm2decimal(degrees, minutes + AMBIGUITY_CENTER_MINUTES[ambiguity]) 55 56 57def decode_position_uncompressed(data: bytes): 58 """ 59 :return: dict with keys lat, long, sym_table_id, symbol_code, ambiguity, 60 and long_ambiguity when the longitude has a different number of 61 blanked digits than the latitude 62 63 An ambiguous position (APRS101 p24) is placed in the middle of its box. 64 Only blanked digits are centred, so a longitude sent with more precision 65 than the latitude keeps it. 66 """ 67 text = data.decode("latin1") 68 if len(text) < 19 or not text.startswith(POSITION_UNCOMPRESSED_SIGNATURE): 69 raise ValueError(f"{data[:19]!r} is not an uncompressed position") 70 lat_text, lat_hemisphere = text[:7], text[7:8] 71 long_text, long_hemisphere = text[9:17], text[17:18] 72 if lat_hemisphere not in ("N", "S") or long_hemisphere not in ("E", "W"): 73 raise ValueError(f"{data[:19]!r} is not an uncompressed position") 74 lat = _decode_dm(lat_text, 2) * (-1 if lat_hemisphere == "S" else 1) 75 long = _decode_dm(long_text, 3) * (-1 if long_hemisphere == "W" else 1) 76 # APRS101 p24: the latitude sets the ambiguity 77 ambiguity = deambiguate(lat_text.encode("ascii")) 78 long_ambiguity = deambiguate(long_text.encode("ascii")) 79 extra = {} if long_ambiguity == ambiguity else {"long_ambiguity": long_ambiguity} 80 return dict( 81 lat=lat, 82 sym_table_id=data[8:9], 83 long=long, 84 symbol_code=data[18:19], 85 ambiguity=ambiguity, 86 **extra, 87 ) 88 89 90def encode_position_uncompressed( 91 lat: float | Decimal, 92 long: float | Decimal, 93 sym_table_id: bytes, 94 symbol_code: bytes, 95 ambiguity: int | None = None, 96 long_ambiguity: int | None = None, 97) -> bytes: 98 if long_ambiguity is None: 99 long_ambiguity = ambiguity 100 return b"".join( 101 [ 102 ambiguate(dec2dm_lat(lat), ambiguity), 103 sym_table_id, 104 ambiguate(dec2dm_lng(long), long_ambiguity), 105 symbol_code, 106 ] 107 ) 108 109 110def decompress_lat(data: str) -> float: 111 return 90 - to_decimal(data) / 380926 112 113 114def compress_lat(data: float) -> bytes: 115 return from_decimal(int(round(380926 * (90 - data))), width=4).encode("ascii") 116 117 118def decompress_long(data: str) -> float: 119 return -180 + to_decimal(data) / 190463 120 121 122def compress_long(data: float) -> bytes: 123 return from_decimal(int(round(190463 * (180 + data))), width=4).encode("ascii") 124 125 126def decode_position_compressed(data: bytes): 127 """ 128 :return: dict with keys lat, long, sym_table_id, symbol_code, data_ext, 129 and altitude_ft when the cs bytes hold an altitude 130 """ 131 if len(data) < 13 or chr(data[0]) in POSITION_UNCOMPRESSED_SIGNATURE: 132 raise ValueError(f"{data[:13]!r} is not a compressed position") 133 text = data.decode("latin1") 134 sym_table_id = data[0:1] 135 lat = Decimal(str(decompress_lat(text[1:5]))) 136 long = Decimal(str(decompress_long(text[5:9]))) 137 symbol_code = data[9:10] 138 c_ext = text[10:12] 139 comp_type = data[12] - 33 140 init_kwargs = {} 141 data_ext = b"" 142 143 # APRS101 p38-40: a space in c means no course/speed, range or altitude, 144 # and s is ignored (but kept so the position re-encodes unchanged) 145 if c_ext[0] == " ": 146 if c_ext != " ": 147 init_kwargs["ignored_cs"] = data[10:12] 148 else: 149 if (comp_type >> 3) & 0b11 == 0b10: 150 # GGA source: cs is an altitude 151 init_kwargs["altitude_ft"] = 1.002 ** to_decimal(c_ext) 152 elif c_ext[0] == "{": 153 data_ext = RNG(range=2 * 1.08 ** to_decimal(c_ext[1])) 154 else: 155 data_ext = CourseSpeed( 156 course=to_decimal(c_ext[0]) * 4, speed=1.08 ** to_decimal(c_ext[1]) - 1 157 ) 158 159 return dict( 160 sym_table_id=sym_table_id, 161 lat=lat, 162 long=long, 163 symbol_code=symbol_code, 164 data_ext=data_ext, 165 compression_type=comp_type, 166 **init_kwargs, 167 ) 168 169 170# Compression type bytes used when encoding a Position that wasn't decoded: 171# current GPS fix, compressed origin; GGA source when cs holds an altitude 172COMPRESSION_TYPE_DEFAULT = ord("#") - 33 173COMPRESSION_TYPE_ALTITUDE = ord("S") - 33 174 175 176def _encode_cs(data_ext, altitude_ft, ignored_cs=None) -> bytes: 177 if isinstance(data_ext, CourseSpeed): 178 return ( 179 # 360 (due north) is code 0: code 90 ("{") marks a range 180 from_decimal(int(data_ext.course) % 360 // 4, 1) 181 + from_decimal(int(round(math.log(data_ext.speed + 1, 1.08))), 1) 182 ).encode("ascii") 183 if isinstance(data_ext, RNG): 184 return b"{" + from_decimal( 185 int(round(math.log(data_ext.range / 2, 1.08))), 1 186 ).encode("ascii") 187 if altitude_ft is not None: 188 if altitude_ft <= 0: 189 # 1.002**c cannot produce 0 (or a negative value); encode the 190 # lowest valid code instead of failing on math.log()'s domain error 191 return from_decimal(0, 2).encode("ascii") 192 return from_decimal(int(round(math.log(altitude_ft, 1.002))), 2).encode("ascii") 193 return ignored_cs or b" " 194 195 196def encode_position_compressed( # pylint: disable=too-many-arguments 197 lat, 198 long, 199 sym_table_id, 200 symbol_code, 201 ambiguity=None, # pylint: disable=unused-argument 202 data_ext=None, 203 altitude_ft=None, 204 compression_type=None, 205 ignored_cs=None, 206) -> bytes: 207 if compression_type is None: 208 compression_type = ( 209 COMPRESSION_TYPE_ALTITUDE 210 if altitude_ft is not None and not data_ext 211 else COMPRESSION_TYPE_DEFAULT 212 ) 213 return b"".join( 214 [ 215 sym_table_id, 216 compress_lat(lat), 217 compress_long(long), 218 symbol_code, 219 _encode_cs(data_ext, altitude_ft, ignored_cs), 220 bytes([compression_type + 33]), 221 ] 222 ) 223 224 225def _in_range(limit): 226 def validator(instance, attribute, value): 227 if not -limit <= value <= limit: 228 raise ValueError(f"{attribute.name} must be within ±{limit}, got {value!r}") 229 230 return validator 231 232 233@define(frozen=True, slots=True) 234class Position: 235 """Represents a position including any data extension.""" 236 237 position_format: PositionFormat = field(default=PositionFormat.Uncompressed) 238 lat: float | Decimal = field(default=0.0, validator=_in_range(90)) 239 """Decimal when decoded from uncompressed text (exact), float otherwise.""" 240 sym_table_id: bytes = field(default=b"/") 241 long: float | Decimal = field(default=0.0, validator=_in_range(180)) 242 symbol_code: bytes = field(default=b"-") 243 altitude_ft: float | None = field(default=None) 244 """Whole feet from "/A=", a float from compressed cs bytes.""" 245 data_ext: bytes | DataExt = field(default=b"") 246 ambiguity: int = field(default=0) 247 """Uncompressed only: how many trailing digits are blanked (0-4).""" 248 long_ambiguity: int | None = field(default=None) 249 """ 250 Uncompressed only: blanked longitude digits, when they differ from the 251 latitude's; None means the same as ambiguity. 252 """ 253 compression_type: int | None = field(default=None) 254 """Compressed only: the type byte (minus 33); None picks a default.""" 255 ignored_cs: bytes | None = field(default=None) 256 """Compressed only: cs bytes starting with a space, which carry no data.""" 257 258 @classmethod 259 def from_bytes_with_data_and_remainder( 260 cls, raw: bytes 261 ) -> tuple["Position", bytes, bytes]: 262 """ 263 Create a Position from raw packet bytes. 264 265 :return: a Position and remaining bytes, which may be any unparsed 266 extended data or comments. 267 """ 268 try: 269 ( 270 position_format, 271 position, 272 ) = PositionFormat.Uncompressed, decode_position_uncompressed(raw[:19]) 273 data, remainder = raw[:19], raw[19:] 274 except ValueError: 275 try: 276 ( 277 position_format, 278 position, 279 ) = PositionFormat.Compressed, decode_position_compressed(raw[:13]) 280 data, remainder = raw[:13], raw[13:] 281 except ValueError: # pylint: disable=try-except-raise 282 # eventually we may try to decode other position types here 283 raise 284 # try to decode extended data; a compressed position carries 285 # course/speed or range in its cs bytes (APRS101 p36), so text after 286 # it (e.g. an igate's PHG) stays in the comment 287 data_ext = b"" 288 if position_format is PositionFormat.Uncompressed: 289 data_ext, remainder = DataExt.split_parse(remainder) 290 # try to find the altitude comment 291 alt_match = ALTITUDE_REX.search(remainder) 292 if alt_match and "altitude_ft" not in position: 293 # a compressed altitude (in cs) takes precedence 294 position["altitude_ft"] = int(alt_match.group(1)) 295 return ( 296 cls( 297 position_format=position_format, 298 data_ext=data_ext or position.pop("data_ext", b""), 299 **position, 300 ), 301 data, 302 remainder, 303 ) 304 305 def __bytes__(self) -> bytes: 306 if self.position_format is PositionFormat.Uncompressed: 307 return b"".join( 308 [ 309 encode_position_uncompressed( 310 self.lat, 311 self.long, 312 self.sym_table_id, 313 self.symbol_code, 314 ambiguity=self.ambiguity, 315 long_ambiguity=self.long_ambiguity, 316 ), 317 bytes(self.data_ext), 318 ] 319 ) 320 if self.position_format is PositionFormat.Compressed: 321 return encode_position_compressed( 322 self.lat, 323 self.long, 324 self.sym_table_id, 325 self.symbol_code, 326 data_ext=self.data_ext, 327 altitude_ft=self.altitude_ft, 328 compression_type=self.compression_type, 329 ignored_cs=self.ignored_cs, 330 ) 331 raise ValueError(f"Unknown position format: {self.position_format!r}") 332 333 334# pylint: disable=no-member,inconsistent-return-statements 335class PositionMixin: 336 if TYPE_CHECKING: 337 # provided by the attrs class this is mixed into (read-only: frozen) 338 @property 339 def _position(self) -> Position | None: ... 340 341 @property 342 def lat(self) -> float | Decimal | None: 343 if self._position: 344 return self._position.lat 345 346 @property 347 def long(self) -> float | Decimal | None: 348 if self._position: 349 return self._position.long 350 351 @property 352 def sym_table_id(self) -> bytes | None: 353 if self._position: 354 return self._position.sym_table_id 355 356 @property 357 def symbol_code(self) -> bytes | None: 358 if self._position: 359 return self._position.symbol_code 360 361 @property 362 def altitude_ft(self) -> float | None: 363 if self._position: 364 return self._position.altitude_ft 365 366 @property 367 def data_ext(self) -> DataExt | bytes: 368 if self._position: 369 return self._position.data_ext 370 return b"" 371 372 def format_altitude(self) -> bytes: 373 """The "/A=" comment for altitude_ft, unless it's already encoded.""" 374 position = self._position 375 if ( 376 position is not None 377 and position.position_format is PositionFormat.Compressed 378 and not position.data_ext 379 ): 380 return b"" # carried in the compressed cs bytes 381 if self.altitude_ft is not None and not ALTITUDE_REX.search( 382 getattr(self, "comment", b"") 383 ): 384 return b"/A=%06d" % self.altitude_ft 385 return b""
58def decode_position_uncompressed(data: bytes): 59 """ 60 :return: dict with keys lat, long, sym_table_id, symbol_code, ambiguity, 61 and long_ambiguity when the longitude has a different number of 62 blanked digits than the latitude 63 64 An ambiguous position (APRS101 p24) is placed in the middle of its box. 65 Only blanked digits are centred, so a longitude sent with more precision 66 than the latitude keeps it. 67 """ 68 text = data.decode("latin1") 69 if len(text) < 19 or not text.startswith(POSITION_UNCOMPRESSED_SIGNATURE): 70 raise ValueError(f"{data[:19]!r} is not an uncompressed position") 71 lat_text, lat_hemisphere = text[:7], text[7:8] 72 long_text, long_hemisphere = text[9:17], text[17:18] 73 if lat_hemisphere not in ("N", "S") or long_hemisphere not in ("E", "W"): 74 raise ValueError(f"{data[:19]!r} is not an uncompressed position") 75 lat = _decode_dm(lat_text, 2) * (-1 if lat_hemisphere == "S" else 1) 76 long = _decode_dm(long_text, 3) * (-1 if long_hemisphere == "W" else 1) 77 # APRS101 p24: the latitude sets the ambiguity 78 ambiguity = deambiguate(lat_text.encode("ascii")) 79 long_ambiguity = deambiguate(long_text.encode("ascii")) 80 extra = {} if long_ambiguity == ambiguity else {"long_ambiguity": long_ambiguity} 81 return dict( 82 lat=lat, 83 sym_table_id=data[8:9], 84 long=long, 85 symbol_code=data[18:19], 86 ambiguity=ambiguity, 87 **extra, 88 )
Returns
dict with keys lat, long, sym_table_id, symbol_code, ambiguity, and long_ambiguity when the longitude has a different number of blanked digits than the latitude
An ambiguous position (APRS101 p24) is placed in the middle of its box. Only blanked digits are centred, so a longitude sent with more precision than the latitude keeps it.
91def encode_position_uncompressed( 92 lat: float | Decimal, 93 long: float | Decimal, 94 sym_table_id: bytes, 95 symbol_code: bytes, 96 ambiguity: int | None = None, 97 long_ambiguity: int | None = None, 98) -> bytes: 99 if long_ambiguity is None: 100 long_ambiguity = ambiguity 101 return b"".join( 102 [ 103 ambiguate(dec2dm_lat(lat), ambiguity), 104 sym_table_id, 105 ambiguate(dec2dm_lng(long), long_ambiguity), 106 symbol_code, 107 ] 108 )
127def decode_position_compressed(data: bytes): 128 """ 129 :return: dict with keys lat, long, sym_table_id, symbol_code, data_ext, 130 and altitude_ft when the cs bytes hold an altitude 131 """ 132 if len(data) < 13 or chr(data[0]) in POSITION_UNCOMPRESSED_SIGNATURE: 133 raise ValueError(f"{data[:13]!r} is not a compressed position") 134 text = data.decode("latin1") 135 sym_table_id = data[0:1] 136 lat = Decimal(str(decompress_lat(text[1:5]))) 137 long = Decimal(str(decompress_long(text[5:9]))) 138 symbol_code = data[9:10] 139 c_ext = text[10:12] 140 comp_type = data[12] - 33 141 init_kwargs = {} 142 data_ext = b"" 143 144 # APRS101 p38-40: a space in c means no course/speed, range or altitude, 145 # and s is ignored (but kept so the position re-encodes unchanged) 146 if c_ext[0] == " ": 147 if c_ext != " ": 148 init_kwargs["ignored_cs"] = data[10:12] 149 else: 150 if (comp_type >> 3) & 0b11 == 0b10: 151 # GGA source: cs is an altitude 152 init_kwargs["altitude_ft"] = 1.002 ** to_decimal(c_ext) 153 elif c_ext[0] == "{": 154 data_ext = RNG(range=2 * 1.08 ** to_decimal(c_ext[1])) 155 else: 156 data_ext = CourseSpeed( 157 course=to_decimal(c_ext[0]) * 4, speed=1.08 ** to_decimal(c_ext[1]) - 1 158 ) 159 160 return dict( 161 sym_table_id=sym_table_id, 162 lat=lat, 163 long=long, 164 symbol_code=symbol_code, 165 data_ext=data_ext, 166 compression_type=comp_type, 167 **init_kwargs, 168 )
Returns
dict with keys lat, long, sym_table_id, symbol_code, data_ext, and altitude_ft when the cs bytes hold an altitude
197def encode_position_compressed( # pylint: disable=too-many-arguments 198 lat, 199 long, 200 sym_table_id, 201 symbol_code, 202 ambiguity=None, # pylint: disable=unused-argument 203 data_ext=None, 204 altitude_ft=None, 205 compression_type=None, 206 ignored_cs=None, 207) -> bytes: 208 if compression_type is None: 209 compression_type = ( 210 COMPRESSION_TYPE_ALTITUDE 211 if altitude_ft is not None and not data_ext 212 else COMPRESSION_TYPE_DEFAULT 213 ) 214 return b"".join( 215 [ 216 sym_table_id, 217 compress_lat(lat), 218 compress_long(long), 219 symbol_code, 220 _encode_cs(data_ext, altitude_ft, ignored_cs), 221 bytes([compression_type + 33]), 222 ] 223 )
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.
336class PositionMixin: 337 if TYPE_CHECKING: 338 # provided by the attrs class this is mixed into (read-only: frozen) 339 @property 340 def _position(self) -> Position | None: ... 341 342 @property 343 def lat(self) -> float | Decimal | None: 344 if self._position: 345 return self._position.lat 346 347 @property 348 def long(self) -> float | Decimal | None: 349 if self._position: 350 return self._position.long 351 352 @property 353 def sym_table_id(self) -> bytes | None: 354 if self._position: 355 return self._position.sym_table_id 356 357 @property 358 def symbol_code(self) -> bytes | None: 359 if self._position: 360 return self._position.symbol_code 361 362 @property 363 def altitude_ft(self) -> float | None: 364 if self._position: 365 return self._position.altitude_ft 366 367 @property 368 def data_ext(self) -> DataExt | bytes: 369 if self._position: 370 return self._position.data_ext 371 return b"" 372 373 def format_altitude(self) -> bytes: 374 """The "/A=" comment for altitude_ft, unless it's already encoded.""" 375 position = self._position 376 if ( 377 position is not None 378 and position.position_format is PositionFormat.Compressed 379 and not position.data_ext 380 ): 381 return b"" # carried in the compressed cs bytes 382 if self.altitude_ft is not None and not ALTITUDE_REX.search( 383 getattr(self, "comment", b"") 384 ): 385 return b"/A=%06d" % self.altitude_ft 386 return b""
373 def format_altitude(self) -> bytes: 374 """The "/A=" comment for altitude_ft, unless it's already encoded.""" 375 position = self._position 376 if ( 377 position is not None 378 and position.position_format is PositionFormat.Compressed 379 and not position.data_ext 380 ): 381 return b"" # carried in the compressed cs bytes 382 if self.altitude_ft is not None and not ALTITUDE_REX.search( 383 getattr(self, "comment", b"") 384 ): 385 return b"/A=%06d" % self.altitude_ft 386 return b""
The "/A=" comment for altitude_ft, unless it's already encoded.