laatzen/Common/Hardware/Common.Hardware.SIRT/SIRTMessage.cs
2024-11-13 15:50:04 +01:00

111 lines
2.8 KiB
C#

namespace Common.Hardware.SIRT
{
using Common.Hardware.Ports;
using System;
public class SIRTMessage
{
public const byte MIN_LEN = 12;
public const byte PC2SIRT = 0x55;
public const byte SIRT2PC = 0xFF;
public const byte W_PAM = 0x81;
public const byte R_PAM = 0x82;
public const byte W_REG = 0x84;
public const byte R_REG = 0x87;
public const byte FROMAIR = 0x11;
public const byte ACKNANSW = 0x12;
public const byte STOP = 0x16;
public const byte BUP = 0x00;
public const byte LAT = 0x01;
public const byte DEBUG = 0x0B;
public const byte SEMI = 0x08;
private byte[] bytes;
public SIRTMessage()
{
this.bytes = new byte[MIN_LEN];
this.bytes[0] = PC2SIRT;
}
public SIRTMessage(byte[] bytes)
{
this.bytes = bytes;
this.bytes[0] = SIRT2PC;
}
public byte Cmd
{
get => this.bytes[1];
set => this.bytes[1] = value;
}
public byte P1
{
get => this.bytes[2];
set => this.bytes[2] = value;
}
public byte P2
{
get => this.bytes[3];
set => this.bytes[3] = value;
}
public uint Address
{
get => this.bytes.ToUInt32BE(4);
set => value.GetBytesBE().CopyTo(this.bytes, 4);
}
public byte Length => this.bytes[8];
public byte[] Data
{
get
{
var data = new byte[this.Length];
Array.Copy(this.bytes, 9, data, 0, this.Length);
return data;
}
set
{
if (value is null)
{
value = new byte[0];
}
this.bytes[8] = (byte)value.Length;
Array.Resize(ref this.bytes, MIN_LEN + this.Length);
Array.Clear(this.bytes, 9, this.bytes.Length - 9);
Array.Copy(value, 0, this.bytes, 9, this.Length);
}
}
public ushort CRC => this.bytes.ToUInt16BE(this.bytes.Length - 3);
public byte[] ToByteArray()
{
var length = this.bytes.Length;
var crc = this.bytes.CRCCCITT(1, length - 3);
var crcBytes = crc.GetBytesBE();
this.bytes[length - 3] = crcBytes[0];
this.bytes[length - 2] = crcBytes[1];
this.bytes[length - 1] = STOP;
return this.bytes;
}
public override string ToString()
=> BitConverter.ToString(this.ToByteArray());
public static implicit operator byte[](SIRTMessage message)
=> message.ToByteArray() ?? new byte[0];
}
}