Repository navigation
Expand file tree
/
Copy pathframsat1_decoder.py
More file actions
176 lines (148 loc) · 6.28 KB
/
Copy pathframsat1_decoder.py
File metadata and controls
176 lines (148 loc) · 6.28 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
"""FramSat-1 Telemetry and Frame Decoder.
Developed by Orbit NTNU (SatCom Team).
Licensed under MIT License.
"""
from datetime import datetime, timezone
import socket
import struct
import sys
EXPECTED_CALLSIGN = "LA1ORB"
GROUND_STATION_CALLSIGN = "LA1NGS"
def parse_framsat_telemetry(payload_bytes: bytes):
"""Parses FramSat-1 Housekeeping Telemetry (starting with 'FS1.0')."""
# 1. Health & Status Header (19 bytes, Big-Endian)
fmt_health = ">5sBBBHBHHI"
hdr_size = struct.calcsize(fmt_health)
if len(payload_bytes) < hdr_size:
print(f" Payload Raw Hex: {payload_bytes.hex().upper()}")
return
sign, bcn_id, bcn_type, rssi, cmd_count, eps_flags, reboots, v_mv, uptime = (
struct.unpack(fmt_health, payload_bytes[:hdr_size])
)
mode_str = (
"LEOP (Launch / Deployment Mode)"
if bcn_type == 2
else "DEFAULT (Nominal Orbit)"
)
v_bat = v_mv / 1000.0
uptime_hrs = uptime / 3600.0
rssi_str = f"-{rssi} dBm" if rssi > 0 else "N/A (No uplink signal received)"
print("\n ─── [ FramSat-1 Housekeeping Telemetry ] ───")
print(f" Signature: {sign.decode('ascii', errors='replace')}")
print(f" Beacon ID: #{bcn_id}")
print(f" Operating Mode: {mode_str}")
print(f" Satellite Uplink RSSI: {rssi_str}")
print(f" Telecommands Accepted: {cmd_count}")
print(f" EPS Flags: 0x{eps_flags:02X}")
print(f" OBC / EPS Reboot Count:{reboots}")
print(f" Battery Voltage: {v_bat:.3f} V ({v_mv} mV)")
print(f" Satellite Uptime: {uptime} s ({uptime_hrs:.2f} hours)")
# Strip the trailing 4-byte CRC-32 trailer from the frame if present
raw_sensors = payload_bytes[hdr_size : hdr_size + 180]
# Check if in LEOP mode and sensor array is unpopulated (zero-padding)
if bcn_type == 2 and all(b == 0 for b in raw_sensors):
print(
f"\n ─── [ Attitude Sensors (LEOP Mode) ] ───\n Status: "
f" Sensors unpowered during deployment ({len(raw_sensors)}"
" bytes zero-padded)."
)
return
# In Nominal Mode (or populated LEOP), unpack 20-byte sensor samples
num_samples = len(raw_sensors) // 20
if num_samples > 0:
print(f"\n ─── [ Attitude Sensors: {num_samples}x Samples ] ───")
print(" # | Time (s) | Sun Sensor GSS (a, b, c, d) | Earth Sensor ESS (x, y, illum)")
print(" ───+──────────+────────────────────────────────────────+─────────────────────────────")
sample_fmt = ">BHHHHBBBBBHI"
for i in range(min(num_samples, 9)):
chunk = raw_sensors[i * 20 : (i + 1) * 20]
if len(chunk) == 20:
s_id, g_a, g_b, g_c, g_d, e_x, e_y, i1, i2, i3, s_size, s_time = struct.unpack(sample_fmt, chunk)
gss_str = f"{g_a:5d}, {g_b:5d}, {g_c:5d}, {g_d:5d}"
ess_str = f"X={e_x:3d}, Y={e_y:3d}, Illum=[{i1},{i2},{i3}]"
print(f" {i+1:1d} | {s_time:<8d} | {gss_str:<38s} | {ess_str}")
def parse_framsat_frame(frame_bytes: bytes):
"""Parses a received frame (handles direct HDLC and AX.25 UI encapsulation)."""
# Strip KISS TNC framing encapsulation (e.g., from Direwolf or SoundModem)
if frame_bytes.startswith(b"\xc0\x00"):
frame_bytes = frame_bytes[2:]
elif frame_bytes.startswith(b"\xc0"):
frame_bytes = frame_bytes[1:]
if frame_bytes.endswith(b"\xc0"):
frame_bytes = frame_bytes[:-1]
# Unescape KISS transpositions (0xDB 0xDC -> 0xC0, 0xDB 0xDD -> 0xDB)
frame_bytes = frame_bytes.replace(b"\xdb\xdc", b"\xc0").replace(b"\xdb\xdd", b"\xdb")
if len(frame_bytes) < 5:
print("[-] Frame rejected: Length is less than 5 bytes.")
return
now_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
print("\n" + "=" * 65)
print(f"🛰️ FramSat-1 Frame Received at {now_utc}")
print(f" Total Frame Length: {len(frame_bytes)} bytes")
idx = frame_bytes.find(b"FS1.0")
if idx != -1:
print(f" Telemetry Found: Offset index {idx}")
if idx >= 16:
dest_call = "".join(chr(b >> 1) for b in frame_bytes[0:6]).strip()
src_call = "".join(chr(b >> 1) for b in frame_bytes[7:13]).strip()
print(f" Encapsulation: AX.25 UI-Frame ({src_call} -> {dest_call})")
print(f" Source: {src_call} (Expected: {EXPECTED_CALLSIGN})")
elif idx > 0:
print(
f" Transport Header: {frame_bytes[:idx].hex().upper()} ({idx}"
" bytes)"
)
else:
print(" Encapsulation: Direct HDLC (Payload starts at offset 0)")
parse_framsat_telemetry(frame_bytes[idx:])
else:
print(
f" Payload Text: "
f" '{frame_bytes.decode('latin-1', 'replace')}'"
)
print(f" Payload Raw Hex: {frame_bytes.hex().upper()}")
print("=" * 65 + "\n")
def listen_live_gnuradio(host="127.0.0.1", port=52001):
print(f"[*] Connecting to GNU Radio Socket PDU at {host}:{port}...")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("[+] Connected! Listening for live satellite passes...\n")
while True:
data = s.recv(1024)
if not data:
break
parse_framsat_frame(data)
except Exception as e:
print(f"[-] Connection failed: {e}")
finally:
s.close()
if __name__ == "__main__":
# Verified On-Orbit SatNOGS Downlink Frame (209 bytes, 11:01 UTC, 8.308 V Battery)
VERIFIED_ON_ORBIT_FRAME = (
"8500850000CF4653312E30B50200000000000120740000BD59"
+ "00" * 180
+ "CE47AF75"
)
if len(sys.argv) > 1:
if sys.argv[1] == "--listen":
listen_live_gnuradio()
else:
# Strip spaces, newlines, and carriage returns for clean copy-pasting
raw_hex = (
sys.argv[1]
.replace(" ", "")
.replace("\n", "")
.replace("\r", "")
.replace("0x", "")
)
parse_framsat_frame(bytes.fromhex(raw_hex))
else:
print(
"[*] No arguments provided. Running test against verified on-orbit"
" frame:\n"
)
parse_framsat_frame(bytes.fromhex(VERIFIED_ON_ORBIT_FRAME))
print("Usage:")
print(" python3 framsat1_decoder.py <HEX_STRING>")
print(" python3 framsat1_decoder.py --listen")