refactor - 重构进度70%

dep
SoulStar 3 months ago
parent e6d718f3ee
commit 2407ffe9b4

@ -95,11 +95,4 @@ namespace HighWayIot.Common
/// </summary> /// </summary>
public string ID { get; set; } public string ID { get; set; }
} }
public class ExportPathConfig
{
public string ExportConfig { get; set; }
public string Config { get; set; }
}
} }

@ -104,6 +104,7 @@
<ItemGroup> <ItemGroup>
<Compile Include="ClientStringAnalysis.cs" /> <Compile Include="ClientStringAnalysis.cs" />
<Compile Include="Entity\BaseMessagePack.cs" /> <Compile Include="Entity\BaseMessagePack.cs" />
<Compile Include="MessageFactory.cs" />
<Compile Include="ServerBufferAnalysis.cs" /> <Compile Include="ServerBufferAnalysis.cs" />
<Compile Include="TcpClientServer.cs" /> <Compile Include="TcpClientServer.cs" />
<Compile Include="TcpServer.cs" /> <Compile Include="TcpServer.cs" />
@ -114,6 +115,10 @@
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj"> <ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</Project> <Project>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</Project>
<Name>HighWayIot.Log4net</Name> <Name>HighWayIot.Log4net</Name>

@ -0,0 +1,162 @@
using HighWayIot.TouchSocket.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace HighWayIot.TouchSocket
{
/// <summary>
/// 消息工厂
/// </summary>
public class MessageFactory
{
private static readonly Lazy<MessageFactory> lazy = new Lazy<MessageFactory>(() => new MessageFactory());
public static MessageFactory Instance => lazy.Value;
private ServerBufferAnalysis serverBufferAnalysis = ServerBufferAnalysis.Instance;
private TcpServer tcpServer = TcpServer.Instance;
/// <summary>
/// 消息分类工厂
/// </summary>
public void Factory(BaseMessagePack messagePack, string id)
{
if (messagePack == null)
{
return;
}
int functionCode = BitConverter.ToUInt16(messagePack.FunctionCode, 0);
if (functionCode == 0) //心跳报文
{
HeartbeatProcess(messagePack, id);
}
if (functionCode == 1) //连接注册请求报文
{
RegisterProcess(messagePack, id);
}
if (functionCode == 600) //读码报文接收
{
ReadCodeReportProcess(messagePack);
}
if (functionCode == 610) //状态上报报文
{
StateReportProcess(messagePack, id);
}
}
/// <summary>
/// 心跳报文处理
/// </summary>
private void HeartbeatProcess(BaseMessagePack messagePack, string id)
{
//直接反馈
tcpServer.SendMessage(
serverBufferAnalysis.BasePackedServerBufferAnalysis(
HeartbeatResponse(messagePack)
),
id);
}
/// <summary>
/// 注册报文处理
/// </summary>
private void RegisterProcess(BaseMessagePack messagePack, string id)
{
//直接反馈
tcpServer.SendMessage(
serverBufferAnalysis.BasePackedServerBufferAnalysis(
StandardResponse(messagePack)
),
id);
}
/// <summary>
/// 读码应答报文处理
/// </summary>
private void ReadCodeReportProcess(BaseMessagePack messagePack)
{
//存数据库,无需反馈
}
/// <summary>
/// 状态上报报文处理
/// </summary>
private void StateReportProcess(BaseMessagePack messagePack, string id)
{
//存数据库,需反馈
tcpServer.SendMessage(
serverBufferAnalysis.BasePackedServerBufferAnalysis(
StandardResponse(messagePack)
),
id);
}
/// <summary>
/// 包封装(心跳响应)
/// </summary>
/// <returns></returns>
public BaseMessagePack HeartbeatResponse(BaseMessagePack messagePack)
{
PackedData(ref messagePack, 0, new byte[0]);
return messagePack;
}
/// <summary>
/// 包封装(注册和状态上报响应)
/// </summary>
/// <returns></returns>
public BaseMessagePack StandardResponse(BaseMessagePack messagePack)
{
//解析来时报文
//看了一眼协议好像不太用解析
//封包应答报文
byte[] data = new byte[6];
int index = 0;
//来时报文序列号
Array.Reverse(messagePack.SerialCode);
Array.Copy(messagePack.SerialCode, 0, data, index, 4);
Array.Reverse(messagePack.SerialCode);
index += 4;
//来时报文功能码
Array.Reverse(messagePack.FunctionCode);
Array.Copy(messagePack.FunctionCode, 0, data, index, 2);
Array.Reverse(messagePack.FunctionCode);
index += 2;
PackedData(ref messagePack, 10, data);
return messagePack;
}
/// <summary>
/// 封装数据部分(版本号沿用,序列号自动加一)
/// </summary>
/// <param name="messagePack">源数据包</param>
/// <param name="functionCode">新的功能码</param>
/// <param name="dataContent">新的DataContent</param>
public void PackedData(ref BaseMessagePack messagePack, ushort functionCode, byte[] dataContent)
{
if (dataContent == null)
{
return;
}
messagePack.Length = BitConverter.GetBytes(functionCode);
uint code = BitConverter.ToUInt32(messagePack.SerialCode, 0);
code++;
messagePack.SerialCode = BitConverter.GetBytes(code);
messagePack.TimeStamp = BitConverter.GetBytes(Convert.ToUInt64(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()));
messagePack.DataContent = dataContent;
messagePack.Length = BitConverter.GetBytes(Convert.ToUInt16(messagePack.DataContent.Length + 13u));
}
}
}

