qx
czw
2025-06-18 9862f9e1237c3d360cb4fb5547d8b11e33578d39
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
using HH.WCS.QingXigongchang.api;
using HH.WCS.QingXigongchang.core;
using HH.WCS.QingXigongchang.device;
using HH.WCS.QingXigongchang.process;
using HH.WCS.QingXigongchang.util;
using HH.WCS.QingXigongchang.wms;
using Microsoft.Owin.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
using Monitor = HH.WCS.QingXigongchang.core.Monitor;
 
namespace HH.WCS.QingXigongchang
{
    internal class Program
    {
        #region 关闭控制台 快速编辑模式、插入模式
        const int STD_INPUT_HANDLE = -10;
        const uint ENABLE_QUICK_EDIT_MODE = 0x0040;
        const uint ENABLE_INSERT_MODE = 0x0020;
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr GetStdHandle(int hConsoleHandle);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);
 
        public static void DisbleQuickEditMode()
        {
            IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);
            uint mode;
            GetConsoleMode(hStdin, out mode);
            mode &= ~ENABLE_QUICK_EDIT_MODE;//移除快速编辑模式
            mode &= ~ENABLE_INSERT_MODE;      //移除插入模式
            SetConsoleMode(hStdin, mode);
        }
        #endregion
        static void Main(string[] args)
        {
            string currentProcessName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(currentProcessName);
            if (processes.Length <= 1)
            {
                LogHelper.Info(">>>>>>>>>>>>>>>>>>> 程序启动<<<<<<<<<<<<<<<<<<<<<<<<");
                #region MyRegion
 
                //Monnn.StartMonitoring(2000);
                //object c = new object();
                //void CCT(int i)
                //{
                //    lock (c)
                //    {
                //        Console.WriteLine("cccccc" + i);
                //        Thread.Sleep(1000);
                //    }
                //}
                //for (int i = 0; i < 10; i++)
                //{
                //    CCT(i);
                //}
 
                //var set1 = new HashSet<string>("aaa,bbb,ccc".Split(','));
                //var set2 = new HashSet<string>("aaa,bbb,ccc,ddd".Split(','));
                //var set3 = new HashSet<string>("bbb,aaa,ccc".Split(','));
                //Console.WriteLine(set1.SetEquals(set2));
                //Console.WriteLine(set1.SetEquals(set3));
                #endregion
 
                var uuu16 = "TN" + (DateTime.Now.ToString("yy")) + ((6180010+ "").PadLeft(8, '0'));
                Console.WriteLine(uuu16);
            }
            else
            {
                Console.WriteLine("程序已经在运行,无法开启新的实例。");
                return;
            }
 
            //List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
            //foreach (var item in ints.GroupBy(x => (x + 1) / 2))
            //{
            //    Console.WriteLine(item.Key + ":::" + JsonConvert.SerializeObject(item.ToList()));
            //}
 
            //string avvv = "";
            //Encoding.UTF8.GetBytes(avvv);
 
            //List<string> strings = new List<string>() { "", "1", "" };
            //byte[] a = new byte[] { };
            //var _b = a.Skip(addr).Take(len).toarray();
 
            //_b.skip(_b.tolist().FindIndex(x => x > 0));
            //var a = Settings.GetDeviceInfoList()[2].taskPri;
 
            //string te = "成品-空托上线xiaoban";
            //var aa=Settings.GetDeviceInfoList();
 
            //    return true;
            //});
 
            //Dictionary<string, List<Location>> dsll = new Dictionary<string, List<Location>>();
            var List = new List<Location>();
            //dsll.Add("vvv", List);
            var List2 = new List<Location>();
            List.Add(new Location
            {
                S_LOC_CODE = "1-2",
                N_COL = 2,
                N_ROW = 1,
                N_CURRENT_NUM = 2
            });
 
            List.Add(new Location
            {
                S_LOC_CODE = "1-1",
                N_COL = 1,
                N_ROW = 1,
                N_CURRENT_NUM = 2
            });
 
            List.Add(new Location
            {
                S_LOC_CODE = "3-1",
                N_COL = 1,
                N_ROW = 3,
                N_CURRENT_NUM = 0
            });
 
            var 了 = (new Location
            {
                S_LOC_CODE = "2-2",
                N_COL = 2,
                N_ROW = 2,
                N_CURRENT_NUM = 1
            });
            List.Add(了);
            List2.Add(了);
            了.S_LOC_CODE = "2----2";
            //dsll.TryGetValue("vvv", out List<Location> ll);
 
            List.Add(new Location
            {
                S_LOC_CODE = "2-1",
                N_COL = 1,
                N_ROW = 2,
                N_CURRENT_NUM = 0
            });
 
            //Console.WriteLine(dsll);
            //var bbbc = List.OrderBy(x => x.N_COL).ThenBy(x => x.N_ROW).Skip(List.FindLastIndex(x => x.N_ROW == 3));//.Select(x => new { x.N_ROW, x.N_COL });
            //var bbb = List.GroupBy(x => x.N_ROW).OrderBy(x => x.ToList().FindAll(y => y.N_CURRENT_NUM > 0).Count);
            //Dictionary<string, int> map = new Dictionary<string, int>();
            //map.Add("1-2", -3);
            //map.Add("1-3", 3);
            //map.Add("1-4", 0);
            //map.Add("2-3", 2);
            //map.Add("2-4", 1);
            //map.Add("3-4", -2);
            //var _map = map.OrderBy(x => x.Value);
            //var _map2 = map.OrderBy(x => x.Value > 0);
            //var _map3 = map.OrderBy(x => x.Value).ThenBy(n => Math.Abs(n.Value)).ToArray();
            //var _map4 = map.OrderBy(x => Math.Abs(x.Value)).ThenBy(n => n.Value).ToArray();
            //var _map5 = map.OrderBy(x => x.Value >= 0).ThenBy(n => Math.Abs(n.Value)).ToArray();
            //foreach (var item in map)
            {
                //Console.WriteLine(item);
            }
            //var v = new string[] { "HS-12BHQ", "HS-C_XC", "1HS-C_XC", "QX-04_J", "QX-04_D", "QX04_J", "QX4_X", "QX-12_A", "QX-08_X", "QX-08_XC", "QX-08_DC" };
            //foreach (var item in v)
            //{
            //    var m = System.Text.RegularExpressions.Regex.IsMatch(item,@"^HS-[A-Z]+_");// @"QX-\d+_X$");
            //    if (m)
            //    {
            //        Console.WriteLine(m);
            //    }
            //    //if (m.Count > 0)
            //    //    foreach (System.Text.RegularExpressions.Match match in m)
            //    //    {
            //    //        Console.WriteLine(match.Value);
            //    //    }
            //}
            //Console.WriteLine("");
            //new WmsController().BindLoc3(new { loc = "PPMKCK=1-2", LineNo = "翻斗机", ItemCode = "550ml水_15入_膜包_6" });
            //var b = new List<Location>(List);
            //b.RemoveRange(0, 2);
            //var b = List.OrderBy(x => x.N_CURRENT_NUM).GroupBy(x => x.N_COL);
            //var a = TaskHelper.GetAgvTask(new WMSTask { S_TASK_NO = "WW0001" });
            //var 是 = Settings.GetDoorOneToMany();
 
 
            //SuGGAttribute.attributes = new Dictionary<string, string>();
            #region 获取表配置
            int tableCount = 0;
            LogHelper.Info("开始加载表配置信息");
            try
            {
                var jsonFile = System.AppDomain.CurrentDomain.BaseDirectory + "\\TableSetting.json";
                if (!File.Exists(jsonFile))
                {
                    LogHelper.Error("获取json文件失败!原因:这个json文件就不存在,有个屁的值,\n 你去看看这个路径有没有文件→:【" + jsonFile + "】", new FileLoadException("没有表配置文件"));
                    Console.ReadKey();
                }
                using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject o = (JObject)JToken.ReadFrom(reader);
                        foreach (Newtonsoft.Json.Linq.JProperty keyValue in o.Properties())
                        {
                            string value = keyValue.Value.ToString();
                            if (string.IsNullOrEmpty(value))
                            {
                                LogHelper.Error("【" + keyValue.Name.Trim() + "】" + "表配置表名为空!", new ArgumentException("表名为空"));
                                Console.ReadKey();
                            }
                            SuGGAttribute.attributes.Add(keyValue.Name.Trim(), value);
                            tableCount++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("加载表配置文件失败!" + ex.Message, ex);
                Console.ReadKey();
            }
            if (tableCount == 0)
            {
                LogHelper.Error("加载到0个表配置信息。", new Exception("加载表配置文件失败!"));
                Console.ReadKey();
            }
            #endregion
            #region 测试代码区域。 
 
            //LocationHelper.DoAction(db =>
            //{
            //    var S_CNTRS = "FTP2312050001vTP2312050002";
            //    var fulectlist = LocationHelper.GetFuLeTrayCodeList(f => S_CNTRS.Contains(f.trayCode.Trim()));
            //    LogHelper.Info("Fu成品取货" + S_CNTRS + "--<>--" + JsonConvert.SerializeObject(fulectlist));
            //    //foreach (var item in fulectlist)
            //    //{
            //    //    item.SQL_State = "完成";
            //    //    db.Updateable<FuLeTrayCode>(item).UpdateColumns(it => new { it.SQL_State }).ExecuteCommand();
            //    //}
            //    if (fulectlist.Any())
            //        db.Updateable<FuLeTrayCode>(fulectlist).ReSetValue(it => { it.SQL_State = "完成" }).ExecuteCommand();
            //    return true;
            //});
 
            //var l = LocationHelper.GetAllLocList().First();
            //var b = l.S_LOC_CODE;
            //LocationHelper.lOCReSetValue(x => x.S_LOC_CODE == b, lo =>
            //{
            //    lo.S_LOCK_STATE = "出库锁";
            //});
 
            //l = LocationHelper.GetAllLocList().First();
            //b = l.S_LOCK_STATE;
            //LocationHelper.lOCReSetValue(x => x.S_LOC_CODE.Trim() == l.S_LOC_CODE, y =>
            //{
            //    y.N_CURRENT_NUM++;
            //});
            //var c = LocationHelper.GetAllLocList().First();
            //var d = c.N_CURRENT_NUM;
 
 
            //var asasd = Settings.GetInStockCacheList();
            //var locs = LocationHelper.GetAllLocList();
            //var b = locs.OrderBy(x => x.N_COL).ThenBy(x => x.N_ROW).GroupBy(x => x.N_COL).ToList();
            //foreach (var item in b)
            //{
            //    var _collocs = item.ToList();
            //}
            //var l = LocationHelper.GetAllLocList();
            #endregion
 
            //关闭 快速编辑、插入模式
            DisbleQuickEditMode();
 
            #region 即产 铁塑  非即产 铁塑
            //Container c_tie = ContainerHelper.GetContainer(x => x.S_CNTR_CODE == "UsNow2347" && x.S_TYPE == "铁筐");
            //if (c_tie == null)
            //{
            //    LocationHelper.DoAction(db =>
            //    {
            //        var res = db.Insertable<Container>(new Container
            //        {
            //            S_CNTR_CODE = "UsNow2347",
            //            S_TYPE = "铁筐",
            //        }).ExecuteCommand() > 0;
            //        return res;
            //    });
            //}
            //c_tie = ContainerHelper.GetContainer(x => x.S_CNTR_CODE == "UsAfter2347" && x.S_TYPE == "塑料筐");
            //if (c_tie == null)
            //{
            //    LocationHelper.DoAction(db =>
            //    {
            //        var res = db.Insertable<Container>(new Container
            //        {
            //            S_CNTR_CODE = "UsAfter2347",
            //            S_TYPE = "塑料筐",
            //        }).ExecuteCommand() > 0;
            //        return res;
            //    });
            //}
            // 即+tmesapn
            #endregion
 
 
            {
                //PlcHelper.Receive("10.140.3.196", "3f0011");
 
                if (true)
                {
                    Task task = null;
                    var ips = "";
                    var host = Dns.GetHostEntry(Dns.GetHostName());
                    foreach (var ip in host.AddressList)
                    {
                        if (ip.AddressFamily == AddressFamily.InterNetwork)
                        {
                            Console.WriteLine($"ip= {ip.ToString()}");
                            ips = ip.ToString();
                            break;
                        }
                    }
                    if (true)
                        Task.Run(() =>
                        {
                            // 设置监听的端口和地址
                            int port = 8908;
                            string url = $"http://{ips}:" + port + "/";
 
                            // 创建一个新的 HttpListener
                            HttpListener listener = new HttpListener();
                            listener.Prefixes.Add(url);
 
                            // 开始监听
                            listener.Start();
                            Console.WriteLine("HTTP服务器已启动:" + url);
 
                            while (true)
                            {
                                // 等待客户端连接
                                HttpListenerContext context = listener.GetContext();
                                HttpListenerRequest request = context.Request;
                                HttpListenerResponse response = context.Response;
 
                                // 读取请求内容并输出到控制台
                                Stream body = request.InputStream;
                                StreamReader reader = new StreamReader(body, request.ContentEncoding);
                                string content = reader.ReadToEnd();
                                Console.WriteLine("收到请求: " + content + ">" + request.Url);
                                // 获取请求的文件路径
                                string filePath = request.Url.AbsolutePath.Substring(1).ToLower();
                                var file = false;
                                // 检查请求的文件类型并返回相应的静态文件
                                if (filePath.Contains(".js") || filePath.Contains(".css") || filePath.Contains(".ico"))
                                {
                                    file = true;
                                    filePath = Path.Combine("Static", filePath);
                                    //response.ContentType = "text/javascript";
                                }
                                //else if (filePath.EndsWith(".css"))
                                //{
                                //    file = true;
                                //    filePath = Path.Combine("Static", filePath);
                                //    //response.ContentType = "text/css";
                                //}
                                else if (string.IsNullOrEmpty(filePath))
                                {
                                    file = true;
                                    filePath = Path.Combine("Static", "index.html");
                                    response.ContentType = "text/html";
 
                                    // 设置响应内容和状态码
                                    //byte[] buffer = File.ReadAllBytes(Path.Combine("Static", "W.html")); ;//
                                    //buffer = System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(Path.Combine("Static", "W.html")));
 
                                    //response.ContentLength64 = buffer.Length;
                                    //response.OutputStream.Write(buffer, 0, buffer.Length);
                                    //response.ContentType = "text/html";
                                    //response.StatusCode = 200;
                                    //response.OutputStream.Close();
                                }
                                else
                                {
                                    response.StatusCode = 404;
                                    var bt = Encoding.UTF8.GetBytes("地址无效!");
                                    response.OutputStream.Write(bt, 0, bt.Length);
                                    response.OutputStream.Close();
                                }
                                //// 读取文件内容并发送给客户端
                                if (file)
                                    try
                                    {
                                        //byte[] buffer = File.ReadAllBytes(filePath);
                                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(filePath));
                                        response.ContentLength64 = buffer.Length;
                                        response.OutputStream.Write(buffer, 0, buffer.Length);
                                        response.StatusCode = 200;
                                    }
                                    catch (FileNotFoundException ex)
                                    {
                                        response.StatusCode = 404;
                                        response.OutputStream.Write(Encoding.UTF8.GetBytes("文件未找到"), 0, Encoding.UTF8.GetBytes("文件未找到").Length);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    finally
                                    {
                                        response.OutputStream.Close();
                                    }
                            }
                        });
 
                    Task.Run(() =>
                    {
                        var httpListener = new HttpListener();
                        httpListener.Prefixes.Add($"http://{ips}:8181/");
                        httpListener.Start();
                        Console.WriteLine($"WebSocket Listening on http://{ips}:8181/");
 
                        while (true)
                        {
                            var context = httpListener.GetContext();
                            if (context.Request.IsWebSocketRequest)
                            {
                                ProcessRequest(context);
                            }
                        }
                    });
                }
                // 要执行的 C# 代码字符串
                //        string code = @"
                //    int Add(int a, int b, int c)
                //    {
                //        return a + b + c;
                //    }
                //    Add(a, b, c);
                //";
 
                //        // 定义参数
                //        var gg = new tempClass();
                //        gg.a = 5;
                //        gg.b = 10;
                //        gg.c = 15;
 
                //        try
                //        {
                //            // 执行代码并获取结果
                //            var result = CSharpScript.Create<int>(code, ScriptOptions.Default, typeof(tempClass)).RunAsync(gg);
                //            result.Wait();
                //            Console.WriteLine($"Result: {result.Result}");
                //        }
                //        catch (CompilationErrorException e)
                //        {
                //            Console.WriteLine("Compilation Errors:");
                //            foreach (var diagnostic in e.Diagnostics)
                //            {
                //                Console.WriteLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
                //            }
                //        }
                //        catch (Exception e)
                //        {
                //            Console.WriteLine($"Execution Error: {e.Message}");
                //        }
 
                ////string code1 = @"
                ////public class ScriptedClass
                ////{
                ////    public string HelloWorld { get; set; }
                ////    public ScriptedClass()
                ////    {
                ////        HelloWorld = ""Hello Roslyn!"";
                ////    }
 
                ////}";
 
                ////var script = CSharpScript.RunAsync(code1).Result;
 
                ////var result = script.ContinueWithAsync<string>("new ScriptedClass().HelloWorld").Result;
 
                ////Console.WriteLine(result.ReturnValue);
 
                //var loc = new Location
                //{
                //    S_LOC_CODE = "2-1",
                //    N_COL = 1,
                //    N_ROW = 2,
                //    N_CURRENT_NUM = 0
                //};
                //string code = @"int result = 1 + 2; Console.WriteLine(result);if (S_LOC_CODE==""2-1"")return true; else return false;";
                //var options = ScriptOptions.Default.WithImports("System");
                //var script1 = CSharpScript.Create<bool>(code, options, typeof(Location));
                //var v = script1.RunAsync(loc);
                //v.Wait();
                //Console.WriteLine(v.Result.ReturnValue);
                //code = @"int result = 1 + 2; return new tempClass().Good(S_LOC_CODE);";
                //options = ScriptOptions.Default.WithImports("System");
                //var script2 = CSharpScript.Create(code, options.WithReferences(typeof(tempClass).Assembly), typeof(Location));
                //var v2 = script2.RunAsync(loc);
                //v2.Wait();
                //Console.WriteLine(v.Result.ReturnValue);
 
 
 
                //Console.SetWindowSize(120, 36);
                //Console.SetBufferSize(120, 36);
                //Console.Title = "清溪 wcs程序控制总台";
                //Console.CursorVisible = false;
                //Console.SetCursorPosition(0, 0);
                //Console.WriteLine("根目录" + System.Environment.CurrentDirectory);
                //Console.WriteLine("系统目录" + System.Environment.SystemDirectory);
                //Console.WriteLine("该进程的命令行" + System.Environment.CommandLine);
                //Console.WriteLine("获取此本地计算机的 NetBIOS 名称。" + System.Environment.MachineName);
                //Console.WriteLine("获取当前计算机上的处理器数" + System.Environment.ProcessorCount);
                //Console.WriteLine("一个包含平台标识符和版本号的对象" + System.Environment.OSVersion);
                //Console.WriteLine("获取为此环境定义的换行字符串。" + System.Environment.NewLine);
                //Console.WriteLine("获取当前登录用户" + System.Environment.UserName);
                //Console.WriteLine("获取一个值,用以指示当前进程是否在用户交互模式中运行" + System.Environment.UserInteractive);
                //Console.WriteLine("获取与当前用户关联的网络域名。" + System.Environment.UserDomainName);
                //Console.WriteLine("获取系统启动后经过的毫秒数" + System.Environment.TickCount);
                //Console.WriteLine("获取当前的堆栈跟踪信息。" + System.Environment.StackTrace);
                //Console.WriteLine(" 获取映射到进程上下文的物理内存量。" + System.Environment.WorkingSet);
                //Console.WriteLine("用于显示公共语言运行时版本的对象" + System.Environment.Version);
                //Console.WriteLine("从当前进程检索环境变量的值" + System.Environment.GetEnvironmentVariable("Path"));
                //Console.WriteLine("从当前进程检索环境变量的值" + System.Environment.GetEnvironmentVariables());
                //Console.WriteLine("从当前进程或者从当前用户或本地计算机的 Windows 操作系统注册表项检索所有环境变量名及其值" + System.Environment.GetEnvironmentVariables());
                //Console.WriteLine("返回桌面的路径" + System.Environment.GetFolderPath(SpecialFolder.Desktop));
                //Console.SetCursorPosition(0, 0);
 
                //for (int i = 0; i < 15; i++)
                //{
                //    Console.WriteLine(i + "···················································");
                //}
 
                //for (int i = 0; i < 6; i++)
                //{
                //    Console.SetCursorPosition(2, i * 2);
                //    Console.WriteLine("vv");
                //    Thread.Sleep(1000);
                //}
 
            }
 
 
 
            //LocationHelper.DoAction(db =>
            //{
            //    //var a = db.Queryable<Location>().Includes(aa => aa.LocCntrRels).Where(x => x.S_LOC_CODE == "PGKQ-03-10").ToList();
 
            //    //var a = db.Queryable
            //ContainerHelper.GetCntrItemRel
 
 
 
            //1.0 开启api
            Startup();
            //2.0 开启tcp
            StartTcp();
 
            //LocationHelper.DoAction(db =>
            //{
            //    var c = db.Queryable<CntrItemRel>().Where(a => a.S_CNTR_CODE.Contains("TP" + Settings._TPcc)).OrderByDescending(x => x.T_CREATE).ToList().FirstOrDefault();
            //    LogHelper.Info("托盘初始化1- " + c?.S_CNTR_CODE);
            //    if (c != null)
            //    {
            //        string tp = c.S_CNTR_CODE.Split('v')[0];
            //        var t = tp.Split('_')[0];
            //        Settings._TPnum = Convert.ToInt32(t.Substring(8));
            //    }
            //    LogHelper.Info("托盘初始化2- " + Settings._TPnum);
            //    return true;
            //});
            //3.0 开启线程
            var rc = HostFactory.Run(x =>
            {
                x.Service<WorkThread>(s =>
                {
                    s.ConstructUsing(name => new WorkThread());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();
 
                x.SetDescription("hh");
                x.SetDisplayName("hh.wms");
                x.SetServiceName("hh.wms");
 
            });
 
            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;
        }
 
 
 
        private static async void ProcessRequest(HttpListenerContext context)
        {
            var webSocketContext = await context.AcceptWebSocketAsync(null);
            var webSocket = webSocketContext.WebSocket;
 
            while (webSocket.State == WebSocketState.Open)
            {
                var buffer = new ArraySegment<byte>(new byte[1024]);
                var received = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
 
                if (received.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                }
                else
                {
                    string read = Encoding.UTF8.GetString(buffer.Array).TrimEnd('\0');
                    if (read != "reLoad")
                    {
                        Console.WriteLine("WebSocket Request Received   " + read);
                        await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Connection opened")), WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    else
                    {
                        // Echo the message back to the client                       
                        //await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(DeviceProcess.Deviceooo))), WebSocketMessageType.Text, true, CancellationToken.None);
                        //if (!DeviceProcess.Deviceooo.Any())
                        //{
                        //    DeviceProcess.Deviceooo.Add("192.168.1.1", new
                        //    {
                        //        产线号 = "ccc1",
                        //        富勒产线号 = "plc.FuLeLineNo",
                        //        设备号 = new List<string> { "","66"},
                        //        设备类型 = "plc.deviceType",
                        //        货位 = new List<string> { "","22233"},
                        //        任务权重 = "plc.taskPri",
                        //        信号 = "3f0010210d0a",
                        //    });
                        //    DeviceProcess.Deviceooo.Add("192.168.1.2", new
                        //    {
                        //        产线号 = "ccc12",
                        //        富勒产线号 = "plc.FuLeLineNo2",
                        //        设备号 = "plc.deviceNo2",
                        //        设备类型 = "plc.deviceTyp2e",
                        //        货位 = "plc.location2",
                        //        任务权重 = "plc.taskPri2",
                        //        信号 = "3f0010210d0a",
                        //    });
                        //}
 
                        await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(DeviceProcess.Deviceooo))), WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                }
            }
        }
        private static void Startup()
        {
            Task.Run(() =>
            {
                var url = "http://+:8801";//{SettingHelper.port}
            restart:
                try
                {
                    using (WebApp.Start<Startup>(url))
                    {
                        Console.WriteLine("API Running on {0}", url);
                        while (true)
                            Thread.Sleep(int.MaxValue);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Thread.Sleep(1000);
                }
                Console.WriteLine("API - 终止");
                goto restart;
            });
            //Console.WriteLine("Startup ApiController");
            //Action action = () =>
            //{
            //    var url = "http://+:8801";//{SettingHelper.port}
            //    using (WebApp.Start<Startup>(url))
            //    {
            //        Console.WriteLine("Running on {0}", url);
            //        Console.ReadLine();
            //    }
            //    Console.WriteLine("API - 终止");
            //};
            //Task task = Task.Run(action);
            //Action action1 = () =>
            //{
            //    while (true)
            //    {
            //        if (task.IsCanceled || task.IsCompleted || task.IsFaulted)
            //        {
            //            Console.WriteLine("API - 线程中断,重启重启。");
            //            task = Task.Run(action);
            //        }
            //        Thread.Sleep(1000);
            //    }
            //};
            //Task.Run(action1);
        }
        private static void StartTcp()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    Console.WriteLine($"ip= {ip.ToString()}");
                    new TcpServer(ip.ToString());
                }
            }
        }
 
        public class WorkThread
        {
            public void Start()
            {
                List<Task> tasks = new List<Task>
                {
                    GetTask(Monitor.A),//计数器  清除 控制台
                    //添加任务推送线程
                    GetTask(TaskCore.Dispatch),
                    GetTask(TaskCore.Kuronggg),
 
                    GetTask(TaskCore.ChargeHostAgv),
                    //手动转运
                    GetTask(Monitor.BottleCapAuto2),
                    /// 自动转运
                    GetTask(Monitor.BottleCapAuto3, 1),
                    //锁排 - 清除  排空了才解锁。 
                    GetTask(Monitor.BottleCapAuto4),
                    //自动领料 - 上输送线 
                    GetTask(Monitor.BottleCapAuto5),
                    //空框中转,转拆框
                    GetTask(Monitor.BottleCapAuto6),
                    //出库单批分
                    GetTask(Monitor.BottleCapAuto7),
                    //自动中转
                    GetTask(Monitor.BB7),
                    //原材料 自动中转 - 展示流程。 前期测试用的
                    //GetTask(Monitor.AutoRun),
                    GetTask(Monitor.YwlTKPEBQ_Auto),//标签无菌水线出入库。
                    //原材料的 新中转流程。 
                    GetTask(Monitor.YWL_ZX_Turn),
                    GetTask(Monitor.BottTask),// 纸箱自动中转
                    GetTask(Monitor.AutoRunABD),
                    GetTask(Monitor.AutoRun13TSJ),
 
                    //GetTask(Monitor.AutoTK_PE),//提扣 - PE膜出入库
                    //GetTask(Monitor.chargeCCD),//YWL 入库工单。未使用。
                    //GetTask(Monnn.StartMonitoring),
 
                    //tasks.Add(GetTask(DeviceProcess.WJGInoutEF));
 
                    /// 水盖同。  入库人工解,  出入从出库位转 550 出入库。 5L 
                    /* - - 重做瓶盖流程。 不使用入库了
                    //水盖也入库
                    GetTask(DeviceProcess.TakeNotUsing2WH),
                    GetTask(DeviceProcess.TakeNotUsing2FDJXB),
                    GetTask(DeviceProcess.TakeEmpty2WH),
                    GetTask(DeviceProcess.TakeNotUsing2PGXB)
                    */
                };
 
 
 
                //tasks.Add(GetTask(DeviceProcess.TakeNotUsing2PGJ));/// 水盖空框, 无菌空框  放 TakeNotUsing2FDJXB 一起了
 
                //上线区   出库满框空了  区框  - 仓库先进显出。 同列 先进后出
 
                //翻斗机 取空 送满   (即产 取上线即产满区    非即产 取出库满区)
 
                //翻斗机  取满 ,按列 从右往左取 - 
                //tasks.Add(GetTask(Monitor.TipperAuto));
                //电梯
                //tasks.Add(GetTask(Monitor.ElevatorTask));
                //电梯
                //tasks.Add(GetTask(Monitor.OutGo));
 
                Task.WaitAll(tasks.ToArray());
            }
            public void Stop() { Console.WriteLine("work stopped"); }
            private Task GetTask(Action action, int i = 0)
            {
                var task = Task.Run(() =>
                {
                    while (true)
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(ex.Message, ex);
                            if (i == 1)
                                Monitor.AutoTurn = 0;
                        }
                        Thread.Sleep(2500);
                    }
                });
                return task;
            }
        }
    }
 
    public class tempClass
    {
        public int a;
        public int b;
 
        public int c { get; set; }
 
        public string Good(string a)
        {
            if (a == "2-1")
                return "oooooooooo";
            return a;
        }
    }
}