quanzhou
2025-08-27 69ee76c13978285f07e183e013bd601cb72afc92
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
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.Device.InsCamera;
using Bro.M135.Common;
using Bro.M135.DBManager;
using Bro.M141.Process.UI;
using Bro.Process;
using Bro.Process.DataBase.Models;
using Bro.UI.Model.Winform;
using HalconDotNet;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Function;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Ocsp;
using ScottPlot.Drawing.Colormaps;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using Windows.ApplicationModel.Appointments;
using ZXing;
using static Bro.Common.Helper.EnumHelper;
using static Bro.Process.ProcessControl;
using static Org.BouncyCastle.Math.EC.ECCurve;
 
namespace Bro.M141.Process
{
    public partial class M141Process : ProcessControl
    {
        #region constructor
        public M141Process() { }
 
        public M141Process(string productCode) : base(productCode) { }
        #endregion
 
        TaskFactory _taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
 
        public event Action<string, P_PRODUCT_DETAIL, string> OnSinglePostionDetectResultUpdate;
 
        protected M141Config M141Config => Config as M141Config;
 
        public static object _productListLock = new object();
        public List<ProductModel> ProductList = new List<ProductModel>();
        MachineLearningBase ML = null;
        Spec _errorSpec = null;
 
        //volatile int _productIndex = 0;
 
        public M141Process_Mysql mysqlhelper = new M141Process_Mysql();
 
        public event Action RerefreshBasketcodeUI;
 
        public Action<bool, string> OnContinuousNGAlarmRaised;
 
        public void RerefreshBasketcode()
        {
            RerefreshBasketcodeUI?.Invoke();
        }
 
 
 
        public override void InitialProcessMethods()
        {
            base.InitialProcessMethods();
 
            if (ThHeartPlc == null)
            {
                ThHeartPlc = new Thread(Heartplc);
                ThHeartPlc.IsBackground = true;
                ThHeartPlc.Start();
            }
        }
 
        public override void ProcessRunStateChanged()
        {
            base.ProcessRunStateChanged();
            //if (CurrentState == EnumHelper.RunState.Running)
            //{
            //    OldDataClear.Instance.SetAllowFlag(false, M141Config.DBDataTimeLimit);
            //}
            //else
            //{
            //    OldDataClear.Instance.SetAllowFlag(true, M141Config.DBDataTimeLimit);
            //}
        }
 
        public PLCBase Plc1;
        bool devicestate = false;
        PLCBase Plc2;
        public Thread ThHeartPlc;
 
        public RabbitMQHelper mqtt;
 
 
 
        public override void Open()
        {
            base.Open();
 
            devicestate = true;
            ML = DeviceCollection.FirstOrDefault(u => u is MachineLearningBase) as MachineLearningBase;
            if (ML == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"未设置ML实例");
            }
            Plc1 = DeviceCollection.FirstOrDefault(u => u is PLCBase) as PLCBase;
 
            if (Plc1 == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"未设置plc");
            }
            _errorSpec = M141Config.SpecCollection.FirstOrDefault(u => u.Code == M141Config.CheckErrorSpecCode) as Spec;
 
            //InitialProductList();
 
            NetWarmUp();
 
            _positionCheckTimeDict.Clear();
            _positionSpecHeads.Clear();
 
            mysqlhelper.IniDBIP(M141Config.IPforall);
            RerefreshBasketcode();
 
 
            if (M141Config.ISupMES)
            {
                mqtt = new RabbitMQHelper(M141Config.zIP, M141Config.zport, M141Config.zuser, M141Config.zpassword);
                mqtt.Connect(M141Config.MESchannel);
            }
 
