source: ntrip/trunk/BNC/tests/tools/bncraw.py

Last change on this file was 11215, checked in by stuerze, 2 weeks ago

Upload Ephemeris: majority vote included

  • Property svn:executable set to *
File size: 10.0 KB
Line 
1#!/usr/bin/env python3
2"""Helpers for BNC raw capture files (rawOutFile / --file format).
3
4File layout (see src/bncrawfile.cpp):
5 "1 Version of BNC raw file\n"
6 then repeated: "<ISO time> <staID> <format> <nBytes>\n" <nBytes raw bytes> "\n"
7
8Sub-commands:
9 info <raw> [<raw> ...] streams, byte counts, time span, RTCM3 message types
10 slice <raw> <out> [options] cut a time window / subset of stations
11 crs <raw> decode RTCM 1300/1301/1302 (CRS messages)
12 ephsats <raw> satellite IDs of the ephemeris messages
13"""
14
15import argparse
16import collections
17import sys
18
19HEADER = b"1 Version of BNC raw file\n"
20
21
22def read_chunks(path):
23 """Yield (time, staID, format, data) for every chunk of a raw file."""
24 with open(path, "rb") as f:
25 first = f.readline()
26 if b"Version of BNC raw file" not in first:
27 raise ValueError("%s: not a BNC raw file" % path)
28 while True:
29 line = f.readline()
30 if not line:
31 return
32 parts = line.split()
33 if len(parts) < 4:
34 raise ValueError("%s: bad chunk header %r" % (path, line[:80]))
35 n = int(parts[3])
36 data = f.read(n)
37 if len(data) != n:
38 raise ValueError("%s: truncated chunk" % path)
39 f.read(1) # trailing '\n'
40 yield parts[0].decode(), parts[1].decode(), parts[2].decode(), data
41
42
43def write_chunks(path, chunks):
44 with open(path, "wb") as o:
45 o.write(HEADER)
46 for t, sta, fmt, data in chunks:
47 o.write(("%s %s %s %d\n" % (t, sta, fmt, len(data))).encode())
48 o.write(data)
49 o.write(b"\n")
50
51
52# RTCM3 framing -----------------------------------------------------------
53
54def _crc24q_table():
55 tab = []
56 for i in range(256):
57 c = i << 16
58 for _ in range(8):
59 c <<= 1
60 if c & 0x1000000:
61 c ^= 0x1864CFB
62 tab.append(c & 0xFFFFFF)
63 return tab
64
65
66_CRC_TAB = _crc24q_table()
67
68
69def crc24q(buf):
70 crc = 0
71 for b in buf:
72 crc = ((crc << 8) & 0xFFFFFF) ^ _CRC_TAB[(crc >> 16) ^ b]
73 return crc
74
75
76class Rtcm3Framer:
77 """Incremental CRC-validated RTCM3 frame extractor (one per stream)."""
78
79 def __init__(self):
80 self.buf = bytearray()
81
82 def feed(self, data):
83 self.buf += data
84 frames = []
85 i = 0
86 buf = self.buf
87 while True:
88 i = buf.find(0xD3, i)
89 if i < 0 or len(buf) - i < 6:
90 break
91 length = ((buf[i + 1] & 0x03) << 8) | buf[i + 2]
92 if len(buf) - i < length + 6:
93 break
94 frame = bytes(buf[i:i + length + 6])
95 if crc24q(frame[:-3]) == int.from_bytes(frame[-3:], "big"):
96 frames.append(frame[3:-3])
97 i += length + 6
98 else:
99 i += 1
100 self.buf = buf[i:] if i >= 0 else bytearray()
101 return frames
102
103
104def msg_type(payload):
105 """Message number; for 4076 return '4076_<subtype>'."""
106 if len(payload) < 2:
107 return "empty"
108 t = (payload[0] << 4) | (payload[1] >> 4)
109 if t == 4076 and len(payload) >= 3:
110 # 12 bit type, 3 bit version, 8 bit subtype
111 sub = ((payload[1] & 0x01) << 7) | (payload[2] >> 1)
112 return "4076_%03d" % sub
113 return str(t)
114
115
116class BitReader:
117 def __init__(self, data):
118 self.data = data
119 self.pos = 0
120
121 def u(self, n):
122 v = 0
123 for _ in range(n):
124 if self.pos >= 8 * len(self.data):
125 raise ValueError("message too short")
126 v = (v << 1) | ((self.data[self.pos // 8] >> (7 - self.pos % 8)) & 1)
127 self.pos += 1
128 return v
129
130 def s(self, n):
131 v = self.u(n)
132 return v - (1 << n) if v >> (n - 1) else v
133
134 def text(self):
135 n = self.u(5)
136 return bytes(self.u(8) for _ in range(n)).decode("latin-1")
137
138 def left(self):
139 return 8 * len(self.data) - self.pos
140
141
142def decode_crs(p):
143 """One line per 1300/1301/1302 message (RTCM 10403.4, DF562-DF587)."""
144 r = BitReader(p)
145 t = r.u(12)
146 if t == 1300:
147 out = "1300 name %r CE %.2f" % (r.text(), r.u(16) / 100.0)
148 elif t == 1301:
149 src, tgt = r.text(), r.text()
150 out = "1301 source %r target %r sys %d util %d mjd %d par" % (
151 src, tgt, r.u(8), r.u(10), r.u(16) + 44244)
152 for n in (23, 23, 23, 32, 32, 32, 25, 17, 17, 17, 17, 17, 17, 14):
153 out += " %d" % r.s(n)
154 else:
155 out = "1302 name %r anchor %d plate %d links" % (r.text(), r.u(1), r.u(5))
156 out += " %r" % [r.text() for _ in range(r.u(3))]
157 if r.left() >= 8: # more than the padding to the byte boundary
158 out += " TRAILING %d bits" % r.left()
159 return out
160
161
162# Commands ----------------------------------------------------------------
163
164def cmd_info(args):
165 for path in args.files:
166 stats = collections.OrderedDict()
167 t0 = t1 = None
168 n = 0
169 for t, sta, fmt, data in read_chunks(path):
170 n += 1
171 t0 = t0 or t
172 t1 = t
173 s = stats.get(sta)
174 if s is None:
175 s = stats[sta] = {"fmt": fmt, "bytes": 0, "chunks": 0,
176 "framer": Rtcm3Framer(),
177 "types": collections.Counter()}
178 s["bytes"] += len(data)
179 s["chunks"] += 1
180 if fmt.upper().startswith("RTCM_3") or fmt.upper().startswith("RTCM3"):
181 for p in s["framer"].feed(data):
182 s["types"][msg_type(p)] += 1
183 print("%s: %d chunks %s -> %s" % (path, n, t0, t1))
184 for sta, s in stats.items():
185 print(" %-12s %-9s %10d bytes %6d chunks" %
186 (sta, s["fmt"], s["bytes"], s["chunks"]))
187 if s["types"]:
188 types = sorted(s["types"].items(),
189 key=lambda kv: (len(kv[0].split("_")[0]), kv[0]))
190 line = " "
191 for k, v in types:
192 item = "%s:%d " % (k, v)
193 if len(line) + len(item) > 100:
194 print(line)
195 line = " "
196 line += item
197 print(line)
198
199
200def frame(payload):
201 """RTCM3 frame (preamble, length, payload, CRC24Q) of a payload."""
202 head = bytes([0xD3, (len(payload) >> 8) & 0x03, len(payload) & 0xFF])
203 return head + payload + crc24q(head + payload).to_bytes(3, "big")
204
205
206def cmd_slice(args):
207 stations = set(args.stations.split(",")) if args.stations else None
208 types = args.types.split(",") if args.types else None
209 parsers = {}
210
211 def selected():
212 for t, sta, fmt, data in read_chunks(args.input):
213 if stations and sta not in stations:
214 continue
215 if args.start and t < args.start:
216 continue
217 if args.end and t >= args.end:
218 continue
219 if types:
220 # keep only the RTCM3 messages of the given types (or type prefixes)
221 frames = parsers.setdefault(sta, Rtcm3Framer()).feed(data)
222 kept = b"".join(frame(pl) for pl in frames
223 if any(msg_type(pl).startswith(tt) for tt in types))
224 if not kept:
225 continue
226 data = kept
227 yield t, sta, fmt, data
228
229 write_chunks(args.output, selected())
230
231
232def cmd_crs(args):
233 """Distinct CRS message contents per stream, with their number."""
234 stats = collections.OrderedDict()
235 framers = {}
236 for t, sta, fmt, data in read_chunks(args.input):
237 for p in framers.setdefault(sta, Rtcm3Framer()).feed(data):
238 if msg_type(p) in ("1300", "1301", "1302"):
239 try:
240 line = decode_crs(p)
241 except ValueError as e:
242 line = "%s %s" % (msg_type(p), e)
243 key = (sta, line)
244 stats[key] = stats.get(key, 0) + 1
245 for (sta, line), n in stats.items():
246 print("%s %4dx %s" % (sta, n, line))
247
248
249EPH_SYS = {"1019": ("G", 6), "1020": ("R", 6), "1041": ("I", 6), "1042": ("C", 6),
250 "1044": ("J", 4), "1045": ("E", 6), "1046": ("E", 6)}
251
252
253def cmd_ephsats(args):
254 """Satellite IDs of the ephemeris messages per stream and message type."""
255 sats = collections.OrderedDict()
256 framers = {}
257 for t, sta, fmt, data in read_chunks(args.input):
258 for p in framers.setdefault(sta, Rtcm3Framer()).feed(data):
259 mt = msg_type(p)
260 if mt in EPH_SYS:
261 sy, nb = EPH_SYS[mt]
262 b = BitReader(p)
263 b.u(12)
264 sats.setdefault((sta, mt), set()).add("%s%02d" % (sy, b.u(nb)))
265 for (sta, mt), s in sorted(sats.items()):
266 print("%s %s %s" % (sta, mt, " ".join(sorted(s))))
267
268
269def main():
270 ap = argparse.ArgumentParser(description=__doc__,
271 formatter_class=argparse.RawDescriptionHelpFormatter)
272 sub = ap.add_subparsers(dest="cmd", required=True)
273
274 p = sub.add_parser("info", help="summarise raw capture(s)")
275 p.add_argument("files", nargs="+")
276 p.set_defaults(func=cmd_info)
277
278 p = sub.add_parser("slice", help="cut a raw capture")
279 p.add_argument("input")
280 p.add_argument("output")
281 p.add_argument("--start", help="ISO time, inclusive (string compare, e.g. 2025-11-17T13:49)")
282 p.add_argument("--end", help="ISO time, exclusive")
283 p.add_argument("--stations", help="comma separated staIDs to keep")
284 p.add_argument("--types", help="comma separated RTCM3 message types or prefixes to keep, "
285 "e.g. 1019,4076_02 (GPS ephemerides and IGS-SSR GPS messages)")
286 p.set_defaults(func=cmd_slice)
287
288 p = sub.add_parser("crs", help="decode CRS messages 1300/1301/1302")
289 p.add_argument("input")
290 p.set_defaults(func=cmd_crs)
291
292 p = sub.add_parser("ephsats", help="satellite IDs of the ephemeris messages")
293 p.add_argument("input")
294 p.set_defaults(func=cmd_ephsats)
295
296 args = ap.parse_args()
297 args.func(args)
298
299
300if __name__ == "__main__":
301 sys.exit(main())
Note: See TracBrowser for help on using the repository browser.