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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
using Autofac;
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.Common.Model.Interface;
using Bro.Common.PubSub;
using Bro.Common.UI;
using Bro.Device.AuboRobot;
using Bro.Device.OmronFins;
using Bro.Device.SeerAGV;
using Bro.Device.Station.Forms;
using HalconDotNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using static Bro.Common.Helper.EnumHelper;
 
namespace A032.Process
{
    public partial class ProcessControl : IStationProcess
    {
        ContainerBuilder builder = new ContainerBuilder();
 
        private void AutoFacRegister(bool isBuild = true)
        {
            #region AutoFac注册
            builder.RegisterInstance<ProcessConfig>(StationConfig as ProcessConfig);
            builder.RegisterInstance<List<IDevice>>(GetDeviceList());
            builder.RegisterInstance<List<ProcessMethodAttribute>>(CollectProcessMethods());
 
            if (isBuild)
            {
                GlobalVar.Container = builder.Build();
            }
            #endregion
        }
 
        public IStationConfig StationConfig { get; set; }
 
        string CONFIG_PATH = "";
        private string productionCode = "";
        public string ProductionCode
        {
            get => productionCode;
            set
            {
                if (productionCode != value)
                {
                    productionCode = value;
 
                    string baseDir = "";
 
                    string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
                    if (File.Exists(configPath))
                    {
                        using (StreamReader reader = new StreamReader(configPath, System.Text.Encoding.UTF8))
                        {
                            string dataStr = reader.ReadToEnd();
                            JObject data = JsonConvert.DeserializeObject<JObject>(dataStr);
                            baseDir = data.Value<string>("ConfigPath");
                        }
                    }
 
                    if (string.IsNullOrWhiteSpace(baseDir))
                    {
                        baseDir = AppDomain.CurrentDomain.BaseDirectory;
                    }
 
                    if (!string.IsNullOrWhiteSpace(productionCode) && productionCode != "Default")
                    {
                        CONFIG_PATH = Path.Combine(baseDir, $"Config_{productionCode}.json");
                    }
                    else
                    {
                        CONFIG_PATH = Path.Combine(baseDir, "Config.json");
                    }
                }
            }
        }
 
        #region Event
        public Action<string, Bitmap> OnBitmapOutput { get; set; }
        public Action<string> OnBitmapClear { get; set; }
        public Action<string, object> OnObjectOutput { get; set; }
        public Action<string, Exception> OnExceptionOccured { get; set; }
        public Action<DeviceState> OnProcessStateChanged { get; set; }
        #endregion
 
        #region Property & Field
        private DeviceState processState = DeviceState.DSUninit;
        public DeviceState ProcessState
        {
            get => processState;
            set
            {
                if (processState != value)
                {
                    processState = value;
                    Task.Run(() =>
                    {
                        OnProcessStateChanged?.Invoke(value);
                    });
                    //OnProcessStateChanged?.BeginInvoke(value, null, null);
                }
            }
        }
 
        Dictionary<string, OmronFinsDriver> PLCDict = new Dictionary<string, OmronFinsDriver>();
        Dictionary<string, AuboRobotDriver> RobotDict = new Dictionary<string, AuboRobotDriver>();
        Dictionary<string, SeerAGVDriver> AGVDict = new Dictionary<string, SeerAGVDriver>();
        Dictionary<string, CameraBase> CameraDict = new Dictionary<string, CameraBase>();
 
        private ProcessConfig Config { get => StationConfig as ProcessConfig; }
 
        string _configBackupStr = "";
 
        PubSubCenter PubSubCenter = PubSubCenter.GetInstance();
        #region constance variables
        //const int OFFLINE_FLAG = -999;
        //const int IGNORE_FEEDBACK = -999;
        #endregion
        #endregion
 
        public ProcessControl()
        {
            InitialStationProcess();
        }
 
        public ProcessControl(string productionCode, string configPath = "")
        {
            ProductionCode = productionCode;
            InitialStationProcess(configPath);
        }
 
        public virtual void Close()
        {
            if (ProcessState == DeviceState.DSClose)
                return;
 
            CloseDevice(PLCDict.Values.ToList());
            CloseDevice(RobotDict.Values.ToList());
            CloseDevice(AGVDict.Values.ToList());
            CloseDevice(CameraDict.Values.ToList());
 
            ProcessState = DeviceState.DSClose;
 
            LogAsync(DateTime.Now, "Process Closed", "");
        }
 
        public virtual void Open()
        {
            if (ProcessState == DeviceState.DSOpen)
                return;
 
            InitialProcessMethods();
 
            OpenDevices(RobotDict.Values.ToList());
            OpenDevices(AGVDict.Values.ToList());
 
            OpenCameras();
            PubSubCenter.Subscribe(PubTag.DeviceOperation.ToString(), OnCameraOp);
 
            OpenDevices(PLCDict.Values.ToList());
 
            ProcessState = DeviceState.DSOpen;
 
            QueryRobotIO();
 
            //Task.Run(() =>
            //{
            //    //PLCMonitor();
            //});
 
            LogAsync(DateTime.Now, "Process Opened", "");
        }
 
        private object OnCameraOp(ISubscriber arg1, object arg2, object arg3)
        {
            string cameraId = arg2.ToString();
 
            if (CameraDict.ContainsKey(cameraId))
            {
                CameraDict[cameraId].Snapshot();
            }
 
            return null;
        }
 
        public virtual void OpenCameras()
        {
            //Config.CameraConfigs.ForEach(c =>
            //{
            //    CameraBase camera = CameraHelper.GetCameraInstance(c.DriverType);
            //    camera.InitialConfig = c;
 
            //    OpenCamera(camera);
 
            //    CameraDict[camera.InitialConfig.ID] = camera;
            //});
 
            CameraDict.Values.ToList().ForEach(c =>
            {
                OpenCamera(c);
            });
        }
 
        protected void OpenCamera(CameraBase camera)
        {
            if (camera.InitialConfig?.IsEnabled ?? false)
            {
                camera.UpdateShowImage -= CameraUpdateImage;
                camera.UpdateShowImage += CameraUpdateImage;
                camera.OnLog = OnDeviceLog;
 
                camera.StateChange(DeviceState.DSInit);
                camera.StateChange(DeviceState.DSOpen);
 
                (camera as Bro.Device.HikCamera.HikCameraDriver).HImageOutput = HikCameraHImageOutput;
            }
        }
 
