Skip to content

Commit b8e2e0f

Browse files
committed
enhance VEC parser with robust encoding, comment stripping, and validation
1 parent ddc870e commit b8e2e0f

2 files changed

Lines changed: 42 additions & 22 deletions

File tree

‎examples/process_flight_767.py‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,35 @@
1+
import zipfile
12
from pathlib import Path
23

34
from pyarinc.arinc767.decoder import Arinc767Decoder
45
from pyarinc.arinc767.vec_parser import parse_vec_file_767, vec_to_parameters_767
56
from pyarinc.io.csv_export import export_csv
6-
from pyarinc.io.datafile import read_binary
77
from pyarinc.io.parquet_export import export_parquet
88

99

10-
def process_flight_767_data(vec_path: Path, data_path: Path, output_dir: Path) -> None:
11-
"""Read a VEC config, parse raw ARINC 767 flight data, decode parameters, and export."""
10+
def process_flight_767_data(
11+
vec_path: Path, archive_path: Path, output_dir: Path
12+
) -> None:
13+
"""Read VEC config, extract and read raw ARINC 767 flight data from zip, decode, and export."""
1214
print(f"Loading parameters from VEC file {vec_path}...")
1315
mapping = parse_vec_file_767(vec_path)
1416
parameters = vec_to_parameters_767(mapping)
1517

16-
print(f"Reading raw ARINC 767 data from {data_path}...")
17-
raw_bytes = read_binary(data_path)
18+
print(f"Extracting raw ARINC 767 data from zip archive {archive_path}...")
19+
with zipfile.ZipFile(archive_path, "r") as z:
20+
inner_filename = z.namelist()[0]
21+
print(f"Reading inner file: {inner_filename}")
22+
raw_bytes = z.read(inner_filename)
23+
24+
print(f"Loaded {len(raw_bytes)} bytes of raw flight data.")
1825

1926
print("Decoding ARINC 767 parameters using Arinc767Decoder...")
2027
decoder = Arinc767Decoder(list(parameters.values()), frames_per_second=1.0)
2128

22-
# decode_raw_bytes parses the raw frame stream and returns a scheduled DataFrame
2329
df = decoder.decode_raw_bytes(raw_bytes)
2430

31+
print(f"Decoded {len(df)} rows.")
32+
2533
out_dir = Path(output_dir)
2634
out_dir.mkdir(parents=True, exist_ok=True)
2735

@@ -38,10 +46,10 @@ def process_flight_767_data(vec_path: Path, data_path: Path, output_dir: Path) -
3846

3947
if __name__ == "__main__":
4048
vec_file = Path("tests/fixtures/ags767/078711.vec")
41-
data_file = Path("tests/fixtures/ags767/B-678920010203001603N.zip")
49+
archive_file = Path("tests/fixtures/ags767/B-678920010203001603N.zip")
4250
output_directory = Path("output")
4351

44-
if vec_file.exists() and data_file.exists():
45-
process_flight_767_data(vec_file, data_file, output_directory)
52+
if vec_file.exists() and archive_file.exists():
53+
process_flight_767_data(vec_file, archive_file, output_directory)
4654
else:
4755
print("Sample fixture files not found. Check paths to run the example.")

‎pyarinc/arinc767/vec_parser.py‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@
1616
)
1717

1818

19+
def _read_text_file(path: Path) -> str:
20+
"""Read text file with automatic encoding fallback."""
21+
for encoding in ("utf-8", "latin-1", "cp1252"):
22+
try:
23+
return path.read_text(encoding=encoding).strip()
24+
except UnicodeDecodeError:
25+
continue
26+
raise UnicodeDecodeError(
27+
f"Failed to decode VEC file with standard encodings: {path}"
28+
)
29+
30+
1931
def _parse_bitrange_767(token: str) -> dict[str, int] | None:
2032
m = _VEC_BITRANGE_RE_767.search(token)
2133
if not m:
@@ -35,15 +47,9 @@ def _parse_bitrange_767(token: str) -> dict[str, int] | None:
3547

3648

3749
def parse_vec_file_767(path: Path) -> dict[str, Any]:
38-
"""ARINC 767 VEC parser with improved hex FID and single-pass token parsing."""
50+
"""Advanced ARINC 767 VEC parser with robust encoding, inline comment stripping, and validation."""
3951
try:
40-
text = path.read_text(encoding="utf-8").strip()
41-
except UnicodeDecodeError:
42-
try:
43-
text = path.read_text(encoding="latin-1").strip()
44-
except Exception as e:
45-
logger.error(f"Failed to read VEC file 767 {path}: {e}")
46-
raise
52+
text = _read_text_file(path)
4753
except Exception as e:
4854
logger.error(f"Failed to read VEC file 767 {path}: {e}")
4955
raise
@@ -59,8 +65,9 @@ def parse_vec_file_767(path: Path) -> dict[str, Any]:
5965
out: dict[str, Any] = {}
6066

6167
for line_num, line in enumerate(text.splitlines(), start=1):
62-
line = line.strip()
63-
if not line or line.startswith("#"):
68+
# Strip inline comments and whitespace
69+
line = line.split("#")[0].strip()
70+
if not line:
6471
continue
6572

6673
parts = line.split()
@@ -81,6 +88,9 @@ def parse_vec_file_767(path: Path) -> dict[str, Any]:
8188
entry.update(br)
8289
break
8390

91+
if "word" not in entry:
92+
logger.debug(f"Line {line_num}: No bitrange found for parameter '{name}'")
93+
8494
# Rate extraction fallback (ignoring key-value parameters)
8595
for tok in reversed(parts):
8696
if "=" in tok:
@@ -91,10 +101,10 @@ def parse_vec_file_767(path: Path) -> dict[str, Any]:
91101
except ValueError:
92102
continue
93103

94-
# Single-pass token processing
104+
# Single-pass token processing for metadata flags
95105
for tok in parts[1:]:
96106
upper_tok = tok.upper()
97-
if upper_tok in ("BNR", "BCD", "CHAR"):
107+
if upper_tok in ("BNR", "BCD", "CHAR", "DISCRETE"):
98108
entry["type"] = upper_tok
99109
continue
100110

@@ -111,7 +121,9 @@ def parse_vec_file_767(path: Path) -> dict[str, Any]:
111121
base = 16 if val.lower().startswith("0x") else 10
112122
entry["frame_id_767"] = int(val, base)
113123
except ValueError:
114-
pass
124+
logger.warning(
125+
f"Line {line_num}: Invalid FID value '{val}' for parameter '{name}'"
126+
)
115127
elif key == "COB":
116128
entry["cob_formula"] = val
117129
elif key == "TYPE":

0 commit comments

Comments
 (0)