wenxiangchao
2026-11-02 fe2aa4880d5c9fd88088ad0ed81ebaca05629f5f
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
using HMI.Core.Api;
using HMI.Core.Entity;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.Simple.Util;
using log4net;
using S7Driver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Timers;
 
namespace HMI.Util.Alarm
{
 
    public class AlarmHelper : IDisposable
    {
 
        public event EventHandler<List<AlarmText>> OnAlarm;
 
        public event EventHandler<LoadMsg> LoadMessageAppend;
 
        internal static ILog log = LogManager.GetLogger("AlarmHelper");
 
        internal AlarmHelper()
        {
 
        }
 
        public ObservableCollection<AlarmSetting> BlockSettings { get; private set; }
        Dictionary<string, Dictionary<string, AlarmSetting>> BlockMap = new Dictionary<string, Dictionary<string, AlarmSetting>>();
        Dictionary<string, string> BlockReadCache = new Dictionary<string, string>();
 
        public ObservableCollection<AlarmSetting> MarkSettings { get; private set; }
 
        private string blockFilePath = PathHelper.BlockAlarmSettingPath();
        private string markFilePath = PathHelper.MarkAlarmSettingPath();
 
        /// <summary>
        /// 接收报警的队列
        /// </summary>
        private MSMQHelper alarmQueue = new MSMQHelper("HMI_Alarm");
        /// <summary>
        /// 刷新报警的队列
        /// </summary>
        private MSMQHelper alarmRefershToMain = new MSMQHelper("LTHMI_Alarm_Rrfresh");
 
 
        private PLCS7Driver pLCS7Driver;
 
        private Timer plcTimer;
        private Timer mqTimer;
 
        /// <summary>
        /// 报警信息缓存
        /// </summary>
        private List<AlarmText> currentPLCAlarmCache = new List<AlarmText>();
 
        /// <summary>
        /// 报警信息缓存
        /// </summary>
        private List<AlarmText> currentMQAlarmCache = new List<AlarmText>();
 
        private bool isHaveAlarm = false;
        private volatile bool isClosing = false;
 
        public void InitInstance()
        {
            LoadMessageAppend?.Invoke(this, new LoadMsg
            {
                Type = LoadMsgType.INIT,
                Message = "加载报警设置..."
            });
            LoadAlarmSetting();
 
            var systemSetting = SystemSetting.Instance;
            pLCS7Driver = new PLCS7Driver(systemSetting.PlcIp, systemSetting.PlcPort);
 
            plcTimer = new Timer
            {
                Interval = 1000,
                AutoReset = false
            };
            plcTimer.Elapsed += PLCTimer_Elapsed;
 
            if (pLCS7Driver.Connect(out string errMSg))
            {
                plcTimer.Start();
            }
            else
            {
                LoadMessageAppend?.Invoke(this, new LoadMsg
                {
                    Type = LoadMsgType.INIT,
                    Message = "连接PLC失败",
                    Result = false
                });
            }
 
            mqTimer = new Timer
            {
                Interval = 1000,
                AutoReset = false
            };
            mqTimer.Elapsed += MQTimer_Elapsed;
            mqTimer.Enabled = true;
        }
 
        public void Dispose()
        {
            isClosing = true;
            mqTimer.Enabled = false;
            mqTimer?.Dispose();
 
            plcTimer.Enabled = false;
            plcTimer?.Dispose();
            pLCS7Driver?.Dispose();
        }
 
        /// <summary>
        /// PLC报警读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PLCTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                plcTimer.Enabled = false;
                isHaveAlarm = false;
                List<AlarmText> cache = new List<AlarmText>();
 