        private void HikCameraHImageOutput(HImage arg1, string arg2)
        {
        }
 
        private void OpenDevices<T>(List<T> devices) where T : IDevice
        {
            devices.ForEach(d =>
            {
                if (d.InitialConfig?.IsEnabled ?? false)
                {
                    d.OnLog = OnDeviceLog;
 
                    d.StateChange(DeviceState.DSInit);
                    d.StateChange(DeviceState.DSOpen);
                }
            });
        }
 
        private void CloseDevice<T>(List<T> devices) where T : IDevice
        {
            devices.ForEach(d =>
            {
                if (d.CurrentState != DeviceState.DSClose)
                {
                    d.StateChange(DeviceState.DSClose);
                }
            });
        }
 
        public List<ProcessMethodAttribute> CollectProcessMethods()
        {
            List<ProcessMethodAttribute> resultList = new List<ProcessMethodAttribute>();
            var methods = this.GetType().GetMethods().ToList();
 
            methods.ForEach(m =>
            {
                var attr = m.GetCustomAttribute<ProcessMethodAttribute>();
                if (attr != null)
                {
                    resultList.Add(attr);
                }
            });
 
            return resultList;
        }
 
        public void InitialStationProcess(string configPath = "")
        {
            ProcessException.OnExceptionNotice = LogAsync;
 
            StationConfig = LoadStationConfig(configPath);
 
            #region 个别配置的特别处理
 
            #endregion
 
            _warningRemains.CollectionChanged -= _warningRemains_CollectionChanged;
            _warningRemains.CollectionChanged += _warningRemains_CollectionChanged;
 
            InitialPLCs();
            InitialRobots();
            InitialAGVs();
            InitialCameras();
 
            AutoFacRegister();
 
            LogAsync(DateTime.Now, "Process Initialized", "");
        }
 
        private void InitialCameras()
        {
            Config.CameraConfigCollection.ForEach(c =>
            {
                CameraBase camera = CameraHelper.GetCameraInstance(c.DriverType);
                camera.InitialConfig = c;
                CameraDict[camera.InitialConfig.ID] = camera;
            });
        }
 
        private void InitialPLCs()
        {
            Config.PLCConfigCollection.ForEach(c =>
            {
                OmronFinsDriver plc = new OmronFinsDriver();
                plc.InitialConfig = c;
                PLCDict[plc.InitialConfig.ID] = plc;
 
                plc.OnMonitorAlarm -= Plc_OnMonitorAlarm;
                plc.OnMonitorInvoke -= Plc_OnMonitorInvoke;
 
                plc.OnMonitorAlarm += Plc_OnMonitorAlarm;
                plc.OnMonitorInvoke += Plc_OnMonitorInvoke;
            });
        }
 
        private void InitialRobots()
        {
            Config.RobotConfigCollection.ForEach(c =>
            {
                AuboRobotDriver robot = new AuboRobotDriver();
                robot.InitialConfig = c;
                RobotDict[robot.InitialConfig.ID] = robot;
            });
        }
 
        private void InitialAGVs()
        {
            Config.AGVConfigCollection.ForEach(c =>
            {
                SeerAGVDriver agv = new SeerAGVDriver();
                agv.InitialConfig = c;
                AGVDict[agv.InitialConfig.ID] = agv;
            });
        }
 
        public void InitialStationProcess()
        {
            InitialStationProcess("");
        }
 
        private ProcessConfig LoadStationConfig(string configPath = "")
        {
            ProcessConfig config = new ProcessConfig();
 
            if (string.IsNullOrWhiteSpace(configPath))
            {
                configPath = CONFIG_PATH;
            }
 
            try
            {
                if (File.Exists(configPath))
                {
                    using (StreamReader reader = new StreamReader(configPath, System.Text.Encoding.UTF8))
                    {
                        _configBackupStr = reader.ReadToEnd();
                        config = JsonConvert.DeserializeObject<ProcessConfig>(_configBackupStr, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
                    }
                }
 
                if (config == null)
                {
                    config = new ProcessConfig();
                }
            }
            catch (Exception ex)
            {
            }
 
            return config;
        }
 
        public void Pause()
        {
        }
 
        public void Resume()
        {
        }
 
        public void SaveStationConfig(IStationConfig config)
        {
            AutoFacRegister(false);
 
            ProcessConfig pConfig = config as ProcessConfig;
            if (pConfig == null)
                throw new ProcessException("目前只支持ProcessConfig类型的非空内容保存", null);
 
            string newConfig = JsonConvert.SerializeObject(pConfig, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto });
            using (StreamWriter writer = new StreamWriter(CONFIG_PATH, false, System.Text.Encoding.UTF8))
            {
                writer.Write(newConfig);
                writer.Flush();
                writer.Close();
            }
 
            if (_configBackupStr != newConfig)
            {
                SaveBackupConfig();
            }
        }
 
        private void SaveBackupConfig()
        {
            string backPath = Path.GetDirectoryName(CONFIG_PATH);
            backPath = Path.Combine(backPath, ProductionCode + "_bk");
            if (!Directory.Exists(backPath))
            {
                Directory.CreateDirectory(backPath);
            }
 
            backPath = Path.Combine(backPath, $"Config_{ProductionCode}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.json");
 
            using (StreamWriter writer = new StreamWriter(backPath, false, System.Text.Encoding.UTF8))
            {
                writer.Write(_configBackupStr);
                writer.Flush();
                writer.Close();
            }
        }
 
        /// <summary>
        /// 调用方法的字典集合
        /// Key:MethodCode,Value:MethodInfo
        /// </summary>
        public Dictionary<string, MethodInfo> _processMethodDict = new Dictionary<string, MethodInfo>();
 
        /// <summary>
        /// Halcon算法工具字典,在初始化时统一一次性载入
        /// Key:MethodCode,Value:HalconTool
        /// </summary>
        protected Dictionary<string, HDevEngineTool> _halconToolDict = new Dictionary<string, HDevEngineTool>();
 
