zs
2024-11-06 2f0fe710bf011d4f0051339bfbfebb597bff1a50
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using DataCapture_MA.Const;
using DataCapture_MA.Entity;
using DataCapture_MA.log4Net;
using DataCapture_MA.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
 
namespace DataCapture_MA.DataHnadle
{
    public class ReceiveDataHandle
    {
        public static void SaveDataForSqlite(MessageAnalysis messageAnalysis)
        {
            try
            {
                using(DbModel dbModel = new DbModel())
                {
                    var robotInfo = AutoMapper.Mapper.Map<MessageAnalysis, RobotInfo>(messageAnalysis);
                    robotInfo.WarnningContent = JsonConvert.SerializeObject(messageAnalysis.Warnings);
                    robotInfo.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    robotInfo.CreateStamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                    dbModel.RobotInfo.Add(robotInfo);
                    dbModel.SaveChanges();
                }
            }
            catch(Exception ex)
            {
                Log4NetHelper.WriteErrorLog(LogType.Receive, "保存至数据库异常:" + ex.Message);
            }
        }
 
        public static void SendWarnForMes(MessageAnalysis messageAnalysis)
        {
            var sendCount = 0;
            Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备完整信息:" + JsonConvert.SerializeObject(messageAnalysis));
            while (true)
            {
                try
                {
                    if (sendCount >= 5)
                    {
                        Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备报警信息失败停止推送");
                        return;
                    }
                    // 推送
                    var pushResult = MesApiHelper.PushEquipmentWarning(messageAnalysis);
                    if(pushResult != null && pushResult.statusCode == 0)
                    {
                        Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备报警消息至mes成功,返回:" + JsonConvert.SerializeObject(pushResult));
                        return;
                    }
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备报警消息至mes失败,返回:" + JsonConvert.SerializeObject(pushResult));
                    Thread.Sleep(2000);
                    sendCount++;
                }
                catch (Exception ex)
                {
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送报警消息至mes失败:" + ex.Message);
                    sendCount++;
                    continue;
 
                }
            }
        }
        public static void SendEquipmentStatusForMes(MessageAnalysis messageAnalysis)
        {
            var sendCount = 0;
            Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备完整信息:" + JsonConvert.SerializeObject(messageAnalysis));
            while (true)
            {
                try
                {
                    if (sendCount >= 5)
                    {
                        Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备状态信息失败停止推送");
                        return;
                    }
                    // 推送
                    var pushResult = MesApiHelper.PushEquipmentStatus(messageAnalysis);
                    if (pushResult != null && pushResult.statusCode == 0)
                    {
                        Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备状态消息至mes成功,返回:"+JsonConvert.SerializeObject(pushResult) );
                        return;
                    }
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备状态消息至mes失败,返回:" + JsonConvert.SerializeObject(pushResult));
                    Thread.Sleep(2000);
                    sendCount++;
                }
                catch (Exception ex)
                {
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备状态消息至mes失败:" + ex.Message);
                    sendCount++;
                    continue;
                }
            }
        }
        public static void SendEquipmentInfoForMes(MessageAnalysis messageAnalysis)
        {
            var sendCount = 0;
            Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备完整信息:" + JsonConvert.SerializeObject(messageAnalysis));
            while (true)
            {
                try
                {
                    if (sendCount >= 5)
                    {
                        Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备信息失败停止推送");
                        return;
                    }
                    // 推送
                    var pushResult = MesApiHelper.PushEquipmentInfo(messageAnalysis);
                    if (pushResult != null && pushResult.statusCode == 0)
                    {
                        Log4NetHelper.WriteInfoLog(LogType.PushMes, "推送设备消息至mes成功,返回:" + JsonConvert.SerializeObject(pushResult));
                        return;
                    }
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送设备消息至mes失败,返回:" + JsonConvert.SerializeObject(pushResult));
                    Thread.Sleep(2000);
                    sendCount ++ ;
                }
                catch (Exception ex)
                {
                    Log4NetHelper.WriteErrorLog(LogType.PushMes, "推送消息至mes失败:" + ex.Message);
                    sendCount++;
                    continue;
                }
            }
        }
 
