chengsc
2025-04-14 d2588d8d1305171e7716055b23a6b5706e9cc04b
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
using Admin.NET.Core.Service;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Charts;
using Furion.Logging;
using Microsoft.AspNetCore.SignalR;
using NewLife.Serialization;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System;
using System.Drawing.Drawing2D;
using System.Net.NetworkInformation;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinExpressIntracityUpdateStoreRequest.Types;
//using WCS.Application.Util;
 
namespace WCS.Application;
public static class PLCTaskAction
{
    //服务运行状态
    public static bool boRunningState = false;
    //脱机模式
    public static bool boOffline = false;
    //自刷新
    public static bool boRefresh = false;
    //演示模式
    public static bool boDemo = false;
    //滚筒反转
    public static bool boDrumReversal = false;
    //出库锁定
    public static bool boOutLock = false;
    //入库锁定
    public static bool boEnterLock = false;
 
    public static List<PlcPositionInfo> listPositionInfo = new List<PlcPositionInfo>();
 
    private static readonly ISqlSugarClient _db = SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
    private static readonly SysCacheService sysCacheService = App.GetRequiredService<SysCacheService>();
    private static readonly SysConfigService _sysConfigService = App.GetService<SysConfigService>();
 
    private static List<WcsPlc> listPlc = new List<WcsPlc>();
    private static List<WcsDevice> listPlcDevice = new List<WcsDevice>();
    private static List<WcsPosition> listPlcPosition = new List<WcsPosition>();
    private static List<WcsAlarmInfo> listAlarmInfo = new List<WcsAlarmInfo>();
 
    private static List<PLCUtil> listPlcUtil = new List<PLCUtil>();
    private static CancellationTokenSource cts = new CancellationTokenSource();//取消线程标识
 
    private static List<ModbusUtil> listModbusUtil = new List<ModbusUtil>();
 