        private void InitialProcessMethods()
        {
            _processMethodDict = new Dictionary<string, MethodInfo>();
            var methods = this.GetType().GetMethods().ToList();
            methods.ForEach(m =>
            {
                var attr = m.GetCustomAttribute<ProcessMethodAttribute>();
                if (attr != null)
                {
                    _processMethodDict[attr.MethodCode] = m;
 
                    #region 初始化HalconTool
                    //if (attr.DeviceType.EndsWith("Camera"))
                    //{
                    //    if (StationConfig.ProcessOpConfigDict.Keys.Contains(attr.MethodCode))
                    //    {
                    //        var opConfig = StationConfig.ProcessOpConfigDict[attr.MethodCode] as HalconRelatedCameraOprerationConfigBase;
 
                    //        if (opConfig != null)
                    //        {
                    //            if (!string.IsNullOrWhiteSpace(opConfig.AlgorithemPath))
                    //            {
                    //                string directoryPath = Path.GetDirectoryName(opConfig.AlgorithemPath);
                    //                string fileName = Path.GetFileNameWithoutExtension(opConfig.AlgorithemPath);
 
                    //                HDevEngineTool tool = new HDevEngineTool(directoryPath);
                    //                tool.LoadProcedure(fileName);
 
                    //                _halconToolDict[attr.MethodCode] = tool;
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion
                }
            });
 
            #region 初始化HalconTool
            _halconToolDict = new Dictionary<string, HDevEngineTool>();
            Config.PLCConfigCollection.SelectMany(plcConfig => plcConfig.MonitorSetCollection).Select(ms => ms.OpConfig).ToList().ForEach(c =>
                {
                    IHalconToolPath toolPath = c as IHalconToolPath;
                    if (toolPath != null)
                    {
                        toolPath.GetHalconToolPathList().ForEach(path =>
                        {
                            if (!string.IsNullOrWhiteSpace(path))
                            {
                                string directoryPath = Path.GetDirectoryName(path);
                                string fileName = Path.GetFileNameWithoutExtension(path);
 
                                HDevEngineTool tool = new HDevEngineTool(directoryPath);
                                tool.LoadProcedure(fileName);
 
                                _halconToolDict[path] = tool;
                            }
                        });
                    }
                });
            #endregion
        }
 
        public List<IDevice> GetDeviceList()
        {
            List<IDevice> list = new List<IDevice>();
 
            list.AddRange(PLCDict.Values);
            list.AddRange(RobotDict.Values);
            list.AddRange(AGVDict.Values);
            list.AddRange(CameraDict.Values);
 
            return list;
        }
 
        #region PLC监听
 
        private void Plc_OnMonitorInvoke(DateTime dt, MonitorSet monitorSet)
        {
            IOperationConfig config = monitorSet.OpConfig;
            string methodCode = monitorSet.MethodCode;
            object res = null;
            int reTryTimes = config.ReTryTimes;
 
            do
            {
                try
                {
                    //有IOperationConfig参数的调用
                    res = _processMethodDict[methodCode].Invoke(this, new object[] { config });
                    reTryTimes = -1;
                }
                catch (Exception invokeEX)  //流程动作异常失败
                {
                    Exception ex = invokeEX.InnerException == null ? invokeEX : invokeEX.InnerException;
                    reTryTimes--;
 
                    if (reTryTimes <= 0) //如果没有重试次数了就通知PLC
                    {
                        if (config == null || config.ExceptionValue == 0)
                        {
                            if (!(ex is ProcessException))
                            {
                                //如果是算法异常,返回NG值;否则返回异常值
                                if (ex is HDevEngineException)
                                {
                                    res = new ProcessResponse((int)ReturnValue.NGVALUE);
                                }
                                else
                                {
                                    res = new ProcessResponse((int)ReturnValue.EXCEPTIONVALUE);
                                }
 
                                var newEx = new ProcessException("函数" + methodCode + "执行异常", ex);
                            }
                            else
                            {
                                if ((ex as ProcessException).OriginalException != null)
                                {
                                    res = new ProcessResponse((int)ReturnValue.EXCEPTIONVALUE);
                                }
                                else
                                {
                                    res = new ProcessResponse((int)ReturnValue.NGVALUE);
                                }
                            }
                        }
                        else
                        {
                            res = new ProcessResponse(config.ExceptionValue);
                        }
 
                        LogAsync(DateTime.Now, methodCode + "异常信息", ex.GetExceptionMessage());
                    }
                }
 
                if (reTryTimes > 0)
                {
                    LogAsync(DateTime.Now, methodCode + " reTryTimes", reTryTimes.ToString());
                }
            } while (reTryTimes > 0);
 
            #region 设置返回值
            monitorSet.Response = res as ProcessResponse;
 
            //测试模式下始终反馈OK信号
            if (StationConfig.IsDemoMode && monitorSet.Response.ResultValue <= 0)
            {
                monitorSet.Response.ResultValue = (int)ReturnValue.OKVALUE;
            }
            #endregion
 
            //sw.Stop();
            //LogAsync(DateTime.Now, methodCode + " 调用耗时: " + sw.ElapsedMilliseconds.ToString() + "ms", "");
            //TimeRecordCSV(DateTime.Now, methodCode + "调用", (int)sw.ElapsedMilliseconds);
            //sw.Start();
 
            #region 原有PLC写入结果操作,现转到异步调用后回调去执行
            //ProcessResponse resValues = res as ProcessResponse;
 
            //if (resValues.ResultValue == (int)PLCReplyValue.IGNORE)
            //{
            //    return;
            //}
 
            //if (monitorSet.ReplyDataAddress != -1 && resValues.DataList.Count > 0)
            //{
            //    PLC_ITEM item = new PLC_ITEM();
            //    item.OP_TYPE = 2;
            //    item.ITEM_LENGTH = resValues.DataList.Count;
            //    item.ADDRESS = monitorSet.ReplyDataAddress.ToString();
            //    item.ITEM_VALUE = String.Join(",", resValues.DataList);
            //    PLC.WriteItem(item, false);
            //}
 
            //if (monitorSet.NoticeAddress != -1)
            //{
            //    //测试模式下始终反馈OK信号
            //    if (StationConfig.IsDemoMode && resValues.ResultValue <= 0)
            //    {
            //        resValues.ResultValue = (int)ReturnValue.OKVALUE;
            //    }
 
            //    int repeatTime = 5;
 
            //    //LogAsync(DateTime.Now, methodCode + "开始反馈", "");
            //    do
            //    {
            //        try
            //        {
            //            PLC.WriteSingleAddress(set.NoticeAddress, resValues.ResultValue, false);
            //            repeatTime = 0;
            //        }
            //        catch (Exception ex)
            //        {
            //            repeatTime--;
 
            //            if (repeatTime <= 0)
            //            {
            //                new ProcessException("PLC反馈写入异常", ex);
            //            }
            //        }
            //    } while (repeatTime > 0);
            //}
            #endregion
        }
 
