ke_junjie
2025-06-04 84620534eb627e95811b971a4b552b6a177829bf
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
using iWareCC.BLL;
using iWareCC.Common.Helper;
using iWareCC.DeviceThreadFactory;
using iWareCC.Forms;
using iWareCC.RgvService;
using iWareCC.SrmService;
using iWareCC.ConveyorService;
 
using iWareCommon.Utils;
using iWareModel;
using iWareSql.DataAccess;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using XiGang.Core.Model;
using iWareSql.DbOrm;
using System.Runtime.InteropServices;
using Admin.NET.Core.TaskModule.Enum;
using System.Text;
using System.Xml.Linq;
 
namespace iWareCC
{
    public partial class FormCC : Form
    {
        //AutoSizeFormClass asc_panel_DeviceTaskList = new AutoSizeFormClass();
 
        public static string current_rgv_stationName;
 
        /// <summary>
        /// 是否模拟PLC
        /// </summary>
        public static bool IsSimulationPLC = ConfigHelper.GetConfigBool("IsSimulationPLC");
 
        private string currentCheckModelText = "";
 
        const int cycleDelay_Device = 1000;//各个线程的延迟毫秒数
        const int cycleDelay_Task = 1000;
 
        Thread startModelTipsThread;//启动线程提示
        private bool isStartModelTipsThread = false;//是否启动了线程提示
        private Color default_btn_Start_Color = Color.FromArgb(0, 192, 0);//默认的开始模拟按钮颜色
        private Color ss_btn_Start_Color1 = Color.FromArgb(255, 255, 192);//开始模拟按钮后闪烁的颜色1
        private Color ss_btn_Start_Color2 = Color.FromArgb(192, 192, 255);//开始模拟按钮后闪烁的颜色1
 
        #region 信息获取线程
        Thread tskSetSrmLable;//各种堆垛机工作状态的显示的控制线程  
 
        Thread tskGetConveyerInfo;//获取RGV信息的线程
        #endregion
 
        #region 堆垛机变量
        /// <summary>
        /// 堆垛机的枚举变量列表
        /// </summary>
        public static List<EDevice> SrmDeviceList;
        /// <summary>
        /// 堆垛机的实时数据对象字典
        /// key:EDevice的Int值, Value:SrmView
        /// </summary>
        public static IDictionary<int, SrmView> srmViewDict;
        #endregion
 
        public static ConveyerView conveyerView;//Rgv实体类
        public static ConveyerServiceClient conveyerServiceClient = null;
        public static bool IsAGVAllowSendTranTask = false;
 
        public FormCC()
        {
            InitializeComponent();
 
            SrmDeviceList = BusinessHelper.GetSrmDeviceList();
 
            //初始化数据
            InitSrmDict();
 
            CheckForIllegalCrossThreadCalls = false;
 
            //startModelTipsThread = new Thread(ShowTipsWhenStartModel);
            //startModelTipsThread.Start();
 
            #region 获取设备数据
            ParameterizedThreadStart parStart1 = new ParameterizedThreadStart(GetSrmInfo);
            Thread thread1 = new Thread(parStart1);
            object o1 = (int)EDevice.堆垛机;
            thread1.Start(o1);
 
            //ParameterizedThreadStart parStart2 = new ParameterizedThreadStart(GetSrmInfo);
            //Thread thread2 = new Thread(parStart2);
            //object o2 = (int)EDevice.二号堆垛机;
            //thread2.Start(o2);
 
 
            tskGetConveyerInfo = new Thread(GetConveyorInfo);
            tskGetConveyerInfo.Start();
 
 
            //堆垛机UI赋值
            //SetSrmUI();
 
            #endregion
 
            #region 设置显示UI
            //tskSetSrmLable = new Thread(SrmRead_Label);
            //tskSetSrmLable.Start();
            /*
            tskSetRgvLable = new Thread(SetConveyerLable);
            tskSetRgvLable.Start();
             */
            #endregion
 
            #region 服务线程启动
 
 
            //堆垛机任务服务线程启动
            var srmService = DeviceThreadServiceFactory.GetHandle(EDeviceType.堆垛机);
            srmService.StartService();
            ///*
            ////RGV任务服务线程启动
            //var rgvService = DeviceThreadServiceFactory.GetHandle(EDeviceType.RGV);
            //rgvService.StartService();
            // */
            var conveyerService = DeviceThreadServiceFactory.GetHandle(EDeviceType.输送线);
            conveyerService.StartService();
 
            var agvService = DeviceThreadServiceFactory.GetHandle(EDeviceType.AGV);
            agvService.StartService();
 
 
            //处理【下发中】的出库计划任务
            //new Thread(OutPlanTaskDecompose.HandlerIssuingTask).Start();
 
 
            ////任务分解线程
            new Thread(MainTaskDecompose.HandlerMainTaskDecompose).Start();
 
            ////读码线程
            new Thread(ScanContainerCode.HandlerMainTaskScanCode1).Start();
 
            //任务完成单据状态库存处理线程
            new Thread(MainTaskCompleteHandle.HandlerMainTaskStatus).Start();
 
            //移库线程
            new Thread(MoveTaskHandle.HandlerMainTaskStatus).Start();
 
            //任务分解线程-组盘入库
            //new Thread(MainTaskDecompose_ZPRK.HandlerMainTaskDecompose_ZPRK).Start();
 
            //空托盘转运任务
            //new Thread(EmptySalverTransferTask.Handler).Start();
 
            //1014库位转运到1020线程
            //new Thread(Place1014To1020Task.Handler).Start();
 
            ////1009库位增加库存线程
            //new Thread(Place1009AddStoreTask.Handler).Start();
 
            new Thread(DeleteData).Start();
 
            //new Thread(ClearMemory).Start();
 
            //new Thread(LineInSacnResult.HandlerLineInSacnResult).Start();
 
            //入库口扫码器处理线程
 
            //*/
            #endregion
 
            //new Thread(GetAgvVehicles).Start();//AGV车辆信息
 
            //new Thread(OutTaskRetryToMes.Handler).Start();
 
            //暂时不启用虚拟出入库功能
            //new Thread(VirtualTaskNoOutPlanTaskHandler.Handler).Start();
        }
        private void FormCC_Load(object sender, EventArgs e)
        {
            this.dgvPartTask.ReadOnly = true;
            btn_Start.Enabled = false;
            btn_End.Enabled = true;
            /*
            trCancelBatchBackToStore = new Thread(CancelBatchBackToStore);
            trCancelBatchBackToStore.Start();
            //*/
 
            /*
            var tr_reverseSplitFinishProdOutStoreThread = new Thread(ReverseSplitFinishProdOutStoreThread);
            tr_reverseSplitFinishProdOutStoreThread.Start();
            //*/
 
            #region 对外发布WCF形式数据访问服务
            //try
            //{
            //    #region 对外发布WCF形式数据访问服务
            //    var lineServiceHost = new ServiceHost(typeof(CCWcfService));
            //    lineServiceHost.Open();
            //    lbl_WCFMsg.Text = "发布WCF成功," + lineServiceHost.BaseAddresses[0].AbsoluteUri;
            //    lbl_WCFMsg.ForeColor = Color.Green;
            //    #endregion
 
            //}
            //catch (Exception ex)
            //{
            //    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "发布WCF失败", ex);
            //    lbl_WCFMsg.Text = "发布WCF失败:" + ex.Message;
            //    lbl_WCFMsg.ForeColor = Color.Red;
            //}
 
            #endregion
 
 
            this.lbl_IsSimulationPLC.Text = "是否模拟PLC:" + (IsSimulationPLC ? "是" : "否");
            if (IsSimulationPLC)
            {
                //暂时注释
                this.panel_Model.BackColor = Color.Tomato;
            }
            else
            {//正式模式 
                //rgvServiceClient = new RgvServiceClient();
                //conveyerServiceClient = new ConveyerServiceClient();
            }
 
            this.lbl_IsSimulationPLC.BackColor = IsSimulationPLC ? Color.Red : Color.Green;
 
            //此处暂时快速启动 调试模式,用于开发用
            //btn_Start_Click(null, null);
        }
 
 
        public static string showNowTime = "";
        //public static int count = 0;
        #region 堆垛机线程和UI处理
 
