Skip to content

Commit fa94c7b

Browse files
committed
add file-streaming parser and diagnostic telemetry statistics
1 parent 46273a4 commit fa94c7b

4 files changed

Lines changed: 270 additions & 37 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ Tests cover:
8181
- Parameter extraction using **absolute bit indexing** (`start_bit`)
8282
- VEC/PRM/FRED‑based configuration
8383
- Raw‑byte convenience decoding via `decode_raw_bytes()`
84+
- File-streaming support for multi-gigabyte logs via `iter_frames_from_file()` (chunk-by-chunk processing with memory efficiency)
85+
- Diagnostic telemetry reporting via `parse_with_stats()` and `Arinc767ParseResult` (tracking valid counts, gaps, total gap bytes, and trailer mismatches)
86+
- Robust stream controls:
87+
- `strict` mode parsing (rejecting invalid lengths or trailer mismatches)
88+
- `max_gap` threshold enforcement
89+
- `max_frames` safety limits
8490
- Full data‑type support:
8591
- BNR (signed/unsigned)
8692
- BCD

‎examples/process_flight_767.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from pathlib import Path
33

44
from pyarinc.arinc767.decoder import Arinc767Decoder
5+
from pyarinc.arinc767.parser import Arinc767FrameParser
56
from pyarinc.arinc767.vec_parser import parse_vec_file_767, vec_to_parameters_767
67
from pyarinc.io.csv_export import export_csv
78
from pyarinc.io.parquet_export import export_parquet
@@ -22,6 +23,17 @@ def process_flight_767_data(
2223
raw_bytes = z.read(inner_filename)
2324

2425
print(f"Loaded {len(raw_bytes)} bytes of raw flight data.")
26+
print("Analyzing stream health with Arinc767FrameParser.parse_with_stats()...")
27+
stats = Arinc767FrameParser.parse_with_stats(raw_bytes)
28+
print("--- Stream Health Diagnostics ---")
29+
print(f" Total Bytes Processed : {stats.total_bytes_processed}")
30+
print(f" Valid Frames Found : {stats.valid_frames_count}")
31+
print(
32+
f" Gaps Encountered : {stats.gaps_encountered} (Total gap bytes: {stats.total_gap_bytes})"
33+
)
34+
print(f" Trailer Mismatches : {stats.trailer_mismatches}")
35+
print(f" Embedded Headers : {stats.embedded_headers_detected}")
36+
print("--------------------------------")
2537

2638
print("Decoding ARINC 767 parameters using Arinc767Decoder...")
2739
decoder = Arinc767Decoder(list(parameters.values()), frames_per_second=1.0)

‎pyarinc/arinc767/parser.py‎

Lines changed: 193 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import logging
44
import struct
55
from collections.abc import Iterable
6+
from dataclasses import dataclass, field
7+
from pathlib import Path
68

79
from .frame import Arinc767Frame
810

@@ -12,8 +14,21 @@
1214
_STRUCT_U32 = struct.Struct(">I")
1315

1416

17+
@dataclass
18+
class Arinc767ParseResult:
19+
"""Diagnostic container for parsing statistics and frames."""
20+
21+
frames: list[Arinc767Frame] = field(default_factory=list)
22+
total_bytes_processed: int = 0
23+
valid_frames_count: int = 0
24+
gaps_encountered: int = 0
25+
total_gap_bytes: int = 0
26+
trailer_mismatches: int = 0
27+
embedded_headers_detected: int = 0
28+
29+
1530
class Arinc767FrameParser:
16-
"""Parse ARINC 767 frames from raw byte stream."""
31+
"""Parse ARINC 767 frames from raw byte streams or massive files with telemetry diagnostics."""
1732

1833
SYNC_WORD: int = 0xEB90
1934
"""Sync word constant: 0xEB90 (big-endian)."""
@@ -93,35 +108,39 @@ def find_valid_frame_start(data: bytes, start_pos: int) -> tuple[int, int] | Non
93108
@staticmethod
94109
def parse_frame(
95110
data: bytes, frame_start: int, frame_index: int, strict: bool = False
96-
) -> Arinc767Frame | None:
97-
"""Parse a single frame starting at frame_start byte offset."""
111+
) -> tuple[Arinc767Frame | None, bool]:
112+
"""Parse a single frame starting at frame_start byte offset.
113+
114+
Returns:
115+
Tuple of (Arinc767Frame or None, trailer_mismatch_occurred_bool)
116+
"""
98117
if frame_start + Arinc767FrameParser.HEADER_SIZE > len(data):
99118
logger.debug(
100119
f"Frame {frame_index}: not enough data for header at offset {frame_start:#x}"
101120
)
102-
return None
121+
return None, False
103122

