|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Self-contained demo of PyDSDL serialization. |
| 4 | +""" |
| 5 | + |
| 6 | +import pydsdl |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +SCRIPT_DIR = Path(__file__).parent |
| 10 | +DSDL_FILE = SCRIPT_DIR / "DemoMessage.1.0.dsdl" |
| 11 | + |
| 12 | + |
| 13 | +def main() -> None: |
| 14 | + print("Loading DSDL type from:", DSDL_FILE.name) |
| 15 | + types, _ = pydsdl.read_files( |
| 16 | + dsdl_files=DSDL_FILE, |
| 17 | + root_namespace_directories_or_names=SCRIPT_DIR, |
| 18 | + lookup_directories=[], |
| 19 | + ) |
| 20 | + schema = types[0] |
| 21 | + print(f"✓ Loaded type: {schema.full_name} v{schema.version.major}.{schema.version.minor}") |
| 22 | + print(" Fields:", [f"{f.data_type} {f.name}" for f in schema.fields_except_padding]) |
| 23 | + |
| 24 | + print("Creating example object:") |
| 25 | + obj = { |
| 26 | + "flag": True, |
| 27 | + "counter": 42, |
| 28 | + "temperature": 23.5, |
| 29 | + "numeric_data": [1.0, 2.0, 3, 4], |
| 30 | + "text_data": "Hello, SerDes!", |
| 31 | + "binary_data": b"\x00\x01\x02\x03", |
| 32 | + } |
| 33 | + for key, value in obj.items(): |
| 34 | + value_repr = repr(value) |
| 35 | + if len(value_repr) > 50: |
| 36 | + value_repr = value_repr[:47] + "..." |
| 37 | + print(f" {key:15} = {value_repr} ({type(value).__name__})") |
| 38 | + |
| 39 | + print("Serializing object to bytes") |
| 40 | + serialized_data = pydsdl.serialize(schema, obj) |
| 41 | + print(f"✓ Serialized to {len(serialized_data)} bytes:") |
| 42 | + print(f" {serialized_data.hex()}") |
| 43 | + |
| 44 | + print("Deserializing bytes back to object") |
| 45 | + deserialized = pydsdl.deserialize(schema, serialized_data) |
| 46 | + print("✓ Deserialized successfully:") |
| 47 | + for key, value in deserialized.items(): |
| 48 | + value_repr = repr(value) |
| 49 | + if len(value_repr) > 50: |
| 50 | + value_repr = value_repr[:47] + "..." |
| 51 | + print(f" {key:15} = {value_repr} ({type(value).__name__})") |
| 52 | + |
| 53 | + print("Verifying roundtrip equality") |
| 54 | + assert obj == deserialized, "Roundtrip failed! Objects don't match." |
| 55 | + print("✓ Roundtrip verification passed: Original == Deserialized") |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + main() |
0 commit comments