81 lines
2.1 KiB
C#
81 lines
2.1 KiB
C#
using OmniPlus.Connection;
|
|
|
|
using System;
|
|
|
|
namespace OmniPlus.Connections.Messages
|
|
{
|
|
public class IrdaMessage : SerialPortMessage
|
|
{
|
|
public const int MIN_LENGTH = 5;
|
|
public const int CRC_LENGTH = 2;
|
|
|
|
public IrdaMessage(byte[] bytes, bool full = false) : base(bytes, full)
|
|
{
|
|
}
|
|
|
|
public byte Start
|
|
{
|
|
get => this.bytes[0];
|
|
set => this.bytes[0] = value;
|
|
}
|
|
|
|
public byte Type
|
|
{
|
|
get => this.bytes[1];
|
|
set => this.bytes[1] = value;
|
|
}
|
|
|
|
public byte DataLength
|
|
{
|
|
get => this.bytes[2];
|
|
set => this.bytes[2] = value;
|
|
}
|
|
|
|
public void CopyCRC16(byte[] bytes, int sourceIndex)
|
|
{
|
|
var crcPosition = this.bytes.Length - CRC_LENGTH;
|
|
|
|
Array.Copy(bytes, sourceIndex, this.bytes, crcPosition, CRC_LENGTH);
|
|
|
|
var crc16 = this.bytes.CalculateCRC(0, crcPosition);
|
|
|
|
if (crc16[0] == this.bytes[crcPosition] && crc16[0] == this.bytes[crcPosition + 1])
|
|
{
|
|
// TODO: message validated.
|
|
}
|
|
}
|
|
|
|
protected override byte[] CreateMessage(byte[] payload)
|
|
{
|
|
var messageLength = payload.Length;
|
|
messageLength += messageLength % 2;
|
|
|
|
var index = 0;
|
|
var message = new byte[messageLength + 5];
|
|
message[index++] = IrdaConnection.MSG_START;
|
|
message[index++] = IrdaConnection.MSG_PC2OMNI;
|
|
message[index++] = (byte)(messageLength / 2);
|
|
|
|
payload.CopyTo(message, index);
|
|
|
|
messageLength = message.Length;
|
|
|
|
var crc16 = message.CalculateCRC(0, messageLength - CRC_LENGTH);
|
|
message[messageLength - 2] = crc16[1];
|
|
message[messageLength - 1] = crc16[0];
|
|
|
|
return message;
|
|
}
|
|
|
|
protected override byte[] ParseMessage(byte[] message)
|
|
{
|
|
var payloadLength = message.Length - MIN_LENGTH;
|
|
var payload = new byte[payloadLength];
|
|
|
|
Array.Copy(message, 3, payload, 0, payloadLength);
|
|
|
|
return payload;
|
|
}
|
|
}
|
|
}
|