104123
try:
105124
sync = _STRUCT_U16.unpack(data[frame_start : frame_start + 2])[0]
106125
except struct.error:
107126
logger.debug(
108127
f"Frame {frame_index}: failed to read sync at offset {frame_start:#x}"
109128
)
110-
return None
129+
return None, False
111130

112131
if sync != Arinc767FrameParser.SYNC_WORD:
113132
logger.debug(
114133
f"Frame {frame_index}: sync mismatch (expected 0x{Arinc767FrameParser.SYNC_WORD:04x}, got 0x{sync:04x})"
115134
)
116-
return None
135+
return None, False
117136

118137
try:
119138
frame_len = _STRUCT_U16.unpack(data[frame_start + 2 : frame_start + 4])[0]
120139
except struct.error:
121140
logger.debug(
122141
f"Frame {frame_index}: failed to read frame length at offset {frame_start:#x}"
123142
)
124-
return None
143+
return None, False
125144

126145
if (
127146
frame_len < Arinc767FrameParser.MIN_FRAME_SIZE
@@ -130,7 +149,7 @@ def parse_frame(
130149
logger.debug(
131150
f"Frame {frame_index}: invalid length {frame_len} (expected 14-2048) at offset {frame_start:#x}"
132151
)
133-
return None
152+
return None, False
134153

135154
if strict and frame_len != (
136155
Arinc767FrameParser.HEADER_SIZE
@@ -140,14 +159,14 @@ def parse_frame(
140159
logger.debug(
141160
f"Frame {frame_index}: strict length match failure at offset {frame_start:#x}"
142161
)
143-
return None
162+
return None, False
144163

145164
if frame_start + frame_len > len(data):
146165
logger.debug(
147166
f"Frame {frame_index}: frame extends beyond buffer "
148167
f"(start={frame_start:#x}, len={frame_len}, buf_len={len(data)})"
149168
)
150-
return None
169+
return None, False
151170

152171
try:
153172
timestamp_ms = _STRUCT_U32.unpack(data[frame_start + 4 : frame_start + 8])[
@@ -157,7 +176,7 @@ def parse_frame(
157176
logger.debug(
158177
f"Frame {frame_index}: failed to read timestamp at offset {frame_start:#x}"
159178
)
160-
return None
179+
return None, False
161180

162181
try:
163182
frame_type_id = _STRUCT_U16.unpack(
@@ -167,7 +186,7 @@ def parse_frame(
167186
logger.debug(
168187
f"Frame {frame_index}: failed to read frame type/id at offset {frame_start:#x}"
169188
)
170-
return None
189+
return None, False
171190

172191
frame_type = (frame_type_id >> 8) & 0xFF
173192
frame_id = frame_type_id & 0xFF
@@ -186,14 +205,16 @@ def parse_frame(
186205
logger.debug(
187206
f"Frame {frame_index}: frame too small at offset {frame_start:#x}"
188207
)
189-
return None
208+
return None, False
190209

210+
trailer_mismatch = False
191211
if not frame.validate_trailer():
212+
trailer_mismatch = True
192213
if strict:
193214
logger.debug(
194215
f"Frame {frame_index}: trailer mismatch (strict mode) at offset {frame_start:#x}"
195216
)
196-
return None
217+
return None, True
197218
logger.warning(
198219
f"Frame {frame_index}: trailer type/id mismatch "
199220
f"(header: type=0x{frame_type:02x}, id=0x{frame_id:02x}) at offset {frame_start:#x}"
@@ -202,7 +223,7 @@ def parse_frame(
202223
logger.debug(
203224
f"Frame {frame_index}: parsed successfully at offset {frame_start:#x} (len={frame_len})"
204225
)
205-
return frame
226+
return frame, trailer_mismatch
206227

207228
@staticmethod
208229
def iter_frames(
@@ -227,22 +248,13 @@ def iter_frames(
227248
while pos < len(data) and frame_index < max_frames:
228249
result = Arinc767FrameParser.find_valid_frame_start(data, pos)
229250
if result is None:
230-
if pos < len(data):
231-
remaining = len(data) - pos
232-
logger.debug(
233-
f"End of frame stream: {remaining} bytes remaining at offset {pos:#x}"
234-
)
235251
break
236252

237253
frame_start, frame_len = result
238254

239-
# Gap tracking & threshold enforcement
240255
if frame_start > pos:
241256
gap_size = frame_start - pos
242257
if strict:
243-
logger.debug(
244-
f"Strict mode: gap of {gap_size} bytes rejected at offset {frame_start:#x}"
245-
)
246258
return
247259
if max_gap is not None and gap_size > max_gap:
248260
logger.warning(
@@ -270,7 +282,7 @@ def iter_frames(
270282
pos = inner_sync
271283
continue
272284

273-
frame = Arinc767FrameParser.parse_frame(
285+
frame, _ = Arinc767FrameParser.parse_frame(
274286
data, frame_start, frame_index, strict=strict
275287
)
276288
if frame is not None:
@@ -293,10 +305,163 @@ def iter_frames(
293305

294306
pos = frame_start + frame_len
295307

296-
if frame_index >= max_frames:
297-
logger.warning(
298-
f"Maximum frame limit ({max_frames}) reached during parsing."
308+
@staticmethod
309+
def parse_with_stats(
310+
data: bytes,
311+
strict: bool = False,
312+
timestamp_wrap: bool = False,
313+
max_gap: int | None = None,
314+
max_frames: int = 500000,
315+
) -> Arinc767ParseResult:
316+
"""Parse frames from buffer and compile complete diagnostic statistics."""
317+
stats = Arinc767ParseResult(total_bytes_processed=len(data))
318+
if b"\xEB\x90" not in data:
319+
return stats
320+
321+
pos = 0
322+
frame_index = 0
323+
last_gap_pos = None
324+
last_timestamp = None
325+
cumulative_offset = 0
326+
327+
while pos < len(data) and frame_index < max_frames:
328+
result = Arinc767FrameParser.find_valid_frame_start(data, pos)
329+
if result is None:
330+
break
331+
332+
frame_start, frame_len = result
333+
334+
if frame_start > pos:
335+
gap_size = frame_start - pos
336+
if strict:
337+
break
338+
stats.gaps_encountered += 1
339+
stats.total_gap_bytes += gap_size
340+
if max_gap is not None and gap_size > max_gap:
341+
logger.warning(
342+
f"Large gap detected: {gap_size} bytes exceeds max_gap threshold ({max_gap}) at {frame_start:#x}"
343+
)
344+
if frame_start != last_gap_pos:
345+
logger.warning(
346+
f"Frame {frame_index}: gap of {gap_size} bytes before frame at offset {frame_start:#x}"
347+
)
348+
last_gap_pos = frame_start
349+
350+
inner_sync = None
351+
end_search = min(frame_start + frame_len, len(data) - 1)
352+
for i in range(frame_start + 1, end_search):
353+
if Arinc767FrameParser._looks_like_frame_start(data, i):
354+
inner_sync = i
355+
break
356+
357+
if inner_sync is not None:
358+
stats.embedded_headers_detected += 1
359+
logger.warning(
360+
f"Frame {frame_index}: embedded frame header detected at "
361+
f"{inner_sync:#x} inside frame starting at {frame_start:#x}; "
362+
f"resuming parse from inner frame"
363+
)
364+
pos = inner_sync
365+
continue
366+
367+
frame, trailer_mismatch = Arinc767FrameParser.parse_frame(
368+
data, frame_start, frame_index, strict=strict
299369
)
370+
if trailer_mismatch:
371+
stats.trailer_mismatches += 1
372+
373+
if frame is not None:
374+
ts = frame.timestamp_ms
375+
if timestamp_wrap:
376+
if last_timestamp is not None and ts < last_timestamp:
377+
cumulative_offset += 24 * 3600 * 1000
378+
ts_adj = ts + cumulative_offset
379+
frame.timestamp_ms = ts_adj
380+
last_timestamp = ts_adj
381+
else:
382+
if last_timestamp is not None and ts < last_timestamp:
383+
logger.warning(
384+
f"Frame {frame_index}: timestamp regression detected ({ts} < {last_timestamp})"
385+
)
386+
last_timestamp = ts
387+
388+
stats.frames.append(frame)
389+
stats.valid_frames_count += 1
390+
frame_index += 1
391+
392+
pos = frame_start + frame_len
393+
394+
return stats
395+
396+
@staticmethod
397+
def iter_frames_from_file(
398+
file_path: str | Path,
399+
chunk_size: int = 1024 * 1024,
400+
**kwargs,
401+
) -> Iterable[Arinc767Frame]:
402+
"""Stream-parse ARINC 767 frames from a file path chunk-by-chunk to save memory."""
403+
path = Path(file_path)
404+
buffer = bytearray()
405+
overlap_size = 2048 # Max frame size to safely handle boundary sync splits
406+
frame_index = 0
407+
cumulative_offset = 0
408+
last_timestamp = None
409+
410+
with open(path, "rb") as f:
411+
while True:
412+
chunk = f.read(chunk_size)
413+
if not chunk:
414+
break
415+
buffer.extend(chunk)
416+
417+
# Process all complete frames currently in buffer
418+
pos = 0
419+
while pos < len(buffer):
420+
result = Arinc767FrameParser.find_valid_frame_start(buffer, pos)
421+
if result is None:
422+
break
423+
424+
frame_start, frame_len = result
425+
426+
# If the valid frame requires data beyond our current buffer edge, stop and wait for next chunk
427+
if frame_start + frame_len > len(buffer):
428+
break
429+
430+
frame, _ = Arinc767FrameParser.parse_frame(
431+
buffer,
432+
frame_start,
433+
frame_index,
434+
strict=kwargs.get("strict", False),
435+
)
436+
if frame is not None:
437+
ts = frame.timestamp_ms
438+
if kwargs.get("timestamp_wrap", False):
439+
if last_timestamp is not None and ts < last_timestamp:
440+
cumulative_offset += 24 * 3600 * 1000
441+
ts_adj = ts + cumulative_offset
442+
frame.timestamp_ms = ts_adj
443+
last_timestamp = ts_adj
444+
else:
445+
last_timestamp = ts
446+
447+
yield frame
448+
frame_index += 1
449+
450+
pos = frame_start + frame_len
451+
452+
# Retain tail bytes in buffer to handle sync boundaries across chunks
453+
if pos > 0:
454+
del buffer[:pos]
455+
elif len(buffer) > chunk_size * 2:
456+
# Safety valve if no frames found for a very long stretch
457+
del buffer[:-overlap_size]
458+
459+
# Process any remaining residual buffer bytes after EOF
460+
if len(buffer) >= Arinc767FrameParser.MIN_FRAME_SIZE:
461+
for frame in Arinc767FrameParser.iter_frames(bytes(buffer), **kwargs):
462+
frame.frame_index = frame_index
463+
yield frame
464+
frame_index += 1
300465

301466
@staticmethod
302467
def parse_all(data: bytes, **kwargs) -> list[Arinc767Frame]:

0 commit comments

Comments
 (0)