        private void Plc_OnMonitorAlarm(DateTime dt, WarningSet warning, bool isAlarmRaised)
        {
        }
 
        //List<int> _monitorList = new List<int>();
        //List<MonitorSet> _monitorSetList = new List<MonitorSet>();
        //List<string> _methodCodeList = new List<string>();
 
        //ConcurrentDictionary<string, Task> _halconTaskDict = new ConcurrentDictionary<string, Task>();
        //ConcurrentDictionary<string, AutoResetEvent> _halconHandleDict = new ConcurrentDictionary<string, AutoResetEvent>();
 
        ///// <summary>
        ///// PLC监听
        ///// </summary>
        //private void PLCMonitor()
        //{
        //    _monitorSetList = StationConfig.PLCMonitorSet.Values.ToList();
        //    _methodCodeList = StationConfig.PLCMonitorSet.Keys.ToList();
 
        //    while (PLC.CurrentState == DeviceState.DSOpen)
        //    {
        //        try
        //        {
        //            List<int> newMonitorList = PLC.Monitor(PLC.IConfig.EventStartAddress, PLC.IConfig.EventLength);
 
        //            if (newMonitorList == null || newMonitorList.Count == 0)
        //                continue;
 
        //            Stopwatch sw = new Stopwatch();
        //            sw.Start();
        //            if (_monitorList.Count == newMonitorList.Count)
        //            {
        //                var tempNew = new List<int>(newMonitorList);
        //                var tempOld = new List<int>(_monitorList);
        //                //Task.Run(() =>
        //                //{
        //                MonitorCheckAndInvoke(tempNew, tempOld);
        //                //});
        //            }
        //            _monitorList = new List<int>(newMonitorList);
        //            sw.Stop();
 
        //            if (sw.ElapsedMilliseconds > 10)
        //            {
        //                LogAsync(DateTime.Now, $"轮询时间:{sw.ElapsedMilliseconds}", "");
        //                TimeRecordCSV(DateTime.Now, "轮询时间", (int)sw.ElapsedMilliseconds);
        //            }
 
        //            Thread.Sleep(PLC.IConfig.ScanInterval);
        //        }
        //        catch (Exception ex)
        //        {
        //            LogAsync(DateTime.Now, "PLC监听异常", ex.GetExceptionMessage());
        //        }
        //    };
        //}
 
        //private void MonitorCheckAndInvoke(List<int> newMonitorList, List<int> monitorList)
        //{
        //    //await Task.Run(() =>
        //    {
        //        Parallel.For(0, monitorList.Count, (index) =>
        //        //for (int index = 0; index < monitorList.Count; index++)
        //        {
        //            int plcValue = newMonitorList[index];
        //            int plcOldValue = monitorList[index];
 
        //            #region PLC警报信息
        //            //bool warningSignal = (index >= Config.PLCConfig.WarningStartIndex && index < Config.PLCConfig.WarningStartIndex + Config.PLCConfig.WarningLength);
 
        //            // if (warningSignal)
        //            // {
        //            //     if (plcValue != plcOldValue)
        //            //     {
        //            //         int warningIndex = index - Config.PLCConfig.WarningStartIndex;
        //            //         for (int i = 0; i < 16; i++)
        //            //         {
        //            //             var ws = StationConfig.WarningSets.FirstOrDefault(w => w.WaringIndex == (warningIndex * 16) + i);
 
        //            //             if (ws != null)
        //            //             {
        //            //                 int newValue = plcValue >> i & 1;
        //            //                 int oldValue = plcOldValue >> i & 1;
 
        //            //                 if (newValue != oldValue)
        //            //                 {
        //            //                    //CurrentPubSub.Publish(PubTag.PLCWarningUpdate.ToString(), newValue == 1, ws, true);
 
        //            //                    //仅保存警报信息,不保存提示信息
        //            //                    if (ws.WarningLvl == 0)
        //            //                     {
        //            //                         if (newValue == 1)
        //            //                         {
        //            //                             if (!_warningRemains.Contains(ws.WarningCode))
        //            //                             {
        //            //                                 _warningRemains.Add(ws.WarningCode);
        //            //                             }
        //            //                         }
        //            //                         else
        //            //                         {
        //            //                             if (_warningRemains.Contains(ws.WarningCode))
        //            //                             {
        //            //                                 _warningRemains.Remove(ws.WarningCode);
        //            //                             }
        //            //                         }
 
        //            //                         SaveAlarm(Config.StationCode, ws, newValue);
        //            //                     }
        //            //                 }
        //            //             }
        //            //         }
        //            //     }
 
        //            //    //continue;
        //            //    return;
        //            // }
        //            #endregion
 
        //            if (plcValue != plcOldValue)
        //            {
        //                _monitorSetList.Where(u => u.TriggerIndex == index).ToList().ForEach(monitorSet =>
        //                {
        //                    int monitorSetIndex = _monitorSetList.IndexOf(monitorSet);
        //                    string methodCode = _methodCodeList[monitorSetIndex];
        //                    LogAsync(DateTime.Now, $"索引{monitorSet.TriggerIndex}变动,方法:{methodCode}", $"原先值:{plcOldValue},变化值:{plcValue}");
 
        //                    //触发值为-999时,监听地址数据变动即触发函数
        //                    if (monitorSet != null && (plcValue == monitorSet.TriggerValue || monitorSet.TriggerValue == -999))
        //                    {
        //                        List<int> inputData = new List<int>();
        //                        if (monitorSet.InputDataIndex != null && monitorSet.InputDataIndex.Count > 0)
        //                        {
        //                            monitorSet.InputDataIndex.ForEach(p =>
        //                            {
        //                                inputData.Add(newMonitorList[p]);
        //                            });
        //                        }
 
        //                        LogAsync(DateTime.Now, "PLC触发", methodCode + "触发\r\n触发值:" + plcValue + ";传入值:" + (inputData == null || inputData.Count == 0 ? "NA" : string.Join(",", inputData)));
 
        //                        if (_halconToolDict.Keys.Contains(methodCode))
        //                        {
        //                            if (!_halconTaskDict.Keys.Contains(methodCode))
        //                            {
        //                                _halconHandleDict[methodCode] = new AutoResetEvent(false);
        //                                _halconTaskDict[methodCode] = new Task((obj) =>
        //                                {
        //                                    while (true)
        //                                    {
        //                                        _halconHandleDict[methodCode].WaitOne();
 
