1
czw
9 天以前 1393661a4f59fb30aea8e5893fdd8c85331b32d1
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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
#region    [自定义类-VS][20250701112200484][AutoThread]
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using GZ.Modular.Redis;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Windows.Interop;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
using System.Security.Cryptography;
using System.Windows.Markup;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using ServiceStack.Configuration;
using ServiceStack;
using static Dapper.SqlMapper;
using System.IO;
using System.Net.WebSockets;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using NLog.Config;
using NLog.Targets;
using NLog;
using ServiceStack.Messaging.Rcon;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.RightsManagement;
using static GZ.Projects.HnSx.Clloc.sendTask;
using static GZ.Projects.HnSx.Clloc.modifyTaskPriority;
using static GZ.Projects.HnSx.Clloc.stockInException;
using static GZ.Projects.HnSx.Clloc.taskFeedback;
using static GZ.Projects.HnSx.Clloc.stockInInteraction;
using static GZ.Projects.HnSx.Clloc.cancelTask;
using static GZ.Projects.HnSx.Clloc.palletStackerInteraction;
using static GZ.Projects.HnSx.Clloc.putConveyorTask;
using static GZ.Projects.HnSx.Clloc.reportWeightinfo;
using System.Threading.Channels;
using static GZ.Projects.HnSx.Clloc;
 
namespace GZ.Projects.HnSx
{
    public partial class AutoThread
    {
 
        private static AutoThread _instance;
 
        // 私有构造函数防止外部实例化
        private AutoThread() { }
 
