harp-tech / protocol

Description of the Harp protocol.
https://harp-tech.org/protocol/BinaryProtocol-8bit.html
MIT License
3 stars 5 forks source link

Heterogenous register types in yaml schema #40

Open bruno-f-cruz opened 3 months ago

bruno-f-cruz commented 3 months ago

@Poofjunior Thanks for the great input and raising this requirement, I agree having more flexibility in passing around packed custom structures with possibly heterogeneous types is important.

Following the meeting, I was playing around with the YAML schema and actually there is a small kink that doesn't allow it to represent heterogeneous types out-of-the-box (yet). It is definitely fixable though and this is a use case we should indeed support so I will flag an issue to fix it. Nevertheless, for aligned types, you could do:

%YAML 1.1
---
# yaml-language-server: $schema=https://raw.githubusercontent.com/harp-tech/reflex-generator/main/schema/device.json
device: harpy
whoAmI: 0000
firmwareVersion: "0.1"
hardwareTargets: "0.0"
registers:
  Accelerometer:
    address: 32
    type: S16
    length: 3
    access: Event
    payloadSpec:
      X:
        offset: 0
        description: Represents the x-coordinate of the payload.
      Y:
        offset: 1
        description: Represents the y-coordinate of the payload.
      Z:
        offset: 2
        description: Represents the z-coordinate of the payload.

This will generate in the high-level interface the type AccelerometerPayload with the following signature (edited for conciseness):

public struct AccelerometerPayload
{
    public AccelerometerPayload(short x, short y, short z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public short X;
    public short Y;
    public short Z;
}

And the auto-generated converters:

static AccelerometerPayload ParsePayload(short[] payload)
{
    AccelerometerPayload result;
    result.X = payload[0];
    result.Y = payload[1];
    result.Z = payload[2];
    return result;
}

static short[] FormatPayload(AccelerometerPayload value)
{
    short[] result;
    result = new short[3];
    result[0] = value.X;
    result[1] = value.Y;
    result[2] = value.Z;
    return result;
}

It is actually possible using the message manipulation API to marshal arbitrary payload structs directly (with the equivalent of memcpy), and having an easy way to specify something like this in the spec is definitely interesting. I think I have a solution but need to go through a few edge cases more carefully to make sure it will be workable. Thanks for the push! I'll post here once I have something more complete.

Originally posted by @glopesdev in https://github.com/harp-tech/protocol/discussions/27#discussioncomment-5994453