            InitialContinuousNGAlarm();
        }
 
 
        public override void Close()
        {
            devicestate = false;
            base.Close();
 
        }
 
 
        public void Heartplc()
        {
            Thread.Sleep(1000);
 
            //Open();
 
            string _statisticFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Statistic.json");
            if (File.Exists(_statisticFilePath))
            {
                try
                {
                    string dataStr = "";
                    using (StreamReader reader = new StreamReader(_statisticFilePath, System.Text.Encoding.UTF8))
                    {
                        dataStr = reader.ReadToEnd();
                    }
 
                    lock (StatisticRecordsFull)
                    {
                        var temRecords = JsonConvert.DeserializeObject<StatisticRecords_Full>(dataStr);
                        if (StatisticRecordsFull != null && temRecords != null)
                        {
                            StatisticRecordsFull.CurRecord = temRecords.CurRecord;
                            StatisticRecordsFull.HistoryRecord = temRecords.HistoryRecord;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"产品统计信息反序列化异常");
                    StatisticRecordsFull = new StatisticRecords_Full();
                }
            }
 
            int numsum = 0;
            //List<int> Statelist = new List<int>();
 
 
            Dictionary<string, List<int>> StateDIC = new Dictionary<string, List<int>>();
            List<string> AlarmTypeList = new List<string>();
 
            int numplc = 0;
            while (true)
            {
                numplc++;
                numsum++;
 
 
                if (!devicestate)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                try
                {
                    if (M141Config.WorkShiftList != null && M141Config.WorkShiftList.Count > 0 && numsum >= 0)
                    {
                        for (int i = 0; i < M141Config.WorkShiftList.Count; i++)
                        {
                            if (M141Config.WorkShiftList[i].IsClearProductSummary)
                            {
                                double timeshap = (DateTime.Now - M141Config.WorkShiftList[i].ShiftTime_Start).TotalMinutes % 1440;
 
                                if (timeshap > 0 && timeshap < 1)
                                {
                                    StatisticRecordsFull.CurRecord.ProductSummary.RecordsList.Clear();
                                    StatisticRecordsFull.CurRecord.DefectSummary.RecordsList.Clear();
                                    numsum = -62;
                                }
                            }
                        }
                    }
                    if (numsum > 20)
                    {
                        numsum = 0;
                        StatisticRecordsFull.SaveSummaryRecord();
                    }
                    //lock (StatisticRecordsFull)
                    //{
                    //    if (numsum > 20)
                    //    {
                    //        numsum = 0;
 
 
                        //        using (FileStream fileStream = new FileStream(_statisticFilePath, FileMode.OpenOrCreate, FileAccess.Write))
                        //        {
                        //            fileStream.Seek(0L, SeekOrigin.Begin);
                        //            string s = JsonConvert.SerializeObject(StatisticRecordsFull);
                        //            byte[] bytes = Encoding.UTF8.GetBytes(s);
                        //            fileStream.Write(bytes, 0, bytes.Length);
                        //            fileStream.SetLength(bytes.Length);
                        //            fileStream.Flush();
                        //            fileStream.Close();
                        //        }
                        //    }
                        //}
                }
                catch (Exception ex)
                {
 
                }
 
 
                try
                {
                    if (numplc > 3)
                    {
                        numplc = 0;
                        if (Plc1 != null)
                        {
                            Plc1.WriteSingleAddress(M141Config.heartadd, 0, out _);
                        }
                    }
                }
                catch
                {
 
                }
 
 
                try
                {
                    string csvhead = "时间";
                    string csvdata = DateTime.Now.ToString("yyyyMMddHHmmss") + "T";
 
                    if (Plc1 != null)
                    {
                        foreach (var item1 in M141Config.PLCAlarm)
                        {
                            try
                            {
                                if (!item1.isused)
                                {
                                    continue;
                                }
 
                                var alrams = item1.AlarmDetails;
 
                                var plcdev = DeviceCollection.FirstOrDefault(u => u.Id == item1.plcname) as PLCBase;
 
                                  
                                
                                foreach (var item in alrams.GroupBy(u => u.address))
                                {
                                    int add = item.Key;
 
                                    var readres = plcdev.Read(add, 1, out _)[0];
 
                                    var Allbin = Convert.ToString(readres, 2).PadLeft(16, '0').Select(c => c - '0').ToArray();
 
                                    Allbin = Allbin.Reverse().ToArray();
 
                                    foreach (var item2 in item)
                                    {
                                        item2.value = Allbin[item2.address2];
 
                                        if (!AlarmTypeList.Contains(item2.alarmtype))
                                        {
 
                                            AlarmTypeList.Add(item2.alarmtype);
 
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"报警类别{item2.alarmtype}加入队列,队列个数为{AlarmTypeList.Count}");
                                        }
                                    }
                                }
 
                                string StateDICKey = "";
 
                                foreach (var item in AlarmTypeList)
                                {
 
                                    StateDICKey = plcdev.Name +"_"+ item;
 
                                    if (!StateDIC.ContainsKey(StateDICKey))
                                    {
 
                                        StateDIC[StateDICKey] = new List<int>();
 
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"报警类别{StateDICKey}加入字典:StateDIC");
 
                                    }
 
                                    //if (!StateDIC.ContainsKey(plcdev.Name))
                                    //{
 
                                    //       StateDIC[plcdev.Name] = new List<int>();
                                    //}
                                }
 
                                Dictionary<string, AlarmTypeData> AlarmType = new Dictionary<string, AlarmTypeData>();
 
                                List<int> list = new List<int>();
                             
                                foreach (var item in alrams)
                                {
                                    if (!AlarmType.ContainsKey(item.alarmtype))
                                    {
                                        AlarmType.Add(item.alarmtype, new AlarmTypeData()
                                        {
                                            CSVhead = csvhead,
                                            CSVdata = csvdata,
                                        });
 
                                    }
 
                                    if (AlarmType.ContainsKey(item.alarmtype))
                                    {
                                        AlarmType[item.alarmtype].CSVhead += $",{item.alarmname}";
 
                                        AlarmType[item.alarmtype].CSVdata += $",{(item.value == 1 ? "1" : "")}";
 
                                        AlarmType[item.alarmtype].AlarmTypeValue.Add(item.value);
 
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"报警类别{item.alarmtype};数值{item.value}加入字典:AlarmType");
                                    }
                                    
                                }
                                foreach(var item in AlarmType.Keys)
                                {
 
                                    list = AlarmType[item].AlarmTypeValue;
 
                                    string key = plcdev.Name+"_"+item;
 
                                    if (!StateDIC[key].SequenceEqual(list))
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{plcdev.Name}报警类型:{item}的信号发生变化");
 
                                        StateDIC[key].Clear();
 
                                        StateDIC[key].AddRange(list);
 
                                        CSVRecordAsync($"PLCstate_{key}.csv", AlarmType[item].CSVhead, AlarmType[item].CSVdata);
 
                                        var showdata = alrams.Where(u => u.value == 1).Select(u => u.alarmname).ToList();
 
                                        if (showdata == null)
                                        {
                                            showdata = new List<string>();
                                        }
 
                                        if (showdata.Count > 0)
                                        {
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"{plcdev.Name}报警 个数:{showdata.Count}  {string.Join(',', showdata)}");
                                        }
                                        else
                                        {
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{plcdev.Name}报警 个数:0");
                                        }
                                    }
 
                                }                                
                            }
                            catch
                            {
 
                            }
                        }
                    }
 
                }
                catch
                {
 
                }
 
                try
                {
                    if (Plc1 != null)
                    {
                        DateTime dt = DateTime.Now;
                        Plc1.WriteSingleAddress(10, dt.Year, out _);
                        Plc1.WriteSingleAddress(11, dt.Month, out _);
                        Plc1.WriteSingleAddress(12, dt.Day, out _);
                        Plc1.WriteSingleAddress(13, dt.Hour, out _);
                        Plc1.WriteSingleAddress(14, dt.Minute, out _);
                        Plc1.WriteSingleAddress(15, dt.Second, out _);
                        Plc1.WriteSingleAddress(16, (int)dt.DayOfWeek, out _);
                    }
                }
                catch
                {
 
                }
 
                Thread.Sleep(1000);
            }
        }
 
        public class AlarmTypeData
        {
            public List <int> AlarmTypeValue;
 
            public string CSVhead;
 
            public string CSVdata;
 
        }
 
 
 
        /// <summary>
        /// 网络预热
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void NetWarmUp()
        {
            string warmUpImageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WarmUp");
            if (!Directory.Exists(warmUpImageFolder))
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"程序根目录下没有\"WarmUp\"预热图片文件夹");
                return;
            }
 
            var ml = DeviceCollection.FirstOrDefault(u => u is MachineLearningBase && u.CurrentState == EnumHelper.DeviceState.DSOpen) as MachineLearningBase;
            if (ml == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"预热时未能获取开启的深度学习驱动");
                return;
            }
            var netNames = ml.IConfig.NetCollections.Where(u => u.IsEnabled).Select(u => u.Name).ToList();
            var imageFiles = new DirectoryInfo(warmUpImageFolder).GetFiles().Select(u => u.FullName).ToList();
 
            Parallel.ForEach(netNames, n =>
            {
                Parallel.ForEach(imageFiles, i =>
                {
                    HImage hImage = new HImage();
                    hImage.ReadImage(i);
 
                    ml.RunNetEvaluate(n, hImage);
 
                    hImage.Dispose();
                    hImage = null;
                });
            });
 
            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, "深度学习驱动预热完成");
 
 
            //if (M141Config.WarmUp && M141Config.WarmUpList.Count > 0)
            //{
            //    M141Config.WarmUpList.AsParallel().ForAll(x =>
            //    {
            //        try
            //        {
            //            HImage im = new HImage(x.PicFilePath);
            //            var tool = GetHalconTool(null, "", x.HalconFilePath);
            //            if (tool != null)
            //            {
            //                //int num = 0;
            //                //for (int i = 0; i < 10; i++)
            //                //{
            //                try
            //                {
            //                    var res = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", im } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
            //                    //if (res != null)
            //                    //{
            //                    //    if (res.Item1&& res.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble()[0]!=-1234)
            //                    //    {
            //                    //        num++;
            //                    //        if (num >= 2)
            //                    //        {
            //                    //            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"算法{x.HalconFilePath}预热完成{i}");
            //                    //            break;
            //                    //        }
            //                    //    }
            //                    //}
            //                }
            //                catch
            //                {
 
            //                }
            //                //if (i==9)
            //                //{
            //                //    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"算法{x.HalconFilePath}预热失败{num}");
            //                //}
            //                //}
            //            }
            //            im.Dispose();
 
            //        }
            //        catch
            //        {
            //            LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"算法{x.HalconFilePath}预热失败");
            //        }
            //    });
            //}
 
            //LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, "算法预热完成");
        }
 
        static object _positionCheckTimeLock = new object();
        Dictionary<string, List<int>> _positionCheckTimeDict = new Dictionary<string, List<int>>();
        Dictionary<string, List<string>> _positionSpecHeads = new Dictionary<string, List<string>>();
 
 
        volatile int uploadId = 0;
 
 
        public void NewProductIntoList(ProductModel p, bool isSaveDB)
        {
            lock (_productListLock)
            {
                ProductList.RemoveAll(u => u.PID == p.PID || u.SEQUENCE == p.SEQUENCE);
                ProductList.Insert(0, p);
                while (ProductList.Count > 200)
                {
                    ProductList.RemoveAt(ProductList.Count - 1);
                }
            }
 
            if (isSaveDB)
            {
                mysqlhelper.NewProduct(p);
            }
 
            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"{p.PID}_{p.SEQUENCE}产品入列完成");
        }
 
        public virtual ProductModel FindProductBySequence(string sequence, bool isEnabelQueue)
        {
            ProductModel p = null;
            if (isEnabelQueue)
            {
                lock (_productListLock)
                {
                    p = ProductList.FirstOrDefault(u => u.SEQUENCE == sequence);
                }
            }
 
            if (p != null)
            {
                return p;
            }
            else
            {
                p = mysqlhelper.GetProduct(sequence);
                if (p == null)
                {
                    p = new ProductModel();
                    p.SEQUENCE = sequence;
                    p.PID = p.PID + "_" + sequence.Split('_')[sequence.Split('_').Length - 1];
 
                    p.Initial(M141Config.StationCode, M141Config.WorkPositionCollection.Where(u => u.IsEnabled).Select(u => u.PositionName).ToList());
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"未能从数据库获取产品对象,使用临时新建产品对象   {sequence}");
                }
                NewProductIntoList(p, false);
            }
 
            return p;
        }
 
        public async Task RunImageCheckAsync(List<ProductModel> products, string triggerText, string triggerSource, IImageSet imgSet, MeasureBind measureBind)
        {
            await Task.Run(() =>
            {
                List<DetectResult> resultList = new List<DetectResult>();
                if (products == null || products.Count == 0)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"工位{measureBind.WorkPosition}检测时产品信息为空");
                    imgSet.HImage?.Dispose();
                    imgSet.HImage = null;
                    return;
                }
 
                try
                {
                    List<string> pidList = products.Select(u => u.PID).OrderBy(u => u).ToList();
                    if (imgSet == null || imgSet.HImage == null)
                    {
                        throw new Exception($"产品{string.Join(",", pidList)}检测{measureBind.GetDisplayText()}未能获取图片对象");
                    }
 
                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedMonitorId, resultList);
                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedCombineMethodId, resultList);
 
                    //检测顺序 ML->自定义检测
                    if (!string.IsNullOrWhiteSpace(measureBind.DetectionId))
                    {
                        string detectionName = (ML.InitialConfig as MLInitialConfigBase).DetectionConfigs.FirstOrDefault(u => u.Id == measureBind.DetectionId)?.Name;
 
                        List<DetectResult> detectResults = ML?.RunMLDetectionSync(imgSet, pidList, measureBind.DetectionId, false, null, null, "", products[0].ImagePaths);
 
 
 
                        if (measureBind.WorkPosition == "P1" && M141Config.StationCode == "S5" && detectResults.GetDefectDescList().Count == 0)
                        {
                            var defecttem = detectResults.SelectMany(u => u.AllNetResults.SelectMany(m => m.DetectDetails)).Where(u => u.ClassName == M141Config.defectname).ToList();
 
                            List<Netdefectdetail> Netdefectdetails = mysqlhelper.GetNetdefectdetails(products[0].SEQUENCE);
 
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5检测 S3数据{Netdefectdetails.Count}  S5数据{defecttem.Count}");
 
                            Netdefectdetails.ForEach(x =>
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5检测 S3数据{x.name}  {x.centerX},{x.centerY} ");
                            });
 
                            int num = 0;
                            foreach (var item1 in defecttem)
                            {
                                double x1 = item1.Rect.Point_LU.X + item1.Rect.Width / 2.0;
                                double y1 = item1.Rect.Point_LU.Y + item1.Rect.Height / 2.0;
                                num++;
 
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5检测  原坐标{num}   {x1},{y1}");
                                HOperatorSet.ProjectiveTransPixel(new HTuple(products[0].Centermatrix.ToArray()), y1, x1, out HTuple qx, out HTuple qy);
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5检测  新坐标{num}   {qx},{qy}");
 
 
                                Netdefectdetail temc = new Netdefectdetail()
                                {
                                    centerX = qx,
                                    centerY = qy,
                                    name = M141Config.defectname,
                                };
                                if (Netdefectdetails.Any(u => u == temc))
                                {
                                    item1.IsAbandoned = false;
                                    item1.FinalResult = ResultState.NG;
 
                                    //products[0].Result = M141Config.defectname;
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{products[0].PID}_{products[0].SEQUENCE}工位{measureBind.WorkPosition}   S3S5组合检测检出缺陷:{item1.NetName},产品结果为{products[0].Result}");
                                    break;
                                }
                            }
                        }
 
                        List<DetectResult> ngResults = new List<DetectResult>();
                        detectResults.GroupBy(u => u.PID).ToList().ForEach(u =>
                        {
                            if (u.ToList().Count > 0 && u.ToList().Any(m => m.ResultState != EnumHelper.ResultState.OK))
                            {
                                if (u.ToList().GetDefectDescList().Count == 0)
                                {
                                    var errorSpec = _errorSpec.Copy();
                                    errorSpec.Code = "检测TBD";
                                    errorSpec.ActualValue = -999;
                                    DetectResult ngResult = new DetectResult() { Specs = new List<ISpec>() { errorSpec }, PID = u.Key, Id = Guid.NewGuid().ToString() };
                                    ngResults.Add(ngResult);
                                }
                            }
                        });
                        detectResults.AddRange(ngResults);
                        resultList.AddRange(detectResults);
                    }
 
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"工位{measureBind.WorkPosition}检测过程异常,{ex.ToString()}");
 
                    var errorSpec = _errorSpec.Copy();
                    errorSpec.ActualValue = -999;
                    products.ForEach(p =>
                    {
                        p.AddNewDetectResults(M141Config.StationCode, measureBind.WorkPosition, new List<DetectResult>()
                         {
                            new DetectResult()
                            {
                                Specs = new List<ISpec>()
                                {
                                    errorSpec
                                },
                                PID = p.PID,
                            }
                         });
                    });
                }
                finally
                {
 
                    try
                    {
                        if (resultList.Count > 0)
                        {
                            products.ForEach(p =>
                            {
                                var pResults = resultList.Where(u => u.PID == p.PID).ToList();
                                p.AddNewDetectResults(M141Config.StationCode, measureBind.WorkPosition, pResults);
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}添加工位{measureBind.WorkPosition}检测结果,数量{pResults.Count}");
                            });
                        }
 
                        products.ForEach(p =>
                        {
                            if (p.PositoinCheckDone(measureBind.WorkPosition, measureBind.CheckIndex, out string msg))
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}工位{measureBind.WorkPosition}的第{measureBind.CheckIndex}检测完成,该工位检测全部结束");
                            }
                            else
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}工位{measureBind.WorkPosition}的第{measureBind.CheckIndex}检测完成,{msg}");
                            }
                        });
 
 
                        if (resultList.Any(u => u.ResultState != EnumHelper.ResultState.OK))
                        {
 
                            if (measureBind.NGImageSwitch)
                            {
                                if (string.IsNullOrWhiteSpace(M141Config.NGImageFolder))
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"未配置NG图片保存目录");
                                }
                                else
                                {
                                    string folder = Path.Combine(M141Config.NGImageFolder, DateTime.Now.ToString("yyyyMMdd"), measureBind.WorkPosition, "NG");
 
                                    if (!Directory.Exists(folder))
                                    {
                                        Directory.CreateDirectory(folder);
                                    }
 
                                    string id = string.Join("_", products.Select(u => $"{u.PID}_{u.SN}")) + $"-{measureBind.ImageIndex}_{DateTime.Now.ToString("HHmmssfff")}";
 
                                    string post = "";
                                    if (ImageSet.ImageFormatPostDict.ContainsKey(M141Config.ImageFormatNG))
                                    {
                                        post = ImageSet.ImageFormatPostDict[M141Config.ImageFormatNG];
                                    }
                                    else
                                    {
                                        post = M141Config.ImageFormatNG.ToString().ToLower();
                                    }
 
                                    string ngImageFile = Path.Combine(folder, $"{id}.{post}");
                                    //var bitmap = imgSet.HImage.ConvertHImageToBitmap();
                                    //bitmap.Save(ngImageFile, M141Config.ImageFormatNG);
                                    //LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{id}NG图片已保存");
                                    //bitmap.Dispose();
                                    try
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{id}NG图片测试转存{ngImageFile}");
                                        imgSet.HImage.WriteImage(M141Config.ImageFormatOK.ToString().ToLower(), 0, ngImageFile);
                                    }
                                    catch (Exception)
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{id}NG图片保存失败");
                                    }
                                }
                            }
                        }
                        else
                        {
 
                            if (measureBind.OKImageSwitch)
                            {
                                if (string.IsNullOrWhiteSpace(M141Config.NGImageFolder))
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"未配置NG图片保存目录");
                                }
                                else
                                {
                                    string folder = Path.Combine(M141Config.NGImageFolder, DateTime.Now.ToString("yyyyMMdd"), measureBind.WorkPosition, "OK");
 
                                    if (!Directory.Exists(folder))
                                    {
                                        Directory.CreateDirectory(folder);
                                    }
 
                                    string id = string.Join("_", products.Select(u => $"{u.PID}_{u.SN}")) + $"-{measureBind.ImageIndex}_{DateTime.Now.ToString("HHmmssfff")}";
                                    string post = "";
                                    if (ImageSet.ImageFormatPostDict.ContainsKey(M141Config.ImageFormatOK))
                                    {
                                        post = ImageSet.ImageFormatPostDict[M141Config.ImageFormatOK];
                                    }
                                    else
                                    {
                                        post = M141Config.ImageFormatOK.ToString().ToLower();
                                    }
 
                                    string ngImageFile = Path.Combine(folder, $"{id}.{post}");
                                    //var bitmap = imgSet.HImage.ConvertHImageToBitmap();
                                    //bitmap.Save(ngImageFile, M141Config.ImageFormatOK);
                                    //LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{id}OK图片已保存");
                                    //bitmap.Dispose();
                                    try
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{id}OK图片测试转存{ngImageFile}");
                                        imgSet.HImage.WriteImage(M141Config.ImageFormatOK.ToString().ToLower(), 0, ngImageFile);
                                    }
                                    catch (Exception)
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{id}OK图片保存失败");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{measureBind.WorkPosition},产品{string.Join(",", products.Select(u => u.PID))}的NG图片保存异常,{ex.GetExceptionMessage()}");
                    }
 
                    try
                    {
 
                        if (imgSet != null && imgSet.HImage != null)
                        {
                            var camera = DeviceCollection.FirstOrDefault(u => u.Id == measureBind.CameraId) as CameraBase;
                            List<IShapeElement> eleList = new List<IShapeElement>();
                            TextDisplay txt = new TextDisplay();
                            txt.LineLimit = M141Config.LineLimit_p;
                            txt.FontSize = M141Config.FontSize_p;
                            eleList.Add(txt);
 
                            txt.StartX = txt.StartY = 0;
 
                            txt.AddText(products[0].SN, products[0].SN != "NOREAD" ? Color.Lime : Color.Red, Color.Transparent);
                            txt.AddText(" ", Color.Transparent, Color.Transparent);
 
 
                            var specList = products[0].Details.SelectMany(u => u.ResultList.SelectMany(r => r.Specs)).ToList();
                            specList.ForEach(v =>
                            {
                                txt.AddText($"{v.Code} {v.GetMeasureValueStr(3)}", v.MeasureResult == true ? Color.Lime : Color.Red, Color.Transparent);
                            });
 
                            camera.SaveFitImage(eleList, imgSet);
                        }
                    }
                    catch
                    {
 
                    }
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"图片{imgSet.PID}开始释放");
                    imgSet.HImage?.Dispose();
                    imgSet.HImage = null;
                    imgSet.Dispose();
                    imgSet = null;
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"图片已释放");
 
                }
            });
        }
 
 
        public async Task RunImageCheckAsync(List<ProductModel> products, string triggerText, string triggerSource, MeasureBind measureBind)
        {
            await Task.Run(() =>
            {
                List<DetectResult> resultList = new List<DetectResult>();
                if (products == null || products.Count == 0)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"工位{measureBind.WorkPosition}检测时产品信息为空");
                    return;
                }
 
                try
                {
 
                    RunCustomizedMethod(products, triggerText, triggerSource, null, measureBind.CustomizedMonitorId, resultList);
                    RunCustomizedMethod(products, triggerText, triggerSource, null, measureBind.CustomizedCombineMethodId, resultList);
 
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"工位{measureBind.WorkPosition}检测过程异常,{ex.ToString()}");
 
                    var errorSpec = _errorSpec.Copy();
                    errorSpec.ActualValue = -999;
                    products.ForEach(p =>
                    {
                        p.AddNewDetectResults(M141Config.StationCode, measureBind.WorkPosition, new List<DetectResult>()
                         {
                            new DetectResult()
                            {
                                Specs = new List<ISpec>()
                                {
                                    errorSpec
                                },
                                PID = p.PID,
                            }
                         });
                    });
                }
                finally
                {
 
                    try
                    {
                        if (resultList.Count > 0)
                        {
                            products.ForEach(p =>
                            {
                                var pResults = resultList.ToList();
                                p.AddNewDetectResults(M141Config.StationCode, measureBind.WorkPosition, pResults);
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}添加工位{measureBind.WorkPosition}检测结果,数量{pResults.Count}");
                            });
                        }
 
                        products.ForEach(p =>
                        {
                            if (p.PositoinCheckDone(measureBind.WorkPosition, measureBind.CheckIndex, out string msg))
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}工位{measureBind.WorkPosition}的第{measureBind.CheckIndex}检测完成,该工位检测全部结束");
                            }
                            else
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID}_{p.SEQUENCE}工位{measureBind.WorkPosition}的第{measureBind.CheckIndex}检测完成,{msg}");
                            }
                        });
 
 
 
                    }
                    catch (Exception ex)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{measureBind.WorkPosition},产品{string.Join(",", products.Select(u => u.PID))}的NG图片保存异常,{ex.GetExceptionMessage()}");
                    }
 
                }
            });
        }
 
 
        private void RunCustomizedMethod(List<ProductModel> products, string triggerText, string triggerSource, IImageSet imgSet, string methodId, List<DetectResult> resultList)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(methodId))
                {
 
                    var monitorSet = Config.GetAllMonitorSet().FirstOrDefault(u => u.Id == methodId);
 
                    if (monitorSet.OpConfig is IImageCheckOperationConfig iConfig)
                    {
                        var opConfig = iConfig.Clone();
 
                        opConfig.Products = new List<ProductModel>(products);
                        opConfig.ImageSet = imgSet;
 
                        opConfig.TriggerStr = triggerText;
                        opConfig.TriggerSource = triggerSource;
 
 
 
                        //LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"图片id,{imgSet.id}");
                        var res = RunSelectedMonitorSetByManual(methodId, opConfig);
 
                        if (res.DataObj is List<DetectResult> dr)
                        {
                            dr.ForEach(r =>
                            {
                                r.IsPreTreatDone = r.IsNetCheckDone = r.IsAfterTreatDone = true;
                                r.SetResult();
                            });
                            resultList.AddRange(dr);
                        }
 
                        if (res.Result != 1)
                        {
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"自定义检测过程异常,{res.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"自定义检测过程异常,{ex.GetExceptionMessage()}");
            }
        }
 
 
 
 
 
        #region plc
        public ResponseMessage RunImageCheck_plc(IOperationConfig config)
        {
 
            ResponseMessage msg = new ResponseMessage();
            msg.Result = 1;
            List<MeasureBind> measureBinds = new List<MeasureBind>();
            string inputSequence = "";
            var triggerDatas = config.TriggerStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                RunImageCheckPreTreat_plc(config, out measureBinds, out inputSequence);
            }
            catch (Exception ex)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"检测预处理异常,{ex.GetExceptionMessage()}");
                msg.Result = -1;
                msg.Message = ex.Message;
                return msg;
            }
 
            List<string> cameraIds = measureBinds.Select(u => u.CameraId).ToList();
            try
            {
                ConcurrentDictionary<MeasureBind, IImageSet> imgSetDicts = new ConcurrentDictionary<MeasureBind, IImageSet>();
                var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == triggerDatas[0]);
 
                measureBinds.AsParallel().ForAll(b =>
                {
                    var camera = DeviceCollection.FirstOrDefault(u => u.Id == b.CameraId) as CameraBase;
                    if (camera != null)
                    {
                        imgSetDicts[b] = null;
 
                        try
                        {
                            imgSetDicts[b] = CollectHImage(camera, b.SnapshotOpConfig);
                            if (positionSet.ispiccover)
                            {
                                Plc1.WriteSingleAddress(positionSet.plcover, 1, out _);
                            }
                        }
                        catch (Exception ea)
                        {
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"工位{measureBinds[0].WorkPosition}的第{measureBinds[0].CheckIndex}检测获取图像信息异常    {ea.ToString()}");
                        }
 
                        var pList = b.ProductIndices.Select(pi =>
                        {
                            string sequence = $"{inputSequence}_{pi}";
                            return FindProductBySequence(sequence, true);
                        }).ToList();
 
                        RunImageCheckAsync(pList, config.TriggerStr, config.TriggerSource, imgSetDicts[b], b);
                    }
                    else
                    {
                        var pList = b.ProductIndices.Select(pi =>
                        {
                            string sequence = $"{inputSequence}_{pi}";
                            return FindProductBySequence(sequence, true);
                        }).ToList();
 
                        RunImageCheckAsync(pList, config.TriggerStr, config.TriggerSource, b);
                    }
                });
            }
            catch (Exception ex)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"检测处理异常,{ex.GetExceptionMessage()}");
                msg.Result = -1;
                msg.Message = ex.Message;
                return msg;
            }
 
            CheckPositionDoneAsync_plc(measureBinds[0].WorkPosition, inputSequence, config, cameraIds);
 
         
            return msg;
 
        }
 
 
        public void RunImageCheckPreTreat_plc(IOperationConfig config, out List<MeasureBind> measureBinds, out string inputSequence)
        {
            Task.Run(() =>
            {
                SetProcessRunState(EnumHelper.RunState.Running);
            });
 
            measureBinds = new List<MeasureBind>();
            inputSequence = "";
 
            var triggerDatas = config.TriggerStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (triggerDatas.Length < 2)
            {
                throw new ProcessException($"触发文本{config.TriggerStr}解析失败,数据长度小于2");
            }
 
            string positionValue = triggerDatas[0];
            int checkIndex = -1;
            if (!int.TryParse(triggerDatas[1].Replace("Scan", ""), out checkIndex))
            {
                throw new ProcessException($"触发文本{config.TriggerStr}解析失败,未能获取检测序号");
            }
 
 
            var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == positionValue);
            if (positionSet == null)
            {
                throw new ProcessException($"触发文本{config.TriggerStr}未能获取{positionValue}对应的可用工位信息");
            }
 
            measureBinds = M141Config.MeasureBindCollection.Where(u => u.WorkPosition == positionSet.PositionName && u.CheckIndex == checkIndex).ToList();
            if (measureBinds.Count == 0)
            {
                throw new ProcessException($"未能获取工位{positionSet.PositionName}的第{checkIndex}检测配置信息");
            }
 
            measureBinds.Select(u => u.CameraId).ToList().ForEach(c =>
            {
                var camera = DeviceCollection.FirstOrDefault(u => u.Id == c) as CameraBase;
                if (camera != null)
                {
                    camera.ClearImageBufferQueue();
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"相机{camera.Name}检测前清理缓存完成");
                }
            });
 
 
 
            inputSequence = triggerDatas[triggerDatas.Length - 1];
 
            string tempSequence = inputSequence;
 
            string pidstr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            measureBinds.Where(b => b.IsFirstPosition).ToList().ForEach(b =>
            {
                b.ProductIndices.ForEach(i =>
                {
                    ProductModel p = new ProductModel();
                    p.SEQUENCE = $"{tempSequence}_{i}";
                    p.PID = $"{pidstr}T_{i}";
 
                    if (M141Config.Isreadbasketcode)
                    {
                        p.BasketCode = M141Config.basketcode;
                        p.Zword = M141Config.zwoid;
                    }
                    else
                    {
                        p.BasketCode = mysqlhelper.Getbasketcode(p.SEQUENCE, out string sntem, out string zword);
                        p.Zword = zword;
                        p.SN = sntem;
                        p.PID = $"{sntem}_{i}";
                        if ("NoRead".Equals(p.BasketCode))
                        {
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{p.PID}_{p.SEQUENCE}获取框具码失败 赋值Noread");
                        }
                    }
 
                    if (positionSet.IsLastPosition)
                    {
                        p.Initial(M141Config.StationCode, new List<string>() { positionSet.PositionName });
                    }
                    else
                    {
                        p.Initial(M141Config.StationCode, M141Config.WorkPositionCollection.Select(u => u.PositionName).ToList());
                    }
                    NewProductIntoList(p, true);
                });
            });
 
            Thread.Sleep(50);
 
            int de = 0;
            measureBinds.Where(b => (b.CheckIndex == de || b.CheckIndex == 1) && b.ImageIndex == 0).AsParallel().ForAll(b =>
            {
                List<int> temint = new List<int>();
 
                temint = new List<int>() { 1 };
 
                temint.ForEach(i =>
                {
                    string sequence = $"{tempSequence}_{i}";
                    var p = FindProductBySequence(sequence, b.IsEnabelQueryFromQueue);
 
                    //初始化产品的检测次数
                    var checkIndexList = M141Config.MeasureBindCollection.Where(u => u.WorkPosition == b.WorkPosition && u.ProductIndices.Contains(i)).Select(u => u.CheckIndex).OrderBy(u => u).ToList();
                    p.InitialPositionCheckList(b.WorkPosition, checkIndexList, M141Config.StationCode);
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{p.PID}_{p.SEQUENCE}已清理{b.WorkPosition}检测数据。当前已完成工位{string.Join(",", p.Details.Select(u => u.PositionName))}");
 
                });
 
                //初始化工位的检测次数
                var positionCheckTimes = M141Config.MeasureBindCollection.Where(u => u.WorkPosition == b.WorkPosition).Select(u => u.CheckIndex).ToList();
                lock (_positionCheckTimeLock)
                {
                    _positionCheckTimeDict[b.WorkPosition] = positionCheckTimes;
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"工位{b.WorkPosition}初始化检测次数:{string.Join(",", positionCheckTimes)}");
                }
            });
 
            measureBinds.AsParallel().ForAll(b =>
            {
                lock (_positionCheckTimeLock)
                {
                    _positionCheckTimeDict[b.WorkPosition].RemoveAll(u => u == b.CheckIndex);
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"工位{b.WorkPosition}开始第{b.CheckIndex}次检测,待检测序号:{string.Join(",", _positionCheckTimeDict[b.WorkPosition])}");
                }
            });
        }
 
        public async Task<List<ProductModel>> CheckPositionDoneAsync_plc(string positionName, string inputSequence, IOperationConfig config, List<string> cameraIds)
        {
           
            string triggerSource = config.TriggerSource;
            return await _taskFactory.StartNew(() =>
            {
                try
                {
                    
                    string index = config.TriggerStr.Split(',')[1];
                    var positionSet = M141Config.WorkPositionCollection.FirstOrDefault(u => u.PositionName == positionName);
 
                    var checkRemains = _positionCheckTimeDict[positionName];
 
                    var pIndices = M141Config.MeasureBindCollection.Where(u => u.WorkPosition == positionName).SelectMany(u => u.ProductIndices).Distinct().OrderBy(u => u).ToList();
                    pIndices = new List<int> { 1 };
 
 
                    var pList = pIndices.Select(u =>
                    {
                        string sequence = $"{inputSequence}_{u}";
                        return FindProductBySequence(sequence, true);
                    }).ToList();
                    List<bool> plcresult = new List<bool>();
                    if (pList.Any(u => u == null))
                    {
                        plcresult = new List<bool>() { false, false, false };
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"获取工位{positionName}汇总结果时产品信息为空");
                    }
                    else
                    {
                        int waitInterval = 300;
                        int repeatTime = M141Config.DetectTimeout / waitInterval;
                        do
                        {
                            if (!pList.All(p =>
                            {
                                p.GetPositionResult(M141Config.StationCode, positionName, out P_PRODUCT_DETAIL detail);
                                return detail?.IsDone ?? false;
                            }))
                            {
                                Thread.Sleep(waitInterval);
                                repeatTime--;
                            }
                            else
                            {
                                Thread.Sleep(50);
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"成功完成工位{positionName}产品{string.Join(",", pList.Select(u => $"{u.PID}_{u.SEQUENCE}"))}检测");
                                break;
                            }
 
                            if (repeatTime < 0)
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"工位{positionName}产品{string.Join(",", pList.Select(u => $"{u.PID}_{u.SEQUENCE}"))}检测获取结果超时");
                                break;
                            }
                        } while (true);
                    }
 
 
                    pList.ForEach(p =>
                    {
                        var isOK = p.GetPositionResult(M141Config.StationCode, positionName, out P_PRODUCT_DETAIL detail);
                        plcresult.Add(isOK);
                        List<string> specHeads = new List<string>();
                        string head = p.GetCSVHead(ref specHeads, positionName);
 
                        //_positionSpecHeads[positionName] = specHeads;
 
                        string data = p.GetCSVData(specHeads, positionName);
                        CSVRecordAsync($"{positionName}_Record_{DateTime.Now.ToString("yyyyMMdd")}.csv", data, head);
 
                        //UpdatePositionResultToDB(detail);
                        //var seqData = p.SEQUENCE.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries).ToList();
 
                        if (M141Config.StationCode == "S4" && isOK)
                        {
                            ////mysqlhelper.GetS2Result(productList[0].SEQUENCE);
                            //Plc1.WriteSingleAddress(1526, mysqlhelper.GetS2Result(productList[0].SEQUENCE) ? 1 : 2, out _);
 
                            bool temS2 = mysqlhelper.GetS2Result(p.SEQUENCE);
                            ReplyPlcData(positionSet, new List<bool>() { temS2 });
                            if (!temS2)
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"{p.SN}    S2工站NG抛料");
                            }
                        }
                        else
                        {
                            ReplyPlcData(positionSet, plcresult);
                        }
 
 
 
                        mysqlhelper.UpdateProduct(p);
 
 
 
                        if (positionSet.IsLastPosition)
                        {
                            //班次统计时间划分
                            if (M141Config.WorkShiftList.Count == 0)
                            {
                                //生成一个报表
                                string name = $"ProductRecord_{DateTime.Now.ToString("yyyyMMdd")}.csv";
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"创建{name}数据报表");
                                UpdateProductResultAsync(p, name);
                            }
                            else
                            {
                                foreach (var item in M141Config.WorkShiftList)
                                {
                                    DateTime now = DateTime.Now;
 
                                    if (item.ShiftTime_Start < item.ShiftTime_End)
                                    {
                                        if (now.TimeOfDay >= item.ShiftTime_Start.TimeOfDay && now.TimeOfDay < item.ShiftTime_End.TimeOfDay)
                                        {
                                            //生成一个报表
                                            string name = $"ProductRecord_{DateTime.Now.ToString("yyyyMMdd")}_{item.ShiftName}.csv";
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"创建{name}数据报表");
                                            UpdateProductResultAsync(p, name);
                                        }
                                    }
                                    else
                                    {
                                        if (now.TimeOfDay >= item.ShiftTime_Start.TimeOfDay)
                                        {
                                            //生成一个报表
                                            string name = $"ProductRecord_{DateTime.Now.ToString("yyyyMMdd")}_{item.ShiftName}.csv";
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"创建{name}数据报表");
                                            UpdateProductResultAsync(p, name);
                                        }
                                        if (now.TimeOfDay < item.ShiftTime_End.TimeOfDay)
                                        {
                                            // 生成一个报表
                                            string name = $"ProductRecord_{DateTime.Now.AddDays(-1).ToString("yyyyMMdd")}_{item.ShiftName}.csv";
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"创建{name}数据报表");
                                            UpdateProductResultAsync(p, name);
                                        }
                                    }
                                }
                            }
                            //UpdateProductResultAsync(p);
                            mysqlhelper.NewForAll(p, M141Config.StationCode, M141Config.defectname);
 
                            if (M141Config.IsfinDevice)
                            {
                                SummaryAllprodata(p);
                            }
                        }
                    });
 
 
                    cameraIds.ForEach(c =>
                    {
                        var camera = DeviceCollection.FirstOrDefault(u => u.Id == c) as CameraBase;
                        if (camera != null)
                        {
                            camera.ClearImageBufferQueue();
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"相机{camera.Name}清理缓存");
                        }
                    });
 
                    //ReplyPlcData(positionSet, plcresult);
                    if (positionSet.IsLastPosition)
                    {
                        if (_ct != null)
                        {
                            UpdateCT(null, (float)((DateTime.Now - _ct.Value).TotalSeconds));
                        }
                        _ct = DateTime.Now;
 
                        if (M141Config.ISupMES && (M141Config.MESchannel == -1 || M141Config.MESchannel == 1))
                        {
                            if (M141Config.numpro >= 50)
                            {
                                M141Config.numpro = 0;
                            }
 
                            string Msgreceice = null;
 
                            if (pList[0].Result == "OK")
                            {
                                M141Config.numpro++;
                                Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(pList[0], M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                            }
                            else
                            {
                                if (M141Config.ISupNG)
                                {
                                    Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(pList[0], M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}启动NG上传");
 
                                }
                                else
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}关闭NG上传");
                                }
                            }
                            M141Config.mesnum2++;
                            if (Msgreceice == null && !M141Config.ISupNG)
                            {
                                if (!M141Config.ISupNG)
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}数据NG,开启关闭NG上传MES");
                                }
                                else
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{pList[0].PID}数据上传MES异常 返回数据为null");
                                }
                            }
                            else
                            {
                                try
                                {
                                    var obj = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(Msgreceice);
 
                                    if (obj.zstatus == "200")
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}数据上传MES成功  {Msgreceice}");
                                    }
                                    else
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{pList[0].PID}数据上传MES失败  {Msgreceice}");
                                    }
                                }
                                catch
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{pList[0].PID}数据上传MES异常  {Msgreceice}");
                                }
                            }
 
 
 
                            int numplca = Convert.ToInt32(pList[0].SEQUENCE.Split('_')[0]);
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"plc给出的产品序号为{numplca}");
 
                            lock (plcnumlock)//1-29999   
                            {
 
                                if (PlcNumForAll == -1)
                                {
                                    PlcNumForAll = numplca;
                                }
 
                                int differ = numplca - PlcNumForAll;
 
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"两个产品中间的差值differ为{differ}");
 
                                if (differ > 1)
                                {
                                    for (int i = PlcNumForAll + 1; i < numplca; i++)
                                    {
                                        try
                                        {
                                            var plist = mysqlhelper.GetProductList(i + "_1");
                                            ProductModel newp = new ProductModel();
                                            newp.SEQUENCE = plist[0].SEQUENCE;
                                            newp.PID = plist[0].PID;
                                            newp.BasketCode = plist[0].BasketCode;
                                            newp.Zword = plist[0].Zword;
                                            newp.Result = "NG";
                                            newp.SN = plist[0].SN;
 
                                            if (M141Config.IsfinDevice)
                                            {
                                                SummaryAllprodata(newp);
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}提前NG加入汇总数据报表统计");
                                            }
                                            if (M141Config.ISupNG)
                                            {
                                                var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                                M141Config.mesnum2++;
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}启动NG上传");
                                            }
                                            else
                                            {
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}关闭NG上传");
                                            }
 
                                        }
                                        catch
                                        {
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{i + "_1"}上传失败");
                                        }
                                    }
                                }
                                else if (differ == -29998 && differ == 1 && differ == 0)
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"生产过程中未失去产品");
                                }
                                else if (differ < 0 && differ > -29998)
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PlcNumForAll为{PlcNumForAll},numplca为{numplca}");
                                    //产品从新计数时
                                    for (int i = PlcNumForAll + 1; i <= 29999; i++)
                                    {
                                        try
                                        {
                                            var plist = mysqlhelper.GetProductList(i + "_1");
                                            ProductModel newp = new ProductModel();
                                            newp.SEQUENCE = plist[0].SEQUENCE;
                                            newp.PID = plist[0].PID;
                                            newp.Zword = plist[0].Zword;
                                            newp.BasketCode = plist[0].BasketCode;
                                            newp.Result = "NG";
                                            newp.SN = plist[0].SN;
                                            if (M141Config.IsfinDevice)
                                            {
                                                SummaryAllprodata(newp);
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}提前NG加入汇总数据报表统计");
                                            }
                                            if (M141Config.ISupNG)
                                            {
                                                var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                                M141Config.mesnum2++;
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}启动NG上传");
                                            }
                                            else
                                            {
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}关闭NG上传");
                                            }
                                            //var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                            //M141Config.mesnum2++;
                                            //LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PlcNumForAll,前站NG排料且plc触发清零产品{newp.PID}数据上传,结果为{newp.Result}");
 
                                        }
                                        catch
                                        {
 
                                        }
                                    }
                                    for (int i = 1; i < numplca; i++)
                                    {
                                        try
                                        {
                                            var plist = mysqlhelper.GetProductList(i + "_1");
                                            ProductModel newp = new ProductModel();
                                            newp.SEQUENCE = plist[0].SEQUENCE;
                                            newp.PID = plist[0].PID;
                                            newp.BasketCode = plist[0].BasketCode;
                                            newp.Zword = plist[0].Zword;
                                            newp.Result = "NG";
                                            newp.SN = plist[0].SN;
                                            if (M141Config.IsfinDevice)
                                            {
                                                SummaryAllprodata(newp);
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}提前NG加入汇总数据报表统计");
                                            }
                                            if (M141Config.ISupNG)
                                            {
                                                var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                                M141Config.mesnum2++;
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}启动NG上传");
                                            }
                                            else
                                            {
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}关闭NG上传");
                                            }
 
                                            //var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                            //M141Config.mesnum2++;
                                            //LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"numplca,前站NG排料且plc触发清零产品{newp.PID}数据上传,结果为{newp.Result}");
                                        }
                                        catch
                                        {
                                        }
                                    }
                                }
                                PlcNumForAll = numplca;
                            }
 
                        }
 
                    }
 
                    //ReplyPlcData(positionName, config.TriggerValue);
 
                    return pList;
 
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, ex.ToString());
                    return null;
                }
 
            });
        }
 
 
        public void ReplyPlcData(WorkPositionSet p, List<bool> result)
        {
            if (p.plcresult != 0)
            {
                Plc1.WriteSingleAddress(p.plcresult, result[0] ? 1 : 2, out _);
            }
            Plc1.WriteSingleAddress(p.plcover, 1, out _);
 
        }
 
 
        public void SummaryAllprodata(ProductModel p)
        {
 
            _taskFactory.StartNew(() =>
            {
                try
                {
                    ProductModel newp = new ProductModel();
                    newp.SEQUENCE = p.SEQUENCE;
                    newp.PID = p.PID;
                    newp.BasketCode = p.BasketCode;
                    newp.Zword = p.Zword;
                    newp.Result = p.Result;
                    newp.SN = p.SN;
 
                    Thread.Sleep(500);
                    var plist = mysqlhelper.GetProductList(p.SEQUENCE);
 
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"产品{p.PID}检测结果为{p.Result}从数据库中获取的数据为产品{plist[0].PID}检测结果为{plist[0].Result}");
                    if (plist != null)
                    {
                        foreach (var item in plist)
                        {
                            newp.Details.AddRange(item.Details);
                        }
                    }
 
                    //LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"AllDeviceProductRecord从数据库获取到数据{p.SEQUENCE} plist数量{plist.Count} Details数量{newp.Details.Count}");
 
                    //newp.Details.AddRange(p.Details);
 
                    List<string> specHeadListforall = new List<string>();
                    List<string> positionListforall = new List<string>();
                    string csvHeadforall = newp.GetCSVHead(ref specHeadListforall, ref positionListforall);
                    string csvDataforall = newp.GetCSVData(specHeadListforall, positionListforall);
 
                    string data = "";
 
                    string Head = "时间,PID,栏具码,物料码,条码,汇总检测结果,S2_P1检测明细,S2_P2检测明细,S2_P3检测明细,S3_P1检测明细,S3_P2检测明细,S4_P1检测明细,S4_P2检测明细,S5_P1检测明细,S5_P2检测明细,S5_P3检测明细,Barcode,SPC_A,SPC_BF_A1,SPC_BF_A2,SPC_BF_A3,SPC_BF_A4,SPC_BF_A5,SPC_BF_A6,SPC_BF_A7,SPC_BF_A8,SPC_BF_A9,SPC_BS_A1,SPC_BS_A2,SPC_BS_A3,SPC_BS_A4,SPC_BS_A5,SPC_BS_A6,SPC_BS_A7,SPC_BS_A8,SPC_BS_A9,SPC_BT_A100RES,SPC_BT_A101RES,SPC_BT_A102RES,SPC_BT_A103RES,SPC_BT_A104RES,SPC_BT_A105RES,SPC_BT_A106RES,SPC_BT_A107RES,SPC_BT_A108RES,SPC_BT_A109RES,SPC_BT_A10RES,SPC_BT_A110RES,SPC_BT_A111RES,SPC_BT_A112RES,SPC_BT_A113RES,SPC_BT_A11RES,SPC_BT_A12RES,SPC_BT_A13RES,SPC_BT_A14RES,SPC_BT_A15RES,SPC_BT_A16RES,SPC_BT_A17RES,SPC_BT_A18RES,SPC_BT_A19RES,SPC_BT_A1RES,SPC_BT_A20RES,SPC_BT_A21RES,SPC_BT_A22RES,SPC_BT_A23RES,SPC_BT_A24RES,SPC_BT_A25RES,SPC_BT_A26RES,SPC_BT_A27RES,SPC_BT_A28RES,SPC_BT_A29RES,SPC_BT_A2RES,SPC_BT_A30RES,SPC_BT_A31RES,SPC_BT_A32RES,SPC_BT_A33RES,SPC_BT_A34RES,SPC_BT_A35RES,SPC_BT_A36RES,SPC_BT_A37RES,SPC_BT_A38RES,SPC_BT_A39RES,SPC_BT_A3RES,SPC_BT_A40RES,SPC_BT_A41RES,SPC_BT_A42RES,SPC_BT_A43RES,SPC_BT_A44RES,SPC_BT_A45RES,SPC_BT_A46RES,SPC_BT_A47RES,SPC_BT_A48RES,SPC_BT_A49RES,SPC_BT_A4RES,SPC_BT_A50RES,SPC_BT_A51RES,SPC_BT_A52RES,SPC_BT_A53RES,SPC_BT_A54RES,SPC_BT_A55RES,SPC_BT_A56RES,SPC_BT_A57RES,SPC_BT_A58RES,SPC_BT_A59RES,SPC_BT_A5RES,SPC_BT_A60RES,SPC_BT_A61RES,SPC_BT_A62RES,SPC_BT_A63RES,SPC_BT_A64RES,SPC_BT_A65RES,SPC_BT_A66RES,SPC_BT_A67RES,SPC_BT_A68RES,SPC_BT_A69RES,SPC_BT_A6RES,SPC_BT_A70RES,SPC_BT_A71RES,SPC_BT_A72RES,SPC_BT_A73RES,SPC_BT_A74RES,SPC_BT_A75RES,SPC_BT_A76RES,SPC_BT_A77RES,SPC_BT_A78RES,SPC_BT_A79RES,SPC_BT_A7RES,SPC_BT_A80RES,SPC_BT_A81RES,SPC_BT_A82RES,SPC_BT_A83RES,SPC_BT_A84RES,SPC_BT_A85RES,SPC_BT_A86RES,SPC_BT_A87RES,SPC_BT_A88RES,SPC_BT_A89RES,SPC_BT_A8RES,SPC_BT_A90RES,SPC_BT_A91RES,SPC_BT_A92RES,SPC_BT_A93RES,SPC_BT_A94RES,SPC_BT_A95RES,SPC_BT_A96RES,SPC_BT_A97RES,SPC_BT_A98RES,SPC_BT_A99RES,SPC_BT_A9RES,SPC_C";
 
                    for (int i = 0; i < Head.Split(",").ToList().Count(); i++)
                    {
                        int index = csvHeadforall.Split(",").ToList().IndexOf(Head.Split(",").ToList()[i]);
                        if (index != -1)
                        {
                            data += $"{string.Join(" ", csvDataforall.Split(",").ToList()[index])},";
                        }
                        else
                        {
                            data += "NA,";
                        }
                    }
                    CSVRecordAsync($"AllDeviceProductRecord.csv", data, Head);
 
                }
                catch (Exception exx)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, "AllDeviceProductRecord数据汇总异常  " + exx.ToString());
                }
            });
 
        }
 
 
 
 
        #endregion
 
        List<DefectNGRecord> DefectNGRecordList = new List<DefectNGRecord>();
 
        public void InitialContinuousNGAlarm()
        {
            DefectNGRecordList = M141Config.ContinuousNGAlarmColletion.Where(u => u.IsEnabled).Select(u =>
            {
                DefectNGRecord record = new DefectNGRecord();
                record.DefectName = u.DefectType;
                record.AlarmSetting = u;
                return record;
            }).ToList();
            OnContinuousNGAlarmRaised = NGAlarmRaised;
            if (M141Config.ContinuousNGAlarmAddress > 0 && Plc1 != null)
            {
                if (!Plc1.WriteSingleAddress(M141Config.ContinuousNGAlarmAddress, 0, out string error))
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"连续NG监控通知PLC重置报警失败,{error}");
                }
            }
        }
        public async void CheckContinuousNGAlarmAsync(ProductModel product)
        {
            await Task.Run(() =>
            {
                if (!M141Config.IsEnableContinuousNGAlarm)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"连续NG报警总开关已关闭");
                    return;
                }
 
                if (DefectNGRecordList.Count == 0)
                    return;
 
                string allMsg = "";
                bool isAlarmRaised = false;
                int alarmType = 0;
                string ngItem = "";
                try
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"连续NG数据记录");
                    DefectNGRecordList.ForEach(d =>
                    {
                        string alarmMsg = "";
                        int alarmTypeTemp = 0;
 
                        if (product.Result == "OK")
                        {
                            if (d.CheckIsAlarmRaised(product.Result == "OK", out alarmMsg, out alarmTypeTemp))
                            {
                                allMsg += $"{alarmMsg}\r\n";
 
                                isAlarmRaised = true;
                                ngItem = "产品结果";
                                alarmType = alarmTypeTemp;
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{product.PID}数据结果为{product.Result}参与连续NG统计");
                            }
                        }
                        else
                        {
                            if (product.Result.Contains(d.DefectName))
                            {
                                if (d.CheckIsAlarmRaised(!product.Result.Contains(d.DefectName), out alarmMsg, out alarmTypeTemp))
                                {
                                    allMsg += $"{alarmMsg}\r\n";
                                    isAlarmRaised = true;
                                    ngItem = "产品结果";
                                    alarmType = alarmTypeTemp;
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{product.PID}数据结果为{product.Result}参与连续NG统计");
                                }
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"连续NG数据记录失败");
                }
                if (isAlarmRaised)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"连续NG监控报警,{allMsg}");
                    if (M141Config.IsOperatorReset)
                    {
                        if (M141Config.ContinuousNGAlarmAddress > 0 && Plc1 != null)
                        {
                            if (!Plc1.WriteSingleAddress(M141Config.ContinuousNGAlarmAddress, 1, out string error))
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"连续NG监控通知PLC重置报警失败,{error}");
                            }
                        }
                        OnContinuousNGAlarmRaised?.Invoke(true, allMsg);
                    }
                    else
                    {
                        Task.Delay(50).Wait();
                        ResetContinuousNGAlarm();
                    }
                }
            });
        }
 
        object _continuousNGAlarmLock = new object();
 
        FrmContinuousNGAlarm _continuousNGAlarmFrm = null;
        private async void NGAlarmRaised(bool isRaiseAlarm, string alarmMsg)
        {
            await Task.Run(() =>
            {
                if (isRaiseAlarm)
                {
                    if (_continuousNGAlarmFrm == null)
                    {
                        lock (_continuousNGAlarmLock)
                        {
                            if (_continuousNGAlarmFrm == null)
                            {
                                _continuousNGAlarmFrm = new FrmContinuousNGAlarm();
 
                                _continuousNGAlarmFrm.TopMost = true;
 
                                _continuousNGAlarmFrm.FormClosed += _continuousNGAlarmFrm_FormClosed;
 
                                Task.Run(() =>
                                {
                                    _continuousNGAlarmFrm.ShowDialog();
 
                                });
                            }
                        }
                    }
                    Task.Delay(100).Wait();
                    _continuousNGAlarmFrm.ShowAlarmMsg(alarmMsg);
                }
                else
                {
                    if (_continuousNGAlarmFrm != null)
                    {
                        _continuousNGAlarmFrm.Close();
                    }
 
                }
            });
 
        }
 
        private void _continuousNGAlarmFrm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            ResetContinuousNGAlarm();
            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"连续NG报警已复位");
            _continuousNGAlarmFrm = null;
        }
 
        public void ResetContinuousNGAlarm()
        {
            //连续NG复位
            DefectNGRecordList.Where(u => u.IsAlarmRaised).ToList().ForEach(u => u.ResetAlarm());
            if (M141Config.ContinuousNGAlarmAddress > 0 && Plc1 != null)
            {
                if (!Plc1.WriteSingleAddress(M141Config.ContinuousNGAlarmAddress, 0, out string error))
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"连续NG监控通知PLC重置报警失败,{error}");
                }
            }
 
        }
 
        [ProcessMethod("", "ContinuousNGAlarmTest", "连续NG报警测试", InvokeType.TestInvoke)]
        public ResponseMessage ContinuousNGAlarmTest(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ProductModel p = new ProductModel();
 
            p.Result = config.TriggerStr;
 
            CheckContinuousNGAlarmAsync(p);
 
            return new ResponseMessage();
        }
    }
 
    public class DefectNGRecord
    {
        public string DefectName { get; set; }
        public List<DateTime> NGRecords { get; set; } = new List<DateTime>();
        public int ContinuousNGNum { get; set; } = 0;
        public ContinuousNGAlarm AlarmSetting { get; set; }
 
        private object _lockObj = new object();
 
        public bool IsAlarmRaised = false;
 
        bool _isContinuousAlarm = false;
 
        bool _timeAlarm = false;
 
        public bool CheckIsAlarmRaised(bool isOK, out string alarmMsg, out int alarmType)
        {
            alarmType = 0;
            alarmMsg = "";
            bool isAlarmRasied = false;
 
            if (IsAlarmRaised)
                return false;
 
            lock (_lockObj)
            {
                if (IsAlarmRaised)
                    return false;
 
                if (isOK)
                {
                    ContinuousNGNum = 0;
                }
                else
                {
                    //连续NG数量阈值
                    if (AlarmSetting.ContinuousNumThreshold > 0)
                    {
                        ContinuousNGNum++;
                        CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{DefectName}连续NG数量为:{ContinuousNGNum}个");
                    }
                    //时间内NG数量阈值
                    if (AlarmSetting.TimePeriodNumThresold > 0)
                    {
                        NGRecords.Add(DateTime.Now);
                    }
                }
 
                if (NGRecords.Count >= AlarmSetting.TimePeriodNumThresold && NGRecords.Count > 0)
                {
 
                    NGRecords = NGRecords.Skip(NGRecords.Count - AlarmSetting.TimePeriodNumThresold).OrderBy(u => u).ToList();
 
                    int timeInMinute = (int)Math.Ceiling((NGRecords[NGRecords.Count - 1] - NGRecords[0]).TotalMinutes);
                    //监控时间段
                    if (timeInMinute <= AlarmSetting.TimePeriod)
                    {
                        isAlarmRasied = true;
                        alarmMsg += $"{DefectName}{timeInMinute}分钟内NG{NGRecords.Count}个 ";
                        alarmType = AlarmSetting.TimePeriodAlarmType;
                        _timeAlarm = true;
                    }
                }
 
                if (ContinuousNGNum >= AlarmSetting.ContinuousNumThreshold)
                {
                    isAlarmRasied = true;
                    alarmMsg += $"{DefectName}连续NG{ContinuousNGNum}个 ";
                    alarmType = AlarmSetting.ContinuousAlarmType;
                    _isContinuousAlarm = true;
                }
                IsAlarmRaised = isAlarmRasied;
                return isAlarmRasied;
            }
        }
 
        public void ResetAlarm()
        {
            string msg = "";
            lock (_lockObj)
            {
                IsAlarmRaised = false;
                if (_isContinuousAlarm)
                {
                    _isContinuousAlarm = false;
                    ContinuousNGNum = 0;
                    msg += "连续NG报警 ";
                }
 
                if (_timeAlarm)
                {
 
                    _timeAlarm = false;
                    NGRecords.Clear();
                    msg += "时段内NG报警 ";
                }
            }
            CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{DefectName}{msg}已重置");
        }
 
    }
}