                foreach (var key in BlockMap.Keys)
                {
                    if (pLCS7Driver.ReadShort(key, out short alarmVal, out string errMsg) && BlockMap[key].ContainsKey(alarmVal.ToString()))
                    {
                        //if(BlockReadCache.ContainsKey(key) && alarmCode)
                        var alarmCode = alarmVal.ToString();
                        isHaveAlarm = true;
                        var text = BlockMap[key][alarmCode]?.Description;
                        var newAlarm = new AlarmText
                        {
                            PLC_DB_BLOCK = key,
                            Source = "PLC",
                            AlarmCode = alarmCode,
                            VirtualId = $"{key}.{alarmCode}",
                            Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            AlarmInfo = $"{text}",
                            Level = BlockMap[key][alarmCode]?.Level ?? 0d
                        };
                        if (currentPLCAlarmCache
                                .Find(alarm => alarm.VirtualId == newAlarm.VirtualId && alarm.PLC_DB_BLOCK == newAlarm.PLC_DB_BLOCK) == null)
                        {
                            currentPLCAlarmCache.Add(newAlarm);
                        }
                    }
                }
 
                foreach (var item in MarkSettings)
                {
                    var name = $"{item.DBAddress}.{item.StartAddress}";
                    if (pLCS7Driver.ReadShort(name, out short alarmVal, out string errMsg) && alarmVal != 0)
                    {
                        var alarmCode = alarmVal.ToString();
                        isHaveAlarm = true;
                        var newAlarm = new AlarmText
                        {
                            Source = "PLC",
                            VirtualId = alarmCode,
                            Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            AlarmInfo = item.Description
                        };
                        if (currentPLCAlarmCache
                                .Find(d => d.AlarmInfo == newAlarm.AlarmInfo) == null)
                        {
                            currentPLCAlarmCache.Add(newAlarm);
                        }
                    }
                }
                RefershAlarm();
 
