93 lines
2.6 KiB
C#
93 lines
2.6 KiB
C#
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Globalization;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using static LibrarySDR.Helpers.BinaryHexHelper;
|
|||
|
|
|||
|
namespace LibrarySDR.Requests
|
|||
|
{
|
|||
|
public class Header
|
|||
|
{
|
|||
|
private static int sendingCounter = 0;
|
|||
|
public static int SendingCounter
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
// rest counter to value 0 after max value inside a byte
|
|||
|
if (sendingCounter > 255)
|
|||
|
sendingCounter = 0;
|
|||
|
|
|||
|
return sendingCounter++;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private static int MagicNumber = 0xA5;
|
|||
|
|
|||
|
private Int16 length;
|
|||
|
public Int16 Length { get { return length; } }
|
|||
|
|
|||
|
private Int16 counter;
|
|||
|
public Int16 Counter { get { return counter; } }
|
|||
|
|
|||
|
public Header(string hexHeader)
|
|||
|
{
|
|||
|
int i = 0;
|
|||
|
int prevIdx = 0;
|
|||
|
Int16 magicNumber = 0;
|
|||
|
|
|||
|
// get magic number
|
|||
|
String hex = LittleToBigEndianHexString(hexHeader.Substring(i = i + prevIdx, prevIdx = 2));
|
|||
|
Int16.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out magicNumber);
|
|||
|
|
|||
|
// get counter
|
|||
|
hex = LittleToBigEndianHexString(hexHeader.Substring(i = i + prevIdx, prevIdx = 2));
|
|||
|
//i = i + 2;
|
|||
|
Int16.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out counter);
|
|||
|
|
|||
|
// get length
|
|||
|
hex = LittleToBigEndianHexString(hexHeader.Substring(i = i + prevIdx, prevIdx = 2 * 2));
|
|||
|
//i = i + 4;
|
|||
|
Int16.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out length);
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public static String GetHeader(int length)
|
|||
|
{
|
|||
|
StringBuilder sb = new StringBuilder("");
|
|||
|
|
|||
|
// get the binary data for the header
|
|||
|
sb.Append(GetHeaderBinary(length));
|
|||
|
|
|||
|
// generate the hex command
|
|||
|
String headerHex = BinaryStringToHexString(sb.ToString(), Padding.RIGHT);
|
|||
|
|
|||
|
return headerHex;
|
|||
|
}
|
|||
|
|
|||
|
public static String GetHeaderBinary(int length)
|
|||
|
{
|
|||
|
StringBuilder sb = new StringBuilder("");
|
|||
|
|
|||
|
// Magic Number (8 bits)
|
|||
|
sb.Append(GetBits(MagicNumber, 8));
|
|||
|
|
|||
|
// Counter (8 bits)
|
|||
|
sb.Append(GetBits(SendingCounter, 8));
|
|||
|
|
|||
|
// Length of the following message (16 bits)
|
|||
|
sb.Append(GetBits(length, 16));
|
|||
|
|
|||
|
return sb.ToString();
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public static void ResetCounter()
|
|||
|
{
|
|||
|
sendingCounter = 0;
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
}
|