From af2b598f118fe73aad5dce5a8b68a5d078314a5d Mon Sep 17 00:00:00 2001 From: plun1331 Date: Fri, 15 Nov 2024 16:20:37 -0800 Subject: [PATCH] feat: fix bugs with parsing --- hytek/hy3/converters.py | 8 ++++++-- hytek/hy3/records.py | 15 +++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/hytek/hy3/converters.py b/hytek/hy3/converters.py index f6a8094..f6168be 100644 --- a/hytek/hy3/converters.py +++ b/hytek/hy3/converters.py @@ -4,14 +4,18 @@ __all__ = ("date", "time") -def date(data: str) -> datetime.date: +def date(data: str) -> datetime.date | None: + if not data: + return None month = int(data[:2]) day = int(data[2:4]) year = int(data[-4:]) return datetime.date(year, month, day) -def time(data: str) -> datetime.time: +def time(data: str) -> datetime.time | None: + if not data: + return None _time, ampm = data.split(" ") hours, minutes = _time.split(":") hours = int(hours) diff --git a/hytek/hy3/records.py b/hytek/hy3/records.py index a240e34..3dd0a93 100644 --- a/hytek/hy3/records.py +++ b/hytek/hy3/records.py @@ -108,10 +108,10 @@ def to_line(self) -> bytes: class Hy3Record: - record_type: str - fields: list[Field] - data: dict[str, Any] - raw: bytes + record_type: str = "" + fields: list[Field] = [] + data: dict[str, Any] = {} + raw: bytes = b"" children: list[Type[Hy3Record | Hy3RecordGroup]] = [] def __init__(self, raw: bytes = b"", /, **kwargs): @@ -204,14 +204,16 @@ def parse_record(cls, line: bytes): return cls(line) given_checksum = line[-2:] if cls.calculate_checksum(line[:-2]) != given_checksum: - print(line, type(line)) raise Exception("Bad checksum") params = {} index = 2 for field in cls.fields: data = line[index:index + field.length] index += field.length - params[field.name] = field.type(data.decode("utf-8", errors="replace").strip()) + try: + params[field.name] = field.type(data.decode("utf-8", errors="replace").strip()) + except Exception as e: + raise Exception(f"Failed to parse field {field.name} as {field.type.__name__}: {e}") from e return cls(line, **params) @staticmethod @@ -297,6 +299,7 @@ class Hy3C3Record(Hy3Record): fields = [] # here for completeness, contains contact info +# one of the files i have has a C8 record # Swimmer data class Hy3D1Record(Hy3Record):