137 lines
3.4 KiB
C#
137 lines
3.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Collections;
|
|
|
|
namespace SN_Server
|
|
{
|
|
public class ServerMSG
|
|
{
|
|
private int len;
|
|
public int Len
|
|
{
|
|
get { return len; }
|
|
set { len = value; }
|
|
}
|
|
|
|
private int opcode;
|
|
public int OPcode
|
|
{
|
|
get { return opcode; }
|
|
set { opcode = value; }
|
|
}
|
|
|
|
private string sn; //serial number
|
|
public string SN
|
|
{
|
|
get { return sn; }
|
|
set { sn = value; }
|
|
}
|
|
|
|
private string payload;
|
|
public string Payload
|
|
{
|
|
get { return payload; }
|
|
set { payload = value; }
|
|
}
|
|
|
|
private string oldMSG;
|
|
|
|
public bool valid;
|
|
|
|
public ServerMSG()
|
|
{
|
|
}
|
|
public ServerMSG(string msg, int len)
|
|
{
|
|
oldMSG = msg;
|
|
//decode
|
|
valid = Decode(msg, len);
|
|
}
|
|
|
|
private bool Decode(string data, int actualLen)
|
|
{
|
|
bool ret = false ;
|
|
string[] tempArr = data.Split('#');
|
|
if ((tempArr.Length == 0) || (tempArr.Length == 1))
|
|
{
|
|
Console.WriteLine("incorect message=" + data);
|
|
return ret;
|
|
}
|
|
|
|
//get len
|
|
len = Convert.ToInt32(tempArr[1]);
|
|
|
|
if (actualLen != len)
|
|
{
|
|
Console.WriteLine("message length({0}) != actual length({1})", len, actualLen);
|
|
return ret;
|
|
}
|
|
|
|
//get opcode
|
|
opcode = Convert.ToInt32(tempArr[2],16);
|
|
|
|
//get serial number
|
|
sn = tempArr[3];
|
|
|
|
//get payload
|
|
payload = tempArr[4];
|
|
|
|
return ret;
|
|
}
|
|
|
|
public static string GenMsg(int opcode, string serialNr, string paylaod)
|
|
{
|
|
string temp = "#" + opcode.ToString("X4") + "#" + serialNr + "#" + paylaod + "#";
|
|
int strlen = ("#" + (temp.Length).ToString() + temp).Length;
|
|
temp = "#" + strlen.ToString() + temp;
|
|
return temp;
|
|
}
|
|
|
|
|
|
public static ArrayList Split(string data, int actualLen)
|
|
{
|
|
ArrayList ar = new ArrayList();
|
|
|
|
string[] tempArr = data.Split('#');
|
|
if ((tempArr.Length == 0) || (tempArr.Length == 1))
|
|
{
|
|
Console.WriteLine("incorect message=" + data);
|
|
return null ;
|
|
}
|
|
|
|
//get len
|
|
int len = Convert.ToInt32(tempArr[1]);
|
|
|
|
if (actualLen != len)
|
|
{
|
|
Console.WriteLine("message length({0}) != actual length({1})", len, actualLen);
|
|
Console.WriteLine(data);
|
|
|
|
if (len < actualLen)
|
|
{
|
|
string first = data.Substring(0, len);
|
|
ar.Add(first);
|
|
|
|
string leftOver = data.Substring(len, actualLen - len);
|
|
|
|
ArrayList ar_new = Split(leftOver, leftOver.Length);
|
|
if (ar_new != null)
|
|
{
|
|
foreach (string str in ar_new)
|
|
ar.Add(str);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ar.Add(data);
|
|
}
|
|
|
|
|
|
return ar;
|
|
}
|
|
}
|
|
}
|