using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BatCharging.Model;
namespace BatCharging.Service
{
///
/// 设备鉴权和操作指令消息封装类-3.3
///
public class MsgSignCmdEncoder
{
///
/// 获取鉴权消息包字节列表
///
///
public byte[] GetMsgPackSignIn(byte[] destAddr,out Auth auth)
{
byte[] result = null;
APCI headAPCI = new APCI();
headAPCI.StartChar = CmnChargerConst.APCI_START_CHAR;
headAPCI.PackLen = 0; //临时赋值为零,具体数值看下面的计算结果
headAPCI.CtlArea = 0; //控制域
headAPCI.DestAddr = destAddr;//目的地址
headAPCI.SrcAddr = 0;//源地址,本系统中,源地址统一为:00000000(即为0)
byte randomNum = CmnChargerParam.GetByteRandomNum();
ASDU headASDU = new ASDU();
headASDU.FrameTypeNo = 45; //帧类型号
headASDU.MsgBodyCount = 1; //信息体个数
headASDU.TransReason = 3; //传送原因
headASDU.PublicAddr = 0; //公共地址
headASDU.MsgBodyAddr = new byte[] { 0, 0, 0 }; //信息体地址
auth = new Auth();
auth.RecordType = 24; //记录类型
auth.ClientType = 1; //客户端类型。1站控 2本地控制器 3测试客户端 4TCU模式 0未知设备
auth.ConnSeq = CmnChargerParam.GetUInt16SeqNum(); //连接序号
auth.AuthCodes = GetAuthCodesResult(CmnChargerConst.AUTH_CODE, randomNum); //鉴权码
auth.AuthCodeKey = randomNum; //鉴码KEY[随机数]
headASDU.MsgBodyContents = GetMsgContents(auth); //信息体
headAPCI.PackLen = Convert.ToUInt16(24 + headASDU.MsgBodyContents.Length); //报文长度
List lstResult = MsgHeadApciEncoder.BuildBaseAPCI(headAPCI);
lstResult.AddRange(MsgHeadAsduEncoder.BuildBaseASDU(headASDU).ToArray());
result = lstResult.ToArray();
return result;
}
///
/// 获取到异或后的鉴权字节数组
///
/// 鉴权字符串
/// 异或后的鉴权字节数组
private byte[] GetAuthCodesResult(string strAuthCodes,byte key)
{
byte[] results = new byte[8];
if (!String.IsNullOrEmpty(strAuthCodes))
{
byte[] authCodes = Encoding.ASCII.GetBytes(strAuthCodes);
results[0] = Convert.ToByte(authCodes[0] ^ key);
results[1] = Convert.ToByte(authCodes[1] ^ key);
results[2] = Convert.ToByte(authCodes[2] ^ key);
results[3] = Convert.ToByte(authCodes[3] ^ key);
results[4] = Convert.ToByte(authCodes[4] ^ key);
results[5] = Convert.ToByte(authCodes[5] ^ key);
results[6] = Convert.ToByte(authCodes[6] ^ key);
results[7] = Convert.ToByte(authCodes[7] ^ key);
}
return results;
}
///
/// 获取鉴权消息体字节数组
///
///
/// 鉴权消息体字节数组
private byte[] GetMsgContents(Auth auth)
{
byte[] results = null;
if (auth!=null)
{
List lstContent = new List();
lstContent.Add(auth.RecordType);
lstContent.Add(auth.ClientType);
lstContent.AddRange(BitConverter.GetBytes(auth.ConnSeq));
lstContent.AddRange(auth.AuthCodes);
lstContent.Add(auth.AuthCodeKey);
results = lstContent.ToArray();
}
return results;
}
}
}