@ -18,25 +18,29 @@ namespace HighWayIot.TouchSocket
/// </summary> /// </summary>
public class ServerBufferAnalysis public class ServerBufferAnalysis
{ {
private static LogHelper logHelper = LogHelper.Instance; private static readonly Lazy<ServerBufferAnalysis> lazy = new Lazy<ServerBufferAnalysis>(() => new ServerBufferAnalysis());
public static ServerBufferAnalysis Instance => lazy.Value;
private LogHelper logHelper = LogHelper.Instance;
List<byte> tempData = new List<byte>(); List<byte> tempData = new List<byte>();
/// <summary> /// <summary>
/// 基础数据转包 /// 基础数据转包
/// </summary> /// </summary>
public void BaseServerBufferAnalysis(byte[] message) public BaseMessagePack BaseUnpackServerBufferAnalysis(byte[] bytes)
{ {
BaseMessagePack unpackEntity = new BaseMessagePack(); BaseMessagePack unpackEntity = new BaseMessagePack();
int index = 1; int index = 1;
//报文完整性验证 //报文完整性验证
if (!MessageCheck(message)) if (!MessageCheck(bytes))
{ {
tempData.AddRange(message.ToList()); tempData.AddRange(bytes.ToList());
message = tempData.ToArray(); bytes = tempData.ToArray();
if (!MessageCheck(message)) if (!MessageCheck(bytes))
{ {
return; return null;
} }
else else
{ {
@ -45,49 +49,105 @@ namespace HighWayIot.TouchSocket
} }
//功能码 //功能码
Array.Copy(message, index, unpackEntity.FunctionCode, 0, 2); Array.Copy(bytes, index, unpackEntity.FunctionCode, 0, 2);
Array.Reverse(unpackEntity.FunctionCode); Array.Reverse(unpackEntity.FunctionCode);
index += 2; index += 2;
//报文字节长度 //报文字节长度
Array.Copy(message, index, unpackEntity.Length, 0, 2); Array.Copy(bytes, index, unpackEntity.Length, 0, 2);
Array.Reverse(unpackEntity.Length); Array.Reverse(unpackEntity.Length);
index += 2; index += 2;
//版本号 //版本号
unpackEntity.VersionCode = message[index]; unpackEntity.VersionCode = bytes[index];
index++; index++;
//报文序列号 //报文序列号
Array.Copy(message, index, unpackEntity.SerialCode, 0, 4); Array.Copy(bytes, index, unpackEntity.SerialCode, 0, 4);
Array.Reverse(unpackEntity.SerialCode); Array.Reverse(unpackEntity.SerialCode);
index += 4; index += 4;
//时间戳 //时间戳
Array.Copy(message, index, unpackEntity.TimeStamp, 0, 8); Array.Copy(bytes, index, unpackEntity.TimeStamp, 0, 8);
Array.Reverse(unpackEntity.TimeStamp); Array.Reverse(unpackEntity.TimeStamp);
index += 8; index += 8;
//数据内容 //数据内容
int dataLength = BitConverter.ToUInt16(unpackEntity.Length, 0) - 13; int dataLength = BitConverter.ToUInt16(unpackEntity.Length, 0) - 13;
unpackEntity.DataContent = new byte[dataLength]; unpackEntity.DataContent = new byte[dataLength];
Array.Copy(message, index, unpackEntity.DataContent, 0, dataLength); Array.Copy(bytes, index, unpackEntity.DataContent, 0, dataLength);
index += dataLength; index += dataLength;
//校验值 //校验值
unpackEntity.CheckSum = message[index]; unpackEntity.CheckSum = bytes[index];
//核对校验值 //核对校验值
byte[] checkBytes = new byte[message.Length - 4]; byte[] checkBytes = new byte[bytes.Length - 4];
Array.Copy(message, 1, checkBytes, 0, message.Length - 4); Array.Copy(bytes, 1, checkBytes, 0, bytes.Length - 4);
if (unpackEntity.CheckSum != CalculateCheckSum(checkBytes)) if (unpackEntity.CheckSum != CalculateCheckSum(checkBytes))
{ {
logHelper.Error("报文校验失败!"); logHelper.Error("报文校验失败!");
return; return null;
} }
//到工厂分类解析 //到工厂分类解析
MessageFactory(unpackEntity); return unpackEntity;
}
/// <summary>
/// 基础数据封包
/// </summary>
public byte[] BasePackedServerBufferAnalysis(BaseMessagePack message)
{
int length = BitConverter.ToUInt16(message.Length, 0) + 8;
byte[] bytes = new byte[length];
int index = 0;
//起始字符
bytes[index] = 0x3A;
index++;
//功能码
Array.Reverse(message.FunctionCode);
Array.Copy(message.FunctionCode, 0, bytes, index, 2);
index += 2;
//报文字节长度
Array.Reverse(message.Length);
Array.Copy(message.Length, 0, bytes, index, 2);
index += 2;
//版本号
bytes[index] = message.VersionCode;
index++;
//报文序列号
Array.Reverse(message.SerialCode);
Array.Copy(message.SerialCode, 0, bytes, index, 4);
index += 4;
//时间戳
Array.Reverse(message.TimeStamp);
Array.Copy(message.TimeStamp, 0, bytes, index, 8);
index += 8;
//数据内容
Array.Reverse(message.Length);
int dataLength = BitConverter.ToUInt16(message.Length, 0) - 13;
Array.Copy(message.DataContent, 0, bytes, index, dataLength);
index += dataLength;
//校验值
byte[] checkBytes = new byte[bytes.Length - 4];
Array.Copy(bytes, 1, checkBytes, 0, bytes.Length - 4);
bytes[index] = CalculateCheckSum(checkBytes);
//结束字符1
bytes[index] = 0x0D;
//结束字符2
bytes[index] = 0x0A;
return bytes;
} }
/// <summary> /// <summary>
@ -123,113 +183,5 @@ namespace HighWayIot.TouchSocket
return result; return result;
} }
/// <summary>
/// 消息分类工厂
/// </summary>
private void MessageFactory(BaseMessagePack messagePack)
{
int functionCode = BitConverter.ToUInt16(messagePack.FunctionCode, 0);
if (functionCode == 0) //心跳报文
{
}
if (functionCode == 1) //连接注册请求报文
{
}
if (functionCode == 600) //读码应答报文
{
}
if (functionCode == 610) //状态上报报文
{
}
}
///// <summary>
///// 心跳报文分析
///// </summary>
///// <param name="bytes"></param>
//public static void HeartbeatSocket(byte[] bytes)
//{
// if (int.TryParse(Encoding.ASCII.GetString(bytes, 4, 4), out int deviceno))
// {
// BaseHeartbeatServiceImpl sql = new BaseHeartbeatServiceImpl();
// if (sql.UpdateHeartbeatInfo(deviceno) == 0)
// {
// RFIDHeartbeat heartbeat = new RFIDHeartbeat()
// {
// DeviceNo = deviceno,
// BeatTime = DateTime.Now,
// };
// sql.AddHeartbeatInfo(heartbeat);
// }
// }
// else
// {
// logHelper.Error("心跳报文编号数值转换出现错误!");
// }
//}
///// <summary>
///// RFID发送设备状态
///// </summary>
///// <param name="bytes"></param>
//public static void RFIDStatusSocket(byte[] bytes)
//{
// if (int.TryParse(Encoding.ASCII.GetString(bytes, 4, 4), out int deviceno) &&
// int.TryParse(Encoding.ASCII.GetString(bytes, 9, 1), out int state))
// {
// BaseStateServiceImpl sql = new BaseStateServiceImpl();
// RFIDState rFIDState = new RFIDState()
// {
// DeviceNo = deviceno,
// DeviceState = state == 1 ? true : false,
// LogTime = DateTime.Now,
// };
// sql.AddStateInfo(rFIDState);
// }
// else
// {
// logHelper.Error("设备状态报文编号数值转换出现错误!");
// }
//}
///// <summary>
///// RFID发送条码
///// </summary>
///// <param name="bytes"></param>
//public static void RFIDCodeSocket(byte[] bytes)
//{
// string readKind = Encoding.ASCII.GetString(bytes, 4, 2);
// if (int.TryParse(Encoding.ASCII.GetString(bytes, 7, 4), out int deviceno))
// {
// RFIDContent rFIDContent = new RFIDContent()
// {
// DeviceNo = deviceno,
// ReadKind = readKind,
// LogTime = DateTime.Now,
// };
// string content = "";
// if (readKind == "NB" || readKind == "GR")
// {
// content = Encoding.ASCII.GetString(bytes, 12, 16);
// }
// else if (readKind == "MR")
// {
// content = Encoding.ASCII.GetString(bytes, 12, bytes.Length - 12 - 2); // 减去条码内容之前和之后内容的长度
// }
// rFIDContent.Content = content;
// BaseContentServiceImpl sql = new BaseContentServiceImpl();
// sql.AddContentInfo(rFIDContent);
// }
// else
// {
// logHelper.Error("条码发送报文编号数值转换出现错误!");
// }
//}
} }
} }