        public static void AnalysisMeassage(string message)
        {
            try
            {
                // 解析收到的消息
                var messageAnalysis = new MessageAnalysis();
 
                foreach (var entry in DictMapping.fieldMapping)
                {
                    try
                    {
                        string tag = entry.Key;
                        string propertyName = entry.Value;
                        if (tag.Contains("MSGBUF")) continue;
 
                        // 正则表达式匹配标签内容
                        string pattern = $@"<{Regex.Escape(tag.Trim())}>(.*?)</{Regex.Escape(tag.Trim())}>";
                        Match match = Regex.Match(message, pattern);
 
                        if (!match.Success) 
                            continue;
 
                        string value = match.Groups[1].Value.Trim(); // 提取内容并去掉首尾空格
 
                        // 通过反射将值赋给实体类属性
                        PropertyInfo property = typeof(MessageAnalysis).GetProperty(propertyName);
                        if (property == null) { continue; }
 
                        if (property.PropertyType == typeof(int))
                        {
                            property.SetValue(messageAnalysis, int.Parse(value));
                        }
                        else if (property.PropertyType == typeof(bool))
                        {
                            property.SetValue(messageAnalysis, bool.Parse(value));
                        }
                        else
                        {
                            property.SetValue(messageAnalysis, value);
                        }
                    }
                    catch(Exception ex)
                    {
                        // 记录错误日志
                        Log4NetHelper.WriteErrorLog(LogType.Receive, "获取消息赋值失败:" + ex.Message);
                    }
                }
                Log4NetHelper.WriteInfoLog(LogType.Receive, JsonConvert.SerializeObject(messageAnalysis));
                // 处理报警信息
                var errorMsg = GetErrorMsg(message);
                if (!string.IsNullOrEmpty(errorMsg))
                {
                    var warringList = WarningInfoHandle(errorMsg);
                    messageAnalysis.Warnings = warringList;
                    Log4NetHelper.WriteInfoLog(LogType.Receive,"报警信息:"+ JsonConvert.SerializeObject(warringList));
                }
                // 推送mes
                _ = Task.Run(() => SendWarnForMes(messageAnalysis));
                _ = Task.Run(() => SendEquipmentStatusForMes(messageAnalysis));
                _ = Task.Run(() => SendEquipmentInfoForMes(messageAnalysis));
 
                // Sqlite数据库保存一份
                _ = Task.Run(() => SaveDataForSqlite(messageAnalysis));
            }
            catch(Exception ex)
            {
                // 记录错误日志
                Log4NetHelper.WriteErrorLog(LogType.Receive, "解析收到消息异常:" + ex.Message);
            }
        }
        private static string GetErrorMsg(string message)
        {
            try
            {
 
                string numberPattern = @"(<ENUMBER>.*?<\/ENUMBER>)";
                Match numberMatch = Regex.Match(message, numberPattern);
 
                // 正则表达式匹配 MSGBUF 标签
                string msgbufPattern = @"(<MSGBUF\[\d+\].NR>.*?<\/MSGBUF\[\d+\].NR>)";
                MatchCollection msgbufMatches = Regex.Matches(message, msgbufPattern);
 
                // 拼接结果
                string result = "";
                var num = "0";
                if (numberMatch.Success)
                {
                    result += numberMatch.Groups[1].Value + Environment.NewLine;
 
                    string pattern = $@"<ENUMBER>(.*?)</ENUMBER>";
                    Match match = Regex.Match(result, pattern);
                    if (match.Success)
                    {
                        num = match.Groups[1].Value.Trim();
                        if (num == "0") return "";
                    }
 
                }
                var count = 0;
                foreach (Match match in msgbufMatches)
                {
                    if (count >= Convert.ToInt32(num))
                    {
                        return result;
                    }
                    result += match.Groups[1].Value + Environment.NewLine;
                    count++;
 
                }
                return result;
            }
            catch(Exception ex)
            {
                // 记录错误日志
                Log4NetHelper.WriteErrorLog(LogType.Receive,"获取报警信息异常:"+ex.Message);
                return "";
            }
        }
 
        private static List<WarningInfo> WarningInfoHandle(string errMsg)
        {
            var warns = new List<WarningInfo>();
            if (string.IsNullOrEmpty(errMsg))
            {
                return warns;
            }
            string pattern = @"<MSGBUF\[\d+\].NR>(.*?)<\/MSGBUF\[\d+\].NR>";
            MatchCollection matches = Regex.Matches(errMsg, pattern);
 
            foreach (Match match in matches)
            {
                var warn = new WarningInfo();
                string msgContent = match.Groups[1].Value.Trim();
                if (!string.IsNullOrEmpty(msgContent))
                {
                    //result += msgContent + ";"; // 添加分割符
                    CacheWarningDict.WarningDict.TryGetValue(msgContent, out var warnContent);
                    if (warnContent != null)
                    {
                        warn.WarningContent = warnContent.WarningContent.Trim();
                        warn.WarningCode = warnContent.WarningCode;
                    }
                    warn.WarningCache = msgContent;
                }
                // 获取报警描述信息
 
                warns.Add(warn);
            }
 
            return warns;
        }
    }
}