131 lines
3.2 KiB
C#
131 lines
3.2 KiB
C#
namespace Common.Hardware.SIRT
|
|
{
|
|
using System;
|
|
|
|
using static SIRTConstants;
|
|
|
|
public class SIRTMessage
|
|
{
|
|
private byte[] bytes;
|
|
private bool buildCRC;
|
|
|
|
public SIRTMessage()
|
|
{
|
|
this.bytes = new byte[MIN_LEN];
|
|
this.bytes[0] = PC_SIRT;
|
|
this.buildCRC = true;
|
|
}
|
|
|
|
public SIRTMessage(byte[] bytes)
|
|
{
|
|
if (bytes is null)
|
|
{
|
|
bytes = Array.Empty<byte>();
|
|
}
|
|
|
|
var length = Math.Max(MIN_LEN, bytes.Length);
|
|
|
|
this.bytes = new byte[length];
|
|
|
|
if (bytes.Length > 0)
|
|
{
|
|
Array.Copy(bytes, 0, this.bytes, 0, bytes.Length);
|
|
}
|
|
}
|
|
|
|
public byte Direction
|
|
{
|
|
get => this.bytes[DIR_IX];
|
|
set => this.bytes[DIR_IX] = value;
|
|
}
|
|
|
|
public byte Command
|
|
{
|
|
get => this.bytes[CMD_IX];
|
|
set => this.bytes[CMD_IX] = value;
|
|
}
|
|
|
|
public byte P1
|
|
{
|
|
get => this.bytes[P1_IX];
|
|
set => this.bytes[P1_IX] = value;
|
|
}
|
|
|
|
public byte P2
|
|
{
|
|
get => this.bytes[P2_IX];
|
|
set => this.bytes[P2_IX] = value;
|
|
}
|
|
|
|
public uint Address
|
|
{
|
|
get => this.bytes.GetAddress(ADDR_IX);
|
|
set => this.bytes.SetAddress(ADDR_IX, value);
|
|
}
|
|
|
|
public byte Length
|
|
{
|
|
get => this.bytes[LEN_IX];
|
|
set => this.bytes[LEN_IX] = value;
|
|
}
|
|
|
|
public byte[] Payload
|
|
{
|
|
get
|
|
{
|
|
var payload = new byte[this.Length];
|
|
|
|
Array.Copy(bytes, DATA_IX, payload, 0, this.Length);
|
|
|
|
return payload;
|
|
}
|
|
set
|
|
{
|
|
var payload = value ?? Array.Empty<byte>();
|
|
this.Length = (byte)payload.Length;
|
|
|
|
Array.Resize(ref this.bytes, MIN_LEN + this.Length);
|
|
Array.Clear(this.bytes, DATA_IX, this.bytes.Length - DATA_IX);
|
|
Array.Copy(payload, 0, this.bytes, DATA_IX, this.Length);
|
|
}
|
|
}
|
|
|
|
public ushort Crc
|
|
{
|
|
get => this.bytes.GetCrc(this.bytes.Length - 3);
|
|
set => this.bytes.SetCrc(this.bytes.Length - 3, value);
|
|
}
|
|
|
|
public byte End
|
|
{
|
|
get => this.bytes[this.bytes.Length - 1];
|
|
set => this.bytes[this.bytes.Length - 1] = value;
|
|
}
|
|
|
|
public string SirtId { get; set; }
|
|
|
|
public int Frequency { get; set; }
|
|
|
|
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;
|
|
|
|
public override string ToString() => $"{this.SirtId}|{this.Frequency:000}|{BitConverter.ToString(this.GetBytes())}";
|
|
|
|
public byte[] GetBytes()
|
|
{
|
|
if (this.buildCRC)
|
|
{
|
|
this.Crc = this.bytes.CRCCCITT(1, this.bytes.Length - 3);
|
|
}
|
|
|
|
this.End = MSG_END;
|
|
|
|
return this.bytes;
|
|
}
|
|
|
|
public static implicit operator SIRTMessage(byte[] bytes)
|
|
=> new SIRTMessage(bytes);
|
|
|
|
public static implicit operator byte[] (SIRTMessage message)
|
|
=> message?.GetBytes() ?? Array.Empty<byte>();
|
|
}
|
|
} |