Skip to content

Commit 5308e25

Browse files
committed
refactor PRM and VEC parsers to support keyword tokens and hex frame IDs
1 parent ac4bed4 commit 5308e25

3 files changed

Lines changed: 195 additions & 135 deletions

File tree

‎pyarinc/config/prm_parser.py‎

Lines changed: 85 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,121 @@
11
from __future__ import annotations
22

33
import json
4+
import logging
45
from pathlib import Path
56
from typing import TYPE_CHECKING, Any
67

78
if TYPE_CHECKING:
89
from ..models.parameter import Parameter
910

11+
logger = logging.getLogger(__name__)
12+
1013

1114
def parse_prm_file(path: Path) -> dict[str, Any]:
1215
"""Parse a PRM file into a mapping of parameter definitions.
1316
1417
Supported line formats (space-separated):
15-
name subframe word bit_offset length rate [superframe]
18+
name subframe word bit_offset length rate [superframe] [KEY=VALUE ...]
1619
Also accepts a JSON file mapping parameter names to definitions.
1720
"""
1821
out: dict[str, Any] = {}
19-
text = path.read_text(encoding="utf-8").strip()
20-
# try JSON first
22+
23+
try:
24+
text = path.read_text(encoding="utf-8").strip()
25+
except Exception as e:
26+
logger.error(f"Failed to read PRM file {path}: {e}")
27+
raise
28+
29+
# Try parsing as JSON first
2130
try:
2231
data = json.loads(text)
2332
if isinstance(data, dict):
2433
return data
25-
except Exception:
26-
pass
34+
else:
35+
logger.warning(
36+
f"PRM file {path} contains valid JSON, but the root element is not a dictionary. Falling back to text line parsing."
37+
)
38+
except json.JSONDecodeError:
39+
pass # Not JSON, fall back to text line parsing
2740

28-
for line in text.splitlines():
41+
for line_num, line in enumerate(text.splitlines(), start=1):
2942
line = line.strip()
3043
if not line or line.startswith("#"):
3144
continue
45+
3246
parts = line.split()
33-
# fallback simple formats
34-
if len(parts) >= 6:
35-
try:
36-
name = parts[0]
37-
subframe = int(parts[1])
38-
word = int(parts[2])
39-
bit_offset = int(parts[3])
40-
length = int(parts[4])
41-
rate = float(parts[5])
42-
superframe = int(parts[6]) if len(parts) > 6 else None
43-
except Exception:
44-
continue
45-
out[name] = {
47+
if len(parts) < 6:
48+
logger.warning(
49+
f"Skipping malformed line {line_num} in {path}: insufficient fields"
50+
)
51+
continue
52+
53+
try:
54+
name = parts[0]
55+
subframe = int(parts[1])
56+
word = int(parts[2])
57+
bit_offset = int(parts[3])
58+
length = int(parts[4])
59+
rate = float(parts[5])
60+
61+
superframe = None
62+
start_idx = 6
63+
64+
# Check if the 7th token is a superframe integer or a keyword
65+
if len(parts) > 6 and "=" not in parts[6]:
66+
try:
67+
superframe = int(parts[6])
68+
start_idx = 7
69+
except ValueError:
70+
pass
71+
72+
param_meta: dict[str, Any] = {
4673
"subframe": subframe,
4774
"word": word,
4875
"bit_offset": bit_offset,
4976
"length": length,
5077
"rate": rate,
5178
"superframe": superframe,
5279
}
80+
81+
# Parse optional trailing key-value tokens (e.g., TYPE=BNR SCALE=0.1)
82+
line_has_error = False
83+
for part in parts[start_idx:]:
84+
if "=" in part:
85+
key, val = part.split("=", 1)
86+
key = key.strip().lower()
87+
val = val.strip()
88+
89+
if key == "type":
90+
param_meta["type"] = val
91+
elif key == "scale":
92+
try:
93+
param_meta["scale"] = float(val)
94+
except ValueError:
95+
logger.warning(
96+
f"Invalid scale value '{val}' on line {line_num} in {path}"
97+
)
98+
line_has_error = True
99+
break
100+
elif key == "offset":
101+
try:
102+
param_meta["offset"] = float(val)
103+
except ValueError:
104+
logger.warning(
105+
f"Invalid offset value '{val}' on line {line_num} in {path}"
106+
)
107+
line_has_error = True
108+
break
109+
110+
if line_has_error:
111+
continue
112+
113+
out[name] = param_meta
114+
115+
except Exception as e:
116+
logger.warning(f"Error parsing line {line_num} in {path}: {e}")
117+
continue
118+
53119
return out
54120

55121

0 commit comments

Comments
 (0)