-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
492 lines (430 loc) · 16.3 KB
/
Copy pathparser.py
File metadata and controls
492 lines (430 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
from __future__ import annotations
"""APRS text parser producing runtime events plus optional canonical metadata."""
import logging
import re
from datetime import UTC, datetime
from core.canonical import empty_canonical_event, iso_utc_now
from core.model import MessageEvent, PositionEvent, Source, build_raw_payload
log = logging.getLogger("aprs.parser")
APRS_FRAME_RE = re.compile(
r"^(?P<src>[A-Z0-9\-]+)>(?P<dst>[^:]+):(?P<body>.+)$",
re.IGNORECASE,
)
POSITION_RE = re.compile(
r"^(?P<type>[!=])"
r"(?P<lat_deg>\d{2})(?P<lat_min>\d{2}\.\d{2})(?P<lat_hemi>[NS])"
r"(?P<symbol_table>.)"
r"(?P<lon_deg>\d{3})(?P<lon_min>\d{2}\.\d{2})(?P<lon_hemi>[EW])"
r"(?P<symbol>.)(?P<comment>.*)$"
)
OBJECT_RE = re.compile(
r"^;"
r"(?P<name>.{9})"
r"(?P<alive>[*_])"
r"(?P<day>\d{2})(?P<hour>\d{2})(?P<minute>\d{2})z"
r"(?P<lat_deg>\d{2})(?P<lat_min>\d{2}\.\d{2})(?P<lat_hemi>[NS])"
r"(?P<symbol_table>.)"
r"(?P<lon_deg>\d{3})(?P<lon_min>\d{2}\.\d{2})(?P<lon_hemi>[EW])"
r"(?P<symbol>.)(?P<comment>.*)$"
)
TACTICAL_NAME_RE = re.compile(r"^\[:(?P<tactical_name>[^\r\n]+)$")
TACTICAL_NAME_INLINE_RE = re.compile(r"\[:(?P<tactical_name>[^\r\n]+)\s*$")
MESSAGE_RE = re.compile(
r"^:(?P<target>.{9}):(?P<message>[^\{]*?)(?:\{(?P<message_id>[^\s\{]+))?$"
)
ACK_MESSAGE_RE = re.compile(r"^ack(?P<ack_id>[A-Za-z0-9]+)$", re.IGNORECASE)
ENCRYPTED_MESSAGE_RE = re.compile(r"^\[(?P<method>[A-Za-z0-9]+),(?P<payload>.+)$")
class APRSParseError(ValueError):
pass
def parse_aprs_event(
frame: str,
*,
source: Source = Source.APRS,
ingress_adapter: str | None = None,
raw_context: dict[str, object] | None = None,
) -> PositionEvent | MessageEvent:
"""Parse an APRS frame into the runtime model."""
canonical = parse_aprs_canonical(frame)
event = canonical_to_aprs_event(
canonical,
source=source,
ingress_adapter=ingress_adapter,
raw_context=raw_context,
)
log.debug(
"APRS canonical -> %s source=%s subtype=%s msg_id=%r",
event.kind,
event.id,
canonical["meta"]["source_subtype"],
canonical["meta"]["message_id"],
)
return event
def parse_aprs_frame(frame: str) -> PositionEvent | MessageEvent:
return parse_aprs_event(frame)
def decode_aprs_frame(frame: str) -> PositionEvent | MessageEvent:
"""Operator-friendly alias for APRS RX decoding."""
return parse_aprs_event(frame)
def parse_aprs_canonical(frame: str) -> dict[str, object]:
frame = frame.strip()
match = APRS_FRAME_RE.match(frame)
if not match:
raise APRSParseError(f"invalid APRS frame: {frame}")
source_id = match.group("src").upper()
destination = match.group("dst").strip()
body = match.group("body").strip()
if body.startswith(("!", "=")):
canonical = _parse_position_canonical(
source_id=source_id,
destination=destination,
body=body,
frame=frame,
)
log.debug(
"APRS canonical event created format=%s subtype=%s callsign=%s lat=%s lon=%s",
canonical["meta"]["source_format"],
canonical["meta"]["source_subtype"],
canonical["identity"]["callsign"],
canonical["position"]["lat"],
canonical["position"]["lon"],
)
return canonical
if body.startswith(";"):
canonical = _parse_object_canonical(
source_id=source_id,
destination=destination,
body=body,
frame=frame,
)
log.debug(
"APRS canonical event created format=%s subtype=%s object=%s lat=%s lon=%s",
canonical["meta"]["source_format"],
canonical["meta"]["source_subtype"],
canonical["identity"]["callsign"],
canonical["position"]["lat"],
canonical["position"]["lon"],
)
return canonical
if body.startswith(":"):
canonical = _parse_message_canonical(
source_id=source_id,
destination=destination,
body=body,
frame=frame,
)
log.debug(
"APRS canonical event created format=%s subtype=%s callsign=%s target=%s msg_id=%r",
canonical["meta"]["source_format"],
canonical["meta"]["source_subtype"],
canonical["identity"]["callsign"],
canonical["sartrack"]["receiver"],
canonical["meta"]["message_id"],
)
return canonical
raise APRSParseError(f"unsupported APRS body: {body}")
def canonical_to_aprs_event(
canonical: dict[str, object],
*,
source: Source = Source.APRS,
ingress_adapter: str | None = None,
raw_context: dict[str, object] | None = None,
) -> PositionEvent | MessageEvent:
identity = canonical["identity"]
position = canonical["position"]
text = canonical["text"]
meta = canonical["meta"]
source_id = identity["callsign"]
if not source_id:
raise APRSParseError("canonical APRS event missing source callsign")
raw_payload = build_raw_payload(
canonical=canonical,
ingress_adapter=ingress_adapter,
raw_context=raw_context,
)
if text["text"]:
return MessageEvent(
id=str(source_id),
target=str(canonical["sartrack"]["receiver"]) if canonical["sartrack"]["receiver"] else None,
message=str(text["text"]),
message_id=str(meta["message_id"]) if meta["message_id"] else None,
source=source,
raw=raw_payload,
)
if position["lat"] is None or position["lon"] is None:
raise APRSParseError("canonical APRS event missing coordinates")
return PositionEvent(
id=str(source_id),
entity_kind="object" if str(meta["source_subtype"] or "") == "object" else "station",
type=str(meta["source_subtype"] or "unit"),
lat=float(position["lat"]),
lon=float(position["lon"]),
tactical_name=str(identity["short_name"]) if identity["short_name"] else None,
message=str(text["comment"]) if text["comment"] else None,
symbol_table=str(canonical["comms"]["symbol_table"]) if canonical["comms"]["symbol_table"] else None,
symbol_code=str(canonical["comms"]["symbol_code"]) if canonical["comms"]["symbol_code"] else None,
object_name=str(canonical["sartrack"]["custom"].get("object_name"))
if isinstance(canonical["sartrack"]["custom"], dict) and canonical["sartrack"]["custom"].get("object_name")
else None,
owner_id=str(canonical["sartrack"]["custom"].get("owner_callsign"))
if isinstance(canonical["sartrack"]["custom"], dict) and canonical["sartrack"]["custom"].get("owner_callsign")
else None,
source=source,
raw=raw_payload,
)
def _parse_position_canonical(
*,
source_id: str,
destination: str,
body: str,
frame: str,
) -> dict[str, object]:
match = POSITION_RE.match(body)
if not match:
raise APRSParseError(f"invalid APRS position body: {body}")
lat = _parse_coordinate(
degrees=match.group("lat_deg"),
minutes=match.group("lat_min"),
hemisphere=match.group("lat_hemi"),
)
lon = _parse_coordinate(
degrees=match.group("lon_deg"),
minutes=match.group("lon_min"),
hemisphere=match.group("lon_hemi"),
)
raw_comment = match.group("comment").strip() or None
comment, tactical_name = _normalize_position_comment(raw_comment)
symbol_table = match.group("symbol_table")
symbol_code = match.group("symbol")
log.debug(
"Parsed APRS position source=%s lat=%s lon=%s symbol=%s%s comment=%r tactical_name=%r",
source_id,
lat,
lon,
symbol_table,
symbol_code,
comment,
tactical_name,
)
canonical = empty_canonical_event()
canonical["meta"]["source_format"] = "aprs_text"
canonical["meta"]["source_subtype"] = "position"
canonical["meta"]["parser_version"] = 1
canonical["meta"]["raw_message"] = frame
canonical["meta"]["received_at_utc"] = iso_utc_now()
canonical["identity"]["uid"] = source_id
canonical["identity"]["callsign"] = source_id
canonical["identity"]["short_name"] = tactical_name
canonical["identity"]["object_type"] = "person"
canonical["position"]["lat"] = lat
canonical["position"]["lon"] = lon
canonical["text"]["comment"] = comment
canonical["comms"]["destination"] = destination
canonical["comms"]["symbol_table"] = symbol_table
canonical["comms"]["symbol_code"] = symbol_code
canonical["sartrack"]["custom"] = {
"frame": frame,
"body": body,
"packet_type": match.group("type"),
"comment": raw_comment,
"tactical_name": tactical_name,
}
return canonical
def _parse_message_canonical(
*,
source_id: str,
destination: str,
body: str,
frame: str,
) -> dict[str, object]:
match = MESSAGE_RE.match(body)
if not match:
raise APRSParseError(f"invalid APRS message body: {body}")
target_id = match.group("target").strip() or None
message = match.group("message").strip()
message_id = (match.group("message_id") or "").strip() or None
if not target_id:
raise APRSParseError(f"missing APRS message target: {body}")
if not message:
raise APRSParseError(f"empty APRS message payload: {body}")
message_subtype, message_meta = _classify_message_subtype(target_id=target_id, message=message)
log.debug(
"Parsed APRS message source=%s target=%s subtype=%s message=%r message_id=%r",
source_id,
target_id,
message_subtype,
message,
message_id,
)
canonical = empty_canonical_event()
canonical["meta"]["source_format"] = "aprs_text"
canonical["meta"]["source_subtype"] = message_subtype
canonical["meta"]["parser_version"] = 1
canonical["meta"]["raw_message"] = frame
canonical["meta"]["received_at_utc"] = iso_utc_now()
canonical["meta"]["message_id"] = message_id
canonical["identity"]["uid"] = source_id
canonical["identity"]["callsign"] = source_id
canonical["identity"]["object_type"] = "person"
canonical["text"]["text"] = message
canonical["comms"]["destination"] = destination
canonical["sartrack"]["receiver"] = target_id
canonical["sartrack"]["custom"] = {
"frame": frame,
"body": body,
"packet_type": ":",
**message_meta,
}
return canonical
def _parse_object_canonical(
*,
source_id: str,
destination: str,
body: str,
frame: str,
) -> dict[str, object]:
match = OBJECT_RE.match(body)
if not match:
raise APRSParseError(f"invalid APRS object body: {body}")
object_name = match.group("name").strip() or source_id
lat = _parse_coordinate(
degrees=match.group("lat_deg"),
minutes=match.group("lat_min"),
hemisphere=match.group("lat_hemi"),
)
lon = _parse_coordinate(
degrees=match.group("lon_deg"),
minutes=match.group("lon_min"),
hemisphere=match.group("lon_hemi"),
)
raw_comment = match.group("comment").strip() or None
comment, tactical_name = _normalize_position_comment(raw_comment)
symbol_table = match.group("symbol_table")
symbol_code = match.group("symbol")
object_timestamp_raw = f"{match.group('day')}{match.group('hour')}{match.group('minute')}z"
object_timestamp_utc = _parse_object_timestamp_utc(
day=match.group("day"),
hour=match.group("hour"),
minute=match.group("minute"),
)
log.debug(
"Parsed APRS object source=%s object=%s object_time_raw=%s object_time_utc=%s lat=%s lon=%s symbol=%s%s comment=%r tactical_name=%r",
source_id,
object_name,
object_timestamp_raw,
object_timestamp_utc,
lat,
lon,
symbol_table,
symbol_code,
comment,
tactical_name,
)
canonical = empty_canonical_event()
canonical["meta"]["source_format"] = "aprs_text"
canonical["meta"]["source_subtype"] = "object"
canonical["meta"]["parser_version"] = 1
canonical["meta"]["raw_message"] = frame
canonical["meta"]["received_at_utc"] = iso_utc_now()
canonical["identity"]["uid"] = object_name
canonical["identity"]["callsign"] = object_name
canonical["identity"]["short_name"] = tactical_name or object_name
canonical["identity"]["object_type"] = "unknown"
canonical["position"]["lat"] = lat
canonical["position"]["lon"] = lon
canonical["position"]["timestamp_utc"] = object_timestamp_utc
canonical["text"]["comment"] = comment
canonical["comms"]["destination"] = destination
canonical["comms"]["symbol_table"] = symbol_table
canonical["comms"]["symbol_code"] = symbol_code
canonical["sartrack"]["custom"] = {
"frame": frame,
"body": body,
"packet_type": ";",
"owner_callsign": source_id,
"object_name": object_name,
"alive": match.group("alive") == "*",
"object_timestamp_raw": object_timestamp_raw,
"object_timestamp_utc": object_timestamp_utc,
"comment": raw_comment,
"tactical_name": tactical_name,
"symbol_table": symbol_table,
"symbol_code": symbol_code,
}
return canonical
def _parse_coordinate(*, degrees: str, minutes: str, hemisphere: str) -> float:
value = int(degrees) + (float(minutes) / 60.0)
if hemisphere in {"S", "W"}:
value *= -1
return value
def _normalize_position_comment(comment: str | None) -> tuple[str | None, str | None]:
if not comment:
return None, None
tactical_match = TACTICAL_NAME_RE.fullmatch(comment)
if tactical_match:
tactical_name = tactical_match.group("tactical_name").strip()
return tactical_name, tactical_name
tactical_inline_match = TACTICAL_NAME_INLINE_RE.search(comment)
if tactical_inline_match:
tactical_name = tactical_inline_match.group("tactical_name").strip()
stripped = comment[: tactical_inline_match.start()].strip() or tactical_name
return stripped, tactical_name
return comment, None
def _classify_message_subtype(*, target_id: str, message: str) -> tuple[str, dict[str, str]]:
target_upper = target_id.strip().upper()
message_stripped = message.strip()
message_upper = message_stripped.upper()
ack_match = ACK_MESSAGE_RE.fullmatch(message_stripped)
if ack_match:
return "ack", {"ack_id": ack_match.group("ack_id")}
encrypted_match = ENCRYPTED_MESSAGE_RE.match(message_stripped)
if encrypted_match:
return (
"encrypted_message",
{
"encryption_method": encrypted_match.group("method"),
"encrypted_payload": encrypted_match.group("payload"),
},
)
if target_upper.startswith("BLN"):
return "bulletin", {"bulletin_id": target_upper}
if target_upper.startswith("TEAM") or target_upper in {"GRUPA", "GROUP", "ALL"}:
return "group_message", {"group_id": target_upper}
if message_upper.startswith("PING"):
return "ping", {}
if message_stripped.startswith("?"):
return "query", {"query": message_stripped}
if message_upper.startswith("!SARTRACK "):
return "status_response", {"status_payload": message_stripped}
return "private_message", {}
def _parse_object_timestamp_utc(*, day: str, hour: str, minute: str) -> str | None:
try:
now = datetime.now(UTC)
candidate = datetime(
year=now.year,
month=now.month,
day=int(day),
hour=int(hour),
minute=int(minute),
tzinfo=UTC,
)
except ValueError:
return None
# If APRS object time lands implausibly far in the future, assume month rollover.
if candidate.timestamp() - now.timestamp() > 36 * 3600:
if now.month == 1:
year = now.year - 1
month = 12
else:
year = now.year
month = now.month - 1
try:
candidate = datetime(
year=year,
month=month,
day=int(day),
hour=int(hour),
minute=int(minute),
tzinfo=UTC,
)
except ValueError:
return None
return candidate.replace(second=0, microsecond=0).isoformat().replace("+00:00", "Z")