        //                                        if (PLC.CurrentState != DeviceState.DSOpen)
        //                                            continue;
 
        //                                        object[] objs = obj as object[];
        //                                        int msIndex = Convert.ToInt32(objs[0]);
        //                                        MonitorSet set = objs[1] as MonitorSet;
        //                                        List<int> inputDataIndex = objs[2] as List<int>;
        //                                        List<int> datas = new List<int>();
 
        //                                        if (inputDataIndex != null)
        //                                        {
        //                                            inputDataIndex.ForEach(p =>
        //                                            {
        //                                                datas.Add(newMonitorList[p]);
        //                                            });
        //                                        }
 
        //                                        MethodHandle(msIndex, set, datas, plcValue);
        //                                    }
        //                                }, new object[] { monitorSetIndex, monitorSet, monitorSet.InputDataIndex });
 
        //                                _halconTaskDict[methodCode].Start();
        //                            }
 
        //                            _halconHandleDict[methodCode].Set();
        //                        }
        //                        else
        //                        {
        //                            ThreadPool.QueueUserWorkItem(MethodHandle, new object[] { monitorSetIndex, monitorSet, inputData, plcValue });
        //                        }
        //                    }
        //                });
        //            }
        //        }
        //        );
        //    }
        //    //);
        //}
 
        //private void MethodHandle(object obj)
        //{
        //    object[] objs = obj as object[];
        //    int monitorSetIndex = Convert.ToInt32(objs[0]);
        //    MonitorSet set = objs[1] as MonitorSet;
        //    List<int> inputDataValue = objs[2] as List<int>;
        //    int triggerValue = Convert.ToInt32(objs[3]);
 
        //    MethodHandle(monitorSetIndex, set, inputDataValue, triggerValue);
        //}
 
        //private void MethodHandle(int monitorSetIndex, MonitorSet set, List<int> inputDataValue, int triggerValue)
        //{
        //    //await Task.Run(() =>
        //    //Task.Run(() =>
        //    {
        //        string methodCode = _methodCodeList[monitorSetIndex];
        //        Stopwatch sw = new Stopwatch();
        //        sw.Start();
 
        //        try
        //        {
        //            if (_processMethodDict.Keys.Contains(methodCode))
        //            {
        //                IOperationConfig config = null;
        //                if (StationConfig.ProcessOpConfigDict.Keys.Contains(methodCode))
        //                {
        //                    config = StationConfig.ProcessOpConfigDict[methodCode];
        //                }
        //                else
        //                {
        //                    config = new OperationConfigBase();
        //                }
 
        //                config.InputPara = inputDataValue;
 
        //                object res = null;
        //                int reTryTimes = config.ReTryTimes;
 
        //                do
        //                {
        //                    try
        //                    {
        //                        //有IOperationConfig参数的调用
        //                        res = _processMethodDict[methodCode].Invoke(this, new object[] { config });
        //                        reTryTimes = -1;
        //                    }
        //                    catch (Exception invokeEX)  //流程动作异常失败
        //                    {
        //                        Exception ex = invokeEX.InnerException == null ? invokeEX : invokeEX.InnerException;
        //                        reTryTimes--;
 
        //                        if (reTryTimes <= 0) //如果没有重试次数了就通知PLC
        //                        {
        //                            //保存最后一次NG的图片
        //                            //SaveNGImage(_processMethodDict[methodCode]);
 
        //                            if (config == null || config.ExceptionValue == 0)
        //                            {
        //                                if (!(ex is ProcessException))
        //                                {
        //                                    //CurrentPubSub.Publish(PubTag.ExceptionUpdate.ToString(), "函数" + methodCode + "执行异常", ex, true);
 
        //                                    //如果是算法异常,返回NG值;否则返回异常值
        //                                    if (ex is HDevEngineException)
        //                                    {
        //                                        res = new ProcessResponse((int)ReturnValue.NGVALUE);
        //                                    }
        //                                    else
        //                                    {
        //                                        res = new ProcessResponse((int)ReturnValue.EXCEPTIONVALUE);
        //                                    }
 
        //                                    var newEx = new ProcessException("函数" + methodCode + "执行异常", ex);
        //                                }
        //                                else
        //                                {
        //                                    if ((ex as ProcessException).OriginalException != null)
        //                                    {
        //                                        res = new ProcessResponse((int)ReturnValue.EXCEPTIONVALUE);
        //                                    }
        //                                    else
        //                                    {
        //                                        res = new ProcessResponse((int)ReturnValue.NGVALUE);
        //                                    }
        //                                }
        //                            }
        //                            else
        //                            {
        //                                res = new ProcessResponse(config.ExceptionValue);
        //                            }
 
        //                            LogAsync(DateTime.Now, methodCode + "异常信息", ex.GetExceptionMessage());
        //                        }
        //                    }
 
        //                    if (reTryTimes > 0)
        //                    {
        //                        LogAsync(DateTime.Now, methodCode + " reTryTimes", reTryTimes.ToString());
        //                    }
        //                } while (reTryTimes > 0);
 
        //                sw.Stop();
        //                LogAsync(DateTime.Now, methodCode + " 调用耗时: " + sw.ElapsedMilliseconds.ToString() + "ms", "");
        //                TimeRecordCSV(DateTime.Now, methodCode + "调用", (int)sw.ElapsedMilliseconds);
        //                sw.Start();
 
        //                ProcessResponse resValues = res as ProcessResponse;
 
        //                //if (resValues != null)
        //                //{
        //                if (resValues.ResultValue == (int)PLCReplyValue.IGNORE)
        //                {
        //                    return;
        //                }
 
        //                if (set.ReplyDataAddress != -1 && resValues.DataList.Count > 0)
        //                {
        //                    //int stepLength = 120;
        //                    //int startAdd = set.ReplyDataAddress;
 
        //                    //while (resValues.DataList.Count > 0)
        //                    //{
        //                    //    var data = resValues.DataList.Take(stepLength).ToList();
 
        //                    //    PLC_ITEM item = new PLC_ITEM();
        //                    //    item.OP_TYPE = 2;
        //                    //    item.ITEM_LENGTH = data.Count;
        //                    //    item.ADDRESS = startAdd.ToString();
        //                    //    item.ITEM_VALUE = String.Join(",", data);
        //                    //    PLC.WriteItem(item);
 