    public static List<ModbusUtil> modbusUtilConn
    {
        get { return listModbusUtil; }
    }
    //对外公布连接状态
    public static List<PLCUtil> listPlcConn
    {
        get { return listPlcUtil; }
    }
    // 交互点集合
    public static List<WcsDevice> plcDevices
    {
        get { return listPlcDevice; }
    }
    public static List<WcsPosition> plcPositions
    {
        get { return listPlcPosition; }
    }
    public static List<WcsPlc> plcs
    {
        get { return listPlc; }
    }
    public static event EventHandler DeviceValueChangeEvent;
    static PLCTaskAction()
    {
        //订阅事件
        DeviceValueChangeEvent += PLCService.OnChangeEvent;
        boRunningState = _sysConfigService.GetConfigValue<bool>("sys_RunningState").Result;
        boOffline = _sysConfigService.GetConfigValue<bool>("sys_Offline").Result;
        boRefresh = _sysConfigService.GetConfigValue<bool>("sys_Refresh").Result;
        boDemo = _sysConfigService.GetConfigValue<bool>("sys_demo").Result;
        boDrumReversal = _sysConfigService.GetConfigValue<bool>("sys_DrumReversal").Result;
        boOutLock = _sysConfigService.GetConfigValue<bool>("sys_BoOutLock").Result;
        boEnterLock = _sysConfigService.GetConfigValue<bool>("sys_BoEnterLock").Result;
    }
    /// <summary>
    /// 初始化PLC连接
    /// </summary>
    public static void Init()
    {
        cts.Cancel();
        listPlc = _db.Queryable<WcsPlc>()
            //.Where(s => s.Type == PLCTypeEnum.ShuttleCar || s.Type == PLCTypeEnum.ConveyorLine || s.Type == PLCTypeEnum.AGV)
            .Where(s => s.Enable == YesNoEnum.Y)
            .ToList();
        listPlcDevice = _db.Queryable<WcsDevice>().ToList();
        listPlcPosition = _db.Queryable<WcsPosition>().ToList();
        listAlarmInfo = _db.Queryable<WcsAlarmInfo>().ToList();
        //等待几秒钟,把已有线程取消掉再连接
        //Thread.Sleep(5000);
        foreach (var modPlcUtil in listPlcUtil)
        {
            modPlcUtil.Close();
        }
        listPlcUtil.Clear();
        foreach (var modPlc in listPlc)
        {
            switch (modPlc.PLCType)
            {
                case PLCEnum.None:
                    break;
                case PLCEnum.S7_200:
                case PLCEnum.S7_200Smart:
                case PLCEnum.S7_300:
                case PLCEnum.S7_400:
                case PLCEnum.S7_1200:
                case PLCEnum.S7_1500:
                    var plc = new PLCUtil(modPlc);
                    listPlcUtil.Add(plc);
                    break;
                case PLCEnum.ModBusTcp:
                    var modbus = new ModbusUtil(modPlc);
                    listModbusUtil.Add(modbus);
                    break;
                default:
                    break;
            }
 
        }
        HubUtil.UpdateService(new PLCServiceModel()
        {
            BoRunningState = boRunningState,
            BoOffline = boOffline,
            BoRefresh = boRefresh
        });
        if (boRunningState)
        {
            cts = new CancellationTokenSource();
            StartRead();
            ConnectionStatus();
            StartWatchAlarm();
            //StartWatchPosition();
        }
    }
    /// <summary>
    /// 开启读取plc线程
    /// </summary>
    public static void StartRead()
    {
        Console.WriteLine("开启读取plc线程");
        foreach (var modPlc in listPlc)
        {
            Task.Run(() =>
            {
                var _modplc = modPlc;
                while (true)
                {
                    //取消线程 关闭PLC连接
                    if (cts.Token.IsCancellationRequested)
                    {
                        foreach (var modPlcUtil in listPlcUtil)
                        {
                            if (modPlcUtil != null && modPlcUtil.Connected)
                                modPlcUtil.Close();
                        }
                        break;
                        //throw new OperationCanceledException();
                    }
                    try
                    {
                        switch (_modplc.PLCType)
                        {
                            case PLCEnum.None:
                                break;
                            case PLCEnum.S7_200:
                            case PLCEnum.S7_200Smart:
                            case PLCEnum.S7_300:
                            case PLCEnum.S7_400:
                            case PLCEnum.S7_1200:
                            case PLCEnum.S7_1500:
                                {
                                    var modPlcUtil = listPlcUtil.FirstOrDefault(s => s != null && s.PlcId == modPlc.Id);
                                    if (modPlcUtil == null)
                                    {
                                        Console.WriteLine($"连接plc{modPlc.IP}");
                                        modPlcUtil = new PLCUtil(modPlc);
                                        listPlcUtil.Add(modPlcUtil);
                                        if (modPlcUtil.Connected)
                                            Console.WriteLine($"连接plc{modPlc.IP}成功");
                                    }
                                    if (!modPlcUtil.Connected)
                                    {
                                        Thread.Sleep(100);
                                        modPlcUtil.Open();
                                        continue;
                                    }
                                    var listDevice = listPlcDevice
                                        .Where(s => s.PlcId == _modplc.Id && s.DeviceType == DeviceTypeEnum.Business)
                                        .WhereIF(modPlc.Type == PLCTypeEnum.ConveyorLine, s => s.Level == DeviceLevelEnum.DB)
                                        .ToList();
                                    //循环读设备
                                    foreach (var modDevice in listDevice)
                                    {
                                        var (result, value) = modPlcUtil.GetPlcDBValue(modDevice.PosType, modDevice.DbNumber, modDevice.PlcPos);
                                        if (result.IsSucceed)
                                        {
                                            //如果是穿梭车,这里发送心跳
                                            if (modPlc.Type == PLCTypeEnum.ShuttleCar)
                                            {
                                                var modHeart = listPlcPosition.Where(s => s.DeviceId == modDevice.Id && s.Text == "心跳").FirstOrDefault();
                                                if (modHeart != null)
                                                {
                                                    modPlcUtil.SetPlcDBValue(modHeart.PosType, modHeart.PlcPos, "1");
                                                }
                                            }
                                            //无流程跳出
                                            if (Convert.ToInt32(value) == 0)
                                                continue;
                                            var dto = modDevice.Adapt<WcsDeviceDto>();
                                            dto.Value = value;
                                            dto.Type = _modplc.Type;
                                            dto.PLCUtil = modPlcUtil;
                                            dto.listStation = listPlcPosition.Where(s => s.DeviceId == modDevice.Id).ToList();
                                            dto.listDevice = listDevice.Where(s => s.StationNum == modDevice.StationNum && s.Level == DeviceLevelEnum.Station).ToList();
                                            //这里触发值变更事件
                                            DeviceValueChangeEvent?.Invoke(dto, EventArgs.Empty);
                                        }
                                        else if (!modPlcUtil.Connected)
                                        {
                                            //重新打开连接
                                            modPlcUtil.Open();
                                        }
                                    }
                                }
                                break;
                            case PLCEnum.ModBusTcp:
                                {
                                    var modbusUtil = listModbusUtil.FirstOrDefault(s => s != null && s.PlcId == _modplc.Id);
                                    if (modbusUtil == null)
                                    {
                                        Console.WriteLine($"连接ModBus{modPlc.IP}");
                                        modbusUtil = new ModbusUtil(modPlc);
                                        listModbusUtil.Add(modbusUtil);
                                        if (modbusUtil.Connected)
                                            Console.WriteLine($"连接ModBus{modPlc.IP}成功");
                                    }
                                    if (!modbusUtil.Connected)
                                    {
                                        Thread.Sleep(100);
                                        modbusUtil.Open();
                                        continue;
                                    }
                                    var listDevice = listPlcDevice
                                        .Where(s => s.PlcId == _modplc.Id && s.DeviceType == DeviceTypeEnum.Business)
                                        .WhereIF(modPlc.Type == PLCTypeEnum.ConveyorLine, s => s.Level == DeviceLevelEnum.DB)
                                        .ToList();
                                    //循环读设备
                                    foreach (var modDevice in listDevice)
                                    {
                                        var (result, value) = modbusUtil.GetDBValue(modDevice.PosType, modDevice.PlcPos);
                                        if (result.IsSucceed)
                                        {
                                            //无流程跳出
                                            if (value == 0)
                                                continue;
                                            var dto = modDevice.Adapt<WcsDeviceDto>();
                                            dto.Value = value;
                                            dto.Type = _modplc.Type;
                                            dto.modbusUtil = modbusUtil;
                                            dto.listStation = listPlcPosition.Where(s => s.DeviceId == modDevice.Id).ToList();
                                            dto.listDevice = listDevice.Where(s => s.StationNum == modDevice.StationNum && s.Level == DeviceLevelEnum.Station).ToList();
                                            //这里触发值变更事件
                                            DeviceValueChangeEvent?.Invoke(dto, EventArgs.Empty);
                                        }
                                        else if (!modbusUtil.Connected)
                                        {
                                            //重新打开连接
                                            modbusUtil.Open();
                                        }
                                    }
                                }
 
                                break;
                            case PLCEnum.HTTP:
                                {
                                    Ping pingSender = new Ping();
                                    try
                                    {
                                        // 发送Ping请求,并等待回复
                                        PingReply reply = pingSender.Send(_modplc.IP);
 
                                        if (reply.Status == IPStatus.Success)
                                        {
                                            var listDevice = listPlcDevice
                                                .Where(s => s.PlcId == _modplc.Id && s.DeviceType == DeviceTypeEnum.Business)
                                                .ToList();
                                            foreach (var modDevice in listDevice)
                                            {
                                                var dto = modDevice.Adapt<WcsDeviceDto>();
                                                dto.modPlc = _modplc;
                                                dto.Type = _modplc.Type;
                                                dto.listStation = listPlcPosition.Where(s => s.DeviceId == modDevice.Id).ToList();
                                                dto.listDevice = listDevice.Where(s => s.StationNum == modDevice.StationNum && s.Level == DeviceLevelEnum.Station).ToList();
                                                //这里触发值变更事件
                                                DeviceValueChangeEvent?.Invoke(dto, EventArgs.Empty);
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine($"连接不到主机: {_modplc.IP} {reply.Status}");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                }
                                break;
                            default:
                                break;
                        }
 
 
 
                        Thread.Sleep(1000);
                    }
                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("中止线程");
                    }
                    catch (Exception ex)
                    {
                        Log.Error("读取PLC线程发生异常", ex);
                    }
                }
            }, cts.Token);
        }
    }
 
    /// <summary>
    /// 连接状态线程
    /// </summary>
    public static void ConnectionStatus()
    {
        Task.Run(() =>
        {
            try
            {
                Console.WriteLine("连接状态线程");
                while (true)
                {
                    //取消线程 关闭PLC连接
                    if (cts.Token.IsCancellationRequested)
                    {
                        foreach (var modPlcUtil in listPlcUtil)
                        {
                            if (modPlcUtil != null && modPlcUtil.Connected)
                                modPlcUtil.Close();
                        }
                        break;
                        //throw new OperationCanceledException();
                    }
                    //获取每个PLC连接状态
                    foreach (var modPlc in listPlc)
                    {
                        switch (modPlc.PLCType)
                        {
                            case PLCEnum.None:
                                break;
                            case PLCEnum.S7_200:
                            case PLCEnum.S7_200Smart:
                            case PLCEnum.S7_300:
                            case PLCEnum.S7_400:
                            case PLCEnum.S7_1200:
                            case PLCEnum.S7_1500:
                                {
                                    var modPlcUtil = listPlcUtil.FirstOrDefault(s => s.PlcId == modPlc.Id);
                                    if (modPlcUtil == null)
                                        modPlc.IsConn = false;
                                    else
                                        modPlc.IsConn = modPlcUtil.Connected;
                                    if (sysCacheService.ExistKey("PLCCONN:" + modPlc.Id))
                                    {
                                        var cachePlc = sysCacheService.Get<WcsPlc>("PLCCONN:" + modPlc.Id);
                                        if (cachePlc.IsConn != modPlc.IsConn)
                                        {
                                            //连接状态变更 通知前端
                                            Console.WriteLine($"通知前端变更{modPlc.Text} {modPlc.IsConn}");
                                            HubUtil.PublicPlcConn(modPlc);
                                        }
                                        sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
                                    }
                                    else
                                    {
                                        sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
                                        HubUtil.PublicPlcConn(modPlc);
                                    }
                                }
                                break;
                            case PLCEnum.ModBusTcp:
                                {
                                    var modbudUtil = listModbusUtil.FirstOrDefault(s => s.PlcId == modPlc.Id);
                                    if (modbudUtil == null)
                                        modPlc.IsConn = false;
                                    else
                                        modPlc.IsConn = modbudUtil.Connected;
                                    if (sysCacheService.ExistKey("PLCCONN:" + modPlc.Id))
                                    {
                                        var cachePlc = sysCacheService.Get<WcsPlc>("PLCCONN:" + modPlc.Id);
                                        if (cachePlc.IsConn != modPlc.IsConn)
                                        {
                                            //连接状态变更 通知前端
                                            Console.WriteLine($"通知前端变更{modPlc.Text} {modPlc.IsConn}");
                                            HubUtil.PublicPlcConn(modPlc);
                                        }
                                        sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
                                    }
                                    else
                                    {
                                        sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
                                        HubUtil.PublicPlcConn(modPlc);
                                    }
                                }
                                break;
                            default:
                                break;
                        }
 
                    }
                    Thread.Sleep(10000);
                }
            }
            catch (OperationCanceledException)
            {
                sysCacheService.RemoveByPrefixKey("PLCCONN");
                Console.WriteLine("中止线程");
            }
            catch (Exception ex)
            {
                Log.Error("连接状态线程发生异常", ex);
            }
 
        }, cts.Token);
 
    }
 
    /// <summary>
    /// 开启报警监控
    /// </summary>
    public static void StartWatchAlarm()
    {
        Task.Run(() =>
        {
            var listPlc = listAlarmInfo.GroupBy(s => new { s.PlcIP, s.PlcPort, s.Type }).Select(s => s.Key).ToList();
            List<PLCUtil> listPlcUtil = new List<PLCUtil>();
            List<ModbusUtil> listModbusUtil = new List<ModbusUtil>();
            int i = 0;
            foreach (var modPlc in listPlc.Where(s => s.Type != PLCTypeEnum.ShuttleCar))
            {
                listPlcUtil.Add(new PLCUtil(new WcsPlc() { Id = i++, IP = modPlc.PlcIP, Port = modPlc.PlcPort, PLCType = PLCEnum.S7_1500 }));
            }
            foreach (var modPlc in listPlc.Where(s => s.Type == PLCTypeEnum.ShuttleCar))
            {
                listModbusUtil.Add(new ModbusUtil(new WcsPlc() { Id = i++, IP = modPlc.PlcIP, Port = modPlc.PlcPort, PLCType = PLCEnum.ModBusTcp }));
            }
            while (true)
            {
                //取消线程 关闭PLC连接
                if (cts.Token.IsCancellationRequested)
                {
                    foreach (var modPlcUtil in listPlcUtil)
                    {
                        if (modPlcUtil != null && modPlcUtil.Connected)
                            modPlcUtil.Close();
                    }
                    foreach (var modModbusUtil in listModbusUtil)
                    {
                        if (modModbusUtil != null && modModbusUtil.Connected)
                            modModbusUtil.Close();
                    }
                    break;
                    //throw new OperationCanceledException();
                }
                try
                {
                    var listPulish = new List<WcsAlarmInfo>();
                    foreach (var modUtil in listPlcUtil)
                    {
                        //报警点位
                        var listAlarm = listAlarmInfo.Where(s => s.PlcIP == modUtil.PlcIP.ToString()).ToList();
                        var listaddress = new Dictionary<string, PLCDataTypeEnum>();
                        foreach (var modAlarm in listAlarm)
                        {
                            listaddress.Add(modAlarm.AlarmCode, PLCDataTypeEnum.Bit);
                        }
                        var result = modUtil.GetPlcBatchDBValue(listaddress);
                        foreach (var item in result.Value)
                        {
                            var value = Convert.ToBoolean(item.Value);
                            var modAlarm = listAlarm.FirstOrDefault(s => s.AlarmCode == item.Key);
                            var stationNum = modAlarm.StationNum;
                            if (value && modAlarm.Status == YesNoEnum.N)
                            {
                                //修改报警状态同时记录报警日志
                                modAlarm.AlarmTime = DateTime.Now;
                                modAlarm.Status = YesNoEnum.Y;
                                listPulish.Add(modAlarm);
                            }
                            //取消报警
                            else if (value && modAlarm.Status == YesNoEnum.Y)
                            {
                                modAlarm.AlarmTime = null;
                                modAlarm.Status = YesNoEnum.N;
                                listPulish.Add(modAlarm);
                            }
                        }
                        if (listPulish.Count > 0)
                        {
                            _db.Updateable(listPulish).ExecuteCommand();
                            var listLog = new List<WcsAlarmLog>();
                            foreach (var mod in listPulish.Where(s => s.Status == YesNoEnum.Y))
                            {
                                WcsAlarmLog modLog = mod.Adapt<WcsAlarmLog>();
                                modLog.Id = 0;
                                listLog.Add(modLog);
                            }
                            _db.Insertable(listLog).ExecuteCommand();
                            HubUtil.PublicAlarm(listPulish);
                        }
                    }
                    //穿梭车报警
                    var listCacheAlarm = sysCacheService.GetHashMap<int>("AlarmInfo_Car");
                    listPulish = new List<WcsAlarmInfo>();
                    foreach (var modCacheAlarm in listCacheAlarm)
                    {
                        if (modCacheAlarm.Value == -1)
                        {
                            //取消报警
                            var modAlarm = listAlarmInfo.FirstOrDefault(s => s.PlcIP == modCacheAlarm.Key && s.Status == YesNoEnum.Y);
                            if (modAlarm != null)
                            {
                                modAlarm.Status = YesNoEnum.N;
                                modAlarm.AlarmTime = null;
                                _db.Updateable(modAlarm).ExecuteCommand();
                                listPulish.Add(modAlarm);
                            }
                        }
                        else
                        {
                            var modAlarm = listAlarmInfo.FirstOrDefault(s => s.PlcIP == modCacheAlarm.Key && s.AlarmCode == modCacheAlarm.Value.ToString());
                            if (modAlarm != null && modAlarm.Status != YesNoEnum.Y)
                            {
                                modAlarm.Status = YesNoEnum.Y;
                                modAlarm.AlarmTime = DateTime.Now;
                                _db.Updateable(modAlarm).ExecuteCommand();
                                WcsAlarmLog modLog = new WcsAlarmLog()
                                {
                                    PlcIP = modAlarm.PlcIP,
                                    AlarmCode = modAlarm.AlarmCode,
                                    AlarmName = modAlarm.AlarmName,
                                    AlarmTime = modAlarm.AlarmTime,
                                };
                                _db.Insertable(modLog).ExecuteCommand();
                                listPulish.Add(modAlarm);
                            }
                        }
                    }
                    if (listPulish.Count > 0)
                    {
                        HubUtil.PublicAlarm(listPulish);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("报警监控发生异常", ex);
                }
                Thread.Sleep(10000);
            }
        }, cts.Token);
    }
    /// <summary>
    /// 开启位置监控
    /// </summary>
    public static void StartWatchPosition()
    {
        Console.WriteLine("开启位置监控");
        Task.Run(() =>
        {
            while (true)
            {
                //取消线程 关闭PLC连接
                if (cts.Token.IsCancellationRequested)
                {
                    foreach (var modPlcUtil in listPlcUtil)
                    {
                        if (modPlcUtil != null && modPlcUtil.Connected)
                            modPlcUtil.Close();
                    }
                    break;
                    //throw new OperationCanceledException();
                }
                try
                {
                    foreach (var modPlcUtil in listPlcUtil)
                    {
                        if (modPlcUtil == null)
                            continue;
                        var plcIp = modPlcUtil.PlcIP;
                        var listDevice = listPlcDevice.Where(s => s.PlcId == modPlcUtil.PlcId && s.DeviceType == DeviceTypeEnum.Show).ToList();
                        var modPlc = listPlc.FirstOrDefault(s => s.Id == modPlcUtil.PlcId);
                        var listaddress = new Dictionary<string, PLCDataTypeEnum>();
                        foreach (var modDevice in listDevice)
                        {
                            listaddress.Add(modDevice.DbNumber + "." + modDevice.PlcPos, modDevice.PosType);
                        }
                        //批量读
                        var result = modPlcUtil.GetPlcBatchDBValue(listaddress);
                        //测试用
                        //foreach (var modDevice in listDevice)
                        //{
                        //    if (modPlc.Type == PLCTypeEnum.StackingMachine)
                        //        result.Value.Add(modDevice.DbNumber + "." + modDevice.PlcPos, new Random().Next(790000));
                        //    else if (modPlc.Type == PLCTypeEnum.ConveyorLine)
                        //        result.Value.Add(modDevice.DbNumber + "." + modDevice.PlcPos, new Random().Next(2) == 0);
                        //}
                        foreach (var item in result.Value)
                        {
                            var modDevice = listDevice.FirstOrDefault(s => item.Key == (s.DbNumber + "." + s.PlcPos));
                            if (modDevice == null)
                                continue;
                            switch (modPlc.Type)
                            {
                                case PLCTypeEnum.StackingMachine:
                                    {
                                        var value = Convert.ToInt32(item.Value);
                                        var height = Math.Round(value / 790000d * 200).ToInt();
                                        var modPosition = listPlcPosition.FirstOrDefault(s => s.DeviceId == modDevice.Id && s.Text == "目的工位");
                                        string EndLocat = "";
                                        if (modPosition != null)
                                        {
                                            var (result2, value2) = modPlcUtil.GetPlcDBValue(modPosition.PosType, modDevice.DbNumber, modPosition.PlcPos);
                                            if (result2.IsSucceed)
                                                EndLocat = Convert.ToString(value2);
                                        }
                                        if (modDevice.BoxHeight != height || modDevice.EndLocat != EndLocat)
                                        {
                                            modDevice.EndLocat = EndLocat;
                                            modDevice.BoxHeight = Math.Round(value / 790000d * 200).ToInt();
                                            var modInfo = new PlcPositionInfo()
                                            {
                                                Type = modPlc.Type,
                                                StationNum = modDevice.StationNum,
                                                BoxHeight = modDevice.BoxHeight,
                                                EndLocat = EndLocat,
                                            };
                                            HubUtil.PublicPosition(modInfo);
                                            UpdatePosition(modInfo);
                                        }
                                    }
                                    break;
                                case PLCTypeEnum.ConveyorLine:
                                    {
                                        var bl = false;
                                        int value = Convert.ToInt32(item.Value);
                                        if (value <= 30)
                                        {
                                            bl = false;
                                        }
                                        else
                                        {
                                            bl = true;
                                        }
 
                                        if (bl != modDevice.BoHaveItem)
                                        {
                                            modDevice.BoHaveItem = bl;
                                            var modInfo = new PlcPositionInfo() { Type = modPlc.Type, StationNum = modDevice.StationNum.PadLeft(3, '0'), BoHaveItem = bl };
                                            HubUtil.PublicPosition(modInfo);
                                            UpdatePosition(modInfo);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    Thread.Sleep(3000);
                }
                catch (Exception ex)
                {
                    Log.Error("位置监控发生异常", ex);
                }
            }
        });
    }
    private static void UpdatePosition(PlcPositionInfo modInfo)
    {
        var modTemp = listPositionInfo.FirstOrDefault(s => s.StationNum == modInfo.StationNum && modInfo.Type == s.Type);
        if (modTemp == null)
        {
            listPositionInfo.Add(modInfo);
        }
        else
        {
            modTemp.BoHaveItem = modInfo.BoHaveItem;
        }
    }
    /// <summary>
    /// 停止服务
    /// </summary>
    public static void Stop()
    {
        cts.Cancel();
        boRunningState = false;
    }
}