                //if (!isHaveAlarm) currentAlarmCachePlc.Clear();
            }
            catch (Exception ex)
            {
                log.Error("Read PLC Alarm Data Error.", ex);
            }
            finally
            {
                if (!isClosing) plcTimer.Enabled = true;
            }
        }
 
        private void RefershAlarm()
        {
            alarmRefershToMain.Send("AlarmRefersh", string.Empty, string.Empty, 0);
            List<AlarmText> alarms = new List<AlarmText>();
 
            foreach (AlarmText alarm in currentPLCAlarmCache)
            {
                alarm.IsPLCAlarm = true;
                if (AlarmShowHelper.ShowAlarm(alarm))
                {
                    alarms.Add(alarm);
                }
            }
            currentPLCAlarmCache.Clear();
 
            foreach (AlarmText alarm in currentMQAlarmCache)
            {
                alarm.IsPLCAlarm = false;
                if (AlarmShowHelper.ShowAlarm(alarm))
                {
                    alarms.Add(alarm);
                }
            }
            currentMQAlarmCache.Clear();
 
            OnAlarm?.Invoke(this, alarms);
        }
 
        private void MQTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                mqTimer.Enabled = false;
                alarmQueue.Receive(100, out string MessageID, out MQAlarm alarm);
                if (MessageID != string.Empty && alarm != null)
                {
                    switch (MessageID)
                    {
                        case "Clear":
                            currentMQAlarmCache.Clear();
                            RefershAlarm();
                            break;
                        case "AlarmCode":
                            //AlarmText aalarm = AlarmTexts.FirstOrDefault(alarm => alarm.AlarmCode == MsgStr);
                            //if (aalarm == null) break;
                            //var data = new AlarmText
                            //{
                            //    Source = "PC",
                            //    AlarmCode = aalarm.AlarmCode,
                            //    AlarmInfo = aalarm.AlarmInfo,
                            //    Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                            //};
                            ////aalarm.Source = "PC";
                            ////aalarm.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                            //if (currentMQAlarmCache.Find(alarm => alarm.AlarmCode == aalarm.AlarmCode) == null)
                            //{
                            //    currentMQAlarmCache.Add(data);
                            //    RefershAlarm();
                            //}
                            break;
                        default:
                            string source = string.IsNullOrEmpty(alarm.Source) ? "PC" : alarm.Source;
                            string info = alarm.Content;
 
                            AlarmText newAlarm = new AlarmText
                            {
                                Source = source,
                                VirtualId = $"{source}:{info}",
                                AlarmInfo = info,
                                Level = alarm.Level,
                                Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                            };
                            if (currentMQAlarmCache
                                .Find(a => a.Source == newAlarm.Source && a.AlarmInfo == newAlarm.AlarmInfo) == null)
                            {
                                currentMQAlarmCache.Add(newAlarm);
                                RefershAlarm();
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Read MSMQ Alarm Data Failed", ex);
            }
            finally
            {
                if (!isClosing) mqTimer.Enabled = true;
            }
        }
 
        public void RefreshBlockSettings()
        {
            BlockMap.Clear();
            BlockReadCache.Clear();
            try
            {
                BlockSettings = HMI.Core.Util.XmlHelper.DeserializeFromXml<ObservableCollection<AlarmSetting>>(blockFilePath);
            }
            catch (Exception ex)
            {
                //log.Error("LoadAlarmSetting Error.", ex);
                BlockSettings = new ObservableCollection<AlarmSetting>();
            }
 
            foreach (var setting in BlockSettings)
            {
                string key = $"{setting.DBAddress}.{setting.StartAddress}";
                if (!BlockMap.ContainsKey(key))
                {
                    BlockMap[key] = new Dictionary<string, AlarmSetting>();
                }
                var codes = BlockMap[key];
                codes[setting.AlarmCode] = setting;
            }
        }
 
        public void RefreshMarkSettings()
        {
            try
            {
                MarkSettings = HMI.Core.Util.XmlHelper.DeserializeFromXml<ObservableCollection<AlarmSetting>>(markFilePath);
            }
            catch (Exception ex)
            {
                //log.Error("LoadAlarmSetting Error.", ex);
                MarkSettings = new ObservableCollection<AlarmSetting>();
            }
        }
 
        public void LoadAlarmSetting()
        {
            RefreshBlockSettings();
            RefreshMarkSettings();
        }
 
        public void UpdateBlockSettings(IEnumerable<AlarmSetting> settings)
        {
            HMI.Core.Util.XmlHelper.SerializeToXml(blockFilePath, settings);
            RefreshBlockSettings();
        }
 
        public void UpdateMarkSettings(IEnumerable<AlarmSetting> settings)
        {
            HMI.Core.Util.XmlHelper.SerializeToXml(markFilePath, settings);
            RefreshMarkSettings();
        }
    }
 
    public class AlarmUtil
    {
        static AlarmHelper Instance { get; set; }
        public static event EventHandler<List<AlarmText>> OnAlarm;
 
        public static event EventHandler<LoadMsg> LoadMessageAppend;
 
        public static ObservableCollection<AlarmSetting> BlockSettings { get => Instance?.BlockSettings; }
        public static ObservableCollection<AlarmSetting> MarkSettings { get => Instance?.MarkSettings; }
 
        public static void Init()
        {
            AlarmHelper.log.Info("AlarmUtil initing...");
            Instance = new AlarmHelper();
            Instance.LoadMessageAppend += Instance_LoadMessageAppend; ;
            Instance.InitInstance();
            Instance.OnAlarm += Instance_OnAlarm;
            AlarmHelper.log.Info("AlarmUtil inited finished.");
        }
 
        private static void Instance_LoadMessageAppend(object sender, LoadMsg e)
        {
            LoadMessageAppend?.Invoke(sender, e);
        }
 
        private static void Instance_OnAlarm(object sender, List<AlarmText> e)
        {
            OnAlarm?.Invoke(sender, e);
        }
 
        public static void Release()
        {
            if (Instance != null)
            {
                Instance.OnAlarm -= Instance_OnAlarm;
            }
            Instance?.Dispose();
            Instance = null;
        }
 
        public static void UpdateBlockSettings(IEnumerable<AlarmSetting> settings)
        {
            Instance?.UpdateBlockSettings(settings);
        }
 
        public static void UpdateMarkSettings(IEnumerable<AlarmSetting> settings)
        {
            Instance?.UpdateBlockSettings(settings);
        }
    }
}