        //                    //    if (resValues.DataList.Count > stepLength)
        //                    //    {
        //                    //        startAdd += stepLength;
        //                    //        resValues.DataList = resValues.DataList.Skip(stepLength).ToList();
        //                    //    }
        //                    //}
 
        //                    //if (resValues.DataList.Count > 0)
        //                    //{
        //                    PLC_ITEM item = new PLC_ITEM();
        //                    item.OP_TYPE = 2;
        //                    item.ITEM_LENGTH = resValues.DataList.Count;
        //                    item.ADDRESS = set.ReplyDataAddress.ToString();
        //                    item.ITEM_VALUE = String.Join(",", resValues.DataList);
        //                    PLC.WriteItem(item, false);
        //                    //}
        //                }
 
        //                if (set.NoticeAddress != -1)
        //                {
        //                    //测试模式下始终反馈OK信号
        //                    if (StationConfig.IsDemoMode && resValues.ResultValue <= 0)
        //                    {
        //                        resValues.ResultValue = (int)ReturnValue.OKVALUE;
        //                    }
 
        //                    int repeatTime = 5;
 
        //                    //LogAsync(DateTime.Now, methodCode + "开始反馈", "");
        //                    do
        //                    {
        //                        try
        //                        {
        //                            PLC.WriteSingleAddress(set.NoticeAddress, resValues.ResultValue, false);
        //                            repeatTime = 0;
        //                        }
        //                        catch (Exception ex)
        //                        {
        //                            repeatTime--;
 
        //                            if (repeatTime <= 0)
        //                            {
        //                                new ProcessException("PLC反馈写入异常", ex);
        //                            }
        //                        }
        //                    } while (repeatTime > 0);
        //                    //LogAsync(DateTime.Now, methodCode + "结束反馈", "");
        //                }
        //                //}
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            LogAsync(DateTime.Now, _methodCodeList[monitorSetIndex] + "调用异常", ex.GetExceptionMessage());
        //        }
        //        //finally
        //        //{
        //        //    //IdleFlag--;
        //        //    //_idleTimer.Change(BaseConfig.IdleTimeThreshold * 1000, Timeout.Infinite);
 
        //        //}
 
        //        sw.Stop();
        //        LogAsync(DateTime.Now, methodCode + " Elapsed: " + sw.ElapsedMilliseconds.ToString() + "ms", "");
        //        TimeRecordCSV(DateTime.Now, methodCode + "完成", (int)sw.ElapsedMilliseconds);
        //    }
        //    //);
        //}
 
        //private async void CTHandle(OperationCTCollection ct, int plcValue)
        //{
        //    await Task.Run(() =>
        //    {
        //        if (plcValue == 0)
        //        {
        //            ct.CSVOutput(StationConfig.CSVFilePath);
 
        //            //ct.CTList.ForEach(u =>
        //            foreach (var u in ct.CTList)
        //            {
        //                u.StartTime = null;
        //                u.EndTime = null;
        //            }
        //            //);
 
        //            //CurrentPubSub.Publish(PubTag.CTUpdate.ToString(), ct, null, true);
        //        }
        //        else
        //        {
        //            for (int i = 0; i < ct.CTList.Count; i++)
        //            {
        //                if (plcValue == ct.CTList[i].OpTrigger)
        //                {
        //                    DateTime dt = DateTime.Now;
 
        //                    if (i < ct.CTList.Count - 1)
        //                    {
        //                        ct.CTList[i].StartTime = dt;
        //                    }
 
        //                    if (i > 1)
        //                    {
        //                        ct.CTList[i - 1].EndTime = dt;
        //                    }
 
        //                    //CurrentPubSub.Publish(PubTag.CTUpdate.ToString(), ct, null, true);
        //                    break;
        //                }
        //            }
        //        }
        //    });
        //}
 
        //public virtual ProcessResponse MonitorMethodInvoke(string methodCode, IOperationConfig config)
        //{
        //    return _processMethodDict[methodCode].Invoke(this, new object[] { config }) as ProcessResponse;
        //    //return null;
        //}
        #endregion
 
        #region 图像处理
        protected Dictionary<string, Queue<string>> CameraBitmapDict = new Dictionary<string, Queue<string>>();
        //protected Dictionary<string, Bitmap> CameraBitmapDict = new Dictionary<string, Bitmap>();
 
        protected HObject CollectHImage(CameraBase camera, IOperationConfig opConfig, string cameraId, string methodCode)
        {
            HObject hImage = null;
 
            if (StationConfig.IsImageOffline)
            {
                using (OfflineImageFrm oiF = new OfflineImageFrm())
                {
                    if (oiF.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        hImage = oiF.HImg;
                    }
                    else
                    {
                        //MessageBox.Show("未能获取离线图片!");
                        throw new ProcessException("未能获取离线图片!", null);
                    }
                }
            }
            else
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
 
                var cameraConifg = opConfig as HalconRelatedCameraOprerationConfigBase;
                if (cameraConifg.DelayBefore > 0)
                {
                    Thread.Sleep(cameraConifg.DelayBefore);
                }
 
                camera.UploadOperationConfig(opConfig);
                camera.Snapshot(opConfig, out hImage);
 
                //SaveTempImage(cameraName, camera.ImageFilePath);
                //SaveTempImage(camera, cameraId);
 
                if (cameraConifg.DelayAfter > 0)
                {
                    Thread.Sleep(cameraConifg.DelayAfter);
                }
 
                sw.Stop();
                LogAsync(DateTime.Now, $"{methodCode}采图耗时:{sw.ElapsedMilliseconds}ms", "");
                TimeRecordCSV(DateTime.Now, methodCode + "采图", (int)sw.ElapsedMilliseconds);
            }
 
            return hImage;
        }
 
        //private async void SaveTempImage(string cameraName, string imgFilePath)
        //{
        //    await Task.Run(() =>
        //    {
        //        //if (!string.IsNullOrWhiteSpace(cameraId))
        //        //{
        //        //    //if (CameraBitmapDict.ContainsKey(cameraId) && CameraBitmapDict[cameraId] != null)
        //        //    //{
        //        //    //    CameraBitmapDict[cameraId].Dispose();
        //        //    //    CameraBitmapDict[cameraId] = null;
        //        //    //}
        //        //    CameraBitmapDict[cameraId] = imgFilePath;
        //        //}
 
