Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/device.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@
::: harp.device.schema.ConverterContext
::: harp.device.schema.DeviceModule
::: harp.device.schema.DeviceModuleLike
::: harp.device.schema.DescribedDeviceModuleLike
::: harp.device.core
3 changes: 2 additions & 1 deletion src/packages/harp-device/src/harp/device/schema/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
40 changes: 39 additions & 1 deletion src/packages/harp-device/src/harp/device/schema/_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
module or by address through ``REGISTER_MAP``.
"""

import codecs
import types
from typing import Any, Mapping, Optional, Protocol, runtime_checkable

Expand All @@ -31,13 +32,30 @@ 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
WHO_AM_I: int
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`.

Expand All @@ -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."""

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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")
16 changes: 15 additions & 1 deletion tests/conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down
195 changes: 195 additions & 0 deletions tests/device/expected_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
__all__ = [
"DEVICE_NAME",
"WHO_AM_I",
"DEVICE_METADATA",
"PortDigitalIOS",
"PwmPort",
"EncoderModeMask",
Expand Down Expand Up @@ -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):
Expand Down
Loading
Loading