C3204
2025-12-29 fec341de45f4b3fd1825807f0b3261143fa13caa
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
using HalconDotNet;
using LB_SmartVision.Forms;
using LB_SmartVision.Forms.Pages;
using LB_SmartVision.Forms.Pages.CameraPage;
using LB_SmartVision.Forms.Pages.CommunicatorPage;
using LB_SmartVision.Forms.Pages.MESPage;
using LB_SmartVision.Forms.Pages.MotionControlPage;
using LB_SmartVision.Forms.Pages.ProcessPage;
using LB_SmartVision.Forms.Pages.SettingPage;
using LB_SmartVision.Forms.Pages.UserManagementPage;
using LB_SmartVision.ProcessRun;
using LB_SmartVision.Tool;
using LB_SmartVisionCommon;
using LB_SmartVisionLoginUI;
using LB_VisionProcesses;
using LB_VisionProcesses.Cameras;
using LB_VisionProcesses.Cameras.HRCameras;
using LB_VisionProcesses.Communicators;
using LB_VisionProcesses.Communicators.TCom;
using LB_VisionProcesses.Forms;
using log4net.Config;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace LB_SmartVision
{
    public partial class VisionForm : Form
    {
        AllProcessesPage AllProcessesPages = new AllProcessesPage();
        CamerasEditPage CamerasEditPage = new CamerasEditPage();
        CommunicatorsEditPage CommunicatorsEditPage = new CommunicatorsEditPage();
        SettingEditPage SettingEditPage = new SettingEditPage();
        MESEditPage MESEditPage = new MESEditPage();
        MotionControlEditPage MotionControlEditPage = new MotionControlEditPage();
        UserManagementEditPage UserManagementEditPage = new UserManagementEditPage();
 
        byte[] Assembly_LB_VisionProcessesBytes = File.ReadAllBytes("LB_VisionProcesses.dll");
        /// <summary>
        /// 用于反序列化的程序集引用
        /// </summary>
        Assembly Assembly_LB_VisionProcessesDll = null;
 
 
        public VisionForm()
        {
            InitializeComponent();
            HOperatorSet.SetWindowAttr("background_color", "gray");
            Assembly_LB_VisionProcessesDll = Assembly.Load(Assembly_LB_VisionProcessesBytes);
 
            GlobalVar.dicCommunicators.DictionaryChanged += CommunicatorsChanged;
            GlobalVar.dicProcesses.DictionaryChanged += ProcessRunBllChanged;
 
            //最开始就清空所有Tab页
            materialTabControl.TabPages.Clear();
            AllProcessesPages.controlsPanel.Dock = DockStyle.Fill;
            materialTabControl.Controls.Add(AllProcessesPages);
 
 
            CamerasEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(CamerasEditPage));
 
            CommunicatorsEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(CommunicatorsEditPage));
 
            SettingEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(SettingEditPage));
 
            MESEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(MESEditPage));
 
            MotionControlEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(MotionControlEditPage));
 
            UserManagementEditPage.LogInfo += LogInfo;
            materialTabControl.Controls.Add(new MyPage(UserManagementEditPage));
 
            for (int i = 0; i < materialTabControl.TabPages.Count; i++)
            {
                //materialTabControl.TabPages[i].Font= new Font("Microsoft YaHei UI", 18F, FontStyle.Regular, GraphicsUnit.Point, 0);
            }
            materialTabSelector.BaseTabControl = materialTabControl;
            //materialTabSelector.Font = new Font("Microsoft YaHei UI", 18F, FontStyle.Regular, GraphicsUnit.Point, 0);
        }
 
        private void ProcessRunBllChanged(object? sender, DictionaryChangedEventArgs<string, ProcessRunBll> e)
        {
            try
            {
                string msg = string.Empty;
                List<MyPage> removeMyPage = new List<MyPage>();
                switch (e.ChangeType)
                {
                    case DictionaryChangeType.Added:
                        string AddProcessName = e.NewKey;
                        GlobalVar.dicProcesses[AddProcessName].LogInfo += LogInfo;
                        if (GlobalVar.dicProcesses[AddProcessName].Load(out msg))
                        {
                            LogInfo($"流程[{AddProcessName}]加载成功", LogInfoType.PASS);
                            IProcess.dicGlobalVars.TryAdd($"{AddProcessName}.Result", false);
                            IProcess.dicGlobalVars.TryAdd($"{AddProcessName}.Msg", "");
 
                            ProcessRunBll processRunBll = GlobalVar.dicProcesses[AddProcessName];
                            ProcessPage ProcessPage = new ProcessPage(processRunBll.Name, processRunBll);
                            ProcessPage.LogInfo += LogInfo;
                            if (materialTabControl.InvokeRequired)
                            {
                                materialTabControl.Invoke(new Action(() =>
                                {
                                    materialTabControl.Controls.Add(new MyPage(ProcessPage));
                                }));
                            }
                            else
                                materialTabControl.Controls.Add(new MyPage(ProcessPage));
                        }
                        else
                            LogInfo($"流程[{AddProcessName}]加载失败,原因是{msg}", LogInfoType.ERROR);
 
                        LogInfo($"添加流程[{AddProcessName}]", LogInfoType.INFO);
                        break;
                    case DictionaryChangeType.Removed:
                        string RemoveProcessName = e.OldKey;
                        foreach (var control in materialTabControl.Controls)
                        {
                            if (control != null && control is MyPage && ((MyPage)control).UserControl is ProcessPage processPage)
                            {
                                if (processPage.Text == RemoveProcessName)
                                {
                                    IProcess.dicGlobalVars.TryRemove($"{RemoveProcessName}.Result", out _);
                                    IProcess.dicGlobalVars.TryRemove($"{RemoveProcessName}.Msg", out _);
                                    processPage.LogInfo -= LogInfo;
                                    removeMyPage.Add((MyPage)control);
                                }
                            }
                        }
 
                        foreach (var myPage in removeMyPage)
                        {
                            if (materialTabControl.InvokeRequired)
                            {
                                materialTabControl.Invoke(new Action(() =>
                                {
                                    materialTabControl.Controls.Remove(myPage);
                                }));
                            }
                            else
                                materialTabControl.Controls.Remove(myPage);
                        }
 
                        LogInfo($"移除流程[{RemoveProcessName}]", LogInfoType.INFO);
                        break;
                    case DictionaryChangeType.Renamed:
                        string OldProcessName = e.OldKey;
                        string NewProcessName = e.NewKey;
                        try
                        {
                            IProcess.dicGlobalVars.TryRemove($"{OldProcessName}.Result", out object obj1);
                            IProcess.dicGlobalVars.TryAdd($"{NewProcessName}.Result", obj1);
 
                            IProcess.dicGlobalVars.TryRemove($"{OldProcessName}.Msg", out object obj2);
                            IProcess.dicGlobalVars.TryAdd($"{NewProcessName}.Msg", obj2);
                        }
                        catch { }
 
                        LB_SmartVision.Tool.Tool.RenameDirectory(GlobalVar.allProcessPath + "\\" + OldProcessName
                            , GlobalVar.allProcessPath + "\\" + NewProcessName);
                        e.NewValue.Name = NewProcessName;
 
                        foreach (var control in materialTabControl.Controls)
                        {
                            if (control != null && control is MyPage && ((MyPage)control).UserControl is ProcessPage)
                            {
                                ProcessPage processPage = ((MyPage)control).UserControl as ProcessPage;
                                if (processPage.Text == OldProcessName)
                                {
                                    if (materialTabControl.InvokeRequired)
                                    {
                                        materialTabControl.Invoke(new Action(() =>
                                        {
                                            materialTabControl.Controls.Remove((MyPage)control);
                                        }));
                                    }
                                    else
                                        materialTabControl.Controls.Remove((MyPage)control);
 
 
                                    if (GlobalVar.dicProcesses[NewProcessName].Load(out msg))
                                    {
                                        LogInfo($"流程[{NewProcessName}]重命名后加载成功", LogInfoType.PASS);
 
                                        IProcess.dicGlobalVars.TryAdd($"{NewProcessName}.Result", false);
                                        IProcess.dicGlobalVars.TryAdd($"{NewProcessName}.Msg", "");
 
                                        ProcessRunBll processRunBll = GlobalVar.dicProcesses[NewProcessName];
                                        ProcessPage ProcessPage = new ProcessPage(processRunBll.Name, processRunBll);
                                        ProcessPage.LogInfo += LogInfo;
                                        if (materialTabControl.InvokeRequired)
                                        {
                                            materialTabControl.Invoke(new Action(() =>
                                            {
                                                materialTabControl.Controls.Add(new MyPage(ProcessPage));
                                            }));
                                        }
                                        else
                                            materialTabControl.Controls.Add(new MyPage(ProcessPage));
                                    }
                                    else
                                        LogInfo($"流程[{NewProcessName}]重命名后加载失败,原因是{msg}", LogInfoType.ERROR);
                                }
                            }
                        }
 
                        LogInfo(string.Format("重命名流程名[{0}]修改为[{1}]", OldProcessName, NewProcessName), LogInfoType.INFO);
                        break;
                }
            }
            catch { }
 
        }
 
        private void CommunicatorsChanged(object? sender, DictionaryChangedEventArgs<string, BaseCommunicator> e)
        {
 
        }
 
        private void LogInfo(string strLog, LogInfoType infoType)
        {
            if (string.IsNullOrEmpty(strLog))
            {
                return;
            }
            string strInfo = DateTime.Now.ToString("[yyyy:MM:dd:HH:mm:ss:fff] ");
            strInfo += strLog;
            if (infoType != LogInfoType.NOSHOW)
            {
                // 如果当前不是 UI 线程,则通过 Invoke 将操作调度到 UI 线程
                if (this.rich_Info.InvokeRequired)
                {
                    this.rich_Info.BeginInvoke(new Action<string>((msg) =>
                    {
                        if (this.rich_Info.Lines.Length > 1000)
                        {
                            this.rich_Info.Clear();
                        }
                        switch (infoType)
                        {
                            case LogInfoType.INFO:
                                {
                                    this.rich_Info.SelectionColor = Color.Wheat;
                                    AsyncLogHelper.Info(strLog);
                                    break;
                                }
                            case LogInfoType.WARN:
                                {
                                    this.rich_Info.SelectionColor = Color.Yellow;
                                    AsyncLogHelper.Warn(strLog);
                                    break;
                                }
                            case LogInfoType.PASS:
                                {
                                    this.rich_Info.SelectionColor = Color.Green;
                                    AsyncLogHelper.Info(strLog);
                                    break;
                                }
                            case LogInfoType.ERROR:
                                {
                                    this.rich_Info.SelectionColor = Color.Red;
                                    AsyncLogHelper.Error(strLog);
                                    break;
                                }
                        }
                        // 更新 UI 控件,比如显示接收到的消息
                        this.rich_Info.AppendText(strInfo);
                        this.rich_Info.AppendText("\r\n");
                        this.rich_Info.SelectionStart = this.rich_Info.Text.Length;
                        this.rich_Info.ScrollToCaret();
                    }), strInfo);
                }
                else
                {
 
                    if (this.rich_Info.Lines.Length > 1000)
                    {
                        this.rich_Info.Clear();
                    }
                    // 如果已经在 UI 线程上,直接更新 UI
                    switch (infoType)
                    {
                        case LogInfoType.INFO:
                            {
                                this.rich_Info.SelectionColor = Color.Wheat;
                                AsyncLogHelper.Info(strLog);
                                break;
                            }
                        case LogInfoType.WARN:
                            {
                                this.rich_Info.SelectionColor = Color.Yellow;
                                AsyncLogHelper.Warn(strLog);
                                break;
                            }
                        case LogInfoType.PASS:
                            {
                                this.rich_Info.SelectionColor = Color.Green;
                                AsyncLogHelper.Info(strLog);
                                break;
                            }
                        case LogInfoType.ERROR:
                            {
                                this.rich_Info.SelectionColor = Color.Red;
                                AsyncLogHelper.Error(strLog);
                                break;
                            }
                    }
                    this.rich_Info.AppendText(strInfo);
                    this.rich_Info.AppendText("\r\n");
                    this.rich_Info.SelectionStart = this.rich_Info.Text.Length;
                    this.rich_Info.ScrollToCaret();
                }
            }
        }
 
        public static bool SaveAllLayout()
        {
            try
            {
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.dicLayout, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allLayoutPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
                File.WriteAllText(GlobalVar.allLayoutPath, strJson, Encoding.UTF8);
                return true;
            }
            catch { return false; }
        }
 
        public static bool LoadAllCsv(string allCsvPath)
        {
            try
            {
                if (!File.Exists(allCsvPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allCsvPath);
                    SaveAllCsv();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allCsvPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                GlobalVar.dicCsvSetting.Clear();
                GlobalVar.dicCsvSetting = JsonConvert.DeserializeObject<ConcurrentDictionary<string, CsvSetting>>(strJson);
                if (GlobalVar.dicCsvSetting == null)
                {
                    GlobalVar.dicCsvSetting = new ConcurrentDictionary<string, CsvSetting>();
                    return false;
                }
                return true;
            }
            catch { return false; }
        }
 
        public static bool SaveAllCsv()
        {
            try
            {
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.dicCsvSetting, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allCsvPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
 
                File.WriteAllText(GlobalVar.allCsvPath, strJson, Encoding.UTF8);
 
                return true;
            }
            catch { return false; }
        }
 
        public bool LoadAllProcessSetting(string allProcessSettingStringPath)
        {
            try
            {
                if (!File.Exists(allProcessSettingStringPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allProcessSettingStringPath);
                    SaveAllProcessSetting();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allProcessSettingStringPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                GlobalVar.dicProcessSetting = JsonConvert.DeserializeObject<ConcurrentDictionary<int, ConcurrentDictionary<string, string>>>(strJson);
 
                if (GlobalVar.dicProcessSetting == null)
                    GlobalVar.dicProcessSetting = new ConcurrentDictionary<int, ConcurrentDictionary<string, string>>();
 
                try
                {
                    string json = File.ReadAllText(GlobalVar.allRunSettingStringPath);
                    var settings = new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto // 处理多态类型
                    };
 
                    GlobalVar.ControlStates = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings);
                }
                catch { }
 
                return true;
            }
            catch { return false; }
        }
 
        public static bool SaveAllProcessSetting()
        {
            try
            {
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.dicProcessSetting, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allProcessSettingStringPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
                File.WriteAllText(GlobalVar.allProcessSettingStringPath, strJson, Encoding.UTF8);
                //LogInfo($"流程设置保存成功", LogInfoType.INFO);
                return true;
            }
            catch { return false; }
        }
        private void EnsureDirectory(string path)
        {
            // 如果是相对路径,转换为绝对路径
            string fullPath = Path.IsPathRooted(path) ? path : Path.GetFullPath(path);
 
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
                LogInfo($"✅ 目录创建: {fullPath}", LogInfoType.INFO);
            }
            else
            {
                LogInfo($"ℹ️ 目录已存在: {fullPath}", LogInfoType.INFO);
            }
        }
 
        private void VisionForm_Load(object sender, EventArgs e)
        {
            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
            string[] paths = {
            @"生产日志\Run",
            @"生产日志\Debug",
            @"生产日志\Error",
            @"生产日志\Fatal",
            @"生产日志\Warn",
            };
            foreach (string path in paths)
            {
                EnsureDirectory(path);
            }
            if (!LB_SmartVision.Tool.Tool.ReadStringConfig("数据库名称", out string DateBaseName))
            {
                DateBaseName = "产品0";
                LB_SmartVision.Tool.Tool.WriteConfig("数据库名称", DateBaseName);
                LB_SmartVision.Tool.Tool.WriteConfig("产品列表", DateBaseName);
            }
            LB_SmartVision.Tool.Tool.ReadStringConfig("User ID", out string User_ID);
            LB_SmartVision.Tool.Tool.ReadStringConfig("Password", out string Password);
            GlobalVar.strProductName = DateBaseName;
            //加载通讯
            foreach (BaseCommunicator com in GlobalVar.dicCommunicators.Values)
            {
                com.Disconnect();
            }
            GlobalVar.dicCommunicators.Clear();
            if (LoadAllCommunicators(GlobalVar.allCommunicatorsConnectionStringPath))
            {
                LogInfo("通讯加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("通讯加载失败", LogInfoType.ERROR);
            }
            //加载相机
            foreach (BaseCamera camera in GlobalVar.dicCameras.Values)
            {
                camera.Dispose();
            }
            GlobalVar.dicCameras.Clear();
            if (LoadAllCameras(GlobalVar.allCamerasConnectionStringPath))
            {
                LogInfo("相机加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("相机加载失败", LogInfoType.ERROR);
            }
            //加载全局变量
            IProcess.dicGlobalVars.Clear();
            if (LoadAllProcessVars(GlobalVar.allProcessVarsPath))
            {
                LogInfo("全局变量加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("全局变量加载失败", LogInfoType.ERROR);
            }
 
            //加载流程
            GlobalVar.dicProcesses.Clear();
            if (LoadAllProcess(GlobalVar.allProcessConnectionStringPath))
            {
                LogInfo("流程加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("流程加载失败", LogInfoType.ERROR);
            }
            //加载触发设置
            if (LoadAllProcessSetting(GlobalVar.allProcessSettingStringPath))
            {
                LogInfo("流程设置加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("流程设置加载失败", LogInfoType.ERROR);
            }
 
            //加载流程布局
            GlobalVar.dicLayout.Clear();
            if (LoadAllLayout(GlobalVar.allLayoutPath))
            {
                LogInfo("流程布局加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("流程布局加载失败", LogInfoType.ERROR);
            }
 
            //加载流程表格
            GlobalVar.dicCsvSetting.Clear();
            if (LoadAllCsv(GlobalVar.allCsvPath))
            {
                LogInfo("流程表格加载成功", LogInfoType.PASS);
            }
            else
            {
                LogInfo("流程表格加载失败", LogInfoType.ERROR);
            }
 
            //显示所有产品
            com_ProductName.Items.Clear();
            LB_SmartVision.Tool.Tool.ReadStringConfig("产品列表", out string Products);
            List<string> lstProduct = (Products.Split(',')).ToList();
            foreach (string DatabaseName in lstProduct)
            {
                com_ProductName.Items.Add(DatabaseName);
            }
            com_ProductName.Items.Add("新增");
            com_ProductName.Text = GlobalVar.strProductName;
            this.WindowState = FormWindowState.Maximized;
        }
 
        public void SaveAllSetting()
        {
            SaveAllProcess();
            SaveAllProcessVars();
            SaveAllCommunicators();
            SaveAllCameras();
            SaveAllProcessSetting();
            SaveAllLayout();
            SaveAllCsv();
        }
 
        public bool LoadAllCameras(string allCamerasConnectionStringPath)
        {
            if (!File.Exists(allCamerasConnectionStringPath))
            {
                Debug.WriteLine("文件不存在创建空文件");
                // 获取不带文件名的目录路径
                string directoryPath = Path.GetDirectoryName(allCamerasConnectionStringPath);
                SaveAllCameras();
                return true;
            }
            string strJson = string.Empty;
            using (StreamReader streamReader = new StreamReader(allCamerasConnectionStringPath, Encoding.UTF8))
            {
                strJson = streamReader.ReadToEnd();
                streamReader.Close();
            }
            GlobalVar.allCamerasConnectionString = JsonConvert.DeserializeObject<ConcurrentDictionary<string, string>>(strJson);
            if (GlobalVar.allCamerasConnectionString == null)
            {
                MessageBox.Show("相机加载失败!", "异常");
                return false;
            }
            BaseCamera camera = null;
            foreach (var CameraConnectionString in GlobalVar.allCamerasConnectionString)
            {
                Enum.TryParse<CameraBrand>(CameraConnectionString.Value, out CameraBrand brand);
                switch (brand)
                {
                    case CameraBrand.HRCamera:
                        {
                            camera = new HRCamera();
                            break;
                        }
                    case CameraBrand.LBCamera:
                        {
                            //camera = new LBCamera();
                            break;
                        }
                    default:
                        {
                            MessageBox.Show($"[{CameraConnectionString.Key}]品牌不支持!", "异常");
                            continue;
                        }
                }
                camera.SN = CameraConnectionString.Key;
                if (!camera.InitDevice(CameraConnectionString.Key, this.Handle))
                {
                    LogInfo($"初始化相机[{CameraConnectionString.Key}]失败", LogInfoType.ERROR);
                    if (camera != null)
                        camera.isGrabbing = false;
                }
 
                GlobalVar.dicCameras.TryAdd(CameraConnectionString.Key, camera);
            }
 
            return true;
        }
 
        public bool SaveAllCameras()
        {
            try
            {
                string strJson = string.Empty;
                GlobalVar.allCamerasConnectionString = new ConcurrentDictionary<string, string>();
 
                foreach (var item in GlobalVar.dicCameras)
                {
                    string CameraSN = item.Value.SN;// "TCP"
                    string CameraBrand = item.Value.Brand.ToString();//"1111"
 
                    if (string.IsNullOrEmpty(CameraSN) || string.IsNullOrEmpty(CameraBrand))
                    {
                        break;
                    }
                    GlobalVar.allCamerasConnectionString.TryAdd(CameraSN, CameraBrand);
                }
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.allCamerasConnectionString, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allCamerasConnectionStringPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch (Exception)
                    { }
                }
                File.WriteAllText(GlobalVar.allCamerasConnectionStringPath, strJson, Encoding.UTF8);
                return true;
            }
            catch { return false; }
        }
 
 
        public bool LoadAllCommunicators(string allCommunicatorsConnectionStringPath)
        {
            try
            {
                if (!File.Exists(allCommunicatorsConnectionStringPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allCommunicatorsConnectionStringPath);
                    SaveAllCommunicators();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allCommunicatorsConnectionStringPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                GlobalVar.allCommunicatorsConnectionString = JsonConvert.DeserializeObject<ConcurrentDictionary<string, string>>(strJson);
                if (GlobalVar.allCommunicatorsConnectionString == null)
                {
                    MessageBox.Show("通讯端口加载失败!", "异常");
                    return false;
                }
 
                //清空通讯口会把所有通讯口断开连接
                GlobalVar.dicCommunicators.Clear();
                ConcurrentDictionary<string, string> clientsCommunicatorsConnectionString = new ConcurrentDictionary<string, string>();
                foreach (var CommunicatorConnectionString in GlobalVar.allCommunicatorsConnectionString)
                {
                    string CommunicatorName = CommunicatorConnectionString.Key;
                    string CommunicatorAddress = CommunicatorConnectionString.Value;
 
                    // 定义正则表达式以提取协议、IP 地址和端口
                    //1.    \((.*?)\):\(和 \) 是用于匹配括号的转义字符。
                    //      (.*?) 是一个非贪婪的匹配,用来匹配类名(MyProcesses.Communicators.TCPServer 或 MyProcesses.Communicators.UARTPort)。
                    //2.    ([^:] +):匹配冒号之前的部分,即地址(127.0.0.1 或 COM5)。这里使用了[^:] 来匹配除了冒号之外的任意字符。
                    //3.    (\d +) :匹配端口号,确保它匹配一个或多个数字。
 
                    string pattern = @"^\((?<ClassName>[^)]+)\)\[(?<IP>[^]]+)\]\[(?<PORT>[^]]+)\]$";
                    Match match = Regex.Match(CommunicatorAddress, pattern);
 
                    if (match.Success)
                    {
                        string ClassName = match.Groups["ClassName"].Value;   // "TCP"
                        string IP = match.Groups["IP"].Value;          // "127.0.0.1"
                        string PORT = match.Groups["PORT"].Value;        // "1111"
 
                        if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
                            break;
 
                        //利用反射创建实例
                        Type type = IProcess.GetExecutingAssembly().GetType(ClassName);
                        if (type == null)
                        {
                            Debug.WriteLine("Class not found.");
                            return false;
                        }
                        var Communicator = Activator.CreateInstance(type, CommunicatorName) as BaseCommunicator;
 
                        if (Communicator == null)
                        {
                            Debug.WriteLine("BaseCommunicator not found.");
                            return false;
                        }
 
                        //TCP客户端最后再连接
                        if (Communicator is TCPClient)
                        {
                            clientsCommunicatorsConnectionString.TryAdd(CommunicatorConnectionString.Key, CommunicatorConnectionString.Value);
                            continue;
                        }
 
                        Communicator.CommunicatorConnections.Add("地址", IP);
                        Communicator.CommunicatorConnections.Add("端口", PORT);
                        Communicator.CommunicatorName = CommunicatorName;
                        if (!Communicator.Connect())
                        {
                            LogInfo($"初始化通讯口[{CommunicatorName}]失败,原因是{Communicator.Msg}", LogInfoType.ERROR);
                        }
                        else
                        {
                            LogInfo($"初始化通讯口[{CommunicatorName}]成功", LogInfoType.PASS);
                        }
                        GlobalVar.dicCommunicators.TryAdd(CommunicatorName, Communicator);
                    }
                    else
                    {
                        Debug.WriteLine("No match found.");
                    }
 
                }
 
                //TCP客户端最后连接
                foreach (var CommunicatorConnectionString in clientsCommunicatorsConnectionString)
                {
                    string CommunicatorName = CommunicatorConnectionString.Key;
                    string CommunicatorAddress = CommunicatorConnectionString.Value;
 
                    // 定义正则表达式以提取协议、IP 地址和端口
                    //1.    \((.*?)\):\(和 \) 是用于匹配括号的转义字符。
                    //      (.*?) 是一个非贪婪的匹配,用来匹配类名(MyProcesses.Communicators.TCPServer 或 MyProcesses.Communicators.UARTPort)。
                    //2.    ([^:] +):匹配冒号之前的部分,即地址(127.0.0.1 或 COM5)。这里使用了[^:] 来匹配除了冒号之外的任意字符。
                    //3.    (\d +) :匹配端口号,确保它匹配一个或多个数字。
 
                    var regex = new Regex(@"^\((?<ClassName>[^)]+)\)\[(?<IP>[^]]+)\]\[(?<PORT>[^]]+)\]$");
                    var match = regex.Match(CommunicatorAddress);
 
                    if (match.Success)
                    {
                        string ClassName = match.Groups[1].Value;   // "TCP"
                        string IP = match.Groups[2].Value;          // "127.0.0.1"
                        string PORT = match.Groups[3].Value;        // "1111"
 
                        if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
                        {
                            break;
                        }
 
                        //利用反射创建实例
                        Type type = IProcess.GetExecutingAssembly().GetType(ClassName);
                        if (type == null)
                        {
                            Debug.WriteLine("Class not found.");
                            return false;
                        }
                        var Communicator = Activator.CreateInstance(type, CommunicatorName) as BaseCommunicator;
 
                        if (Communicator == null)
                        {
                            Debug.WriteLine("BaseCommunicator not found.");
                            return false;
                        }
 
                        Communicator.CommunicatorConnections.Add("地址", IP);
                        Communicator.CommunicatorConnections.Add("端口", PORT);
                        Communicator.CommunicatorName = CommunicatorName;
                        if (!Communicator.Connect())
                        {
                            LogInfo($"初始化通讯口[{CommunicatorName}]失败,原因是{Communicator.Msg}", LogInfoType.ERROR);
                        }
                        else
                        {
                            LogInfo($"初始化通讯口[{CommunicatorName}]成功", LogInfoType.PASS);
                        }
                        GlobalVar.dicCommunicators.TryAdd(CommunicatorName, Communicator);
                    }
                    else
                    {
                        Debug.WriteLine("No match found.");
                    }
 
                }
 
                return true;
            }
            catch { return false; }
        }
 
        public bool SaveAllCommunicators()
        {
            try
            {
                string strJson = string.Empty;
                GlobalVar.allCommunicatorsConnectionString = new ConcurrentDictionary<string, string>();
 
                foreach (var item in GlobalVar.dicCommunicators)
                {
                    string ClassName = item.Value.GetType().FullName;// "TCP"
                    string IP = item.Value.CommunicatorConnections["地址"].ToString();//"127.0.0.1"
                    string PORT = item.Value.CommunicatorConnections["端口"].ToString();//"1111"
 
                    if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
                    {
                        break;
                    }
                    string CommunicatorConnectionString = $"({ClassName})[{IP}][{PORT}]";
                    GlobalVar.allCommunicatorsConnectionString.TryAdd(item.Key, CommunicatorConnectionString);
                }
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.allCommunicatorsConnectionString, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allCommunicatorsConnectionStringPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch (Exception)
                    { }
                }
                File.WriteAllText(GlobalVar.allCommunicatorsConnectionStringPath, strJson, Encoding.UTF8);
                return true;
            }
            catch { return false; }
        }
 
        public bool LoadAllProcess(string allProcessConnectionStringPath)
        {
            try
            {
                if (!File.Exists(allProcessConnectionStringPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allProcessConnectionStringPath);
                    SaveAllProcess();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allProcessConnectionStringPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                List<string> lstProcessName = JsonConvert.DeserializeObject<List<string>>(strJson);
 
                if (lstProcessName == null)
                {
                    return false;
                }
                // 使用方式
                var sortedKeys = lstProcessName
                    .OrderBy(k => k, new NaturalStringComparer())
                    .ToList();
                GlobalVar.dicProcesses.Clear();
                foreach (var ProcessName in sortedKeys)
                {
                    GlobalVar.dicProcesses.TryAdd(ProcessName
                        , new ProcessRunBll(ProcessName, GlobalVar.dicCameras, GlobalVar.dicCommunicators));
                }
                return true;
            }
            catch { return false; }
        }
 
        public bool SaveAllProcess()
        {
            try
            {
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(GlobalVar.dicProcesses.Keys.ToList(), settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allProcessConnectionStringPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
                File.WriteAllText(GlobalVar.allProcessConnectionStringPath, strJson, Encoding.UTF8);
 
                foreach (var process in GlobalVar.dicProcesses.Values)
                {
                    if (!process.Save(out string msg))
                    {
                        LogInfo($"流程[{process.Name}]保存失败,原因:{msg}", LogInfoType.NOSHOW);
                    }
                }
 
                try
                {
                    string json = JsonConvert.SerializeObject(GlobalVar.ControlStates, settings);
                    File.WriteAllText(GlobalVar.allRunSettingStringPath, json);
                    LogInfo($"流程运行设置保存成功", LogInfoType.INFO);
                }
                catch { }
 
 
                return true;
            }
            catch { return false; }
        }
 
        public bool LoadAllProcessVars(string allProcessVarsPath)
        {
            try
            {
                if (!File.Exists(allProcessVarsPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allProcessVarsPath);
                    SaveAllProcessVars();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allProcessVarsPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                IProcess.dicGlobalVars.Clear();
                IProcess.dicGlobalVars = JsonConvert.DeserializeObject<ConcurrentDictionary<string, object>>(strJson);
                if (IProcess.dicGlobalVars == null)
                {
                    IProcess.dicGlobalVars = new ConcurrentDictionary<string, object>();
                    return false;
                }
 
                return true;
            }
            catch { return false; }
        }
 
        public bool SaveAllProcessVars()
        {
            try
            {
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
 
                strJson = JsonConvert.SerializeObject(IProcess.dicGlobalVars, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                string directoryPath = Path.GetDirectoryName(GlobalVar.allProcessVarsPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
 
                File.WriteAllText(GlobalVar.allProcessVarsPath, strJson, Encoding.UTF8);
                LogInfo($"全局变量保存成功", LogInfoType.INFO);
 
                strJson = JsonConvert.SerializeObject(GlobalVar.dicLayout, settings);
                //判断文件夹是否存在,防呆输入为文件名称
                directoryPath = Path.GetDirectoryName(GlobalVar.allLayoutPath);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch { }
                }
 
                File.WriteAllText(GlobalVar.allLayoutPath, strJson, Encoding.UTF8);
                LogInfo($"全局布局保存成功", LogInfoType.INFO);
                return true;
            }
            catch { return false; }
        }
 
        public bool LoadAllLayout(string allLayoutPath)
        {
            try
            {
                if (!File.Exists(allLayoutPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    AsyncLogHelper.Info("文件不存在创建空文件");
                    // 获取不带文件名的目录路径
                    string directoryPath = Path.GetDirectoryName(allLayoutPath);
                    SaveAllLayout();
                    return true;
                }
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(allLayoutPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
 
                GlobalVar.dicLayout.Clear();
                GlobalVar.dicLayout = JsonConvert.DeserializeObject<ConcurrentDictionary<int, Forms.Pages.SettingPage.Layout>>(strJson);
                if (GlobalVar.dicLayout == null)
                {
                    GlobalVar.dicLayout = new ConcurrentDictionary<int, Forms.Pages.SettingPage.Layout>();
                    return false;
                }
                return true;
            }
            catch { return false; }
        }
 
        private void btn_GlobalVar_Click(object sender, EventArgs e)
        {
            GlobalVarForm globalVarForm = new GlobalVarForm(GlobalVar.allProcessVarsPath);
            globalVarForm.ShowDialog();
        }
 
        private void btn_Login_Click(object sender, EventArgs e)
        {
            //this.Hide();
            //MainWindow.InstanceLoginandConfirmation().ShowDialog();
            //if (!MainWindow.InstanceLoginandConfirmation().isQuit && MainWindow.InstanceLoginandConfirmation().correctUser)
            //{
            //    MainWindow.InstanceLoginandConfirmation().closeLoginFrm();
            //    if (UserManager.Instance.CurrentUser.EmployeePermission == UserPermission.Operator)
            //    {
            //        //操作员权限界面
            //    }
            //    else if (UserManager.Instance.CurrentUser.EmployeePermission == UserPermission.Engineer)
            //    {
            //        //技术员权限界面
            //    }
            //    else if (UserManager.Instance.CurrentUser.EmployeePermission == UserPermission.Administrator)
            //    {
            //        //管理员权限界面
            //    }
            //    this.Show();
            //}
        }
 
        private void com_ProductName_SelectedValueChanged(object sender, EventArgs e)
        {
            if (com_ProductName.SelectedItem == null || com_ProductName.SelectedItem?.ToString() == GlobalVar.strProductName)
            {
                return;
            }
            if (com_ProductName.SelectedItem?.ToString() == "新增")
            {
                using (CreateProductForm createDatabaseForm = new CreateProductForm())
                {
                    createDatabaseForm.ShowDialog();
                }
            }
            else
            {
                //变更前保存现有配置
                SaveAllSetting();
                LogInfo($"产品从{GlobalVar.strProductName}切换{com_ProductName.SelectedItem?.ToString()}", LogInfoType.WARN);
                //Tool.WriteConfig("数据库名称", com_ProductName.SelectedItem?.ToString());
                GlobalVar.strProductName = com_ProductName.SelectedItem?.ToString();
                foreach (BaseCamera camera in GlobalVar.dicCameras.Values)
                {
                    camera.Dispose();
                }
                GlobalVar.dicCameras.Clear();
                foreach (BaseCommunicator communicator in GlobalVar.dicCommunicators.Values)
                {
                    communicator.TriggerRunMessageReceived -= TriggerRunMessageReceived;
                    communicator.Disconnect();
                }
                GlobalVar.dicCommunicators.Clear();
                //保存完现有配置后断开所有事件
                foreach (var Process in GlobalVar.dicProcesses.Values)
                {
                    Process.LogInfo -= LogInfo;
                }
                GlobalVar.dicProcesses.Clear();
                //重新加载配置
                this.VisionForm_Load(sender, e);
            }
        }
        private void TriggerRunMessageReceived(string name, string msg)
        {
            if (msg == null || msg.Trim('\0', '\r', '\n', ' ', '\uFEFF') == "" || string.IsNullOrEmpty(msg))
            {
                return;
            }
            LogInfo(string.Format("通讯[{0}]接收到的消息\"{1}\"", name, msg), LogInfoType.INFO);
            var matchedItems = GlobalVar.dicProcessSetting
                .Where(item =>
                {
                    var value = item.Value;
                    var triggerComm = value["触发通讯"];
                    var triggerChar = value["触发字符"];
 
                    return triggerComm != null && triggerComm.Equals(name) &&
                           (string.IsNullOrEmpty(triggerChar?.ToString()) ||
                            msg.StartsWith(triggerChar.ToString()));
                })
                .ToList(); // 避免重复字典访问和装箱操作
            if (matchedItems.Count <= 0)
            {
                return;
            }
            if (!ckb_AllowRun.Checked)
            {
                LogInfo(string.Format($"检查到可被触发的流程,当前不为运行模式!"), LogInfoType.ERROR);
                return;
            }
            GlobalVar.dicProcesses.Values.AsParallel().ForAll(v => v.bCompleted = false);
            LogInfo(string.Format($"检查到可被触发的流程,清空所有流程运行完成标记位!"), LogInfoType.INFO);
            Parallel.ForEach(matchedItems, item =>
            {
                string ProcessName = item.Value["流程名"];
                LogInfo($"流程[{ProcessName}]开始运行", LogInfoType.INFO);
                if (!GlobalVar.dicProcesses.ContainsKey(ProcessName))
                {
                    LogInfo(string.Format("流程[{0}]不存在,请检查流程设置", ProcessName), LogInfoType.ERROR);
                    return;
                }
                ProcessRunBll RunBll = GlobalVar.dicProcesses[ProcessName];
                if (RunBll == null || RunBll.bRuning)
                {
                    LogInfo(string.Format("流程[{0}]上次未运行完成,触发失败", ProcessName)
                        , LogInfoType.ERROR);
                    return;
                }
                try
                {
                    bool result = false;
                    string msg = string.Empty;
                    int times = Convert.ToInt32(item.Value["重测次数"].ToString());
                    string ConnecResult = item.Value["关联结果"];
                    if (times < 0)
                    {
                        result = GlobalVar.dicProcesses[ProcessName].Run();
                        msg = GlobalVar.dicProcesses[ProcessName].Msg;
                        if (!(string.IsNullOrEmpty(ConnecResult) || ConnecResult.Trim() == "未关联"))
                        {
                            GlobalVar.dicProcesses[ProcessName].GetBooleanOutput(ConnecResult, out result);
                            GlobalVar.dicProcesses[ProcessName].Result = result;
                        }
                        if (!result)
                        {
                            LogInfo($"流程[{ProcessName}]被强制运行成功", LogInfoType.WARN);
                            GlobalVar.dicProcesses[ProcessName].Result = true;
                            result = true;
                        }
                    }
                    else
                    {
                        while (times >= 0)
                        {
                            result = RunBll.Run();
                            msg = RunBll.Msg;
                            if (!(string.IsNullOrEmpty(ConnecResult) || ConnecResult.Trim() == "未关联"))
                            {
                                RunBll.GetBooleanOutput(ConnecResult, out result);
                                RunBll.Result = result;
                            }
                            if (result)
                            {
                                break;
                            }
                            else if (!result && times > 0)
                            {
                                LogInfo(string.Format("流程[{0}]运行失败重新测试,剩余次数[{1}]", ProcessName, times), LogInfoType.WARN);
                            }
                            times--;
                        }
                    }
                    string ConnectProcess = item.Value["关联流程"];
                    if (!(ConnectProcess == null || string.IsNullOrEmpty(ConnectProcess) || ConnectProcess.Trim() == ""))
                    {
                        //用逗号或者分号去间隔关联流程
                        string[] arrConnectProcess;
                        if (ConnectProcess.Split(';').Length >= ConnectProcess.Split(',').Length)
                        {
                            arrConnectProcess = ConnectProcess.Split(';');
                        }
                        else
                        {
                            arrConnectProcess = ConnectProcess.Split(',');
                        }
                        foreach (string strConnectProcess in arrConnectProcess)
                        {
                            if (GlobalVar.dicProcesses.ContainsKey(strConnectProcess))
                            {
                                ProcessRunBll ConnectRunBll = GlobalVar.dicProcesses[strConnectProcess];
                                int waitTime = 10;
                                DateTime startTime = DateTime.Now;
                                while ((DateTime.Now - startTime).TotalSeconds < waitTime
                                && (ConnectRunBll.bRuning || !ConnectRunBll.bCompleted))
                                {
                                    LogInfo(string.Format("关联流程[{0}]未运行完成,剩余等待[{1}]s", strConnectProcess, (waitTime - ((DateTime.Now - startTime).TotalSeconds)))
                                        , LogInfoType.NOSHOW);
                                    Thread.Sleep(1000);
                                    continue;
                                }
                                if (ConnectRunBll.bRuning || !ConnectRunBll.bCompleted)
                                {
                                    GlobalVar.dicProcesses[ProcessName].Msg = string.Format("流程[{0}]未运行完成", ProcessName);
                                    LogInfo(string.Format("关联流程[{0}]未运行完成", strConnectProcess), LogInfoType.ERROR);
                                    result = false;
                                    break;
                                }
                                else if (!ConnectRunBll.bRuning && ConnectRunBll.bCompleted)
                                {
                                    LogInfo(string.Format("关联流程[{0}]运行完成", strConnectProcess), LogInfoType.INFO);
                                }
                                result &= ConnectRunBll.Result;
                                if (!ConnectRunBll.Result)
                                {
                                    LogInfo($"流程[{ProcessName}]的关联流程[{strConnectProcess}]运行失败", LogInfoType.ERROR);
                                    msg = $"关联流程[{strConnectProcess}]运行失败";
                                }
                            }
                        }
                    }
                    LogInfo(result ? $"流程[{ProcessName}]运行成功" : $"流程[{ProcessName}]运行失败,原因是{msg}", result ? LogInfoType.PASS : LogInfoType.ERROR);
                    string SendComName = result ? item.Value["成功通讯"] : item.Value["失败通讯"];
                    string SendMsg = result ? item.Value["成功字符"] : item.Value["失败字符"];
                    if (GlobalVar.dicCommunicators.ContainsKey(SendComName) && (!string.IsNullOrEmpty(SendMsg) || SendMsg.Trim() != ""))
                    {
                        GlobalVar.dicCommunicators[SendComName].SendMessage(SendMsg);
                        LogInfo(string.Format("发送给[{0}]了消息\"{1}\"", SendComName, SendMsg), LogInfoType.INFO);
                    }
                }
                catch (Exception ex)
                {
                    LogInfo(string.Format("流程[{0}]运行发生了意外,原因是:{1}", ProcessName, ex.Message + $"【{ex.StackTrace}】"), LogInfoType.ERROR);
                    RunBll.Result = false;
                    RunBll.Msg = $"[意外]{ex.Message}";
                }
                finally
                {
                    #region 从RunSettingPage和Layout中获取是否保存图片
                    string strImageType = "jpeg";
                    bool bSaveRunImage = false;
                    bool bSaveResultImage = false;
                    long lImageQuality = 100L;
                    //ckbSaveRunImage
                    if (GlobalVar.ControlStates.TryGetValue("ckbSaveRunImage_CheckBox", out object oSaveRunImage))
                    {
                        if (oSaveRunImage != null && oSaveRunImage is bool)
                        {
                            bSaveRunImage = (bool)oSaveRunImage;
                        }
                    }
                    //ckbSaveResultImage
                    if (GlobalVar.ControlStates.TryGetValue("ckbSaveResultImage_CheckBox", out object oSaveResultImage))
                    {
                        if (oSaveResultImage != null && oSaveResultImage is bool)
                        {
                            bSaveResultImage = (bool)oSaveResultImage;
                        }
                    }
                    //txtImageQuality
                    if (GlobalVar.ControlStates.TryGetValue("txtImageQuality_TextBox", out object oImageQuality))
                    {
                        if (oImageQuality != null && oImageQuality is string)
                        {
                            lImageQuality = Convert.ToInt64((string)oImageQuality);
                        }
                    }
                    //cmbImageType
                    if (GlobalVar.ControlStates.TryGetValue("cmbImageType_ComboBox", out object oImageType))
                    {
                        try
                        {
                            // 动态解析ComboBox数据
                            var json = JsonConvert.SerializeObject(oImageType);
                            var comboData = JsonConvert.DeserializeAnonymousType(json, new
                            {
                                Items = new List<object>(),
                                SelectedIndex = 0
                            });
 
                            if (comboData != null && comboData.Items.Count > 0)
                            {
                                strImageType = comboData.Items[comboData.SelectedIndex].ToString();
                            }
                        }
                        catch { }
                    }
                    // 生成图片并显示到控件中
                    HImage InputImage = null;
                    HImage RecordImage = null;
 
                    foreach (var layout in GlobalVar.dicLayout.Values
                                .Where(layout => layout.ProcessName == ProcessName)
                                .ToList())
                    {
                        string title = layout.Title;
                        string strImagePath = layout.SaveImageDir;
                        if (!AllProcessesPages.dicProcessControls.ContainsKey(title))
                        {
                            continue;
                        }
                        RunBll.GetImage(layout, out InputImage, out RecordImage);
                        AllProcessesPages.dicProcessControls[title].ShowHoImage(RecordImage);
                        if (!string.IsNullOrEmpty(layout.SaveImageDir))
                        {
                            string fileNameHead = layout.SaveImageHead;
                            string result = Regex.Replace(fileNameHead, @"\{[^}]+\}", match =>
                            {
                                // 去除{}只保留括号内的内容
                                string content = match.Value;
                                content = content.Trim('{', '}'); // 去除首尾的{}
 
                                RunBll.GetStringOutput(content, out string str);
                                return str;
                            });
                            string fileName = $"{result}-[{DateTime.Now.ToString("HH.mm.ss.ffff")}]";
                            // 使用正则表达式替换所有非法字符
                            string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
                            string pattern = $"[{invalidChars}]";
                            fileName = Regex.Replace(fileName, pattern, "-");
                            strImagePath = Regex.Replace(strImagePath, @"\{[^}]+\}", match =>
                            {
                                // 去除{}只保留括号内的内容
                                string content = match.Value;
                                content = content.Trim('{', '}'); // 去除首尾的{}
                                RunBll.GetStringOutput(content, out string str);
                                return str;
                            });
                            if (bSaveRunImage)
                            {
                                // 最后一级目录必须为年月日,会根据时间来删除旧图片
                                string directoryPath = Path.Combine(strImagePath, $"{ProcessName}\\原图\\{RunBll.Result}\\{DateTime.Now.ToString("yyyyMMdd")}\\");
                                LB_SmartVision.Tool.Tool.AddRealImage(InputImage, directoryPath, fileName, strImageType, lImageQuality);
                            }
                            if (bSaveResultImage)
                            {
                                // 最后一级目录必须为年月日,会根据时间来删除旧图片
                                string directoryPath = Path.Combine(strImagePath, $"{ProcessName}\\截图\\{RunBll.Result}\\{DateTime.Now.ToString("yyyyMMdd")}\\");
                                LB_SmartVision.Tool.Tool.AddRealImage(RecordImage, directoryPath, fileName, "jpg", 50L);
                            }
                        }
                    }
                    foreach (var csv in GlobalVar.dicCsvSetting.Values
                                .Where(csv => csv.ProcessName == ProcessName)
                                .ToList())
                    {
                        if (RunBll.GetCsv(csv
                            , out List<string> DataTitle, out Dictionary<string, object> ResultData))
                        {
                            string filePath = Path.Combine(GlobalVar.strPathCsv, $"{ProcessName}.csv");
                            LB_SmartVision.Tool.Tool.SaveData(filePath, DataTitle, ResultData);
                        }
                    }
                    #endregion
                }
            });
        }
 
        private void VisionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveAllSetting();
            if (MessageBox.Show("是否关闭软件?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)//
            {
                e.Cancel = true;
                return;
            }
            //关闭窗体释放资源
            AsyncLogHelper.Dispose();
            foreach (BaseCamera camera in GlobalVar.dicCameras.Values)
            {
                camera.Dispose();
            }
            foreach (BaseCommunicator communicator in GlobalVar.dicCommunicators.Values)
            {
                communicator.Disconnect();
            }
            FormClosing -= VisionForm_FormClosing;
        }
    }
}