-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgust_frame.py
More file actions
1459 lines (1294 loc) · 62.5 KB
/
Copy pathgust_frame.py
File metadata and controls
1459 lines (1294 loc) · 62.5 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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
GUST — Frame Layer Phase 2
═══════════════════════════════════════════════════════════════════════
Autor : OE3GAS
Version : 0.2.0
Datum : Mai 2026
Inhalt dieses Moduls:
• FrameType — Alle Frame-Typ-Konstanten mit Namen
• Rufzeichen-Codec — Basis-40 Encoder/Decoder (4 Byte, 6 Zeichen)
• CRC-16/CCITT — Prüfsumme über TYPE + FROM + PAYLOAD
• Payload-Encoder — Für jeden definierten Frame-Typ (0x01–0x50)
• Payload-Decoder — Rückrichtung: bytes → Python-Dict
• Frame-Builder — Vollständiger Frame-Aufbau inkl. CRC
• Frame-Parser — Empfang: bytes → validiertes Dict
• RS-FEC-Wrapper — Reed-Solomon Encode/Decode (via reedsolo)
• Bytes→Symbole — Interface zum MFSK-Modulator (Phase 1)
• Kanalzuweisung — Deterministisch per Rufzeichen-Hash
Schnittstelle zu Phase 1 (Modulator):
frame_to_symbol_stream(body_bytes) → List[int] (0–7, MFSK-8)
Diese Liste direkt an mfsk8_modulate() aus Phase 1 übergeben.
"""
import struct
import hashlib
import hmac
from dataclasses import dataclass
from typing import Optional
try:
import reedsolo
_RS_AVAILABLE = True
except ImportError:
_RS_AVAILABLE = False
print("[Warnung] reedsolo nicht installiert — RS-FEC deaktiviert.")
# ═══════════════════════════════════════════════════════════════════════
# KONSTANTEN
# ═══════════════════════════════════════════════════════════════════════
VERSION = "0.3.0"
# Broadcast-Adresse (TO-Feld: alle Stationen)
BROADCAST_ADDR = b'\xff\xff\xff\xff'
# MFSK-8 SYNC-Preamble: 8 Symbole (v0.5)
# Costas-Array Ordnung 8 (maschinell verifiziert — alle 28 Differenzvektoren eindeutig)
# Ersetzt [7,0,7,0,7,0,7,0]: alle 8 Töne je einmal → Equalizer-Basis + optimale Autokorrelation
# Dauer: 8 × 32 ms = 256 ms
# → Breitband-Decoder kann SYNC ohne Vorabwissen über den Kanal finden
SYNC_SYMBOLS = [2, 0, 6, 7, 1, 4, 3, 5]
# RS(255,223) Parameter
RS_N = 255 # Codeword-Länge
RS_K = 223 # Nutzdaten pro Block
RS_T = 16 # Korrigierbare Byte-Fehler pro Block
RS_OVERHEAD = RS_N - RS_K # = 32 Byte FEC-Overhead
# ═══════════════════════════════════════════════════════════════════════
# FRAME-TYPEN
# ═══════════════════════════════════════════════════════════════════════
class FrameType:
WEATHER = 0x01 # Wetter-Telemetrie (14 Byte)
POSITION = 0x02 # GPS-Position (18 Byte)
STATION_TLM = 0x03 # Stations-Telemetrie (10 Byte)
ROTOR_STATUS = 0x10 # Rotor-Ist-Position ( 7 Byte)
ROTOR_CMD = 0x11 # Rotor-Steuerbefehl ( 5 Byte)
EMERG_BEACON = 0x20 # Notfall-Beacon (20 Byte)
EMERG_RSRC = 0x21 # Notfall-Ressourcenstatus ( 8 Byte)
SENSOR = 0x30 # Generische Sensor-TLV (variabel)
TEXT = 0x40 # Freitext / QSO-Fragment (variabel)
# 0x41 RESERVED (war: CQ-Anruf, entfernt — CQ via TEXT 0x40 + BROADCAST)
AUTH = 0x50 # HMAC-SHA256 Authentifizierung (bilateral, 20 Byte)
MGMT = 0xF0 # Protokoll-Management (variabel)
# Reverse-Mapping für Anzeige
_TYPE_NAMES = {v: k for k, v in vars(FrameType).items() if not k.startswith('_')}
def frame_type_name(t: int) -> str:
return _TYPE_NAMES.get(t, f"UNKNOWN(0x{t:02X})")
# ═══════════════════════════════════════════════════════════════════════
# RUFZEICHEN-CODEC (BASIS-40)
# ═══════════════════════════════════════════════════════════════════════
#
# 40 gültige Zeichen → jedes Zeichen = ein "Digit" in Basis 40
# 6 Zeichen passen in 40^6 = 4.096.000.000 < 2^32 → exakt 4 Byte
#
# Alphabet-Index:
# 0 = Leerzeichen (Padding)
# 1–10 = '0'–'9'
# 11–36 = 'A'–'Z'
# 37 = '/' 38 = '.' 39 = '-' (und '+' als Index 39 → in GUST reserviert)
_B40_ALPHABET = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/.-+"
def encode_callsign(call: str) -> bytes:
"""
Kodiert Rufzeichen (bis 6 Zeichen) in 4 Byte (Big-Endian, Basis-40).
Unbekannte Zeichen werden als Leerzeichen (Index 0) kodiert.
Beispiel: 'OE3GAS' → b'\\x0c\\x23\\x4f\\x9b'
"""
call = call.upper().strip().ljust(6)[:6]
n = 0
for c in reversed(call):
idx = _B40_ALPHABET.index(c) if c in _B40_ALPHABET else 0
n = n * 40 + idx
return n.to_bytes(4, 'big')
def decode_callsign(data: bytes) -> str:
"""
Dekodiert 4 Byte (Basis-40, Big-Endian) zurück zum Rufzeichen.
Trailing-Spaces werden entfernt.
"""
n = int.from_bytes(data[:4], 'big')
chars = []
for _ in range(6):
chars.append(_B40_ALPHABET[n % 40])
n //= 40
return ''.join(chars).strip()
def callsign_roundtrip_ok(call: str) -> bool:
"""Selbsttest: Encode → Decode muss das Original zurückgeben."""
return decode_callsign(encode_callsign(call)) == call.upper().strip()
# ═══════════════════════════════════════════════════════════════════════
# CRC-16 / CCITT-FALSE (Polynom 0x1021, Init 0xFFFF)
# ═══════════════════════════════════════════════════════════════════════
#
# CRC-Abdeckung: TYPE(1) + FROM(4) + PAYLOAD(var) — OHNE SYNC
# Der CRC schützt den gesamten Frame-Body vor Übertragungsfehlern,
# die vom Reed-Solomon nicht mehr korrigiert werden konnten.
def crc16(data: bytes, init: int = 0xFFFF) -> int:
"""
CRC-16/CCITT-FALSE über beliebige Bytes.
Gibt 16-Bit-Wert zurück (0x0000–0xFFFF).
"""
crc = init
for byte in data:
crc ^= byte << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) if (crc & 0x8000) else (crc << 1)
crc &= 0xFFFF
return crc
def crc16_bytes(data: bytes) -> bytes:
"""CRC-16 als 2 Byte Big-Endian."""
return struct.pack('>H', crc16(data))
def verify_crc(body: bytes, received_crc: bytes) -> bool:
"""Prüft ob CRC über body mit received_crc übereinstimmt."""
return crc16(body) == struct.unpack('>H', received_crc)[0]
# ═══════════════════════════════════════════════════════════════════════
# HMAC-AUTHENTIFIZIERUNG (Frame 0x50 — AUTH, GUST-S, Spec §3.5)
# ═══════════════════════════════════════════════════════════════════════
#
# Payload (20 Byte): TIMESTAMP(4) | REF_TYPE(1) | KEY_ID(1) | HMAC(14)
# HMAC-SHA256 über (Daten-Frame-Body + TIMESTAMP), truncated auf 14 Byte.
# Der TIMESTAMP referenziert den Daten-Frame (kein seq-Feld nötig) UND dient
# als Replay-Schutz (verify_auth prüft |jetzt - TIMESTAMP| <= max_age_s).
# stdlib hmac/hashlib — keine externen Abhängigkeiten.
def auth_tag(frame_body: bytes, timestamp: int, key: bytes) -> bytes:
"""
HMAC-SHA256 über Daten-Frame-Body + TIMESTAMP, truncated auf 14 Byte.
Args:
frame_body: Frame-Body des Daten-Frames (TYPE+CHANNEL+FROM+PAYLOAD,
ohne SYNC und ohne RS-Parität)
timestamp: Unix-Timestamp (uint32) — derselbe Wert wie im AUTH-Frame
key: Gemeinsamer HMAC-Schlüssel (32 Byte empfohlen)
Returns:
bytes: 14 Byte HMAC-SHA256 (truncated, ~112 Bit)
"""
msg = frame_body + struct.pack(">I", timestamp)
return hmac.new(key, msg, hashlib.sha256).digest()[:14]
def verify_auth(frame_body: bytes, timestamp: int,
tag: bytes, key: bytes,
max_age_s: int = 60) -> bool:
"""
Prüft einen AUTH-Frame: HMAC korrekt UND Timestamp nicht zu alt.
Verwendet hmac.compare_digest() gegen Timing-Angriffe.
Args:
frame_body: Frame-Body des Daten-Frames
timestamp: Unix-Timestamp aus dem AUTH-Frame
tag: 14-Byte HMAC aus dem AUTH-Frame (bytes ODER hex-String —
decode_auth() liefert hmac_tag als hex-String)
key: Gemeinsamer Schlüssel
max_age_s: Maximales Alter des Timestamps (Standard: 60 s)
Returns:
True wenn Tag korrekt UND Timestamp nicht zu alt, False sonst.
"""
import time
if abs(time.time() - timestamp) > max_age_s:
return False # Replay-Schutz (TIMESTAMP zu alt)
if isinstance(tag, str):
tag = bytes.fromhex(tag) # hex-String (aus decode_auth) → bytes
expected = auth_tag(frame_body, timestamp, key)
return hmac.compare_digest(expected, tag)
def encode_auth(timestamp: int, ref_type: int,
hmac_tag) -> bytes:
"""
Kodiert den AUTH-Frame Payload (0x50), 20 Byte.
Aufbau: TIMESTAMP(4) | REF_TYPE(1) | RESERVED(1)=0x00 | HMAC(14)
Byte 5 (ehemals KEY_ID) ist RESERVED = 0x00. Der Schlüssel-Lookup
erfolgt über das Rufzeichen im FROM-Feld des Daten-Frames; eine
separate KEY_ID ist überflüssig (ADR Juni 2026).
Args:
timestamp: Unix-Timestamp des Daten-Frames (uint32)
ref_type: Frame-Typ des Daten-Frames (z.B. 0x01 für WEATHER)
hmac_tag: 14-Byte HMAC-SHA256 (Ausgabe von auth_tag()) — bytes
oder hex-String
Returns:
bytes: 20 Byte Payload
"""
if isinstance(hmac_tag, str):
hmac_tag = bytes.fromhex(hmac_tag)
if len(hmac_tag) != 14:
raise ValueError(f"hmac_tag muss 14 Byte sein, erhalten: {len(hmac_tag)}")
return struct.pack(">IBB", timestamp, ref_type, 0x00) + hmac_tag
def decode_auth(payload: bytes) -> dict:
"""
Dekodiert den AUTH-Frame Payload (0x50).
Byte 5 (ehemals KEY_ID) ist RESERVED und wird ignoriert — der
Schlüssel-Lookup erfolgt über das Rufzeichen (FROM-Feld).
Returns:
dict mit: timestamp, ref_type, hmac_tag
hmac_tag wird als hex-String (28 Zeichen) zurückgegeben, nicht als bytes —
damit das Dict (über payload_decoded) JSON-serialisierbar bleibt und den
WebSocket-Broadcast nicht abbricht. verify_auth() akzeptiert beides.
"""
if len(payload) < 20:
raise ValueError(f"AUTH-Payload zu kurz: {len(payload)} < 20 Byte")
timestamp, ref_type = struct.unpack_from(">IB", payload, 0)
# Byte 5 = RESERVED (ehemals KEY_ID), ignorieren
return {
"timestamp": timestamp,
"ref_type": ref_type,
"hmac_tag": payload[6:20].hex(),
}
# ═══════════════════════════════════════════════════════════════════════
# PAYLOAD-ENCODER / DECODER
# ═══════════════════════════════════════════════════════════════════════
#
# Jeder Encoder gibt bytes zurück, jeder Decoder ein Dict.
# Struct-Formate: '>' = Big-Endian (Netzwerkreihenfolge)
# 'x' = 1 Byte Padding (kein Wert)
#
# Größenüberprüfung: Alle Payloads ≤ 20 Byte (Frame-Limit).
# ──────────────────────────────────────────────────────────────────────
# 0x01 WETTER-TELEMETRIE (14 Byte)
#
# Byte-Layout (mit Alignment-Padding nach Olivia-Konvention):
# 0–1 Temperatur int16 0,1 °C (-3276,8 bis 3276,7 °C)
# 2 Luftfeuchte uint8 % (0–100)
# 3 [padding]
# 4–5 Luftdruck uint16 0,1 hPa (0–6553,5 hPa)
# 6 Windgeschw. uint8 km/h (0–255)
# 7 [padding]
# 8–9 Windrichtung uint16 Grad (0–359)
# 10–11 Niederschlag uint16 0,1 mm/h (0–6553,5 mm/h)
# 12 UV-Index uint8 (0–11+)
# 13 Statusflags uint8 (bit0=Batterie, bit1=Sensorok)
# ──────────────────────────────────────────────────────────────────────
_WX_FMT = '>hBxHBxHHBB' # Ergibt exakt 14 Byte
def encode_weather(
temp_c: float,
humidity_pct: int,
pressure_hpa: float,
wind_kmh: int,
wind_deg: int,
rain_mm_h: float = 0.0,
uv_index: int = 0,
flags: int = 0,
) -> bytes:
"""Frame 0x01 — Wetter-Telemetrie (14 Byte)."""
return struct.pack(_WX_FMT,
int(round(temp_c * 10)),
int(humidity_pct) & 0xFF,
int(round(pressure_hpa * 10)),
int(wind_kmh) & 0xFF,
int(wind_deg) % 360,
int(round(rain_mm_h * 10)),
int(uv_index) & 0xFF,
int(flags) & 0xFF,
)
def decode_weather(payload: bytes) -> dict:
"""Frame 0x01 → Dict."""
t, hum, press, wspd, wdir, rain, uv, flags = struct.unpack(_WX_FMT, payload[:14])
return {
"temp_c": t / 10,
"humidity_pct": hum,
"pressure_hpa": press / 10,
"wind_kmh": wspd,
"wind_deg": wdir,
"rain_mm_h": rain / 10,
"uv_index": uv,
"flags": flags,
"bat_ok": bool(flags & 0x01),
"sensor_ok": bool(flags & 0x02),
}
# ──────────────────────────────────────────────────────────────────────
# 0x02 POSITION (18 Byte)
#
# 0–3 Latitude int32 Mikrograd (-90.000.000 bis +90.000.000)
# 4–7 Longitude int32 Mikrograd (-180.000.000 bis +180.000.000)
# 8–9 Altitude int16 Meter (-32768 bis +32767 m)
# 10 Speed uint8 km/h (0–255)
# 11 [padding]
# 12–13 Heading uint16 Grad (0–359)
# 14–15 Timestamp uint16 Modulo 65536 s (~18 Stunden Rollover)
# 16–17 Flags uint16 (bit0=mobil, bit1=GPS-Fix, bit2=Notfall)
# ──────────────────────────────────────────────────────────────────────
_POS_FMT = '>iihBxHHH' # Ergibt exakt 18 Byte
# Statusflag-Bits für Position
POS_FLAG_MOBILE = 0x0001
POS_FLAG_GPS_FIX = 0x0002
POS_FLAG_EMERGENCY = 0x0004
def encode_position(
lat_deg: float,
lon_deg: float,
alt_m: int = 0,
speed_kmh: int = 0,
heading_deg: int = 0,
timestamp: int = 0,
flags: int = 0,
) -> bytes:
"""Frame 0x02 — Position (18 Byte). lat/lon in Dezimalgrad."""
return struct.pack(_POS_FMT,
int(round(lat_deg * 1_000_000)),
int(round(lon_deg * 1_000_000)),
int(alt_m),
int(speed_kmh) & 0xFF,
int(heading_deg) % 360,
int(timestamp) & 0xFFFF,
int(flags) & 0xFFFF,
)
def decode_position(payload: bytes) -> dict:
"""Frame 0x02 → Dict."""
lat, lon, alt, spd, hdg, ts, flags = struct.unpack(_POS_FMT, payload[:18])
return {
"lat_deg": lat / 1_000_000,
"lon_deg": lon / 1_000_000,
"alt_m": alt,
"speed_kmh": spd,
"heading_deg": hdg,
"timestamp": ts,
"flags": flags,
"mobile": bool(flags & POS_FLAG_MOBILE),
"gps_fix": bool(flags & POS_FLAG_GPS_FIX),
"emergency": bool(flags & POS_FLAG_EMERGENCY),
}
# ──────────────────────────────────────────────────────────────────────
# 0x03 STATIONS-TELEMETRIE (10 Byte)
#
# 0–1 Versorgungsspannung uint16 mV (0–65535 mV = 0–65,5 V)
# 2–3 Stromaufnahme uint16 mA (0–65535 mA)
# 4–5 Innentemperatur int16 0,1°C
# 6 CPU-Auslastung uint8 %
# 7–8 Betriebszeit uint16 Min (~45 Tage)
# 9 Statusflags uint8
# ──────────────────────────────────────────────────────────────────────
_STN_FMT = '>HHhBHB' # 10 Byte
def encode_station_tlm(
voltage_mv: int,
current_ma: int,
temp_c: float,
cpu_pct: int,
uptime_min: int,
flags: int = 0,
) -> bytes:
"""Frame 0x03 — Stations-Telemetrie (10 Byte)."""
return struct.pack(_STN_FMT,
int(voltage_mv) & 0xFFFF,
int(current_ma) & 0xFFFF,
int(round(temp_c * 10)),
int(cpu_pct) & 0xFF,
int(uptime_min) & 0xFFFF,
int(flags) & 0xFF,
)
def decode_station_tlm(payload: bytes) -> dict:
"""Frame 0x03 → Dict."""
v, i, t, cpu, uptime, flags = struct.unpack(_STN_FMT, payload[:10])
return {
"voltage_v": v / 1000,
"current_ma": i,
"temp_c": t / 10,
"cpu_pct": cpu,
"uptime_min": uptime,
"flags": flags,
}
# ──────────────────────────────────────────────────────────────────────
# 0x10 ROTOR-STATUS (7 Byte)
# 0x11 ROTOR-STEUERBEFEHL (5 Byte)
#
# Azimut/Elevation in 0,1° Auflösung → uint16 / int16
# ──────────────────────────────────────────────────────────────────────
_ROT_STATUS_FMT = '>HhHB' # az(2) + el(2[signed]) + target_az(2) + flags(1) = 7 Byte
_ROT_CMD_FMT = '>HhB' # target_az(2) + target_el(2[signed]) + cmd(1) = 5 Byte
# Rotor-Befehle
ROTOR_STOP = 0x00
ROTOR_MOVE = 0x01
ROTOR_PARK = 0x02
def encode_rotor_status(
azimuth_deg: float,
elevation_deg: float,
target_az_deg: float = 0.0,
flags: int = 0,
) -> bytes:
"""Frame 0x10 — Rotor-Status (7 Byte). Winkel in Dezimalgrad."""
return struct.pack(_ROT_STATUS_FMT,
int(round(azimuth_deg * 10)) & 0xFFFF, # 0–3599 (0,0°–359,9°)
int(round(elevation_deg * 10)), # signed: -900 bis +900
int(round(target_az_deg * 10)) & 0xFFFF,
int(flags) & 0xFF,
)
def decode_rotor_status(payload: bytes) -> dict:
az, el, t_az, flags = struct.unpack(_ROT_STATUS_FMT, payload[:7])
return {
"azimuth_deg": az / 10,
"elevation_deg": el / 10,
"target_az_deg": t_az / 10,
"flags": flags,
}
def encode_rotor_cmd(
target_az_deg: float,
target_el_deg: float = 0.0,
command: int = ROTOR_MOVE,
) -> bytes:
"""Frame 0x11 — Rotor-Steuerbefehl (5 Byte)."""
return struct.pack(_ROT_CMD_FMT,
int(round(target_az_deg * 10)) & 0xFFFF,
int(round(target_el_deg * 10)),
int(command) & 0xFF,
)
def decode_rotor_cmd(payload: bytes) -> dict:
t_az, t_el, cmd = struct.unpack(_ROT_CMD_FMT, payload[:5])
cmd_names = {ROTOR_STOP: "STOP", ROTOR_MOVE: "MOVE", ROTOR_PARK: "PARK"}
return {
"target_az_deg": t_az / 10,
"target_el_deg": t_el / 10,
"command": cmd,
"command_str": cmd_names.get(cmd, f"UNKNOWN({cmd})"),
}
# Prioritätsstufen (Bits 7–6 des Flags-Byte) — ICS-213 / ARRL NTS konform
PRIO_ROUTINE = 0b00 # Routine
PRIO_WELFARE = 0b01 # Wohlbefinden / Info
PRIO_URGENT = 0b10 # Dringend
PRIO_EMERGENCY = 0b11 # Notfall — unmittelbare Lebensgefahr
# Aliases für Rückwärtskompatibilität (deprecated, werden in v0.4 entfernt)
PRIO_LOW = PRIO_ROUTINE
PRIO_MEDIUM = PRIO_WELFARE
PRIO_HIGH = PRIO_URGENT
# PRIO_URGENT already defined above — no alias needed
# Verletzungsgrad (Bits 5–4 des Flags-Byte)
INJR_UNKNOWN = 0b00
INJR_MINOR = 0b01
INJR_SERIOUS = 0b10
INJR_CRITICAL = 0b11
# Rückwärtskompatibilität: alte Namen INJURY_* → INJR_* (deprecated, v0.4 entfernt).
# Konservativ ergänzt: externe Module (gust.py, gust_gateway.py, gust_tx_test.py,
# gust_hackrf_diag.py) sowie der Legacy-Smoke-Test importieren noch INJURY_*.
# Diese Aliase halten sie lauffähig, ohne die anderen Dateien zu ändern.
INJURY_UNKNOWN = INJR_UNKNOWN
INJURY_MINOR = INJR_MINOR
INJURY_SERIOUS = INJR_SERIOUS
INJURY_CRITICAL = INJR_CRITICAL
# Status-Bits (Bits 3–0 des Flags-Byte)
FLAG_GPS = 0x08 # Bit 3: GPS-Fix gültig
FLAG_BAT = 0x04 # Bit 2: Batterie OK
FLAG_RLY = 0x02 # Bit 1: Relay-Request
# Ressourcen-Flags (Offset 11) — alle 8 Bit definiert
# Nach ICS Resource Management (FEMA) und OCHA Humanitarian Glossary
RSRC_MEDICAL = 0x01 # Bit 0: Sanitäter / Arzt
RSRC_FIRE = 0x02 # Bit 1: Feuerwehr
RSRC_RESCUE = 0x04 # Bit 2: Technische Rettung
RSRC_WATER = 0x08 # Bit 3: Wasser / Lebensmittel
RSRC_SHELTER = 0x10 # Bit 4: Unterkunft
RSRC_COMMS = 0x20 # Bit 5: Kommunikationsunterstützung
RSRC_TRANSPORT = 0x40 # Bit 6: Transport / Fahrzeuge
RSRC_HAZMAT = 0x80 # Bit 7: HAZMAT-Team
# Rückwärtskompatibilität: alter Name RSRC_FOOD → RSRC_WATER (gleiche Semantik)
RSRC_FOOD = RSRC_WATER
# Rückwärtskompatibilität: alter Name RSRC_EVAC → RSRC_TRANSPORT
RSRC_EVAC = RSRC_TRANSPORT
# Ereignistyp-Kodes (Offset 9) — abgeleitet aus OASIS CAP v1.2
EVTYPE_FIRE = 0x01
EVTYPE_FLOOD = 0x02
EVTYPE_MEDICAL = 0x03
EVTYPE_SAR = 0x04 # Search and Rescue
EVTYPE_INFRA = 0x05 # Infrastrukturschaden
EVTYPE_QUAKE = 0x06
EVTYPE_MISSING = 0x07 # Vermisste Person(en)
EVTYPE_UNREST = 0x08 # Civil Unrest
EVTYPE_ACCIDENT = 0x09
EVTYPE_COLLAPSE = 0x0A # Gebäudeeinsturz
EVTYPE_STORM = 0x0B
EVTYPE_LANDSLIDE = 0x0C
EVTYPE_POWEROUT = 0x0D
EVTYPE_COMMSOUT = 0x0E
EVTYPE_EVAC = 0x0F # Evakuierung erforderlich
EVTYPE_CBRNE = 0x10
EVTYPE_MCI = 0x11 # Mass Casualty Incident
EVTYPE_WILDFIRE = 0x13
EVTYPE_OTHER = 0xFF
# ──────────────────────────────────────────────────────────────────────
# 0x20 NOTFALL-BEACON (20 Byte)
#
# 0– 3 Latitude int32 Mikrograd
# 4– 7 Longitude int32 Mikrograd
# 8 Personenanzahl uint8 (0x00=unbekannt, 0xFF=MCI)
# 9 Ereignistyp uint8 (EVTYPE_*, 0x00=ungültig)
# 10 Flags-Byte uint8 bits7-6=PRIO, bits5-4=INJR,
# bit3=GPS, bit2=BAT, bit1=RLY, bit0=res
# 11 Ressourcen uint8 Bitmask RSRC_* (angefordert)
# 12–13 Zeitstempel uint16 Sekunden mod 65536
# 14–19 Freitext 6 Byte ASCII, NUL-aufgefüllt
#
# struct-Format: '>iiB B B B H 6s' = 20 Byte
# ──────────────────────────────────────────────────────────────────────
_EMERG_FMT = '>iiB B B B H 6s' # 20 Byte
_PRIO_NAMES = {0: "ROUTINE", 1: "WELFARE", 2: "URGENT", 3: "EMERGENCY"}
_INJR_NAMES = {0: "UNKNOWN", 1: "MINOR", 2: "SERIOUS", 3: "CRITICAL"}
def encode_emergency_beacon(
lat_deg: float,
lon_deg: float,
persons: int,
event_type: int,
priority: int = PRIO_EMERGENCY,
injury: int = INJR_UNKNOWN,
status_flags: int = 0,
resource_flags: int = 0,
timestamp: int = 0,
text_snippet: str = "",
# Legacy parameter kept for call-site compatibility — ignored
injury_code: int = None,
) -> bytes:
"""Frame 0x20 — Notfall-Beacon (20 Byte, Protokoll v0.3+).
BREAKING CHANGE (v0.3 → 20-Byte-Layout):
Die POSITIONELLE Signatur hat sich gegenüber dem alten 16-Byte-Frame
geändert. Alt war (lat, lon, persons, injury_code, resource_flags,
priority, text_snippet); neu ist (lat, lon, persons, event_type,
priority, injury, status_flags, resource_flags, timestamp,
text_snippet). Alte positionelle Aufrufe brechen daher; Aufrufer
müssen auf Keyword-Argumente umgestellt werden. Das Legacy-Kwarg
`injury_code=` wird weiterhin akzeptiert (auf `injury` gemappt).
Flags-Byte (Offset 10):
bits 7-6 = priority (PRIO_ROUTINE … PRIO_EMERGENCY)
bits 5-4 = injury (INJR_UNKNOWN … INJR_CRITICAL)
bit 3 = GPS-Fix gültig (FLAG_GPS)
bit 2 = Batterie OK (FLAG_BAT)
bit 1 = Relay-Request (FLAG_RLY)
bit 0 = reserviert, immer 0
"""
# Legacy: if old-style injury_code kwarg was passed, use it
if injury_code is not None:
injury = injury_code
flags_byte = ((priority & 0x03) << 6) \
| ((injury & 0x03) << 4) \
| (status_flags & 0x0F)
snippet = text_snippet.encode('ascii', errors='replace')[:6]
snippet = snippet.ljust(6, b'\x00')
return struct.pack(_EMERG_FMT,
int(round(lat_deg * 1_000_000)),
int(round(lon_deg * 1_000_000)),
int(persons) & 0xFF,
int(event_type) & 0xFF,
flags_byte,
int(resource_flags) & 0xFF,
int(timestamp) & 0xFFFF,
snippet,
)
def decode_emergency_beacon(payload: bytes) -> dict:
"""Frame 0x20 → Dict."""
lat, lon, per, evt, flg, rsrc, ts, snip = \
struct.unpack(_EMERG_FMT, payload[:20])
prio = (flg >> 6) & 0x03
injr = (flg >> 4) & 0x03
return {
"lat_deg": lat / 1_000_000,
"lon_deg": lon / 1_000_000,
"persons": per,
"event_type": evt,
"priority": prio,
"priority_str": _PRIO_NAMES.get(prio, "?"),
"injury": injr,
"injury_str": _INJR_NAMES.get(injr, "?"),
"gps_fix": bool(flg & FLAG_GPS),
"battery_ok": bool(flg & FLAG_BAT),
"relay_request": bool(flg & FLAG_RLY),
"resource_flags": rsrc,
"needs_medical": bool(rsrc & RSRC_MEDICAL),
"needs_fire": bool(rsrc & RSRC_FIRE),
"needs_rescue": bool(rsrc & RSRC_RESCUE),
"needs_water": bool(rsrc & RSRC_WATER),
"needs_shelter": bool(rsrc & RSRC_SHELTER),
"needs_comms": bool(rsrc & RSRC_COMMS),
"needs_transport":bool(rsrc & RSRC_TRANSPORT),
"needs_hazmat": bool(rsrc & RSRC_HAZMAT),
"timestamp_s": ts,
"text_snippet": snip.rstrip(b'\x00 ').decode('ascii', 'replace'),
# Legacy keys for call-site compatibility
"resource_flags": rsrc,
"priority_str": _PRIO_NAMES.get(prio, "?"),
}
# ──────────────────────────────────────────────────────────────────────
# 0x21 NOTFALL-RESSOURCENSTATUS (8 Byte)
#
# Quittierung + Ressourcenrückmeldung für Frame 0x20.
# Wird directed gesendet (FROM = quittierungssender, Payload Byte4-7 =
# gequittierte Station).
#
# 0 Ereignistyp-Echo uint8 (spiegelt 0x20 Offset 9)
# 1 Verfügbare Ressourcen uint8 (gleiche Bitmask wie 0x20 Offset 11)
# 2 ETA in Minuten uint8 (0x00=sofort, 0xFF=unbekannt)
# 3 Flags uint8 (bit0=ACK, bit1=RLC, bits7-2=reserviert)
# 4–7 Gequittiertes Rufzeichen 4 Byte Basis-40
#
# struct-Format: '>BBBB4s' = 8 Byte
# ──────────────────────────────────────────────────────────────────────
_EMERG_RSRC_FMT = '>BBBB4s' # 8 Byte
# Flags für Frame 0x21
ACK_FLAG = 0x01 # Bit 0: immer 1 in gültigem EMERG_RSRC
RLC_FLAG = 0x02 # Bit 1: Relay-Confirm (Station leitet Meldung weiter)
def encode_emerg_rsrc(
event_type_echo: int,
avail_resources: int,
eta_minutes: int,
acked_callsign: str,
relay_confirm: bool = False,
) -> bytes:
"""Frame 0x21 — Notfall-Ressourcenstatus / ACK (8 Byte).
event_type_echo : EVTYPE_* aus dem empfangenen Frame 0x20
avail_resources : RSRC_* Bitmask — verfügbare (nicht angeforderte!) Ressourcen
eta_minutes : 0=sofort, 1-254=Minuten, 255=unbekannt
acked_callsign : Rufzeichen der Station, deren 0x20 quittiert wird
relay_confirm : True wenn diese Station die Meldung aktiv weiterleitet
"""
flags = ACK_FLAG
if relay_confirm:
flags |= RLC_FLAG
return struct.pack(_EMERG_RSRC_FMT,
int(event_type_echo) & 0xFF,
int(avail_resources) & 0xFF,
int(eta_minutes) & 0xFF,
flags,
encode_callsign(acked_callsign),
)
def decode_emerg_rsrc(payload: bytes) -> dict:
"""Frame 0x21 → Dict."""
evt, rsrc, eta, flags, call_raw = \
struct.unpack(_EMERG_RSRC_FMT, payload[:8])
return {
"event_type_echo": evt,
"avail_resources": rsrc,
"avail_medical": bool(rsrc & RSRC_MEDICAL),
"avail_fire": bool(rsrc & RSRC_FIRE),
"avail_rescue": bool(rsrc & RSRC_RESCUE),
"avail_water": bool(rsrc & RSRC_WATER),
"avail_shelter": bool(rsrc & RSRC_SHELTER),
"avail_comms": bool(rsrc & RSRC_COMMS),
"avail_transport": bool(rsrc & RSRC_TRANSPORT),
"avail_hazmat": bool(rsrc & RSRC_HAZMAT),
"eta_minutes": eta,
"ack_valid": bool(flags & ACK_FLAG),
"relay_confirm": bool(flags & RLC_FLAG),
"acked_callsign": decode_callsign(call_raw),
}
# ──────────────────────────────────────────────────────────────────────
# 0x40 FREITEXT / QSO-FRAGMENT (6 + bis zu 14 Byte Text = 20 Byte)
#
# 0–3 TO-Rufzeichen 4 Byte Basis-40 (0xFFFFFFFF = Broadcast)
# 4 Sequenz-Nr. uint8 (0–255, wraps around)
# 5 Fragment-Info uint8 (Bits 7-4: Fragment-Index 0-basiert,
# Bits 3-0: Gesamt-Fragments - 1)
# 6–19 UTF-8-Text max. 14 Byte
# ──────────────────────────────────────────────────────────────────────
def encode_text_fragment(
dest_call: str,
text: str,
seq_nr: int,
frag_index: int = 0,
frag_total: int = 1,
) -> bytes:
"""Frame 0x40 — Einzelnes Textfragment (max. 20 Byte Payload)."""
if dest_call.upper() == "BROADCAST" or dest_call == "":
dest = BROADCAST_ADDR
else:
dest = encode_callsign(dest_call)
frag_info = ((frag_index & 0x0F) << 4) | ((frag_total - 1) & 0x0F)
text_bytes = text.encode('utf-8')[:14]
return dest + bytes([seq_nr & 0xFF, frag_info]) + text_bytes
def decode_text_fragment(payload: bytes) -> dict:
"""Frame 0x40 → Dict."""
dest_raw = payload[:4]
dest = "BROADCAST" if dest_raw == BROADCAST_ADDR else decode_callsign(dest_raw)
seq_nr = payload[4]
frag_info = payload[5]
frag_idx = (frag_info >> 4) & 0x0F
frag_tot = (frag_info & 0x0F) + 1
text = payload[6:].decode('utf-8', errors='replace')
return {
"dest": dest,
"seq_nr": seq_nr,
"frag_index": frag_idx,
"frag_total": frag_tot,
"last_frag": (frag_idx == frag_tot - 1),
"text": text,
}
def fragment_text(
text: str,
dest_call: str,
seq_nr: int,
chunk_size: int = 14,
) -> list:
"""
Fragmentiert langen Text in mehrere Frame-0x40-Payloads.
Rückgabe: Liste von Payload-bytes, jeder ≤ 20 Byte.
Beispiel: 42-Zeichen-Text → 3 Fragmente à ≤14 Zeichen.
Übertragungsdauer: len(fragments) × ~2,1 s
"""
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
if not chunks:
chunks = [""]
return [
encode_text_fragment(dest_call, chunk, seq_nr, i, len(chunks))
for i, chunk in enumerate(chunks)
]
def reassemble_text(fragments: list) -> str:
"""
Setzt Fragment-Dicts (aus decode_text_fragment) wieder zusammen.
Erwartet vollständige und sortierte Fragment-Liste.
"""
sorted_frags = sorted(fragments, key=lambda f: f["frag_index"])
return "".join(f["text"] for f in sorted_frags)
# ──────────────────────────────────────────────────────────────────────
# 0x41 RESERVED (war: CQ-Anruf, entfernt)
# CQ-Rufe werden als TEXT-Frame (0x40) mit dest=BROADCAST gesendet.
# ──────────────────────────────────────────────────────────────────────
# ═══════════════════════════════════════════════════════════════════════
# FRAME-BUILDER & PARSER
# ═══════════════════════════════════════════════════════════════════════
def build_frame(frame_type: int, callsign: str, payload: bytes,
channel: int, test: bool = False) -> bytes:
"""
Baut den vollständigen GUST Frame-Body (ohne SYNC, ohne RS-FEC).
Aufbau v0.3: TYPE(1) | CHANNEL(1) | FROM(4) | PAYLOAD(1–20) | CRC(2)
CHANNEL-Byte: Bits 3–0 = Kanal 0–9, Bit 7 = TEST-Flag, Bits 4–6 = reserviert
CRC deckt: TYPE + CHANNEL + FROM + PAYLOAD (alles außer CRC selbst)
SYNC wird erst in frame_to_symbol_stream() vorangestellt.
Returns: bytes, Länge = 8 + len(payload) (9–28 Byte)
"""
if not (1 <= len(payload) <= 20):
raise ValueError(f"Payload-Länge {len(payload)} außerhalb 1–20 Byte")
from_bytes = encode_callsign(callsign)
ch_byte = (channel & 0x0F) | (FRAME_FLAG_TEST if test else 0)
body_without_crc = (bytes([frame_type, ch_byte])
+ from_bytes + payload)
crc = crc16_bytes(body_without_crc)
return body_without_crc + crc
def parse_frame(data: bytes) -> Optional[dict]:
"""
Parst einen Frame-Body v0.3 (ohne SYNC, ohne RS-FEC).
Aufbau: TYPE(1) | CHANNEL(1) | FROM(4) | PAYLOAD(var) | CRC(2)
Returns: Dict mit 'type', 'channel', 'from', 'payload', 'crc_ok'
oder None bei zu kurzem/korruptem Frame.
"""
# Minimum: TYPE(1) + CHANNEL(1) + FROM(4) + PAYLOAD(1) + CRC(2) = 9 Byte
if len(data) < 9:
return None
body = data[:-2]
crc_bytes = data[-2:]
crc_ok = verify_crc(body, crc_bytes)
return {
"type": body[0],
"type_name": frame_type_name(body[0]),
"channel": body[1] & 0x0F,
"test": bool(body[1] & FRAME_FLAG_TEST),
"from": decode_callsign(body[2:6]),
"payload": body[6:],
"crc_ok": crc_ok,
}
def decode_payload(frame_type: int, payload: bytes) -> Optional[dict]:
"""
Dispatcher: Dekodiert Payload je nach Frame-Typ.
Returns None für unbekannte Typen.
"""
decoders = {
FrameType.WEATHER: decode_weather,
FrameType.POSITION: decode_position,
FrameType.STATION_TLM: decode_station_tlm,
FrameType.ROTOR_STATUS: decode_rotor_status,
FrameType.ROTOR_CMD: decode_rotor_cmd,
FrameType.EMERG_BEACON: decode_emergency_beacon,
FrameType.EMERG_RSRC: decode_emerg_rsrc,
FrameType.TEXT: decode_text_fragment,
FrameType.AUTH: decode_auth,
}
decoder = decoders.get(frame_type)
if decoder:
try:
return decoder(payload)
except struct.error as e:
return {"error": str(e)}
return None
# ═══════════════════════════════════════════════════════════════════════
# RS-FEC WRAPPER (Reed-Solomon, via reedsolo)
# ═══════════════════════════════════════════════════════════════════════
#
# RS(255,223): 32 Byte Overhead, korrigiert 16 Byte-Fehler.
# Für kurze GUST-Frames (7–27 Byte) wird shortened RS verwendet:
# Wir kodieren mit RS(7+n, n) durch Zero-Padding auf K=223 Byte.
# Das ist Standard-Verhalten von reedsolo.
if _RS_AVAILABLE:
_rs_codec = reedsolo.RSCodec(RS_OVERHEAD) # nsym=32 Fehlerkorrektur-Bytes
def _rs_encode_raw(data: bytes) -> bytes:
"""
Rohe Reed-Solomon(255,223)-Kodierung — immer RS, KEIN Backend-Dispatch.
Gibt data + 32 Byte RS-Parität zurück.
Wird vom RS-FEC-Backend (gust_fec.ReedSolomonFEC) intern verwendet.
Getrennt von rs_encode(), weil rs_encode() an das aktive Backend
weiterleitet — würde das RS-Backend rs_encode() aufrufen, entstünde
eine Endlosrekursion.
"""
if not _RS_AVAILABLE:
raise RuntimeError("reedsolo nicht installiert")
return bytes(_rs_codec.encode(data))
def _rs_decode_raw(data: bytes) -> bytes:
"""
Rohe Reed-Solomon-Dekodierung — immer RS, KEIN Backend-Dispatch.
Korrigiert bis zu 16 Byte-Fehler, gibt die Nutzdaten zurück.
Wirft reedsolo.ReedSolomonError bei nicht korrigierbarem Fehler.
"""
if not _RS_AVAILABLE:
raise RuntimeError("reedsolo nicht installiert")
decoded, _, _ = _rs_codec.decode(data)
return bytes(decoded)
# ── FEC-Backend (ADR-24) ──────────────────────────────────────────────
# Standard: RS (produktiv). LDPC: opt-in per set_fec_backend().
# Wird von gust.py beim Start gesetzt wenn gateway.json "fec": "ldpc" enthält.
#
# rs_encode()/rs_decode() leiten an das aktive Backend weiter (Default RS),
# damit die Schnittstelle für gust_modulator.py unverändert bleibt. Das
# RS-Backend (gust_fec.ReedSolomonFEC) ruft INTERN _rs_encode_raw/_rs_decode_raw
# auf — niemals rs_encode/rs_decode — sonst entstünde eine Endlosrekursion.
_fec_backend = None # None = lazy init beim ersten Aufruf → RS
def set_fec_backend(name: str) -> None:
"""
FEC-Backend global setzen.
Wird einmalig beim Daemon-Start aufgerufen (aus gust.py).
Args:
name: "rs" (Standard) oder "ldpc" (experimentell)
"""
global _fec_backend
from gust_fec import get_fec_backend
_fec_backend = get_fec_backend(name)
import logging
logging.getLogger("gust.frame").info(
"[FEC] Backend gewechselt: %s (overhead=%d B)",
name, _fec_backend.overhead
)
def _get_fec():
"""Lazy-Init: FEC-Backend holen, RS als Default."""
global _fec_backend
if _fec_backend is None:
from gust_fec import get_fec_backend
_fec_backend = get_fec_backend("rs")
return _fec_backend
def get_fec_overhead() -> int:
"""
Aktuellen FEC-Overhead in Bytes zurückgeben.
Für RS: RS_OVERHEAD (32). Für LDPC: abhängig von der Blockgröße
(variabel/shortened, erst nach dem ersten encode() bekannt → bis dahin
Fallback auf RS_OVERHEAD).
"""
fec = _get_fec()
return fec.overhead if fec.overhead > 0 else RS_OVERHEAD
def rs_encode(data: bytes) -> bytes:
"""
FEC-Kodierung (Backend per set_fec_backend() wählbar, Standard: RS).
Gibt data + Paritätsbytes zurück.
"""
return _get_fec().encode(data)
def rs_decode(data: bytes) -> bytes:
"""
FEC-Dekodierung (Backend per set_fec_backend() wählbar, Standard: RS).
Gibt die originalen Nutzdaten zurück.
Wirft backend-spezifische Exception bei nicht korrigierbaren Fehlern.
"""
return _get_fec().decode(data)
# ═══════════════════════════════════════════════════════════════════════
# BYTES → MFSK-8 SYMBOL-STREAM (Interface zu Phase 1 Modulator)
# ═══════════════════════════════════════════════════════════════════════
#
# Konvertierung: Jede Gruppe von 3 Bits wird ein Symbol (0–7).