        /// <summary>
        /// 设置1/2号堆垛机的前端显示
        /// </summary>
        private void SrmRead_Label()
        {
            while (true)
            {
                //Thread.Sleep(100);
                try
                {
                    //SystemWarningMsg._lbl_Alert_Srm1Release = "测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试" + count++;
                    var showNowTime = "(" + DateTimeHelper.ConvertToStringForOnlyShowTime(DateTime.Now) + ")";
                    //showNowTime = DateTime.Now.ToString("HH:mm:ss");
                    //设置堆垛机任务下发和任务确认线程消息
                    this.lbl_Alter_Srm1Release.Text = showNowTime + SystemWarningMsg._lbl_Alert_Srm1Release;
 
                    //设置堆垛机任务下发和任务完成确认线程消息
                    this.lbl_Alter_Srm1ReleaseFinish.Text = showNowTime + SystemWarningMsg._lbl_Alert_Srm1ReleaseFinish;
 
                    this.lbl_Alter_ConveyerRelease.Text = showNowTime + SystemWarningMsg._lbl_Alert_ConveyerRelease;
 
                    this.lbl_Alert_ConveyerReleaseFinish.Text = showNowTime + SystemWarningMsg._lbl_Alert_ConveyerReleaseFinish;
 
                    this.lbl_TaskDecompose.Text = showNowTime + SystemWarningMsg._lbl_TaskDecompose;
 
                    this.lbl_TaskFinished.Text = showNowTime + SystemWarningMsg._lbl_TaskFinished;
 
                    this.lbl_ScanHandle101.Text = showNowTime + SystemWarningMsg._lbl_ScanHandle101;
 
                    this.lbl_Alert_Agv.Text = showNowTime + SystemWarningMsg._lbl_Alert_Agv;
 
                    //ClearMemory();
                }
                catch (Exception ex)
                {
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.SrmTheadService, "方法SrmRead_Label出现异常:" + ex.Message, ex);
                    continue;
                }
            }
        }
 