@ -1,4 +1,5 @@
using HighWayIot.Log4net; using HighWayIot.Common;
using HighWayIot.Log4net;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -22,7 +23,13 @@ namespace HighWayIot.TouchSocket
private static LogHelper logHelper = LogHelper.Instance; private static LogHelper logHelper = LogHelper.Instance;
private ServerBufferAnalysis _serverBufferAnalysis = new ServerBufferAnalysis(); private ServerBufferAnalysis _serverBufferAnalysis = ServerBufferAnalysis.Instance;
private MessageFactory _messageFactory = MessageFactory.Instance;
private XmlUtil _xmlUtil = XmlUtil.Instance;
private List<ClientsConfig> clientsConfigs;
public ServerState State public ServerState State
{ {
@ -35,12 +42,17 @@ namespace HighWayIot.TouchSocket
get => !(service == null); get => !(service == null);
} }
TcpService service = new TcpService(); private TcpService service = new TcpService();
Dictionary<string, string> Ids = new Dictionary<string, string>(); public List<string> Ids = new List<string>();
public int ConnectCount = 0; public int ConnectCount = 0;
public TcpServer()
{
clientsConfigs = _xmlUtil.ClientReader();
}
public bool ServerStart(string host) public bool ServerStart(string host)
{ {
service = new TcpService(); service = new TcpService();
@ -54,7 +66,16 @@ namespace HighWayIot.TouchSocket
service.Connected = (client, e) => service.Connected = (client, e) =>
{ {
logHelper.Info($"客户端{client.IP}:{client.Port}成功连接"); logHelper.Info($"客户端{client.IP}:{client.Port}成功连接");
ConnectCount++; var now = clientsConfigs.Where(x => x.IP == client.IP && x.Port == client.Port.ToString()).FirstOrDefault();
if (now == null)
{
client.Close();
}
else
{
ConnectCount++;
Ids.Add(now.ID);
}
return EasyTask.CompletedTask; return EasyTask.CompletedTask;
};//有客户端成功连接 };//有客户端成功连接
service.Closing = (client, e) => service.Closing = (client, e) =>
@ -70,7 +91,7 @@ namespace HighWayIot.TouchSocket
};//有客户端断开连接 };//有客户端断开连接
service.Received = (client, e) => service.Received = (client, e) =>
{ {
_serverBufferAnalysis.BaseServerBufferAnalysis(e.ByteBlock.Span.ToArray()); _messageFactory.Factory(_serverBufferAnalysis.BaseUnpackServerBufferAnalysis(e.ByteBlock.Span.ToArray()), client.Id);
return EasyTask.CompletedTask; return EasyTask.CompletedTask;
}; };

Loading…
Cancel
Save