diff --git a/docs/api/device.md b/docs/api/device.md index 8dc7c0a..ba59c5a 100644 --- a/docs/api/device.md +++ b/docs/api/device.md @@ -14,4 +14,5 @@ ::: harp.device.schema.ConverterContext ::: harp.device.schema.DeviceModule ::: harp.device.schema.DeviceModuleLike +::: harp.device.schema.DescribedDeviceModuleLike ::: harp.device.core diff --git a/src/packages/harp-device/src/harp/device/schema/__init__.py b/src/packages/harp-device/src/harp/device/schema/__init__.py index de66397..6bbf293 100644 --- a/src/packages/harp-device/src/harp/device/schema/__init__.py +++ b/src/packages/harp-device/src/harp/device/schema/__init__.py @@ -1,12 +1,13 @@ """Building a device interface from a Harp ``device.yml`` at runtime.""" from ._emit import ConverterContext, parse_device_schema -from ._module import DeviceModule, DeviceModuleLike, create_device_module +from ._module import DeviceModule, DeviceModuleLike, DescribedDeviceModuleLike, create_device_module __all__ = [ "create_device_module", "DeviceModule", "DeviceModuleLike", + "DescribedDeviceModuleLike", "parse_device_schema", "ConverterContext", ] diff --git a/src/packages/harp-device/src/harp/device/schema/_module.py b/src/packages/harp-device/src/harp/device/schema/_module.py index 4b8231a..702d020 100644 --- a/src/packages/harp-device/src/harp/device/schema/_module.py +++ b/src/packages/harp-device/src/harp/device/schema/_module.py @@ -7,6 +7,7 @@ module or by address through ``REGISTER_MAP``. """ +import codecs import types from typing import Any, Mapping, Optional, Protocol, runtime_checkable @@ -31,6 +32,8 @@ class DeviceModuleLike(Protocol): ``DEVICE_NAME`` is required rather than optional, so a generated package always states the name used for its recordings. A schema declaring none still builds, since :class:`DeviceModule` declares the member and leaves it empty. + ``DEVICE_METADATA`` is optional, so a device module written by hand need not carry + a schema; require it with :class:`DescribedDeviceModuleLike`. """ DEVICE_NAME: str @@ -38,6 +41,21 @@ class DeviceModuleLike(Protocol): REGISTER_MAP: dict[int, type[RegisterBase[Any]]] +@runtime_checkable +class DescribedDeviceModuleLike(DeviceModuleLike, Protocol): + """A device module that also carries the schema it describes. + + Generated packages and :class:`DeviceModule` both match, so accept this where the + schema is needed, or narrow a :class:`DeviceModuleLike` to it with ``isinstance``:: + + if isinstance(module, DescribedDeviceModuleLike): + Path("device.yml").write_text(module.DEVICE_METADATA) + """ + + DEVICE_METADATA: str + """The contents of the metadata file describing the device registers.""" + + class DeviceModule(types.ModuleType): """The type of the module returned by :func:`create_device_module`. @@ -52,6 +70,9 @@ class DeviceModule(types.ModuleType): WHO_AM_I: int """The device identity declared by the schema. ``0`` when absent.""" + DEVICE_METADATA: str + """The contents of the metadata file describing the device registers.""" + REGISTER_MAP: dict[int, type[RegisterBase[Any]]] """Address -> register class, the core Harp registers merged with those of the schema.""" @@ -79,6 +100,8 @@ def create_device_module( * ``REGISTER_MAP``, the device address space, so the core registers are present here even though the module does not name them; * ``WHO_AM_I``, the identity declared by the schema (``0`` for an unregistered device); + * ``DEVICE_METADATA``, the schema text itself with line endings normalized to ``\\n``, + as a generated package carries it; * ``DEVICE_NAME``, the ``device`` name of the schema, or ``name`` when given, and empty for a header-less register fragment. Recordings are written under this name, so :class:`~harp.data.DatasetReader` matches files by it; @@ -117,8 +140,23 @@ def create_device_module( vars(module).update( contents, DEVICE_NAME=device_name, + DEVICE_METADATA=_metadata_text(text), REGISTER_MAP=register_map, WHO_AM_I=int(device.whoAmI or 0), - __all__=[*sorted(contents), "DEVICE_NAME", "REGISTER_MAP", "WHO_AM_I"], + __all__=[*sorted(contents), "DEVICE_NAME", "DEVICE_METADATA", "REGISTER_MAP", "WHO_AM_I"], ) return module + + +def _metadata_text(text: str | bytes) -> str: + """The schema as a string, as a generated package declares it. + + Python reads every line ending in a source file as ``\\n``, so a generated + package always holds ``\\n``; normalizing here makes both paths agree for the same + file. Bytes are decoded as the YAML parser does for the encodings it detects by a + byte order mark, defaulting to UTF-8. + """ + if isinstance(text, bytes): + bom_utf16 = text.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)) + text = text.decode("utf-16" if bom_utf16 else "utf-8-sig") + return text.replace("\r\n", "\n").replace("\r", "\n") diff --git a/tests/conformance.py b/tests/conformance.py index 8e24b4a..ee85cfa 100644 --- a/tests/conformance.py +++ b/tests/conformance.py @@ -11,7 +11,12 @@ from harp.data import DatasetReader, open_dataset from harp.device.client import Device, ITransport from harp.device.core import OperationControl, OperationControlPayload, WhoAmI -from harp.device.schema import DeviceModule, DeviceModuleLike, create_device_module +from harp.device.schema import ( + DeviceModule, + DeviceModuleLike, + DescribedDeviceModuleLike, + create_device_module, +) from harp.protocol import ( ArrayConverter, Field, @@ -31,6 +36,15 @@ def schema_built_registers(yml: str) -> None: assert_type(behavior.AnalogData, Any) assert_type(behavior.REGISTER_MAP, dict[int, type[RegisterBase[Any]]]) assert_type(behavior.WHO_AM_I, int) + assert_type(behavior.DEVICE_METADATA, str) + described: DescribedDeviceModuleLike = behavior + assert_type(described.DEVICE_METADATA, str) + + +def device_metadata_narrows(module: DeviceModuleLike) -> None: + """A device module narrows to one carrying its schema, which then reads as str.""" + if isinstance(module, DescribedDeviceModuleLike): + assert_type(module.DEVICE_METADATA, str) def statically_declared_registers(device: Device) -> None: diff --git a/tests/device/expected_device.py b/tests/device/expected_device.py index 0f027f3..d169208 100644 --- a/tests/device/expected_device.py +++ b/tests/device/expected_device.py @@ -33,6 +33,7 @@ __all__ = [ "DEVICE_NAME", "WHO_AM_I", + "DEVICE_METADATA", "PortDigitalIOS", "PwmPort", "EncoderModeMask", @@ -67,6 +68,200 @@ DEVICE_NAME: str = "Tests" WHO_AM_I: int = 0 +DEVICE_METADATA: str = """\ +# yaml-language-server: $schema=https://harp-tech.org/draft-02/schema/registers.json +device: Tests +firmwareVersion: "0.1" +hardwareTargets: "1.0" +registers: + DigitalInputs: + address: 32 + type: U8 + access: Event + AnalogData: + address: 33 + type: Float + length: 6 + access: Event + payloadSpec: + Analog0: + offset: 0 + Analog1: + offset: 1 + Analog2: + offset: 2 + Accelerometer: + offset: 3 + length: 3 + ComplexConfiguration: + address: 34 + type: U8 + length: 17 + access: Write + payloadSpec: + PwmPort: + offset: 0 + maskType: PwmPort + DutyCycle: + offset: 4 + length: 4 + interfaceType: float + Frequency: + offset: 8 + length: 4 + interfaceType: float + EventsEnabled: + offset: 12 + interfaceType: bool + Delta: + offset: 13 + length: 4 + interfaceType: uint + Version: + address: 35 + type: U8 + length: 32 + access: Event + payloadSpec: + ProtocolVersion: + offset: 0 + length: 3 + interfaceType: HarpVersion + FirmwareVersion: + offset: 3 + length: 3 + interfaceType: HarpVersion + HardwareVersion: + offset: 6 + length: 3 + interfaceType: HarpVersion + CoreId: + offset: 9 + length: 3 + interfaceType: string + InterfaceHash: + offset: 12 + length: 20 + CustomPayload: + address: 36 + type: U32 + length: 3 + access: Read + interfaceType: HarpVersion + converter: Payload + CustomRawPayload: + address: 37 + type: U32 + length: 3 + access: Read + interfaceType: HarpVersion + converter: RawPayload + CustomMemberConverter: + address: 38 + type: U8 + length: 3 + access: Read + payloadSpec: + Header: + offset: 0 + Data: + offset: 1 + length: 2 + interfaceType: int + converter: Payload + BitmaskSplitter: + address: 39 + type: U8 + access: Write + payloadSpec: + Low: + mask: 0xF + interfaceType: int + converter: Payload + High: + mask: 0xF0 + interfaceType: int + Counter0: + address: 40 + type: S32 + access: Event + PortDIOSet: + address: 41 + type: U8 + access: Write + maskType: PortDigitalIOS + PulseDOPort0: &pulseDO + address: 42 + type: U16 + access: Write + minValue: 1 + PulseDO0: + <<: *pulseDO + address: 43 + StartPulse: + address: 100 + type: U16 + access: Write + description: Starts a PWM pulse. + payloadSpec: &startPulse + DigitalOutput: + offset: 0 + mask: 0xC00 + maskType: PwmPort + PulseWidth: + offset: 0 + mask: 0x3FF + interfaceType: ushort + StartPulseTrain: + address: 101 + type: U16 + length: 2 + access: Write + description: Starts a PWM pulse train. + payloadSpec: + <<: *startPulse + Frequency: + offset: 1 + mask: 0xFF00 + minValue: 1 + maxValue: 255 + defaultValue: 1 + interfaceType: byte + PulseCount: + offset: 1 + mask: 0xFF + interfaceType: byte + EncoderMode: + address: 103 + type: U8 + access: Write + maskType: EncoderModeMask + description: Configures the operation mode of the encoder. +bitMasks: + PortDigitalIOS: + bits: + DIO0: 0x1 + DIO1: 0x2 + DIO2: 0x4 + DIO3: 0x8 + DIPort0: 0x100 + TestDIPort1: 0x200 + SupplyPort0: 0x400 + PortDIO1: 0x800 +groupMasks: + PwmPort: + values: + Pwm0: 0x1 + Pwm1: 0x2 + Pwm2: 0x4 + Pwm3: 0xA + EncoderModeMask: + description: Specifies the type of encoder mode. + values: + Position: 0x0 + Displacement: 0x1 +""" +"""The contents of the metadata file describing the device registers.""" class PortDigitalIOS(enum.IntFlag): diff --git a/tests/device/test_create_device_module.py b/tests/device/test_create_device_module.py index 02cfac4..3000f3e 100644 --- a/tests/device/test_create_device_module.py +++ b/tests/device/test_create_device_module.py @@ -1,3 +1,4 @@ +import codecs import sys import types @@ -8,6 +9,7 @@ from harp.device.schema import ( DeviceModule, DeviceModuleLike, + DescribedDeviceModuleLike, create_device_module, parse_device_schema, ) @@ -17,7 +19,7 @@ from .converters import DataConverter CONVERTERS = {"DataConverter": DataConverter()} -MODULE_CONSTANTS = {"DEVICE_NAME", "REGISTER_MAP", "WHO_AM_I"} +MODULE_CONSTANTS = {"DEVICE_NAME", "DEVICE_METADATA", "REGISTER_MAP", "WHO_AM_I"} @pytest.fixture @@ -53,6 +55,34 @@ def test_whoami_from_schema(): assert mod.WHO_AM_I == 1216 +def test_device_metadata_is_schema_text(test_module, device_yml): + # The module carries the document it was built from, as the C# interface exposes + # Device.Metadata, so it can be written beside a recording or inspected later. + assert test_module.DEVICE_METADATA == device_yml + + +def test_device_metadata_matches_generated_package(test_module): + # expected_device is generator output for the same schema, so both paths must + # expose the same document. + assert test_module.DEVICE_METADATA == expected_device.DEVICE_METADATA + + +@pytest.mark.parametrize( + "encode", + [ + lambda text: text.replace("\n", "\r\n").encode("utf-8"), + lambda text: codecs.BOM_UTF8 + text.encode("utf-8"), + lambda text: text.encode("utf-16"), + ], + ids=["crlf", "utf-8-bom", "utf-16"], +) +def test_device_metadata_normalizes_encoded_schema(encode): + # A generated package always reads as "\n" without a byte order mark, so a + # module built from the same file read as bytes must agree with it. + text = "device: D\nwhoAmI: 1216\nregisters:\n Foo: {address: 40, type: U16, access: Read}\n" + assert create_device_module(encode(text)).DEVICE_METADATA == text + + def test_docstring_from_schema(core_yml): # The docstring is the schema description rather than composed from the module name, # so a runtime module reads the same as the generated package for the same metadata. @@ -113,6 +143,24 @@ def test_generated_package_matches_device_protocol(): assert isinstance(expected_device, DeviceModuleLike) +def test_module_without_metadata_is_device_module(): + # A device module written by hand need not carry a schema, so DEVICE_METADATA is optional. + mod = types.ModuleType("NoMetadata") + vars(mod).update(DEVICE_NAME="NoMetadata", WHO_AM_I=0, REGISTER_MAP={}) + assert isinstance(mod, DeviceModuleLike) + assert not isinstance(mod, DescribedDeviceModuleLike) + + +def test_emitted_module_carries_metadata(test_module): + assert isinstance(test_module, DescribedDeviceModuleLike) + + +def test_generated_package_carries_metadata(): + # expected_device is a sample of generator output, so this pins that what the + # generator emits is accepted wherever the schema is required. + assert isinstance(expected_device, DescribedDeviceModuleLike) + + def test_core_registers_are_not_device_module(): # They carry REGISTER_MAP but describe no device, so they cannot be passed # where a device module is required, such as to a DatasetReader.