        private short posX1 = 0;
        private short posX2 = 0;
        private static List<String> warningAddressListSrm = new List<string>();
        /// <summary>
        /// 获取堆垛机的实时信息
        /// </summary>
        private void GetSrmInfo(object int_device)
        {
            while (true)
            {
                EDevice device = (EDevice)Enum.Parse(typeof(EDevice), int_device.ToString());
                Thread.Sleep(cycleDelay_Device);
                try
                {
                    using (var opcClinet = new SrmService.SrmServiceClient())
                    {
                        srmViewDict[(int)device] = opcClinet.GetSrmInfo((int)device);
                        //CastToDevice_SrmRealTime(srmViewDict[(int)device]);
 
                        if (srmViewDict[(int)device].R_WarningDBList != null && srmViewDict[(int)device].R_WarningDBList.Length > 0)
                        {
                            var waringList = srmViewDict[(int)device].R_WarningDBList.ToList();
                            if (waringList != null && waringList.Count > 0)
                            {
                                for (int i = 0; i < waringList.Count; i++)
                                {
                                    DeviceWarningHandler.SaveWarning(device, iWareCommon.Utils.LogType.SrmTheadService,
                                        waringList[i].Code, waringList[i].Address, waringList[i].Context);//新增报警
                                    warningAddressListSrm.Add(waringList[i].Address);
                                }
                            }
                        }
                        DeviceWarningHandler.AutoCloseWarning(device, iWareCommon.Utils.LogType.SrmTheadService, warningAddressListSrm);//自动关闭报警
                        warningAddressListSrm.Clear();
                        if (srmViewDict[(int)device].R_PosX != posX1)
                        {
                            using (DbOrm dbOrm = new DbOrm())
                            {
                                posX1 = srmViewDict[(int)device].R_PosX;
                                var equipment = dbOrm.ware_equipment.Where(u => u.Id == 1).FirstOrDefault();
                                if (equipment != null)
                                {
                                    if (posX1 > 11)
                                    {
                                        equipment.CoordinateX = 1;
                                    }
                                    else
                                    {
                                        equipment.CoordinateX = posX1;
                                    }
 
                                    dbOrm.SaveChanges();
                                }
                            }
                        }
                    }
                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.SrmTheadService, "获取" + device.ToString() + "的实时信息异常:" + ex.Message, ex);
                    continue;
                }
            };
        }
 
        /// <summary>
        /// 堆垛机的UI显示
        /// </summary>
        /// <param name="device"></param>
        private void SetSrmUI()
        {
            if (FormCC.IsSimulationPLC == false)
            {
                SrmDeviceList.ForEach(x =>
                {
                    ParameterizedThreadStart parStart = new ParameterizedThreadStart(SingleSetSrmUI);
                    Thread thread = new Thread(parStart);
                    object o = (int)x;
                    thread.Start(o);
                });
            }
        }
 
        /// <summary>
        /// 堆垛机的UI显示
        /// </summary>
        /// <param name="device"></param>
        private void SingleSetSrmUI(object int_device)
        {
            //while (true)
            //{
            try
            {
                EDevice device = (EDevice)Enum.Parse(typeof(EDevice), int_device.ToString());
                SrmView srmInfo = srmViewDict[(int)device];
                var panel = GetSrmPanel(device);
                List<PropertieModel> proList = ClassHelper.GetPropertieModels<SrmView>(srmInfo);
                foreach (var item in DeviceDict.LabelSrmDict)
                {
                    //var lbl = ControlHelper.GetLabel(this, panel, item.Key + (int)device);
                    Object obj = ControlHelper.GetControlInstance(panel, item.Key + (int)device);
                    if (obj != null)
                    {
                        Label lbl = (Label)obj;
                        lbl.Text = item.Value.LablePreStr + proList.Find(x => x.PropertyName == item.Value.LableProName).DataValue;
                    }
                }
                //特殊处理- 报警
                var lbSrmAlarm = GetSrmAlarmLabel(device);
                if (srmInfo.R_Alarm != 1)
                {
                    lbSrmAlarm.Text = string.Empty;
                    lbSrmAlarm.ForeColor = Color.SkyBlue;
                    lbSrmAlarm.BackColor = Color.Transparent;
                    lbSrmAlarm.ForeColor = Color.Maroon;
                    lbSrmAlarm.BackColor = Color.WhiteSmoke;
                }
                else
                { //处于报警状态下
                    if (srmInfo.R_WarningDBList != null && srmInfo.R_WarningDBList.Length > 0)
                    {
                        lbSrmAlarm.Text = String.Join(",", srmInfo.R_WarningDBList.Select(x => x.Context).ToArray());
                    }
 
                    lbSrmAlarm.ForeColor = Color.White;
                    lbSrmAlarm.BackColor = Color.Red;
                    lbSrmAlarm.ForeColor = Color.White;
                    lbSrmAlarm.BackColor = Color.Red;
                }
                //注释
                /*
                if (lbSrmAlarm.Text == string.Empty)
                {
                    using (var opcClinet = new SrmService.SrmServiceClient())
                    {
                        var isHandShare = SrmBLL.IsHandShare(opcClinet, device);
                        if (!isHandShare)
                        {
                            lbSrmAlarm.Text = (int)device + "号堆垛机没有心跳";
                        }
                    }
                }
                //*/
            }
            catch (Exception)
            {
                throw;
            }
            //}
        }
 
        /// <summary>
        /// 获取堆垛机的报警Label
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private Label GetSrmAlarmLabel(EDevice device)
        {
            switch (device)
            {
                case EDevice.堆垛机:
                    return this.lblSrmAlarm1;
            }
            return null;
        }
 
 
        /// <summary>
        /// 获取堆垛机的Panel
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private Panel GetSrmPanel(EDevice device)
        {
            switch (device)
            {
                case EDevice.堆垛机:
                    return this.panel_Srm1;
            }
            return null;
        }
 
 
 
        #endregion
 
        #region Conveyer线程和UI处理
 
        private static List<String> warningAddressList = new List<string>();
        /// <summary>
        /// 获取Conveyer信息
        /// </summary>
        /// <param name="obj"></param>
        private void GetConveyorInfo(object obj)
        {
            while (true)
            {
                Thread.Sleep(500);//1秒钟读取一次
                try
                {
                    using (conveyerServiceClient = new ConveyorService.ConveyerServiceClient())
                    {
                        conveyerView = conveyerServiceClient.GetConveyerInfo((int)EDevice.输送线);
                    }
                    //_CommmonShowAgvStation();
 
                    //显示RGV报警信息
 
                    if (conveyerView.R_Conveyer_WarningDBList != null && conveyerView.R_Conveyer_WarningDBList.Length > 0)
                    {
                        tb_Conveyer_Alter.Text = String.Join(",", conveyerView.R_Conveyer_WarningDBList.Select(x => x.Contextk__BackingField).ToArray());
                        //保存报警
                        var waringList = conveyerView.R_Conveyer_WarningDBList.ToList();
                        if (waringList != null && waringList.Count > 0)
                        {
                            for (int i = 0; i < waringList.Count; i++)
                            {
                                DeviceWarningHandler.SaveWarning(EDevice.输送线, iWareCommon.Utils.LogType.ConveyorThreadService,
                                    waringList[i].Codek__BackingField, waringList[i].Addressk__BackingField, waringList[i].Contextk__BackingField);//新增报警
                                warningAddressList.Add(waringList[i].Addressk__BackingField);
                            }
                        }
                    }
                    else
                    {
                        tb_Conveyer_Alter.Text = "";
                    }
                    DeviceWarningHandler.AutoCloseWarning(EDevice.输送线, iWareCommon.Utils.LogType.ConveyorThreadService, warningAddressList);//自动关闭报警
                    warningAddressList.Clear();
                }
                catch (Exception ex)
                {
                    conveyerView = null;
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.ConveyorThreadService, "获取输送线信息出现异常:" + ex.Message, ex);
                    continue;
                }
            }
        }
        #endregion
 
        #region 其他线程
 
        #region 定时删除数据
 
        /// <summary>
        /// 定时删除数据
        /// </summary>
        public void DeleteData()
        {
            while (true)
            {
                try
                {
                    if (SystemValue.isStartedModel)
                    {
                        LogTextHelper.BatchDeleteLog();
 
                        Thread.Sleep(8 * 60 * 60 * 1000);//每天8小时一次 
                    }
                    else
                    {
                        Thread.Sleep(6 * 1000);
                    }
                }
                catch (Exception ex)
                {
                    SystemWarningMsg._lbl_Alert_DeleteData = "出现异常:" + ex.Message;
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "定时删除数据 出现异常", ex);
                }
                finally
                {
 
                }
            }
        }
 
        #endregion
 
        #region
        /// <summary>
        /// 定时回收内存
        /// </summary>
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        public static void ClearMemory()
        {
            //while (true)
            //{
            //    Thread.Sleep(10000);
            try
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.Common, "GC异常:" + ex.Message, ex);
            }
            //}
        }
        #endregion
 
        #endregion
 
        #region 私有方法
        /// <summary>
        /// 初始化实时堆垛机的字典
        /// </summary>
        private static void InitSrmDict()
        {
            srmViewDict = new Dictionary<int, SrmView>();
            SrmDeviceList.ForEach(singeDevice =>
            {
                srmViewDict.Add((int)singeDevice, new SrmView());
            });
        }
 
        #endregion
 
        private void btnSrm1Send_Click(object sender, EventArgs e)
        {
            try
            {
                ESrmCmd eSrmCmd = (ESrmCmd)Enum.Parse(typeof(ESrmCmd), comboBox1.Text);
                switch (tB_Srm1SourcePlace.Text)
                {
                    case "102":
                        tB_Srm1SourcePlace.Text = "00-901-00";
                        break;
                }
                switch (tB_Srm1ToPlace.Text)
                {
                    case "102":
                        tB_Srm1ToPlace.Text = "00-801-00";
                        break;
                }
                short srm1Tpallettype = 0;
                if (comboBox2.Text == "26")
                {
                    srm1Tpallettype = 1;
                }
                else if (comboBox2.Text == "23")
                {
                    srm1Tpallettype = 2;
                }
                else if (comboBox2.Text == "21")
                {
                    srm1Tpallettype = 2;
                }
                else if (comboBox2.Text == "14")
                {
                    srm1Tpallettype = 2;
                }
                CommonSendSrmTask(eSrmCmd, "1-", tbSrm1TaskId, tB_Srm1SourcePlace, tB_Srm1ToPlace, EDevice.堆垛机, srm1Tpallettype);
            }
            catch
            {
 
            }
        }
 
        private void btnSrm1Move_Click(object sender, EventArgs e)
        {
            try
            {
                // CommonSendSrmTask(ESrmCmd.移动, "1-", tbSrm1TaskId, tB_Srm1SourcePlace, tB_Srm1ToPlace, EDevice.一号堆垛机, Convert.ToInt16(tbSrm1Tpallettype));
            }
            catch
            {
 
            }
        }
 
        private void btnSrm1Confirm_Click(object sender, EventArgs e)
        {
            CommonSrmConfirm(EDevice.堆垛机, tbSrm1TaskId);
        }
 
        private void btnSrm1EStop_Click(object sender, EventArgs e)
        {
            CommonSrmEStop(EDevice.堆垛机);
        }
 
        private void btnSrm1RlsAlert_Click(object sender, EventArgs e)
        {
            using (var opcClinet = new SrmService.SrmServiceClient())
            {
                opcClinet.ReleaseAlert((int)EDevice.堆垛机);
            }
        }
 
        private void btnSrm1Delete_Click(object sender, EventArgs e)
        {
            CommonDeleteSrmTask(EDevice.堆垛机);
        }
 
        #region 公共
 
        /// <summary>
        /// 公共堆垛机急停命令
        /// </summary>
        private void CommonSrmEStop(EDevice _EDevice)
        {
            try
            {
                using (var opcClinet = new SrmService.SrmServiceClient())
                {
                    var result = opcClinet.SendEStop((int)_EDevice);
                    Log4NetHelper.WriteInfoLog(iWareCommon.Utils.LogType.SrmTheadService, "字符串:" + JsonConvert.SerializeObject(result));
                    if (result.result)
                    {
                        WZ.Useful.Commons.MessageUtil.ShowTips("发送" + _EDevice.ToString() + "急停指令成功");
                    }
                    else
                    {
                        WZ.Useful.Commons.MessageUtil.ShowTips("发送" + _EDevice.ToString() + "急停指令失败:" + result.resMsg);
                    }
                }
            }
            catch (Exception ex)
            {
                WZ.Useful.Commons.MessageUtil.ShowError("发送" + _EDevice.ToString() + "急停指令异常:" + ex.Message);
            }
        }
 
 
        /// <summary>
        /// 公共发送堆垛机命令(搬运/移动)
        /// </summary>
        /// <param name="pre_Srm"></param>
        /// <param name="tbTaskId"></param>
        /// <param name="tbSourcePlace"></param>
        /// <param name="tbToPlace"></param>
        /// <param name="_EDevice"></param>
        private void CommonSendSrmTask(ESrmCmd srmCmd, string pre_Srm, TextBox tbTaskId, TextBox tbSourcePlace, TextBox tbToPlace, EDevice _EDevice, short pallettype)
        {
            if (SystemValue.isStartedModel)
            {
                WZ.Useful.Commons.MessageUtil.ShowError("手动发任务,需要将模式关闭!");
                return;
            }
 
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            var deviceName = _EDevice.ToString();
            var cmdName = srmCmd.ToString();
            DialogResult dr = MessageBox.Show("确定要给" + deviceName + "发送" + cmdName + "命令吗?", "确认", messButton);
            if (dr == DialogResult.OK)//如果点击“确定”按钮
            {
                try
                {
                    using (var opcClinet = new SrmService.SrmServiceClient())
                    {
                        var sourcePlce = tbSourcePlace.Text.Trim();
                        var toPlace = tbToPlace.Text.Trim();
 
                        if (!IsNumeric(tbTaskId.Text.Trim()))
                        {
                            WZ.Useful.Commons.MessageUtil.ShowError("任务号格式错误,必须是数字!");
                            return;
                        }
                        var taskId = int.Parse(tbTaskId.Text.Trim());
                        if (!(taskId >= 1 && taskId <= 100))
                        {
                            WZ.Useful.Commons.MessageUtil.ShowError("手动任务号必须是在1-100之间!");
                            return;
                        }
                        string realToPlace = "";
                        string realSourcePlace = "";
 
                        realSourcePlace = tbSourcePlace.Text;
                        realToPlace = tbToPlace.Text;
 
 
                        iWareCC.SrmService.SdaResEntity sdaResult = opcClinet.SendSrmTask((int)_EDevice, int.Parse(tbTaskId.Text.Trim()), pre_Srm + realSourcePlace, pre_Srm + realToPlace, (short)srmCmd, pallettype);
                        if (sdaResult.result)
                        {
                            WZ.Useful.Commons.MessageUtil.ShowTips(deviceName + cmdName + "命令发送成功!");
                            //  tB_Srm1SourcePlace.Clear();
                            // tB_Srm1ToPlace.Clear();
                            Log4NetHelper.WriteInfoLog(iWareCommon.Utils.LogType.CCWCFService, "手动堆垛机任务发送成功,任务号:" + taskId + ",起点:" + sourcePlce + ",目标点:" + toPlace + ",堆垛机:" + deviceName);
                        }
                        else
                        {
                            WZ.Useful.Commons.MessageUtil.ShowError(deviceName + cmdName + "命令发送失败!返回代码:" + sdaResult.resMsg);
                            Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "手动堆垛机任务发送失败!返回代码:" + sdaResult.resMsg + ",任务号:" + taskId + ",起点:" + sourcePlce + ",目标点:" + toPlace + ",堆垛机:" + deviceName);
                        }
                    }
                    tbSourcePlace.Focus();
                    tbSourcePlace.SelectAll();
                }
                catch (Exception ex)
                {
                    WZ.Useful.Commons.MessageUtil.ShowError(deviceName + cmdName + "命令发送出现异常:" + ex.Message);
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, deviceName + cmdName + "命令发送出现异常:" + ex.Message, ex);
                }
            }
            else//如果点击“取消”按钮
            {
 
            }
        }
 
        /// <summary>
        /// 堆垛机任务确认
        /// </summary>
        /// <param name="device"></param>
        /// <param name="tbTaskId"></param>
        private void CommonSrmConfirm(EDevice device, TextBox tbTaskId)
        {
            try
            {
                if (SystemValue.isStartedModel)
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("手动堆垛机任务确认,需要将模式关闭!");
                    return;
                }
 
                iWareCC.SrmService.SdaResEntity sdaResult = new SrmService.SrmServiceClient().ConfirmTaskFinish
                        ((int)device, int.Parse(tbTaskId.Text.Trim()));
                if (sdaResult.result)
                {
                    //tbSrm1TaskId.Clear();
                    Log4NetHelper.WriteInfoLog(iWareCommon.Utils.LogType.CCWCFService, "手动堆垛机任务确认成功,任务号:" + tbTaskId);
                }
                else
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("手动堆垛机任务确认失败:" + sdaResult.resMsg + "!");
                    Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "手动堆垛机任务确认失败:" + sdaResult.resMsg + "!,任务号:" + tbTaskId, null);
                }
            }
            catch (Exception ex)
            {
                WZ.Useful.Commons.MessageUtil.ShowError("手动堆垛机任务确认异常:" + ex.Message);
                Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "手动堆垛机任务确认异常:" + ex.Message, ex);
            }
        }
 
 
        private void CommonDeleteSrmTask(EDevice device)
        {
            //if (SystemValue.isStartedModel)
            //{
            //    WZ.Useful.Commons.MessageUtil.ShowError("手动删除堆垛机任务,需要将模式关闭!");
            //    return;
            //}
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要删除" + device.ToString() + "任务吗?", "确认", messButton);
            if (dr == DialogResult.OK)//如果点击“确定”按钮
            {
                using (var opcClinet = new SrmService.SrmServiceClient())
                {
                    opcClinet.SendSrmDelete((int)device);
                }
            }
            else//如果点击“取消”按钮
            {
 
            }
        }
 
        /// <summary>
        /// 校验输入的库位ID是否符合格式
        /// </summary>
        /// <param name="str">库位号</param>
        /// <returns></returns>
        private bool IsNumeric(string str)
        {
            try
            {
                return (WZ.Useful.Commons.Util.IsNumeric(int.Parse(str)));
            }
            catch (Exception)
            {
                return false;
            }
        }
 
        private void FormCC_SizeChanged(object sender, EventArgs e)
        {
            //asc_panel_DeviceTaskList.controlAutoSize(this.panel_DeviceTaskList);
        }
 
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_End_Click(object sender, EventArgs e)
        {
            if (!SystemValue.isStartedModel)
            {
                WZ.Useful.Commons.MessageUtil.ShowError("当前没有选择模式,停止动作无效!");
                return;
            }
 
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要停止自动模式吗?", "停止模式", messButton);
            if (dr == DialogResult.OK)//如果点击“确定”按钮
            {
                this.btn_Start.Text = "启动模式";
                this.btn_Start.Enabled = true;
                btn_End.Enabled = false;
                SystemValue.isStartedModel = false;
 
 
                isStartModelTipsThread = false;
                this.btn_Start.BackColor = default_btn_Start_Color;//还原颜色
            }
            else//如果点击“取消”按钮
            {
 
            }
        }
 
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_Click(object sender, EventArgs e)
        {
            SystemValue.isStartedModel = true;
            btn_Start.Enabled = false;
            btn_End.Enabled = true;
        }
 
        private void FormCC_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要退出吗?", "确认", messButton);
            if (dr == DialogResult.OK)//如果点击“确定”按钮
            {
                try
                {
                    e.Cancel = false;
                }
                catch (Exception ex)
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("出现错误!" + ex.Message);
                    e.Cancel = true;
                }
            }
            else//如果点击“取消”按钮
            {
                e.Cancel = true;
            }
        }
        private void FormCC_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                Dispose();
            }
            catch (Exception)
            {
            }
            Environment.Exit(0);
        }
 
 
        /// <summary>
        /// 模式启动后,按钮闪烁
        /// </summary>
        /// <param name="obj"></param>
        private void ShowTipsWhenStartModel(object obj)
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (isStartModelTipsThread)
                {
                    try
                    {
                        this.btn_Start.BackColor = ss_btn_Start_Color2;
                        Thread.Sleep(1000);
                        this.btn_Start.BackColor = ss_btn_Start_Color1;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
                else
                {
                    if (this.btn_Start.BackColor != default_btn_Start_Color)
                    {
                        this.btn_Start.BackColor = default_btn_Start_Color;//还原颜色
                    }
                }
            }
        }
 
        /// <summary>
        /// 起始位和目标位互换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Change1_Click(object sender, EventArgs e)
        {
            var old_source = this.tB_Srm1SourcePlace.Text;
            var old_to = this.tB_Srm1ToPlace.Text;
            this.tB_Srm1SourcePlace.Text = old_to;
            this.tB_Srm1ToPlace.Text = old_source;
 
        }
 
        private void CommmonShowAgvStation(object sender)
        {
            var btn = sender as Button;
            var stationName = "";
            int stationCode = 0;
            if (int.TryParse(btn.Text, out stationCode))
            {
                stationName = btn.Text;
            }
            else
            {
                stationName = BusinessHelper.ConvertStationCodeForRGV(btn.Text).ToString();
            }
            current_rgv_stationName = stationName;
 
            _CommmonShowAgvStation();
        }
 
        private void _CommmonShowAgvStation()
        {
            if (string.IsNullOrEmpty(current_rgv_stationName))
            {
 
            }
            else
            {
                var r_station = conveyerView.R_ConveyerForReadCommList.Where(x => x.StationCode == current_rgv_stationName).FirstOrDefault();
                var w_station = conveyerView.W_ConveyerForWriteCommList.Where(x => x.StationCode == current_rgv_stationName).FirstOrDefault();
 
            }
        }
 
        private void btn_1001_Click(object sender, EventArgs e)
        {
            //CommmonShowAgvStation(sender);
            new ConveyerServiceClient().WriteAGVRequestIn(3, false);
        }
 
        private void btn_1003_Click(object sender, EventArgs e)
        {
            //CommmonShowAgvStation(sender);
            new ConveyerServiceClient().WriteAGVRequestInArr(3, false);
        }
 
        private void btn_1004_Click(object sender, EventArgs e)
        {
            CommmonShowAgvStation(sender);
        }
 
        private void btn_1005_Click(object sender, EventArgs e)
        {
            //CommmonShowAgvStation(sender);
            new ConveyerServiceClient().WriteAGVRequestOUT(3, false);
        }
 
        private void btn_1006_Click(object sender, EventArgs e)
        {
            CommmonShowAgvStation(sender);
        }
 
        private void btn_1007_Click(object sender, EventArgs e)
        {
            //CommmonShowAgvStation(sender);
            new ConveyerServiceClient().WriteAGVRequestOutArr(3, false);
        }
 
        private void btn_1008_Click(object sender, EventArgs e)
        {
            //
            //CommmonShowAgvStation(sender);
            new ConveyerServiceClient().WriteAGVRequestIn(3, false);
            new ConveyerServiceClient().WriteAGVRequestInArr(3, false);
            new ConveyerServiceClient().WriteAGVRequestOUT(3, false);
            new ConveyerServiceClient().WriteAGVRequestOutArr(3, false);
        }
 
        private void btn_ResetSTP_Click(object sender, EventArgs e)
        {
            CommmonResetSTP(sender);
        }
 
        private void CommmonResetSTP(object sender)
        {
            var btn = sender as Button;
            var stationName = current_rgv_stationName;
            if (string.IsNullOrEmpty(stationName))
            {
                MessageBox.Show("请选择站点号");
                return;
            }
 
            using (RgvService.RgvServiceClient client = new RgvServiceClient())
            {
                var result = client.WriteStp((int)EDevice.RGV, false, stationName);
                if (result.result == false)
                {
                    MessageBox.Show("失败:" + result.resMsg);
                }
            }
        }
 
        private void btnFind_Click_1(object sender, EventArgs e)
        {
            //查询设备任务列表
            dgvPartTask.AutoGenerateColumns = false;
            for (int i = 0; i < dgvPartTask.Columns.Count; i++)
            {
                if (i == (dgvPartTask.Columns.Count - 1))
                {//最后一列填充
                    dgvPartTask.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
                else
                {//其他列自动适应宽度
                    dgvPartTask.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                }
            }
 
            BindData();
 
            //this.dgvPartTask.Columns["CreateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            //this.dgvPartTask.Columns["IssueTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            //this.dgvPartTask.Columns["FinishTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            //this.dgvPartTask.Columns["AllowSimulateExecute_Time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            FormHelper.DataGridViewSelfAdaptionWidth(this.dgvPartTask);
        }
 
        public void BindData()
        {
            List<ware_task_sub> partList = new List<ware_task_sub>();
            dgvPartTask.ClearSelection();   //可消除所有选择的行      
            dgvPartTask.DataSource = null;
 
            dgvPartTask.CurrentCell = null; //可消除选择行的行头箭头
            using (DbOrm db = new DbOrm())
            {
                //取 最后一个未结束的任务,然后取前5条已经结束的任务
                var queryState1 = (int)SubTaskStateEnum.已取消;
                var queryState2 = (int)SubTaskStateEnum.已完成;
                //var firstNoFinishedTaskList = db.ware_task_sub.Where(x => x.TaskState != queryState1 && x.TaskState != queryState2).OrderBy(x => x.CreatedTime).ToList();
                var firstNoFinishedTaskList = db.ware_task_sub.AsQueryable().OrderBy(x => x.CreatedTime).ToList();
                if (firstNoFinishedTaskList == null)
                {
                    partList = new List<ware_task_sub>();
                }
                else
                {
                    List<long?> mainIdList = new List<long?>();
                    foreach (var item in firstNoFinishedTaskList)
                    {
                        if (!mainIdList.Contains(item.TaskId))
                        {
                            mainIdList.Add(item.TaskId);
                        }
                    }
                    var partList2 = db.ware_task_sub.Where(x => mainIdList.Contains(x.TaskId)).ToList();
 
                    //partList.AddRange(partList1);
                    partList.AddRange(partList2);
                }
                if (partList != null && partList.Count > 0)
                {
                    partList = partList.OrderBy(x => x.TaskId).ThenByDescending(x => x.CreatedTime).ToList();//重新 升序排序
                    dgvPartTask.DataSource = null;
                    dgvPartTask.DataSource = partList;
                }
                else
                {
                    //if (dgvPartTask.Rows.Count > 0)
                    //{
                    //    int i = dgvPartTask.Rows[0].Cells.Count;
                    //    var cells = dgvPartTask.Rows[0].Cells;
                    //    for (int j = 0; j < i; j++)
                    //    {
                    //        cells[j].Value = null;
                    //    }
                    //}
                }
            }
        }
 
        private void btnFinish_Click_1(object sender, EventArgs e)
        {
            //强制完成
            try
            {
                var _AllowSimulateExecute_Rmark = this.tb_AllowSimulateExecute_Rmark.Text;
                if (string.IsNullOrEmpty(_AllowSimulateExecute_Rmark))
                {
                    MessageBox.Show("请输入强制完成原因说明!");
                    return;
                }
                using (DbOrm context = new DbOrm())
                {
                    var row = dgvPartTask.SelectedRows;
 
                    if (row.Count > 0)
                    {
                        var cell = row[0].Cells;
                        // var id = cell[0].Value.ToString();
                        var id = Convert.ToInt64(cell["Column1"].Value.ToString());
                        var task = context.ware_task_sub.FirstOrDefault(x => x.Id == id);
                        if (task != null)
                        {
                            task.TaskState = 2;
                            context.SaveChanges();
                        }
                        else
                        {
                            MessageBox.Show("未找到该任务!");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先选中要标记任务强制完成的行!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("标记任务强制完成异常:" + ex.Message);
            }
        }
 
        private void btnDelete_Click_1(object sender, EventArgs e)
        {
            //任务取消
            try
            {
                if (SystemValue.isStartedModel)
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("手动取消任务,需要将模式关闭!");
                    return;
                }
 
                var _AllowSimulateExecute_Rmark = this.tb_AllowSimulateExecute_Rmark.Text;
                if (string.IsNullOrEmpty(_AllowSimulateExecute_Rmark))
                {
                    MessageBox.Show("请输入取消原因说明!");
                    return;
                }
                var myNotext = "人工取消任务,原因:" + _AllowSimulateExecute_Rmark;
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("【取消任务只是将状态变更为取消,并不处理库存,请谨慎操作。确认取消后,还需人工校验下该任务库存是否正确!】,确定要取消任务吗?", "提示", messButton);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {
 
                }
                else//如果点击“取消”按钮
                {
 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("取消任务异常:" + ex.Message);
                Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "取消任务异常:" + ex.Message, ex);
            }
        }
 
        private void btnReset_Click_1(object sender, EventArgs e)
        {
            //任务重发
            try
            {
                var _AllowSimulateExecute_Rmark = this.tb_AllowSimulateExecute_Rmark.Text;
                if (string.IsNullOrEmpty(_AllowSimulateExecute_Rmark))
                {
                    MessageBox.Show("请输入任务重发原因说明!");
                    return;
                }
 
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
 
                using (DbOrm db = new DbOrm())
                {
                    var row = dgvPartTask.SelectedRows;
 
                    if (row.Count > 0)
                    {
                        var cell = row[0].Cells;
                        //var id = cell[0].Value.ToString();
                        var id = Convert.ToInt64(cell["Column1"].Value.ToString());
                        var task = db.ware_task_sub.FirstOrDefault(x => x.Id == id);
                        if (task != null)
                        {
                            if (task.TaskState == (int)SubTaskStateEnum.已完成)
                            {
                                MessageBox.Show("任务已完成,不允许重发");
                                return;
                            }
                            else if (task.TaskState == (int)SubTaskStateEnum.未开始)
                            {
                                MessageBox.Show("任务未开始,不需要重发");
                                return;
                            }
                            else
                            {
                                //判断设备状态
                                if (task.DeviceId == 3)
                                {
                                    //ValidateDeviceIsAllowSendTask(int int_deviceId, out string errMsg)
                                }
                                else
                                {
 
                                }
 
                                task.TaskState = (int)SubTaskStateEnum.未开始;
                                db.SaveChanges();
                            }
                        }
                        MessageBox.Show("任务重发成功!");
 
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show("请先选中要执行的行!");
                    }
                }
 
            }
            catch (Exception ex)
            {
                MessageBox.Show("任务重发出现异常:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 关闭1015重新扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            using (var opcClinet = new RgvService.RgvServiceClient())
            {
                iWareCC.RgvService.SdaResEntity sdaResult = opcClinet.Write1015ReScan((int)EDevice.RGV, false);
                if (sdaResult.result)
                {
                    WZ.Useful.Commons.MessageUtil.ShowTips("关闭命令发送成功!");
                }
                else
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("关闭命令发送失败!返回消息:" + sdaResult.resMsg);
                }
            }
        }
 
        private void dgvPartTask_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(this.dgvPartTask.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dgvPartTask.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }
        private void btnDeleteTask_Click(object sender, EventArgs e)
        {
            //任务强制删除
            try
            {
                if (SystemValue.isStartedModel)
                {
                    WZ.Useful.Commons.MessageUtil.ShowError("手动任务强制删除,需要将模式关闭!");
                    return;
                }
 
                var _AllowSimulateExecute_Rmark = this.tb_AllowSimulateExecute_Rmark.Text;
                if (string.IsNullOrEmpty(_AllowSimulateExecute_Rmark))
                {
                    MessageBox.Show("请输入任务强制删除原因说明!");
                    return;
                }
                var myNotext = "人工任务强制删除任务,原因:" + _AllowSimulateExecute_Rmark;
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("【任务强制删除,并不处理库存,请谨慎操作。确认任务强制删除后,还需人工校验下该任务库存是否正确!】,确定要任务强制删除吗?", "提示", messButton);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {
 
                }
                else//如果点击“取消”按钮
                {
 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("任务强制删除异常:" + ex.Message);
                Log4NetHelper.WriteErrorLog(iWareCommon.Utils.LogType.CCWCFService, "任务强制删除异常:" + ex.Message, ex);
            }
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            //任务重发
            try
            {
                var _AllowSimulateExecute_Rmark = this.tb_AllowSimulateExecute_Rmark.Text;
                if (string.IsNullOrEmpty(comboBox3.Text))
                {
                    MessageBox.Show("请选择跳步的状态!");
                    return;
                }
 
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
 
                using (DbOrm db = new DbOrm())
                {
                    var row = dgvPartTask.SelectedRows;
 
                    if (row.Count > 0)
                    {
                        var cell = row[0].Cells;
                        //var id = cell[0].Value.ToString();
                        var id = Convert.ToInt64(cell["Column1"].Value.ToString());
                        var task = db.ware_task_sub.FirstOrDefault(x => x.Id == id);
                        if (task != null)
                        {
                            //判断设备状态
                            if (task.DeviceId == 1099)
                            {
                                var vs = (SubTaskStateEnum)Enum.Parse(typeof(SubTaskStateEnum), comboBox3.Text);
                                task.TaskState = (int)vs;
                            }
                            else
                            {
                                MessageBox.Show("只能修改AGV任务!");
                            }
                            db.SaveChanges();
                        }
                        MessageBox.Show("任务重发成功!");
 
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show("请先选中要执行的行!");
                    }
                }
 
            }
            catch (Exception ex)
            {
                MessageBox.Show("任务重发出现异常:" + ex.Message);
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            new ConveyorService.ConveyerServiceClient().WriteReceiveScan((int)EDevice.输送线, "101", true);
        }
 
        private void button5_Click(object sender, EventArgs e)
        {
            new ConveyorService.ConveyerServiceClient().WriteReceiveScan((int)EDevice.输送线, "101", false);
        }
        #endregion
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                showNowTime = DateTime.Now.ToString("HH:mm:ss");
                //设置堆垛机任务下发和任务确认线程消息
                lbl_Alter_Srm1Release.Text = $"{showNowTime}{SystemWarningMsg._lbl_Alert_Srm1Release};";
 
                //设置堆垛机任务下发和任务完成确认线程消息
                lbl_Alter_Srm1ReleaseFinish.Text = showNowTime + SystemWarningMsg._lbl_Alert_Srm1ReleaseFinish;
 
                lbl_Alter_ConveyerRelease.Text = showNowTime + SystemWarningMsg._lbl_Alert_ConveyerRelease;
 
                lbl_Alert_ConveyerReleaseFinish.Text = showNowTime + SystemWarningMsg._lbl_Alert_ConveyerReleaseFinish;
 
                lbl_TaskDecompose.Text = showNowTime + SystemWarningMsg._lbl_TaskDecompose;
 
                lbl_TaskFinished.Text = showNowTime + SystemWarningMsg._lbl_TaskFinished;
 
                lbl_ScanHandle101.Text = showNowTime + SystemWarningMsg._lbl_ScanHandle101;
 
                lbl_Alert_Agv.Text = showNowTime + SystemWarningMsg._lbl_Alert_Agv;
 
                //ClearMemory();
 
                if (isStartModelTipsThread)
                {
                    try
                    {
                        btn_Start.BackColor = ss_btn_Start_Color2;
                        btn_Start.BackColor = ss_btn_Start_Color1;
                    }
                    catch (Exception)
                    {
 
                    }
                }
                else
                {
                    if (btn_Start.BackColor != default_btn_Start_Color)
                    {
                        btn_Start.BackColor = default_btn_Start_Color;//还原颜色
                    }
                }
 
                SingleSetSrmUI(1);
            }
            catch
            {
 
            }
        }
    }
}