        public static AutoThread Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AutoThread();
                }
                return _instance;
            }
        }
 
        // 线程安全的委托缓存
        private static readonly ConcurrentDictionary<string, Delegate> _methodCache = new ConcurrentDictionary<string, Delegate>();
 
        // 方法执行器
        public static object InvokeMethod(object instance, string methodName, params object[] args)
        {
            var cacheKey = $"{instance.GetType().FullName}_{methodName}";
 
            if (!_methodCache.TryGetValue(cacheKey, out var methodDelegate))
            {
                // 获取方法信息
                var methodInfo = instance.GetType().GetMethod(
                    methodName,
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
 
                if (methodInfo == null)
                    throw new MissingMethodException($"Method {methodName} not found");
 
                // 创建委托并缓存
                methodDelegate = Delegate.CreateDelegate(
                    GetDelegateType(methodInfo),
                    instance,
                    methodInfo);
 
                _methodCache.TryAdd(cacheKey, methodDelegate);
            }
 
            // 执行委托
            return methodDelegate.DynamicInvoke(args);
        }
 
        // 根据方法签名生成对应的委托类型
        private static Type GetDelegateType(MethodInfo methodInfo)
        {
            var parameterTypes = methodInfo.GetParameters()
                .Select(p => p.ParameterType)
                .ToList();
 
            if (methodInfo.ReturnType == typeof(void))
            {
                return System.Linq.Expressions.Expression.GetActionType(parameterTypes.ToArray());
            }
            else
            {
                parameterTypes.Add(methodInfo.ReturnType);
                return System.Linq.Expressions.Expression.GetFuncType(parameterTypes.ToArray());
            }
        }
 
        /// <summary>
        /// 配置初始化。
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="action"></param>
        public void ThreadSettingInit(Tag tag)
        {
        }
 
        public async void ThreadwebSoc()
        {
            //read Alldata from database
            //将数据缓存到内存。
            try
            {
                Thread.Sleep(1000);
                while (true)
                {
                    if (/*list.Count > 0 && */WebSocketClientWithReconnect.GetWebSocketState() == WebSocketState.Open)
                        for (int i = 0; i < 70000; i++)
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")}>>>发送 第 {i} 条");
                            //LogHelper.Info($"Hello Server {i}");
                            var req = new ReportWeightInfoRequest
                            {
                                data = new ReportWeightInfoData
                                {
                                    header = new ReportWeightInfoHeader
                                    {
                                        deliveryNo = "F0000" + i,
                                        grossWeight = i,
                                        cube = i,
                                        addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                                        addWho = "WCS"
                                    }
                                }
                            };
                            var b = WebSocketClientWithReconnect.Instance?.SendAsync(JsonConvert.SerializeObject(req)).Result;
                            Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")}>>发送完成!!" + b);
                            if (b == true)
                            {
                                // 等待特定响应
 
                                var rr = reportWeightinfo.GetChinnnl().Result;
 
                                //LogHelper.Info($" {DateTime.Now.ToString("HH:mm:ss.fff")}>> 接收" + JsonConvert.SerializeObject(rr));
                                //}
                                Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")}>>" + JsonConvert.SerializeObject(rr));
                            }
                            else Console.WriteLine("发送失败。");
                        }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);
            }
        }
        public async Task TaskEverythingRun()
        {
            var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    Console.WriteLine($"ip= {ip.ToString()}");
                    new HttpServer(ip.ToString()).HttpServerRun();
                    //new TcpServer(ip.ToString());
                    //var server = new EnhancedWebSocketServer($"http://{ip.ToString()}:8809/").StartAsync(); http://10.20.66.121:18080
                    new WebSocketClientWithReconnect($"ws://10.20.66.121:20001/socket").StartAsync();
                    //new WebSocketClientWithReconnect($"ws://{ip.ToString()}:8809/socket").StartAsync();
                    WebSocketClientWithReconnect.Instance.OnMessageReceived += (msg) =>
                    {
                        //reportWeightinfo.channel.Writer.TryWrite(JsonConvert.DeserializeObject<ReportWeightInfoResponse>(msg));
                        reportWeightinfo.channel.Writer.TryWrite(new ReportWeightInfoResponse
                        {
                            Response = new ReportWeightInfoResponseData
                            {
                                Return = new ReportWeightInfoReturnInfo
                                {
                                    returnCode = "0000",
                                    sortingChute = msg
                                }
                            }
                        });
                    };
                    break;
                }
            }
        }
 
 
 
    }
    public class HttpServer
    {
        public static readonly HttpHelper apiHelper = new HttpHelper();
        System.Net.HttpListener HttpSvcHost = null;
 
        public static string _listenerPrefix = "";
        public HttpServer(string ip)
        {
            _listenerPrefix = $"http://{ip}:8808/";
        }
        public void HttpServerRun()
        {
            HttpSvcHost = new System.Net.HttpListener();
            HttpSvcHost.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;
            HttpSvcHost.Prefixes.Add(_listenerPrefix);
            HttpSvcHost.Start();
            HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null);
        }
 
        private async void HttpSvcListenerCallback(IAsyncResult ar)
        {
            System.Net.HttpListenerContext context = null;
            var data = DateTime.Now;
            string apth = "";
            try
            {
                HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null);
                context = HttpSvcHost.EndGetContext(ar);
                System.Net.HttpListenerRequest request = context.Request;
                System.Net.HttpListenerResponse response = context.Response;
 
                using (var reader = new System.IO.StreamReader(request.InputStream, System.Text.Encoding.UTF8))
                {
                    string requestJson = reader.ReadToEnd();
                    System.Net.HttpStatusCode statusCode = 0;
                    apth = request.Url.AbsolutePath;
                    string respstr = HttpSvcListenerCallback_he(request.HttpMethod, request.Url.AbsolutePath, requestJson, out statusCode);
                    string logContent = "";
                    logContent += $"\r\n[{request.HttpMethod}]{request.Url.AbsolutePath}";
                    logContent += $"\r\n[request]{requestJson}";
                    logContent += $"\r\n[response]{respstr}";
                    _ = Task.Run(() =>
                    {
                        LogHelper.Info(logContent);
                        Conn.log默认日志?.Info(logContent);
                    });
                    byte[] bytstr = Encoding.UTF8.GetBytes(respstr);
                    response.StatusCode = (int)statusCode;
                    response.SendChunked = false;
                    response.ContentLength64 = bytstr.Length;
                    if (request.Url.AbsolutePath.ToLower().Contains(".js"))
                        response.ContentType = "application/javascript";
                    else if (request.Url.AbsolutePath.ToLower().Contains(".svg"))
                        response.ContentType = "image/svg+xml";
                    // 异步写入响应
                    await response.OutputStream.WriteAsync(bytstr, 0, bytstr.Length);
                }
            }
            catch (Exception ex)
            {
                _ = Task.Run(() =>
                {
                    Conn.log默认日志.Error(ex.ToString());
                });
            }
            finally
            {
                context?.Response.Close();
                Console.WriteLine(apth + "<<>>" + DateTime.Now.Subtract(data).TotalMilliseconds);
            }
        }
        public static List<SendTaskHeader> lstr = new List<SendTaskHeader>();
        public static List<PutConveyorTaskHeader> putConveyorTasks = new List<PutConveyorTaskHeader>();
 
        private System.String HttpSvcListenerCallback_he(System.String method, System.String path, System.String requestJson, out System.Net.HttpStatusCode statusCode)
        {
            try
            {
                switch (method)
                {
                    case "POST":
                        {
                            switch (path)
                            {
                                case "/api/Wcs/GetTask":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        return JsonConvert.SerializeObject(new
                                        {
                                            出入移库任务 = lstr,
                                            箱体分发任务 = putConveyorTasks
                                        });
                                        break;
                                    }
                                case "/api/Wcs/RemoveTask":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        lstr.RemoveAll(x => x.palletId == requestJson);
                                        putConveyorTasks.RemoveAll(x => x.palletId == requestJson);
                                        break;
                                    }
                                ///任务下发--WMS-->WC
                                case "/api/Wcs/sendTask":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<SendTaskRequest>(requestJson);
                                        if (req == null || req.data == null || lstr.Find(x => x.groupTaskSequence == req.data.header.groupTaskSequence && x.groupTaskId == req.data.header.groupTaskId) != null)
                                        {
                                            if (req == null || req.data == null)
 
                                                return JsonConvert.SerializeObject(new SendTaskResponse
                                                {
                                                    Response = new ResponseData
                                                    {
                                                        Return = new ReturnInfo
                                                        {
                                                            returnCode = "0001",
                                                            returnDesc = req?.data == null ? "无任务下发!" : "任务重复下发!",
                                                            returnFlag = "0"
                                                        }
                                                    }
                                                });
                                            else
                                                return JsonConvert.SerializeObject(new SendTaskResponse
                                                {
                                                    Response = new ResponseData
                                                    {
                                                        Return = new ReturnInfo
                                                        {
                                                            returnCode = "0000",
                                                            returnDesc = "任务重复下发!",
                                                            returnFlag = "1"
                                                        }
                                                    }
                                                });
                                        }
                                        lstr.Add(req.data.header);
                                        return JsonConvert.SerializeObject(new SendTaskResponse
                                        {
                                            Response = new ResponseData
                                            {
                                                Return = new ReturnInfo
                                                {
                                                    returnCode = "0000",
                                                    returnDesc = "ok",
                                                    returnFlag = "1"
                                                }
                                            }
                                        });
                                    }
                                ///入库异常上报。 WCS-->WMS
                                case "/api/Wcs/stockInException":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var f = string.IsNullOrEmpty(requestJson) ? lstr.FirstOrDefault() : lstr.Find(x => x.palletId == requestJson);
                                        var str = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=STOCKINEXCEP", JsonConvert.SerializeObject(new StockInExceptionRequest
                                        {
                                            data = new StockInExceptionData
                                            {
                                                header = new StockInExceptionHeader
                                                {
                                                    organizationId = f.organizationId,
                                                    warehouseId = f.warehouseId,
                                                    groupTaskId = f.groupTaskId,
                                                    groupTaskSequence = f.groupTaskSequence,
                                                    palletId = f.palletId,
                                                    addTime = f.addTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                                    addWho = f.addWho,
                                                    reason = "库位有货不可用",
                                                    reasonCode = "01"
                                                }
                                            }
                                        }));
 
                                        var strres = JsonConvert.DeserializeObject<StockInExceptionResponse>(str);
                                        if (strres.Response.Return.returnCode == "0000")
                                        {
                                            f.toPosition = strres.Response.Return.toPosition;
                                            f.toLocation = strres.Response.Return.toLocation;
                                        }
                                        return str;
                                    }
                                ///任务状态反馈  WCS-->WM
                                case "/api/Wcs/taskFeedback":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        //foreach (var statu in new List<string> { "", "" })
                                        {
                                            var f = string.IsNullOrEmpty(requestJson) ? lstr.FirstOrDefault() : lstr.Find(x => x.palletId == requestJson);
                                            var str = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=TASKFEEDBACK", JsonConvert.SerializeObject(new TaskFeedbackRequest
                                            {
                                                data = new TaskFeedbackData
                                                {
                                                    header = new TaskFeedbackHeader
                                                    {
                                                        organizationId = f.organizationId,
                                                        warehouseId = f.warehouseId,
                                                        groupTaskId = f.groupTaskId,
                                                        groupTaskSequence = f.groupTaskSequence,
                                                        palletId = f.palletId,
                                                        fmLocation = f.fmLocation,
                                                        fmPosition = f.fmPosition,
                                                        toLocation = f.toLocation,
                                                        toPosition = f.toPosition,
                                                        taskStatus = "80",
                                                        taskType = f.taskType,
                                                        closeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                        closeWho = f.addWho
                                                    }
                                                }
                                            }));
                                        }
                                        return JsonConvert.SerializeObject("");
                                    }
                                ///入库交互  。WCS-->WMS
                                case "/api/Wcs/stockInInteraction":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<StockInInteractionRequest>(requestJson);
 
                                        var str = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=STOCKININTERACTION", requestJson);
                                        //var str = @"{""Response"":{""return"":{""returnCode"":""0000"",""returnDesc"":""Success"",""returnFlag"":""1"",""groupTaskId"":""GT250708000001"",""groupTaskSequence"":""1"",""taskStatus"":""00"",""taskType"":""PA"",""priority"":""3"",""toLocation"":""5A070101"",""toPosition"":""01""}}}";
                                        var res = JsonConvert.DeserializeObject<StockInInteractionResponse>(str);
                                        if (res.Response.Return.returnCode == "0000")
                                        {
                                            var from = req.data.header;
                                            var resss = res.Response.Return;
                                            lstr.Add(new SendTaskHeader
                                            {
                                                groupTaskId = resss.groupTaskId,
                                                groupTaskSequence = resss.groupTaskSequence,
                                                fmLocation = from.fmLocation,
                                                fmPosition = from.fmPosition,
                                                palletId = from.palletId,
                                                taskStatus = resss.taskStatus,
                                                taskType = resss.taskType,
                                                priority = resss.priority,
                                                toLocation = resss.toLocation,
                                                toPosition = resss.toPosition,
                                                addTime = DateTime.Now,
                                                addWho = from.addWho,
                                            });
                                        }
                                        return str;// + JsonConvert.SerializeObject(lstr);
                                        var str1 = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=STOCKININTERACTION", JsonConvert.SerializeObject(new StockInInteractionRequest
                                        {
                                            data = new StockInInteractionData
                                            {
                                                header = new StockInInteractionHeader
                                                {
                                                    palletId = "TP9901",
                                                    grossWeight = 99,
                                                    palletWidth = 99,
                                                    fmLocation = "",
                                                    fmPosition = "",
                                                    addTime = DateTime.Now,
                                                    addWho = ""
                                                }
                                            }
                                        }));
                                        return str1;
                                    }
                                ///入库交互  。WCS-->WMS
                                case "/api/Wcs/stockInInteraction2":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<StockInInteractionRequest>(requestJson);
 
                                        var str = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=STOCKININTERACTION", requestJson);
                                        //var str = @"{""Response"":{""return"":{""returnCode"":""0000"",""returnDesc"":""Success"",""returnFlag"":""1"",""groupTaskId"":""GT250708000001"",""groupTaskSequence"":""1"",""taskStatus"":""00"",""taskType"":""PA"",""priority"":""3"",""toLocation"":""5A070101"",""toPosition"":""01""}}}";
                                        var res = JsonConvert.DeserializeObject<StockInInteractionResponse>(str);
                                        if (res.Response.Return.returnCode == "0000")
                                        {
                                            var from = req.data.header;
                                            var resss = res.Response.Return;
                                            lstr.Add(new SendTaskHeader
                                            {
                                                groupTaskId = resss.groupTaskId,
                                                groupTaskSequence = resss.groupTaskSequence,
                                                fmLocation = from.fmLocation,
                                                fmPosition = from.fmPosition,
                                                palletId = from.palletId,
                                                taskStatus = resss.taskStatus,
                                                taskType = resss.taskType,
                                                priority = resss.priority,
                                                toLocation = resss.toLocation,
                                                toPosition = resss.toPosition,
                                                addTime = DateTime.Now,
                                                addWho = from.addWho,
                                            });
                                        }
                                        return str;// + JsonConvert.SerializeObject(lstr);
                                        var str1 = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=STOCKININTERACTION", JsonConvert.SerializeObject(new StockInInteractionRequest
                                        {
                                            data = new StockInInteractionData
                                            {
                                                header = new StockInInteractionHeader
                                                {
                                                    palletId = "TP9901",
                                                    grossWeight = 99,
                                                    palletWidth = 99,
                                                    fmLocation = "",
                                                    fmPosition = "",
                                                    addTime = DateTime.Now,
                                                    addWho = ""
                                                }
                                            }
                                        }));
                                        return str1;
                                    }
 
                                ///任务取消。 WMS-->WCS
                                case "/api/Wcs/cancelTask":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<CancelTaskRequest>(requestJson);
                                        var task = lstr.Find(x => x.groupTaskId == req.data.header.groupTaskId && x.groupTaskSequence == req.data.header.groupTaskSequence);
                                        if (task == null)
                                            return JsonConvert.SerializeObject(new CancelTaskResponse
                                            {
                                                Response = new ResponseData
                                                {
                                                    Return = new ReturnInfo
                                                    {
                                                        returnCode = "0001",
                                                        returnDesc = "任务不存在!!!",
                                                        returnFlag = "0"
                                                    }
                                                }
                                            });
                                        lstr.Remove(task);
                                        return JsonConvert.SerializeObject(new CancelTaskResponse
                                        {
                                            Response = new ResponseData
                                            {
                                                Return = new ReturnInfo
                                                {
                                                    returnCode = "0000",
                                                    returnDesc = "",
                                                    returnFlag = "1"
                                                }
                                            }
                                        });
                                    }
                                /// 碟盘机申请任务。  WCS-->WMS
                                case "/api/Wcs/palletStackerInteraction":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
 
                                        var str = apiHelper.Post("http://10.20.66.121:18080/datahubjson/wcs/?method=PALLETSTACKERINTERACTION", !string.IsNullOrEmpty(requestJson) ? requestJson : JsonConvert.SerializeObject(new PalletStackerInteractionRequest
                                        {
                                            data = new PalletStackerInteractionData
                                            {
                                                header = new PalletStackerInteractionHeader
                                                {
                                                    palletId = "TP9901",
                                                    taskId = $"X{DateTime.Now.ToString("yyyyMMdd")}001",
                                                    taskType = "PI",
                                                    fmLocation = "2FC1076",
                                                    addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                    addWho = "wcs"
                                                }
                                            }
                                        }));
                                        return str;
                                        //return JsonConvert.SerializeObject("");
                                    }
                                ///修改任务优先级 。 WMS - WCS
                                case "/api/Wcs/modifyTaskPriority":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<ModifyTaskPriorityRequest>(requestJson);
                                        List<TaskErrorInfo> taskErrorInfos = new List<TaskErrorInfo>();
                                        if (req != null)
                                        {
                                            foreach (var item in req.data.header)
                                            {
                                                var task = lstr.Find(x => x.groupTaskSequence == item.groupTaskSequence && x.groupTaskId == item.groupTaskId);
                                                if (task != null)
                                                {
                                                    task.priority = item.priority;
                                                }
                                                else
                                                {
                                                    taskErrorInfos.Add(new TaskErrorInfo
                                                    {
                                                        groupTaskId = item.groupTaskId,
                                                        groupTaskSequence = item.groupTaskSequence,
                                                        errorCode = "0001",
                                                        errorDesc = "没这个任务"
                                                    });
                                                }
                                            }
 
                                        }
 
                                        if (req == null || req.data.header.Count == taskErrorInfos.Count)
                                            return JsonConvert.SerializeObject(new ModifyTaskPriorityResponse
                                            {
                                                Response = new ModifyTaskPriorityResponseData
                                                {
                                                    Return = new ModifyTaskPriorityReturnInfo
                                                    {
                                                        returnCode = "0001",
                                                        returnDesc = "没有任务可更改",
                                                        returnFlag = "0"
                                                    }
                                                }
                                            });
                                        else
                                        {
                                            if (taskErrorInfos.Count == 0)
                                                return JsonConvert.SerializeObject(new ModifyTaskPriorityResponse
                                                {
                                                    Response = new ModifyTaskPriorityResponseData
                                                    {
                                                        Return = new ModifyTaskPriorityReturnInfo
                                                        {
                                                            returnCode = "0000",
                                                            returnFlag = "1",
                                                            returnDesc="ok"
                                                        }
                                                    }
                                                });
                                            else
                                            {
                                                return JsonConvert.SerializeObject(new ModifyTaskPriorityResponse
                                                {
                                                    Response = new ModifyTaskPriorityResponseData
                                                    {
                                                        Return = new ModifyTaskPriorityReturnInfo
                                                        {
                                                            returnCode = "0001",
                                                            returnDesc = "部分任务可更改",
                                                            returnFlag = "2",
                                                            resultInfo = taskErrorInfos
                                                        }
                                                    }
                                                });
                                            }
                                        }
 
                                    }
                                /// 输送线任务推送。 WMS-->WCS  -- 记录箱号数据,分拣下线后根据想好进入对应的区域。 
                                case "/api/Wcs/putConveyorTask":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        var req = JsonConvert.DeserializeObject<PutConveyorTaskRequest>(requestJson);
                                        List<TaskErrorInfo> taskErrorInfos = new List<TaskErrorInfo>();
                                        if (req != null)
                                        {
                                            foreach (var item in req.data.header)
                                            {
                                                var task = putConveyorTasks.Find(x => x.groupTaskSequence == item.groupTaskSequence && x.groupTaskId == item.groupTaskId);
                                                if (task == null)
                                                {
                                                    putConveyorTasks.Add(item);
                                                }
                                                else
                                                {
                                                    taskErrorInfos.Add(new TaskErrorInfo
                                                    {
                                                        groupTaskId = item.groupTaskId,
                                                        groupTaskSequence = item.groupTaskSequence,
                                                        errorCode = "0001",
                                                        errorDesc = "重复"
                                                    });
                                                }
                                            }
 
                                        }
 
                                        if (req == null || req.data.header.Count == taskErrorInfos.Count)
                                            return JsonConvert.SerializeObject(new PutConveyorTaskResponse
                                            {
                                                Response = new PutConveyorTaskResponseData
                                                {
                                                    Return = new PutConveyorTaskReturnInfo
                                                    {
                                                        returnCode = "0001",
                                                        returnDesc = "全部重复",
                                                        returnFlag = "0"
                                                    }
                                                }
                                            });
                                        else
                                        {
                                            if (taskErrorInfos.Count == 0)
                                                return JsonConvert.SerializeObject(new PutConveyorTaskResponse
                                                {
                                                    Response = new PutConveyorTaskResponseData
                                                    {
                                                        Return = new PutConveyorTaskReturnInfo
                                                        {
                                                            returnCode = "0000",
                                                            returnFlag = "1"
                                                        }
                                                    }
                                                });
                                            else
                                            {
                                                return JsonConvert.SerializeObject(new PutConveyorTaskResponse
                                                {
                                                    Response = new PutConveyorTaskResponseData
                                                    {
                                                        Return = new PutConveyorTaskReturnInfo
                                                        {
                                                            returnCode = "0001",
                                                            returnDesc = "部分重复",
                                                            returnFlag = "2",
                                                            resultInfo = taskErrorInfos
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    }
 
                                ///上报称重尺寸 - websocket .这里写着作为记录 
                                case "/api/Wcs/reportWeightinfo":
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        if (/*list.Count > 0 && */WebSocketClientWithReconnect.GetWebSocketState() == WebSocketState.Open)
                                        //for (int i = 60000; i < 70000; i++)
                                        {
                                            //Thread.Sleep(1000);
                                            var req = new ReportWeightInfoRequest
                                            {
                                                data = new ReportWeightInfoData
                                                {
                                                    header = new ReportWeightInfoHeader
                                                    {
                                                        deliveryNo = "F00001",
                                                        grossWeight = 99,
                                                        cube = 66,
                                                        addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                                                        addWho = "WCS"
                                                    }
                                                }
                                            };
                                            //Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")}>>>GGG{i}");
                                            LogHelper.Info(JsonConvert.SerializeObject(req));
                                            var b = WebSocketClientWithReconnect.Instance?.SendAsync(JsonConvert.SerializeObject(req)).Result;
                                            Console.WriteLine(req.data.header.deliveryNo + "发送完成!!" + b);
                                            if (b == true)
                                            {
                                                // 等待特定响应
 
                                                var rr = reportWeightinfo.GetChinnnl().Result;
 
                                                LogHelper.Info("接收" + JsonConvert.SerializeObject(rr));
                                                //}
                                                return JsonConvert.SerializeObject(rr);
                                            }
                                            else return "发送失败。";
                                        }
                                    }
                                    break;
                            }
                            break;
                        }
                    case "GET":
                        {
                            switch (path)
                            {
                                case var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase):
                                    {
                                        statusCode = System.Net.HttpStatusCode.OK;
                                        // 复制到case 上
                                        //var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                                        var filePath = /*Directory.GetCurrentDirectory() + "\\Static" + "\\" + path.Substring(1);*/System.IO.Path.Combine(Directory.GetCurrentDirectory() + "\\Static", path.Substring(1));
                                        return File.ReadAllText(filePath);
                                    }
                            }
                            break;
                        }
                }
                statusCode = System.Net.HttpStatusCode.NotFound;
                return "";
            }
            catch (Exception ex)
            {
                Conn.log默认日志.Error(ex.ToString());
                statusCode = System.Net.HttpStatusCode.InternalServerError;
                return "";
            }
        }
    }
 
    class EnhancedWebSocketServer
    {
        private HttpListener _listener;
        private readonly string _listenerPrefix;
        private readonly ConcurrentDictionary<Guid, WebSocket> _connections = new ConcurrentDictionary<Guid, WebSocket>();
        private CancellationTokenSource _cts = new CancellationTokenSource();
 
        public EnhancedWebSocketServer(string url)
        {
            _listenerPrefix = url;
        }
 
        public async Task StartAsync()
        {
            try
            {
                _listener = new HttpListener();
                _listener.Prefixes.Add(_listenerPrefix);
                _listener.Start();
                Console.WriteLine($"WebSocket服务器已启动,监听 {_listenerPrefix}");
                while (!_cts.IsCancellationRequested)
                {
                    HttpListenerContext context = await _listener.GetContextAsync();
                    if (context.Request.IsWebSocketRequest)
                    {
                        var wsContext = await context.AcceptWebSocketAsync(null);
                        var connectionId = Guid.NewGuid();
                        _connections[connectionId] = wsContext.WebSocket;
                        _ = HandleConnectionAsync(connectionId, wsContext.WebSocket, _cts.Token);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                        context.Response.Close();
                    }
                }
            }
            catch (Exception ex) when (ex is HttpListenerException || ex is ObjectDisposedException)
            {
                // 服务器停止时的正常异常
                Console.WriteLine("服务器正在停止...");
            }
        }
 
        private async Task HandleConnectionAsync(Guid connectionId, WebSocket webSocket, CancellationToken ct)
        {
            var buffer = new byte[1024 * 4];
            try
            {
                while (webSocket.State == WebSocketState.Open && !ct.IsCancellationRequested)
                {
                    var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
 
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "客户端关闭连接", ct);
                        break;
                    }
 
                    string message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                    Console.WriteLine($"连接 {connectionId} 收到消息: {message}");
 
                    // 广播消息给所有客户端
                    await BroadcastMessageAsync($"客户端 {connectionId} 说: {message}");
                }
            }
            catch (WebSocketException ex)
            {
                Console.WriteLine($"连接 {connectionId} 错误: {ex.WebSocketErrorCode} - {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理连接 {connectionId} 时出错: {ex.Message}");
            }
            finally
            {
                _connections.TryRemove(connectionId, out _);
                webSocket?.Dispose();
                Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")} 连接 {connectionId} 已关闭");
            }
        }
 
        public async Task BroadcastMessageAsync(string message)
        {
            var buffer = System.Text.Encoding.UTF8.GetBytes(message);
            foreach (var connection in _connections)
            {
                if (connection.Value.State == WebSocketState.Open)
                {
                    try
                    {
                        await connection.Value.SendAsync(
                            new ArraySegment<byte>(buffer),
                            WebSocketMessageType.Text,
                            true,
                            CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"广播消息到连接 {connection.Key} 失败: {ex.Message}");
                    }
                }
            }
        }
 
        public async Task StopAsync()
        {
            _cts.Cancel();
 
            // 关闭所有连接
            foreach (var connection in _connections)
            {
                try
                {
                    if (connection.Value.State == WebSocketState.Open)
                    {
                        await connection.Value.CloseAsync(
                            WebSocketCloseStatus.NormalClosure,
                            "服务器关闭",
                            CancellationToken.None);
                    }
                    connection.Value.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接 {connection.Key} 时出错: {ex.Message}");
                }
            }
 
            _listener?.Stop();
            _listener?.Close();
            Console.WriteLine("WebSocket服务器已停止");
        }
 
    }
 
    public class WebSocketClientWithReconnect
    {
        //public static List<object> SendList = new List<object>();
 
        public static ClientWebSocket _webSocket;
        private static WebSocketClientWithReconnect _instance;
        private readonly Uri _serverUri;
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private readonly int _reconnectDelayMs;
 
        public event Action<string> OnMessageReceived = msg => Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")}>>>Received: {msg}");
        public event Action OnConnected = () => Console.WriteLine("Connected to server");
        public event Action OnDisconnected = () => Console.WriteLine("Disconnected from webSocket server");
        public event Action<Exception> OnError = ex => Console.WriteLine($"Error: {ex.Message}");
 
        public WebSocketClientWithReconnect(string serverUrl, int reconnectDelayMs = 5000)
        {
            _serverUri = new Uri(serverUrl);
            _reconnectDelayMs = reconnectDelayMs;
        }
        public static WebSocketClientWithReconnect Instance
        {
            get
            {
                return _instance;
            }
        }
 
        public static WebSocketState GetWebSocketState() => _webSocket != null ? _webSocket.State : WebSocketState.Closed;
        public async Task StartAsync()
        {
            _instance = this;
            while (!_cts.IsCancellationRequested)
            {
                try
                {
                    _webSocket = new ClientWebSocket();
                    await _webSocket.ConnectAsync(_serverUri, _cts.Token);
                    OnConnected?.Invoke();
                    await ReceiveMessagesAsync();
                }
                catch (Exception ex) when (!_cts.IsCancellationRequested)
                {
                    OnError?.Invoke(ex);
                    await HandleDisconnection();
                }
            }
        }
 
        private async Task ReceiveMessagesAsync()
        {
            var buffer = new byte[1024 * 4];
 
            while (_webSocket.State == WebSocketState.Open && !_cts.IsCancellationRequested)
            {
                try
                {
                    var result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), _cts.Token);
 
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await HandleDisconnection();
                        break;
                    }
 
                    var message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                    OnMessageReceived?.Invoke(message);
                }
                catch (Exception ex) when (!_cts.IsCancellationRequested)
                {
                    OnError?.Invoke(ex);
                    await HandleDisconnection();
                    break;
                }
            }
        }
 
        private async Task HandleDisconnection()
        {
            OnDisconnected?.Invoke();
 
            try
            {
                if (_webSocket != null && _webSocket.State != WebSocketState.Closed)
                {
                    await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    _webSocket.Dispose();
                }
            }
            catch { /* 忽略关闭时的异常 */ }
 
            if (!_cts.IsCancellationRequested)
            {
                await Task.Delay(_reconnectDelayMs, _cts.Token);
            }
        }
 
        public async Task StopAsync()
        {
            _cts.Cancel();
 
            try
            {
                if (_webSocket != null && _webSocket.State == WebSocketState.Open)
                {
                    await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client shutdown", CancellationToken.None);
                }
            }
            finally
            {
                _webSocket?.Dispose();
            }
        }
 
        public async Task<bool> SendAsync(string message)
        {
            if (_webSocket?.State != WebSocketState.Open)
            {
                throw new InvalidOperationException("WebSocket is not connected");
            }
 
            var bytes = System.Text.Encoding.UTF8.GetBytes(message);
            await _webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, _cts.Token);
            return true;
        }
    }
 
    public class TcpServer
    {
        public static Dictionary<string, string> TrayIps = new Dictionary<string, string>();
        public TcpServer(string ip)
        {
            Init(ip);
        }
        private void Init(string ip)
        {
            //创建一个新的Socket,这里我们使用最常用的基于TCP的Stream Socket(流式套接字)
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //将该socket绑定到主机上面的某个端口
                socket.Bind(new IPEndPoint(IPAddress.Parse(ip), 2025));
                Console.WriteLine($"TCPServer socket 监听{ip}:{2025} ");
                //启动监听,并且设置一个最大的队列长度
                socket.Listen(30);
                //开始接受客户端连接请求
                socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public static Dictionary<string, Socket> clients = new Dictionary<string, Socket>();
        public static Dictionary<string, byte[]> buffers = new Dictionary<string, byte[]>();
        public static void ClientAccepted(IAsyncResult ar)
        {
 
            var socket = ar.AsyncState as Socket;
            var client = socket.EndAccept(ar);
            string remote_ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address.ToString();
            if (clients.Keys.Contains(remote_ip))
            {
                clients[remote_ip] = client;
            }
            else
            {
                clients.Add(remote_ip, client);
            }
            if (!buffers.Keys.Contains(remote_ip))
            {
                buffers.Add(remote_ip, new byte[1024]);
            }
            //给客户端发送一个欢迎消息
            //client.Send(Encoding.Unicode.GetBytes("Hi there, I accept you request at " + DateTime.Now.ToString()));
            Console.WriteLine(remote_ip);
 
            try
            {
                client.BeginReceive(buffers[remote_ip], 0, buffers[remote_ip].Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【接收客户端的消息异常0】:" + ex.Message);
            }
            //准备接受下一个客户端请求
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
        }
 
 
        public static void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                var socket = ar.AsyncState as Socket;
                string remote_ip = ((System.Net.IPEndPoint)socket.RemoteEndPoint).Address.ToString();
                var length = socket.EndReceive(ar);
                if (length == 0)
                {
                    clients.Remove(remote_ip);
                    buffers.Remove(remote_ip);
                    return;
                }
                else
                {
                    if (!clients.Keys.Contains(remote_ip))
                    {
                        clients.Add(remote_ip, socket);
                    }
                    if (!buffers.Keys.Contains(remote_ip))
                    {
                        buffers.Add(remote_ip, new byte[1024]);
                    }
                }
                try
                {
                    if (buffers.Keys.Contains(remote_ip))
                    {
                        //读取出来消息内容
                        var message = GetHexString(buffers[remote_ip], length);
                        //16   10
                        // Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss")} ---> " + remote_ip + "  :   " + message);
                        //if (message.Substring(0, 4) == "3f00" && message.Substring(message.Length - 4) == "0d0a")
                        //{
                        //    //显示消息
                        //    //string msg = message.Replace(@"0d", "").Replace(@"0a", "").Replace(@"0d0a", "").Trim();
                        //    //PlcHelper.Receive(remote_ip, msg);
                        //    //Array.Clear(buffers[remote_ip], 0, buffers[remote_ip].Length);//清空当前IP Buffer
                        //}
                        //else
                        //{
                        Console.WriteLine($"【TCP信息协议 {DateTime.Now.Millisecond}】:IP:{remote_ip},MSG:{message}");
                        var mg = message;// Encoding.ASCII.GetString(PlcHelper.Hex2Bin(message));
                        if (mg.Length > 10)
                        {
                            mg = mg.Substring(0, 10);
                        }
                        Console.WriteLine(mg);
                        if (mg.StartsWith("DK"))//&& mg.Trim().Length == "DK01000024".Length
                        {
                            LogHelper.Info($"扫码器 >{remote_ip} -{mg}");
                            if (TrayIps.TryGetValue(remote_ip, out string traycode))
                            {
                                TrayIps[remote_ip] = mg;
                            }
                            else TrayIps.Add(remote_ip, mg);
 
                            RedisHelper.Add("S扫码器" + (remote_ip.Split('.').LastOrDefault()), mg, out string msg);
                            RedisHelper.Add("S扫码器" + (remote_ip.Split('.').LastOrDefault()) + "#time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), out msg);
                            //Console.WriteLine("TOFF");
                            //var mst = PlcHelper.Hex2Bin("544F4646");
                            //TcpServer.TcpServerSend(remote_ip, mst);
                        }
                        //}
                    }
                    else
                    {
                        if (!buffers.Keys.Contains(remote_ip))
                        {
                            buffers.Add(remote_ip, new byte[1024]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"【处理客户端的消息异常2】:" + ex.StackTrace);
                    throw;
                }
                //接收下一个消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
                socket.BeginReceive(buffers[remote_ip], 0, buffers[remote_ip].Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
        private static string GetHexString(byte[] buffer, int lenght)
        {
            return BitConverter.ToString(buffer, 0, lenght).Replace("-", string.Empty).ToLower();
        }
 
        public static bool TcpServerSend(string ip, byte[] msg)
        {
            LogHelper.Info($"TcpServerSend >{ip}:{msg}");
            if (clients.Keys.Contains(ip))
            {
                var client = clients[ip];
                if (client.Connected)
                {
                    try
                    {
                        client.Send(msg);
                        LogHelper.Info($"TcpServerSend > 发送成功。");
                        return true;
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message);
                        clients[ip].Close();
                        clients.Remove(ip);
                    }
                }
                else
                {
                    clients[ip].Close();
                    clients.Remove(ip);
                }
            }
            else
            {
                Console.WriteLine("未找到设备的链接:" + ip);
            }
            return false;
 
        }
 
        public static int GetBitdata(int num, int wid)
        {
            string bstr = Convert.ToString(num, 2);
            if (bstr.Length <= wid)
            {
                return 0;
            }
            return bstr[bstr.Length - wid - 1] - '0';
        }
        public static int SetBinaryDigit(int number, int n, int value)
        {
            if (value != 0 && value != 1)
                throw new ArgumentException("Value must be 0 or 1.");
 
            string binaryStr = Convert.ToString(number, 2);
 
            // 如果 n 超出当前位数,补 0 扩展
            while (binaryStr.Length <= n)
            {
                binaryStr = "0" + binaryStr;
            }
 
            // 修改第 n 位(从右往左,最低位是第 0 位)
            char[] binaryChars = binaryStr.ToCharArray();
            binaryChars[binaryChars.Length - 1 - n] = value == 1 ? '1' : '0';
 
            // 转换回十进制
            return Convert.ToInt32(new string(binaryChars), 2);
        }
        public static List<string> GetStaticClients() => clients.Keys.ToList();
        public static Dictionary<string, string> GetStaticScan() => TrayIps;
    }
 
    public class LogHelper
    {
        #region    [自定义类][20250323145442478][LogHelper]
        public static Dictionary<string, ILogger> loggers = new Dictionary<string, ILogger>();
 
        public static void Debug(string message, string name = "")
        {
            ILogger logger = null;
            if (loggers.Keys.Contains(name))
            {
                logger = loggers[name];
            }
            else
            {
                logger = LogFactory.CreateLogger(name);
                if (logger != null)
                {
                    loggers.Add(name, logger);
                }
                else
                {
                    logger = LogFactory.CreateLogger("console");
                }
            }
            if (logger != null)
            {
                logger.Debug(message);
            }
        }
 
 
 
        public static void Info(string message, string name = "")
        {
            //logger.Info(message);
            ILogger logger = null;
            if (loggers.Keys.Contains(name))
            {
                logger = loggers[name];
            }
            else
            {
                logger = LogFactory.CreateLogger(name);
                if (logger != null && !loggers.Keys.Contains(name))
                {
                    loggers.Add(name, logger);
                }
                else
                {
                    logger = LogFactory.CreateLogger("infoFile");
                }
            }
            if (logger != null)
            {
                logger.Info(message);
            }
        }
 
        public static void Error(string message, Exception ex, string name = "")
        {
            //logger.Error(ex, message);
            ILogger logger = null;
            if (loggers.Keys.Contains(name))
            {
                logger = loggers[name];
            }
            else
            {
                logger = LogFactory.CreateLogger(name);
                if (logger != null && !loggers.Keys.Contains(name))
                {
                    loggers.Add(name, logger);
                }
                else
                {
                    logger = LogFactory.CreateLogger("errorFile");
                }
            }
            if (logger != null)
            {
                logger.Error($"{message}{ex.StackTrace}");
            }
        }
        #endregion [自定义类][20250323145442478][LogHelper]
    }
    public class LogFactory
    {
        #region    [自定义类][20250323145505759][LogFactory]
        /// <summary>
        /// 通过配置文件配置日志
        /// </summary>
        static LogFactory()
        {
            var loggerNames = new List<string>() { "HosttoagvTask", "HosttoagvCar", "NDC", "杭奥" };
            LogManager.Configuration = DefaultConfig(loggerNames);
        }
        public static ILogger CreateLogger(string name)
        {
            var logger = LogManager.GetLogger(name);
            return logger;
        }
 
        public static LoggingConfiguration DefaultConfig(List<string> loggerNames)
        {
            var config = new LoggingConfiguration();
            loggerNames.ForEach(a =>
            {
                var target = new FileTarget();
                target.ArchiveAboveSize = 1024 * 1024 * 5;//每个文件最大5M
                target.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
                target.ArchiveFileName = @"${basedir}/Logs/" + a + "/{####}.txt";
                target.FileName = @"${basedir}/Logs/" + a + "/${shortdate}.txt";//当前文件路径
                target.Layout = @"${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}";
 
                config.AddTarget(a, target);
                config.AddRuleForOneLevel(LogLevel.Info, target, a);
            });
 
 
            // 添加target-console
            var consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = @"${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}";
 
            config.AddTarget("console", consoleTarget);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, consoleTarget);
 
            //添加target-info
            var infoFileTarget = new FileTarget();
            infoFileTarget.ArchiveAboveSize = 1024 * 1024 * 5;//每个文件最大5M
            infoFileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
            infoFileTarget.ArchiveFileName = @"${basedir}/Logs/Info/{####}.txt";
            infoFileTarget.FileName = @"${basedir}/Logs/Info/${shortdate}.txt";//当前文件路径
            infoFileTarget.Layout = @"${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}";
 
            config.AddTarget("infoFile", infoFileTarget);
            config.AddRuleForOneLevel(LogLevel.Info, infoFileTarget);//INFO写在Info文件
 
            //添加target-err
            var errorFileTarget = new FileTarget();
            errorFileTarget.ArchiveAboveSize = 1024 * 1024 * 5;//每个文件最大5M
            errorFileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
            errorFileTarget.ArchiveFileName = @"${basedir}/Logs/Error/{####}.txt";
            errorFileTarget.FileName = @"${basedir}/Logs/Error/${shortdate}.txt";
            errorFileTarget.Layout = @"${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}";
 
            config.AddTarget("errorFile", errorFileTarget);
            config.AddRule(LogLevel.Error, LogLevel.Fatal, errorFileTarget);
 
 
            return config;
        }
 
        #endregion [自定义类][20250323145505759][LogFactory]
    }
 
    public class HttpHelper
    {
        #region    [自定义类][20250325095622918][HttpHelper]
        public string Post(string url, string postData, string contentType = "application/json", string sessionId = "")
        {
            LogHelper.Info(url + "+" + postData);
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = contentType;
            request.ContentLength = byteArray.Length;
            request.Timeout = 15000;
            if (sessionId != "")
            {
                request.Headers.Set("ASP.NET_SessionId", sessionId);
            }
 
            //Authorization: UApGP6WW9FsBUqAlzxRGOw ==
            request.Headers.Set("Authorization", "UApGP6WW9FsBUqAlzxRGOw==");
            StreamReader reader = null;
            Stream stream = null;
            WebResponse rsp = null;
            try
            {
                stream = request.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();
                rsp = request.GetResponse();
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream);
                string rrend = reader.ReadToEnd();
                LogHelper.Info($"{url} response={rrend}");
                return rrend;
            }
            catch (Exception ex)
            {
                LogHelper.Info($"{url} err={ex.Message}");
                return "";
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
 
        }
        #endregion [自定义类][20250325095622918][HttpHelper]
    }
    public class Clloc
    {
        public class sendTask
        {
            /// <summary>
            /// 任务下发请求
            /// </summary>
            public class SendTaskRequest
            {
                /// <summary>
                /// 请求数据
                /// </summary>
                public SendTaskData data { get; set; }
            }
 
            public class SendTaskData
            {
                /// <summary>
                /// 请求头信息
                /// </summary>
                public SendTaskHeader header { get; set; }
            }
 
            public class SendTaskHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 托盘号
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 来源库位
                /// </summary>
                public string fmLocation { get; set; }
 
                /// <summary>
                /// 来源点位
                /// </summary>
                public string fmPosition { get; set; }
 
                /// <summary>
                /// 目标库位号
                /// </summary>
                public string toLocation { get; set; }
 
                /// <summary>
                /// 目标点位
                /// </summary>
                public string toPosition { get; set; }
 
                /// <summary>
                /// 状态 - 00:创建
                /// </summary>
                public string taskStatus { get; set; } = "00";
 
                /// <summary>
                /// 任务类型 - PA:入库(上架/回库/移库), PK:出库(拣货/移库/补货/盘点), MV:倒库
                /// </summary>
                public string taskType { get; set; }
 
                /// <summary>
                /// 创建时间
                /// </summary>
                public DateTime addTime { get; set; }
 
                /// <summary>
                /// 创建人
                /// </summary>
                public string addWho { get; set; }
 
                /// <summary>
                /// 优先级 - 1-5(1最高,5最低),默认3
                /// </summary>
                public string priority { get; set; } = "3";
 
            }
 
            /// <summary>
            /// 任务下发响应
            /// </summary>
            public class SendTaskResponse
            {
                public ResponseData Response { get; set; }
            }
 
            public class ResponseData
            {
                [JsonProperty("return")]
                public ReturnInfo Return { get; set; }
            }
 
            public class ReturnInfo
            {
                /// <summary>
                /// 返回代码 - 0000:成功, 其他:失败
                /// </summary>
                public string returnCode { get; set; }
 
                /// <summary>
                /// 返回描述
                /// </summary>
                public string returnDesc { get; set; }
 
                /// <summary>
                /// 返回标记 - 1:成功, 0:失败
                /// </summary>
                public string returnFlag { get; set; }
            }
        }
 
        public class stockInException
        {
            /// <summary>
            /// 入库异常请求
            /// </summary>
            public class StockInExceptionRequest
            {
                public StockInExceptionData data { get; set; }
            }
 
            public class StockInExceptionData
            {
                public StockInExceptionHeader header { get; set; }
            }
 
            public class StockInExceptionHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 托盘号
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 创建时间
                /// </summary>
                public string addTime { get; set; }
 
                /// <summary>
                /// 创建设备
                /// </summary>
                public string addWho { get; set; }
 
                /// <summary>
                /// 异常原因描述
                /// </summary>
                public string reason { get; set; }
 
                /// <summary>
                /// 异常原因代码 - 01:库位有货不可用, 03:入内伸位外伸位有货
                /// </summary>
                public string reasonCode { get; set; }
 
                // ... UDF字段
            }
 
            /// <summary>
            /// 入库异常响应
            /// </summary>
            public class StockInExceptionResponse
            {
                public StockInExceptionResponseData Response { get; set; }
            }
 
            public class StockInExceptionResponseData
            {
                [JsonProperty("return")]
                public StockInExceptionReturnInfo Return { get; set; }
            }
 
            public class StockInExceptionReturnInfo : ReturnInfo
            {
                /// <summary>
                /// 新分配的目标库位
                /// </summary>
                public string toLocation { get; set; }
 
                /// <summary>
                /// 新分配的目标点位
                /// </summary>
                public string toPosition { get; set; }
            }
        }
 
        public class taskFeedback
        {
            /// <summary>
            /// 任务反馈请求
            /// </summary>
            public class TaskFeedbackRequest
            {
                public TaskFeedbackData data { get; set; }
            }
 
            public class TaskFeedbackData
            {
                public TaskFeedbackHeader header { get; set; }
            }
 
            public class TaskFeedbackHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 托盘号
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 来源库位
                /// </summary>
                public string fmLocation { get; set; }
 
                /// <summary>
                /// 来源点位
                /// </summary>
                public string fmPosition { get; set; }
 
                /// <summary>
                /// 目标库位号
                /// </summary>
                public string toLocation { get; set; }
 
                /// <summary>
                /// 目标点位
                /// </summary>
                public string toPosition { get; set; }
 
                /// <summary>
                /// 状态 - 80:完成, 98:异常(取货无货)
                /// </summary>
                public string taskStatus { get; set; }
 
                /// <summary>
                /// 任务类型 - PA:入库, PK:出库, MV:倒库
                /// </summary>
                public string taskType { get; set; }
 
                /// <summary>
                /// 完成时间
                /// </summary>
                public string closeTime { get; set; }
 
                /// <summary>
                /// 完成人员
                /// </summary>
                public string closeWho { get; set; }
 
                // ... UDF字段
            }
        }
        public class stockInInteraction
        {
            /// <summary>
            /// 入库交互请求
            /// </summary>
            public class StockInInteractionRequest
            {
                public StockInInteractionData data { get; set; }
            }
 
            public class StockInInteractionData
            {
                public StockInInteractionHeader header { get; set; }
            }
 
            public class StockInInteractionHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 托盘号 - 主键
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 总重量(kg)
                /// </summary>
                public decimal grossWeight { get; set; }
 
                /// <summary>
                /// 码盘宽度(cm)
                /// </summary>
                public decimal palletWidth { get; set; }
 
                /// <summary>
                /// 来源库位
                /// </summary>
                public string fmLocation { get; set; }
 
                /// <summary>
                /// 来源点位
                /// </summary>
                public string fmPosition { get; set; }
 
                /// <summary>
                /// 创建时间
                /// </summary>
                public DateTime addTime { get; set; }
 
                /// <summary>
                /// 创建人
                /// </summary>
                public string addWho { get; set; }
 
                // ... UDF01-UDF10
            }
 
            /// <summary>
            /// 入库交互响应
            /// </summary>
            public class StockInInteractionResponse
            {
                public StockInInteractionResponseData Response { get; set; }
            }
 
            public class StockInInteractionResponseData
            {
                [JsonProperty("return")]
                public StockInInteractionReturnInfo Return { get; set; }
            }
 
            public class StockInInteractionReturnInfo : ReturnInfo
            {
                /// <summary>
                /// 任务组编号
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 状态 - 00:创建
                /// </summary>
                public string taskStatus { get; set; }
 
                /// <summary>
                /// 任务类型 - PA:入库
                /// </summary>
                public string taskType { get; set; }
 
                /// <summary>
                /// 优先级 - 1-5(1最高)
                /// </summary>
                public string priority { get; set; }
 
                /// <summary>
                /// 目标库位号
                /// </summary>
                public string toLocation { get; set; }
 
                /// <summary>
                /// 目标点位
                /// </summary>
                public string toPosition { get; set; }
            }
        }
        public class cancelTask
        {
            /// <summary>
            /// 任务取消请求
            /// </summary>
            public class CancelTaskRequest
            {
                public CancelTaskData data { get; set; }
            }
 
            public class CancelTaskData
            {
                public CancelTaskHeader header { get; set; }
            }
 
            public class CancelTaskHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
            }
 
            /// <summary>
            /// 任务取消响应
            /// </summary>
            public class CancelTaskResponse
            {
                public ResponseData Response { get; set; }
            }
        }
        public class palletStackerInteraction
        {
            /// <summary>
            /// 叠盘机交互请求
            /// </summary>
            public class PalletStackerInteractionRequest
            {
                public PalletStackerInteractionData data { get; set; }
            }
 
            public class PalletStackerInteractionData
            {
                public PalletStackerInteractionHeader header { get; set; }
            }
 
            public class PalletStackerInteractionHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务编号 - 主键,设备发出的请求ID
                /// </summary>
                public string taskId { get; set; }
 
                /// <summary>
                /// 托盘号
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 类型 - PI:入库, PT:出库(当前无出库场景)
                /// </summary>
                public string taskType { get; set; }
 
                /// <summary>
                /// 起始库位 - 叠盘机物理起始位置
                /// </summary>
                public string fmLocation { get; set; }
 
                /// <summary>
                /// 优先级 - 1-5(1最高)
                /// </summary>
                public string priority { get; set; } = "3";
 
                /// <summary>
                /// 创建时间
                /// </summary>
                public string addTime { get; set; }
 
                /// <summary>
                /// 创建设备
                /// </summary>
                public string addWho { get; set; }
 
                // ... UDF01-UDF10
            }
 
            /// <summary>
            /// 叠盘机交互响应
            /// </summary>
            public class PalletStackerInteractionResponse
            {
                public ResponseData Response { get; set; }
            }
 
        }
        public class modifyTaskPriority
        {
            /// <summary>
            /// 修改任务优先级请求
            /// </summary>
            public class ModifyTaskPriorityRequest
            {
                public ModifyTaskPriorityData data { get; set; }
            }
 
            public class ModifyTaskPriorityData
            {
                public List<ModifyTaskPriorityHeader> header { get; set; }
            }
 
            public class ModifyTaskPriorityHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 优先级 - 1-5(1最高)
                /// </summary>
                public string priority { get; set; }
            }
 
            /// <summary>
            /// 修改任务优先级响应(支持部分成功)
            /// </summary>
            public class ModifyTaskPriorityResponse
            {
                public ModifyTaskPriorityResponseData Response { get; set; }
            }
 
            public class ModifyTaskPriorityResponseData
            {
                [JsonProperty("return")]
                public ModifyTaskPriorityReturnInfo Return { get; set; }
            }
 
            public class ModifyTaskPriorityReturnInfo : ReturnInfo
            {
                /// <summary>
                /// 部分成功时的错误详情
                /// </summary>
                public List<TaskErrorInfo> resultInfo { get; set; }
            }
 
            public class TaskErrorInfo
            {
                /// <summary>
                /// 任务组编号
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 错误代码
                /// </summary>
                public string errorCode { get; set; }
 
                /// <summary>
                /// 错误原因
                /// </summary>
                public string errorDesc { get; set; }
            }
        }
        public class putConveyorTask
        {
            /// <summary>
            /// 输送线任务推送请求
            /// </summary>
            public class PutConveyorTaskRequest
            {
                public PutConveyorTaskData data { get; set; }
            }
 
            public class PutConveyorTaskData
            {
                public List<PutConveyorTaskHeader> header { get; set; }
            }
 
            public class PutConveyorTaskHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 任务组编号 - 主键
                /// </summary>
                public string groupTaskId { get; set; }
 
                /// <summary>
                /// 任务组序号 - 主键
                /// </summary>
                public int groupTaskSequence { get; set; }
 
                /// <summary>
                /// 箱号
                /// </summary>
                public string palletId { get; set; }
 
                /// <summary>
                /// 箱型 - 大箱/小箱/周转箱编码
                /// </summary>
                public string palletIdType { get; set; }
 
                /// <summary>
                /// 贴标标记 - Y:需要贴标, N:不需要
                /// </summary>
                public string syncFlag { get; set; }
 
                /// <summary>
                /// 目标区域/道口 - 物理位置道口编码或B2C复核台区域编码
                /// </summary>
                public string dLocation { get; set; }
 
                // ... UDF01-UDF10
            }
 
            /// <summary>
            /// 输送线任务推送响应(支持部分成功)
            /// </summary>
            public class PutConveyorTaskResponse
            {
                public PutConveyorTaskResponseData Response { get; set; }
            }
 
            public class PutConveyorTaskResponseData
            {
                [JsonProperty("return")]
                public PutConveyorTaskReturnInfo Return { get; set; }
            }
 
            public class PutConveyorTaskReturnInfo : ReturnInfo
            {
                /// <summary>
                /// 部分成功时的错误详情
                /// </summary>
                public List<TaskErrorInfo> resultInfo { get; set; }
            }
        }
        public class reportWeightinfo
        {
            public static Channel<ReportWeightInfoResponse> channel = Channel.CreateUnbounded<ReportWeightInfoResponse>();
 
            internal static async Task<ReportWeightInfoReturnInfo> GetChinnnl()
            {
                //var response = await reportWeightinfo.channel.Reader.ReadAllAsync();// foreach (var response in reportWeightinfo.channel.Reader.ReadAllAsync())
                //{
                //    return response?.Response?.Return ?? new ReportWeightInfoReturnInfo { ReturnCode = "0001", SortingChute = "0", ReturnDesc = "返回为空。" };
                //}
                while (await reportWeightinfo.channel.Reader.WaitToReadAsync(CancellationToken.None))
                {
                    while (reportWeightinfo.channel.Reader.TryRead(out var response))
                    {
                        return response?.Response?.Return ?? new ReportWeightInfoReturnInfo { returnCode = "0001", sortingChute = "0", returnDesc = "返回为空。" };
                    }
                }
                return new ReportWeightInfoReturnInfo { returnCode = "0001", sortingChute = "0", returnDesc = "返回为空。" };
            }
 
            /// <summary>
            /// 上报称重信息请求
            /// </summary>
            public class ReportWeightInfoRequest
            {
                public ReportWeightInfoData data { get; set; }
            }
 
            public class ReportWeightInfoData
            {
                public ReportWeightInfoHeader header { get; set; }
            }
 
            public class ReportWeightInfoHeader
            {
                /// <summary>
                /// 组织编号 - 主键,默认MERCURY
                /// </summary>
                public string organizationId { get; set; } = "MERCURY";
 
                /// <summary>
                /// 仓库编号 - 主键,默认HN02
                /// </summary>
                public string warehouseId { get; set; } = "HN02";
 
                /// <summary>
                /// 面单号 - 主键
                /// </summary>
                public string deliveryNo { get; set; }
 
                /// <summary>
                /// 重量(kg)
                /// </summary>
                public decimal grossWeight { get; set; }
 
                /// <summary>
                /// 体积(立方厘米)
                /// </summary>
                public decimal cube { get; set; }
 
                /// <summary>
                /// 创建时间
                /// </summary>
                public string addTime { get; set; }
 
                /// <summary>
                /// 创建设备
                /// </summary>
                public string addWho { get; set; }
 
                // ... UDF字段
            }
 
            /// <summary>
            /// 上报称重信息响应
            /// </summary>
            public class ReportWeightInfoResponse
            {
                public ReportWeightInfoResponseData Response { get; set; }
            }
 
            public class ReportWeightInfoResponseData
            {
                [JsonProperty("return")]
                public ReportWeightInfoReturnInfo Return { get; set; }
            }
 
            public class ReportWeightInfoReturnInfo : ReturnInfo
            {
                /// <summary>
                /// 分拣道口 - 输送线快速分拣道口编码
                /// </summary>
                public string sortingChute { get; set; }
            }
        }
 
    }
}
#endregion [自定义类-VS][20250701112200484][AutoThread]