From 2407ffe9b43986df9f3cfc1f8a14ca2021d477e8 Mon Sep 17 00:00:00 2001 From: SoulStar Date: Fri, 19 Sep 2025 15:38:46 +0800 Subject: [PATCH] =?UTF-8?q?refactor=20-=20=E9=87=8D=E6=9E=84=E8=BF=9B?= =?UTF-8?q?=E5=BA=A670%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HighWayIot.Common/XmlUtil.cs | 7 - .../HighWayIot.TouchSocket.csproj | 5 + HighWayIot.TouchSocket/MessageFactory.cs | 162 ++++++++++++++ .../ServerBufferAnalysis.cs | 204 +++++++----------- HighWayIot.TouchSocket/TcpServer.cs | 33 ++- 5 files changed, 272 insertions(+), 139 deletions(-) create mode 100644 HighWayIot.TouchSocket/MessageFactory.cs diff --git a/HighWayIot.Common/XmlUtil.cs b/HighWayIot.Common/XmlUtil.cs index aef480d..830b2c4 100644 --- a/HighWayIot.Common/XmlUtil.cs +++ b/HighWayIot.Common/XmlUtil.cs @@ -95,11 +95,4 @@ namespace HighWayIot.Common /// public string ID { get; set; } } - - public class ExportPathConfig - { - public string ExportConfig { get; set; } - - public string Config { get; set; } - } } diff --git a/HighWayIot.TouchSocket/HighWayIot.TouchSocket.csproj b/HighWayIot.TouchSocket/HighWayIot.TouchSocket.csproj index 9477bfa..b8af3ed 100644 --- a/HighWayIot.TouchSocket/HighWayIot.TouchSocket.csproj +++ b/HighWayIot.TouchSocket/HighWayIot.TouchSocket.csproj @@ -104,6 +104,7 @@ + @@ -114,6 +115,10 @@ + + {89a1edd9-d79e-468d-b6d3-7d07b8843562} + HighWayIot.Common + {DEABC30C-EC6F-472E-BD67-D65702FDAF74} HighWayIot.Log4net diff --git a/HighWayIot.TouchSocket/MessageFactory.cs b/HighWayIot.TouchSocket/MessageFactory.cs new file mode 100644 index 0000000..a3f863e --- /dev/null +++ b/HighWayIot.TouchSocket/MessageFactory.cs @@ -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 +{ + /// + /// 消息工厂 + /// + public class MessageFactory + { + private static readonly Lazy lazy = new Lazy(() => new MessageFactory()); + + public static MessageFactory Instance => lazy.Value; + + private ServerBufferAnalysis serverBufferAnalysis = ServerBufferAnalysis.Instance; + + private TcpServer tcpServer = TcpServer.Instance; + + /// + /// 消息分类工厂 + /// + 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); + } + } + + /// + /// 心跳报文处理 + /// + private void HeartbeatProcess(BaseMessagePack messagePack, string id) + { + //直接反馈 + tcpServer.SendMessage( + serverBufferAnalysis.BasePackedServerBufferAnalysis( + HeartbeatResponse(messagePack) + ), + id); + } + + /// + /// 注册报文处理 + /// + private void RegisterProcess(BaseMessagePack messagePack, string id) + { + //直接反馈 + tcpServer.SendMessage( + serverBufferAnalysis.BasePackedServerBufferAnalysis( + StandardResponse(messagePack) + ), + id); + } + + /// + /// 读码应答报文处理 + /// + private void ReadCodeReportProcess(BaseMessagePack messagePack) + { + //存数据库,无需反馈 + + } + + /// + /// 状态上报报文处理 + /// + private void StateReportProcess(BaseMessagePack messagePack, string id) + { + //存数据库,需反馈 + + tcpServer.SendMessage( + serverBufferAnalysis.BasePackedServerBufferAnalysis( + StandardResponse(messagePack) + ), + id); + } + + /// + /// 包封装(心跳响应) + /// + /// + public BaseMessagePack HeartbeatResponse(BaseMessagePack messagePack) + { + PackedData(ref messagePack, 0, new byte[0]); + + return messagePack; + } + + /// + /// 包封装(注册和状态上报响应) + /// + /// + 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; + } + + /// + /// 封装数据部分(版本号沿用,序列号自动加一) + /// + /// 源数据包 + /// 新的功能码 + /// 新的DataContent + 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)); + } + + } +} diff --git a/HighWayIot.TouchSocket/ServerBufferAnalysis.cs b/HighWayIot.TouchSocket/ServerBufferAnalysis.cs index 6842d38..9a02ee8 100644 --- a/HighWayIot.TouchSocket/ServerBufferAnalysis.cs +++ b/HighWayIot.TouchSocket/ServerBufferAnalysis.cs @@ -18,25 +18,29 @@ namespace HighWayIot.TouchSocket /// public class ServerBufferAnalysis { - private static LogHelper logHelper = LogHelper.Instance; + private static readonly Lazy lazy = new Lazy(() => new ServerBufferAnalysis()); + + public static ServerBufferAnalysis Instance => lazy.Value; + + private LogHelper logHelper = LogHelper.Instance; List tempData = new List(); /// /// 基础数据转包 /// - public void BaseServerBufferAnalysis(byte[] message) + public BaseMessagePack BaseUnpackServerBufferAnalysis(byte[] bytes) { BaseMessagePack unpackEntity = new BaseMessagePack(); int index = 1; //报文完整性验证 - if (!MessageCheck(message)) + if (!MessageCheck(bytes)) { - tempData.AddRange(message.ToList()); - message = tempData.ToArray(); - if (!MessageCheck(message)) + tempData.AddRange(bytes.ToList()); + bytes = tempData.ToArray(); + if (!MessageCheck(bytes)) { - return; + return null; } 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); index += 2; //报文字节长度 - Array.Copy(message, index, unpackEntity.Length, 0, 2); + Array.Copy(bytes, index, unpackEntity.Length, 0, 2); Array.Reverse(unpackEntity.Length); index += 2; //版本号 - unpackEntity.VersionCode = message[index]; + unpackEntity.VersionCode = bytes[index]; index++; //报文序列号 - Array.Copy(message, index, unpackEntity.SerialCode, 0, 4); + Array.Copy(bytes, index, unpackEntity.SerialCode, 0, 4); Array.Reverse(unpackEntity.SerialCode); index += 4; //时间戳 - Array.Copy(message, index, unpackEntity.TimeStamp, 0, 8); + Array.Copy(bytes, index, unpackEntity.TimeStamp, 0, 8); Array.Reverse(unpackEntity.TimeStamp); index += 8; //数据内容 int dataLength = BitConverter.ToUInt16(unpackEntity.Length, 0) - 13; unpackEntity.DataContent = new byte[dataLength]; - Array.Copy(message, index, unpackEntity.DataContent, 0, dataLength); + Array.Copy(bytes, index, unpackEntity.DataContent, 0, dataLength); index += dataLength; //校验值 - unpackEntity.CheckSum = message[index]; + unpackEntity.CheckSum = bytes[index]; //核对校验值 - byte[] checkBytes = new byte[message.Length - 4]; - Array.Copy(message, 1, checkBytes, 0, message.Length - 4); + byte[] checkBytes = new byte[bytes.Length - 4]; + Array.Copy(bytes, 1, checkBytes, 0, bytes.Length - 4); if (unpackEntity.CheckSum != CalculateCheckSum(checkBytes)) { logHelper.Error("报文校验失败!"); - return; + return null; } //到工厂分类解析 - MessageFactory(unpackEntity); + return unpackEntity; + } + + /// + /// 基础数据封包 + /// + 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; } /// @@ -123,113 +183,5 @@ namespace HighWayIot.TouchSocket return result; } - /// - /// 消息分类工厂 - /// - private void MessageFactory(BaseMessagePack messagePack) - { - int functionCode = BitConverter.ToUInt16(messagePack.FunctionCode, 0); - if (functionCode == 0) //心跳报文 - { - - } - if (functionCode == 1) //连接注册请求报文 - { - - } - if (functionCode == 600) //读码应答报文 - { - - } - if (functionCode == 610) //状态上报报文 - { - - } - - } - - ///// - ///// 心跳报文分析 - ///// - ///// - //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("心跳报文编号数值转换出现错误!"); - // } - //} - - ///// - ///// RFID发送设备状态 - ///// - ///// - //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("设备状态报文编号数值转换出现错误!"); - // } - //} - - ///// - ///// RFID发送条码 - ///// - ///// - //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("条码发送报文编号数值转换出现错误!"); - // } - //} - } } diff --git a/HighWayIot.TouchSocket/TcpServer.cs b/HighWayIot.TouchSocket/TcpServer.cs index d5cbb86..51b9014 100644 --- a/HighWayIot.TouchSocket/TcpServer.cs +++ b/HighWayIot.TouchSocket/TcpServer.cs @@ -1,4 +1,5 @@ -using HighWayIot.Log4net; +using HighWayIot.Common; +using HighWayIot.Log4net; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; @@ -22,7 +23,13 @@ namespace HighWayIot.TouchSocket 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 clientsConfigs; public ServerState State { @@ -35,12 +42,17 @@ namespace HighWayIot.TouchSocket get => !(service == null); } - TcpService service = new TcpService(); + private TcpService service = new TcpService(); - Dictionary Ids = new Dictionary(); + public List Ids = new List(); public int ConnectCount = 0; + public TcpServer() + { + clientsConfigs = _xmlUtil.ClientReader(); + } + public bool ServerStart(string host) { service = new TcpService(); @@ -54,7 +66,16 @@ namespace HighWayIot.TouchSocket service.Connected = (client, e) => { 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; };//有客户端成功连接 service.Closing = (client, e) => @@ -70,7 +91,7 @@ namespace HighWayIot.TouchSocket };//有客户端断开连接 service.Received = (client, e) => { - _serverBufferAnalysis.BaseServerBufferAnalysis(e.ByteBlock.Span.ToArray()); + _messageFactory.Factory(_serverBufferAnalysis.BaseUnpackServerBufferAnalysis(e.ByteBlock.Span.ToArray()), client.Id); return EasyTask.CompletedTask; };