vendredi 5 juillet 2019

What design pattern is this? Object that converts from byte[] to own type and back

I'm working on desktop software that works with embedded device.

On desktop I created classes like this:

// This is C# code

public class ThermostatConfigEntry
{
    public sbyte TempSetting { get; set; }
    public byte HistSetting { get; set; }
    public byte RelayOutputMask { get; set; }
    public byte SensorFailureOutputMask { get; set; }

    // (...) constructors
    // (...) public methods
}

For communication between desktop application and embedded device I'm using Modbus protocol that supports 1-bit (boolean) and 16-bit (unsigned short) data types.

So to create instance of this object from data received from Modbus I'm using constructor:

    public ThermostatConfigEntry(byte id, ushort[] data)
    {
        byte s = 0;
        ushort temp;

        temp = data[s++];
        TempSetting = temp.HighSByte();
        HistSetting = temp.LowByte();

        temp = data[s++];
        RelayOutputMask = temp.HighByte();
        SensorFailureOutputMask = temp.LowByte();
    }

To send this object via Modbus I have created ToUShortArray() methods:

    public ushort[] ToUShortArray()
    {
        return new ushort[] {
            Helpers.FromBytes(TempSetting, HistSetting),
            Helpers.FromBytes(RelayOutputMask, SensorFailureOutputMask)
        };
    }

Complete class looks like this:

public class ThermostatConfigEntry : IModbusMappableObject
{
    public sbyte TempSetting { get; set; }
    public byte HistSetting { get; set; }
    public byte RelayOutputMask { get; set; }
    public byte SensorFailureOutputMask { get; set; }

    public ThermostatConfigEntry(ushort[] data)
    {
        byte s = 0;
        ushort temp;

        temp = data[s++];
        TempSetting = temp.HighSByte();
        HistSetting = temp.LowByte();

        temp = data[s++];
        RelayOutputMask = temp.HighByte();
        SensorFailureOutputMask = temp.LowByte();
    }

    public override ushort[] ToUShortArray()
    {
        return new ushort[] {
            Helpers.FromBytes(TempSetting, HistSetting),
            Helpers.FromBytes(RelayOutputMask, SensorFailureOutputMask)
        };
    }
}

So, this is POCO + constructor that takes array + method that returns array.

Question(s):

  • is there some design pattern or some name for classes like this?

I guess is not enough for DAO (Data Access Object), not DTO (Data Transfer Object), too much for POCO (Plain Old CLR Object).

Aucun commentaire:

Enregistrer un commentaire