Files
laatzen/Common/SIRTBroadcaster.Abstraction/SIRTExtensions.cs
T
2023-08-22 14:58:05 +02:00

112 lines
3.2 KiB
C#

namespace SIRTBroadcaster.Abstraction
{
using System;
using System.Linq;
/// <summary>
/// TODO: Add description ...
/// </summary>
public static class SIRTExtensions
{
public static byte[] ToByteArray(this SIRTMessage message)
{
var length = 12 + message.DataLength;
var bytes = new byte[length];
bytes[0] = message.StartByte;
bytes[1] = message.MessageType;
bytes[2] = message.Parameter1;
bytes[3] = message.Parameter2;
/// TODO: see if radio address is correct hinzugefügt.
/// Copying address bytes to the message bytes.
/// Index 4 <=> 7.
BitConverter
.GetBytes(message.Address)
.Reverse()
.ToArray()
.CopyTo(bytes, 4);
bytes[8] = message.DataLength;
/// Copying data bytes to the message bytes.
/// Index 9 <=> <see cref="SIRTMessage.DataLength"/>.
message.Data.CopyTo(bytes, 9);
/// TODO: see if CRC is correct hinzugefügt.
bytes
.CalculateCRC(1, (ushort)(length - 4))
.Reverse()
.ToArray()
.CopyTo(bytes, length - 3);
bytes[length - 1] = message.StopByte;
return bytes;
}
public static byte[] CalculateCRC(this byte[] data, ushort start, ushort length)
{
var ui_index = start;
var test = default(byte);
var zeichen = default(byte);
var crc_result = ushort.MaxValue;
if (data.Length >= length + start)
{
while (ui_index < length + start)
{
zeichen = data[ui_index];
ui_index++;
for (byte h = 0; h < 8; h++)
{
test = 0;
if ((crc_result & 0x8000) != 0)
{
test = 0x80;
}
crc_result <<= 1;
if (((zeichen & 0x80) ^ test) != 0)
{
crc_result ^= 0x1021;
}
zeichen <<= 1;
}
}
}
return BitConverter.GetBytes(crc_result);
}
public static ushort ToUInt16(this byte[] data, int startIndex)
{
return BitConverter.ToUInt16(new byte[]
{
data[startIndex + 1],
data[startIndex],
}, 0);
}
public static uint ToUInt32(this byte[] data, int startIndex, bool reverced = true)
{
if (reverced)
{
return BitConverter.ToUInt32(new byte[]
{
data[startIndex + 3],
data[startIndex + 2],
data[startIndex + 1],
data[startIndex],
}, 0);
}
return BitConverter.ToUInt32(data, startIndex);
}
}
}