        //        CameraBitmapDict[cameraName] = imgFilePath;
        //    });
        //}
 
        private async void SaveTempImage(CameraBase camera, string cameraId)
        {
            await Task.Run(() =>
            {
                //if (!string.IsNullOrWhiteSpace(cameraId))
                //{
                //    //if (CameraBitmapDict.ContainsKey(cameraId) && CameraBitmapDict[cameraId] != null)
                //    //{
                //    //    CameraBitmapDict[cameraId].Dispose();
                //    //    CameraBitmapDict[cameraId] = null;
                //    //}
                //    CameraBitmapDict[cameraId] = imgFilePath;
                //}
 
                //camera.ImageGetHandle.WaitOne();
                //CameraBitmapDict[cameraName] = camera.ShowImage;
 
                if (string.IsNullOrWhiteSpace(cameraId))
                    return;
 
                camera.ImageSaveDoneHandle.WaitOne();
 
                if (!CameraBitmapDict.ContainsKey(cameraId))
                {
                    CameraBitmapDict.Add(cameraId, new Queue<string>());
                }
                CameraBitmapDict[cameraId].Enqueue(camera.ImageFilePath);
            });
        }
 
        protected async void CameraUpdateImage(CameraBase camera, Bitmap image, string imageFilePath)
        {
            await Task.Run(() =>
            {
                OnBitmapOutput?.Invoke(camera.InitialConfig.ID, image);
            });
        }
 
        //protected async void SaveNGImage(MethodInfo methodInfo)
        //{
        //    await Task.Run(() =>
        //    {
        //        try
        //        {
        //            if (string.IsNullOrWhiteSpace(Config.NGImageFolderPath))
        //                return;
 
        //            var attr = methodInfo.GetCustomAttribute<CameraInvokeAttribute>();
        //            if (attr == null)
        //                return;
 
        //            SaveCameraImage(attr.CameraName);
        //        }
        //        catch (Exception ex)
        //        {
        //            LogAsync(DateTime.Now, "保存NG图片异常", ex.GetExceptionMessage());
        //        }
        //    });
        //}
 
        //protected void SaveCameraImage(string cameraName)
        //{
        //    try
        //    {
        //        if (CameraBitmapDict.ContainsKey(cameraName))
        //        {
        //            DirectoryInfo dir = new DirectoryInfo(Path.Combine(Config.NGImageFolderPath, DateTime.Now.ToString("yyyyMMdd")));
        //            if (!dir.Exists)
        //                dir.Create();
 
        //            //string imageFilePath = Path.Combine(dir.FullName, DateTime.Now.ToString("HHmmssfff") + ".jpg");
 
        //            //if (CameraBitmapDict[cameraName] != null)
        //            //    CameraBitmapDict[cameraName].Save(imageFilePath, ImageFormat.Jpeg);
 
        //            FileInfo file = new FileInfo(CameraBitmapDict[cameraName]);
        //            if (file.Exists)
        //            {
        //                file.CopyTo(Path.Combine(dir.FullName, file.Name));
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogAsync(DateTime.Now, "保存相机图片异常", ex.GetExceptionMessage());
        //    }
        //}
 
        //private async void SaveFitImage(CameraBase camera, HalconRelatedCameraOprerationConfigBase config, List<ElementBase> list)
        //{
        //    await Task.Run(() =>
        //    {
        //        if (!config.IsSaveFitImage)
        //            return;
 
        //        if (string.IsNullOrWhiteSpace(config.FitImagePath))
        //            return;
 
        //        string imageFilePath = "";
 
        //        int repeatTime = 15;
        //        do
        //        {
        //            if (CameraBitmapDict.ContainsKey(camera.InitialConfig.ID) && CameraBitmapDict[camera.InitialConfig.ID].Count > 0)
        //            {
        //                imageFilePath = CameraBitmapDict[camera.InitialConfig.ID].Dequeue();
        //            }
 
        //            if (string.IsNullOrWhiteSpace(imageFilePath) || !File.Exists(imageFilePath))
        //            {
        //                repeatTime--;
        //                Thread.Sleep(50);
        //            }
        //            else
        //            {
        //                repeatTime = 0;
        //            }
 
        //        } while (repeatTime > 0);
 
        //        if (string.IsNullOrWhiteSpace(imageFilePath))
        //            return;
 
        //        var dir = new DirectoryInfo(Path.Combine(config.FitImagePath, DateTime.Now.ToString("yyyyMMdd")));
        //        if (!dir.Exists)
        //        {
        //            dir.Create();
        //        }
 
        //        repeatTime = 10;
        //        do
        //        {
        //            try
        //            {
        //                string fileName = Path.GetFileNameWithoutExtension(imageFilePath);
        //                fileName = Path.Combine(dir.FullName, fileName + ".jpg");
        //                Bitmap image = (Bitmap)Image.FromFile(imageFilePath);
 
        //                SaveFitImage(image, list, fileName);
 
        //                repeatTime = 0;
        //            }
        //            catch (Exception ex)
        //            {
        //                repeatTime--;
        //                LogAsync(DateTime.Now, "保存拟合图片异常1", ex.GetExceptionMessage());
        //                Thread.Sleep(500);
        //            }
        //        } while (repeatTime > 0);
        //    });
        //}
 
        //[HandleProcessCorruptedStateExceptions]
        //private async void SaveFitImage(Bitmap image, List<ElementBase> eleList, string fileName)
        //{
        //    await Task.Run(() =>
        //    {
        //        if (image == null)
        //            return;
 
        //        Bitmap map = new Bitmap(image.Width, image.Height);
        //        using (Graphics g = Graphics.FromImage(map))
        //        {
        //            int saveRetry = 15;
        //            do
        //            {
        //                try
        //                {
        //                    g.DrawImage(image, 0, 0);
 
        //                    eleList.ForEach(e =>
        //                    {
        //                        int repeatTime = 5;
        //                        do
        //                        {
        //                            try
        //                            {
        //                                e.State = ElementState.Normal;
        //                                e.Draw(g);
        //                                repeatTime = 0;
        //                            }
        //                            catch (Exception)
        //                            {
        //                                repeatTime--;
        //                            }
        //                        } while (repeatTime > 0);
        //                    });
 
        //                    map.Save(fileName, ImageFormat.Jpeg);
        //                    saveRetry = 0;
        //                }
        //                //catch (System.AccessViolationException ex)
        //                //{
        //                //    saveRetry--;
        //                //    LogAsync(DateTime.Now, "保存拟合图片异常2", ex.GetExceptionMessage());
 
        //                //    Thread.Sleep(100);
        //                //}
        //                catch (Exception ex)
        //                {
        //                    saveRetry--;
        //                    LogAsync(DateTime.Now, "保存拟合图片异常2", ex.GetExceptionMessage());
 
        //                    Thread.Sleep(100);
        //                }
        //            } while (saveRetry > 0);
        //        }
 
        //        map.Dispose();
        //        image.Dispose();
        //    });
        //}
        #endregion
 
        #region 报警和DownTime
        public ObservableCollection<string> _warningRemains = new ObservableCollection<string>();
 
        bool warningRemainFlag = false;
        bool WarningRemainFlag
        {
            get
            {
                return warningRemainFlag;
            }
            set
            {
                if (value && !warningRemainFlag)
                {
                    //CurrentPubSub.Publish(EnumHelper.PubTag.DownTimeNotice.ToString(), true, null, true);
                    //SaveDownTime(DateTime.Now, true);
                }
 
                if (!value)
                {
                    //CurrentPubSub.Publish(EnumHelper.PubTag.DownTimeNotice.ToString(), false, null, true);
                    //SaveDownTime(DateTime.Now, false);
                }
 
                warningRemainFlag = value;
            }
        }
 
        private void _warningRemains_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            //lock (_idleTimeLock)
            //{
            //    if (_warningRemains.Count == 0)
            //    {
            //        if (!_idleFlag)
            //        {
            //            StartIdleRecordAsync();
            //        }
 
            //        WarningRemainFlag = false;
            //    }
            //    else
            //    {
            //        if (_idleFlag)
            //        {
            //            //_idleFlag = false;
            //            EndIdleRecordAsync();
            //        }
 
            //        WarningRemainFlag = true;
            //    }
            //}
        }
 
        private void SaveAlarm(string stationCode, WarningSet ws, int newValue)
        {
        }
        #endregion
 
        #region Log
        static object logObj = new object();
        public Action<DateTime, string, string> OnLog;
        public virtual async void LogAsync(DateTime dt, string prefix, string msg)
        {
            await Task.Run(() =>
            {
                OnLog?.BeginInvoke(dt, prefix, msg, null, null);
 
                if (!StationConfig.IsLogEnabled)
                    return;
 
                DirectoryInfo dir = new DirectoryInfo(StationConfig.LogPath);
                if (!dir.Exists)
                {
                    dir.Create();
                }
 
                string logPath = Path.Combine(StationConfig.LogPath, DateTime.Today.ToString("yyyyMMdd") + ".txt");
 
                lock (logObj)
                {
                    using (StreamWriter writer = new StreamWriter(logPath, true, System.Text.Encoding.UTF8))
                    {
                        //writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        writer.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        writer.WriteLine(prefix);
                        writer.Write(msg);
                        writer.WriteLine();
                        writer.WriteLine();
 
                        writer.Flush();
                        writer.Close();
                    }
                }
            });
        }
 
        protected void OnDeviceLog(DateTime dt, IDevice device, string msg)
        {
            LogAsync(dt, device.InitialConfig.Name, msg);
        }
 
        static object csvLock = new object();
        private async void TimeRecordCSV(DateTime dt, string desc, int ms)
        {
            await Task.Run(() =>
            {
                lock (csvLock)
                {
                    string filePath = Path.Combine(Config.LogPath, $"TimeRecords_{DateTime.Now.ToString("yyyyMMdd")}.csv");
                    bool isFileExisted = File.Exists(filePath);
                    using (StreamWriter writer = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                    {
                        if (!isFileExisted)
                        {
                            writer.WriteLine("Time,Prefix,Consumed");
                        }
                        writer.WriteLine($"{dt.ToString("HH:mm:ss.fff")},{desc},{ms}");
                        writer.Flush();
                        writer.Close();
                    }
                }
            });
        }
        #endregion
 
        #region 临时数据保存和读取
        protected static Dictionary<string, object> _tempDataLock = new Dictionary<string, object>();
        protected string _tempFileDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempData");
 
        protected virtual T ReadTempDataFromHistory<T>(T t, string propertyName) where T : class
        {
            if (!_tempDataLock.ContainsKey(propertyName))
            {
                _tempDataLock[propertyName] = new object();
            }
 
            if (t != null)
            {
                return t;
            }
            else
            {
                if (!Directory.Exists(_tempFileDirectory))
                {
                    Directory.CreateDirectory(_tempFileDirectory);
                }
 
                string filePath = Path.Combine(_tempFileDirectory, propertyName);
 
                if (!File.Exists(filePath))
                {
                    return null;
                }
 
                lock (_tempDataLock[propertyName])
                {
                    using (StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8))
                    {
                        string content = reader.ReadToEnd();
                        var result = JsonConvert.DeserializeObject<T>(content);
                        return result;
                    }
                }
            }
        }
 
        protected virtual void SaveTempData<T>(T t, string propertyName, string defaultStr = "")
        {
            //await Task.Run(() =>
            {
                if (!_tempDataLock.ContainsKey(propertyName))
                {
                    _tempDataLock[propertyName] = new object();
                }
 
                lock (_tempDataLock[propertyName])
                {
                    try
                    {
                        if (!Directory.Exists(_tempFileDirectory))
                        {
                            Directory.CreateDirectory(_tempFileDirectory);
                        }
 
                        string serialStr = JsonConvert.SerializeObject(t);
 
                        if (!string.IsNullOrWhiteSpace(defaultStr))
                        {
                            if (t == null)
                            {
                                serialStr = defaultStr;
                            }
                        }
                        else
                        {
                            if (t == null)
                                return;
                        }
 
                        string filePath = Path.Combine(_tempFileDirectory, propertyName);
 
                        using (StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
                        {
                            writer.Write(serialStr);
                            writer.Flush();
                            writer.Close();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            //);
        }
        #endregion
    }
 
    public enum ReturnValue
    {
        OKVALUE = 1,
        NGVALUE = -1,
        EXCEPTIONVALUE = -2,
        LEVEL3EXCEPTION = -3,
        INCOMINGMATERIALEXCEPTION = -4,
    }
}