schangxiang@126.com
2025-11-04 f5ed29dc26c7cd952d56ec5721a2efc43cd25992
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
using DataEntity.Share;
using DataEntity.Sockets.Base;
using HxEnum;
using HxSocketImplement.Sockets.HxService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XCommon.Event;
using XCommon.Log;
using XImagingXhandler.XDAL;
using static HxEnum.OperationTypeEnum;
using static HxEnum.SocketS.InfoTypeEnum;
using static HxEnum.StateEnum;
 
namespace HxSocketImplement.Sockets
{
    /// <summary>
    /// 内部服务Socket 服务端
    /// </summary>
    public class SocketInteriorService
    {
        #region 默认参数 
        private static Thread threadReceive = null;             // 接收客户端发送消息的线程       
        private static Thread threadWatch = null;               // 负责监听客户端的线程
        public static Socket socketWatch = null;        // 负责监听客户端的套接字
        public static Socket clientConnection = null;   // 负责和客户端通信的套接字
 
        // 使用令牌取消线程: 从.NET 5 开始,以下 API(Thread.Abort) 被标记为过时 使用CancellationToken中止工作单元的处理,而不是调用Thread.Abort
        static CancellationTokenSource cts = null;
        // wdy
        //public static System.Windows.Forms.ListView listView = new System.Windows.Forms.ListView();
 
        /// <summary>
        /// 实验状态 key:实验ID,value:线程启停控制 
        /// </summary>
        public static Dictionary<string, ManualResetEvent> dicManualResetEvent = new Dictionary<string, ManualResetEvent>();
        #endregion
 
        #region 开启服务端监听
        /// <summary>
        /// 开启服务端监听
        /// </summary>
        public static void OpenService()
        {
            cts = new CancellationTokenSource();
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  // AddressFamily地址类型,SocketType套接字类型,ProtocolType协议类型;
            IPAddress iP = IPAddress.Parse(Shared.SoftwareInformation.ip);                              // 创建对象端口 (这里为ip类型地址)
            IPEndPoint point = new IPEndPoint(iP, Convert.ToInt32(Shared.SoftwareInformation.port));    // 初始化IP及端口号
            socketWatch.Bind(point);                                                                    // 绑定端口
            socketWatch.Listen(20);                                                                     // 开启监听(参数代表排队等待连接的最大数量,不包含已连接数量)0表示无限
 
            threadWatch = new Thread(Listen); //创建监听线程
            threadWatch.IsBackground = true;
            threadWatch.Start();
        }
        #endregion
 
        #region 监听
        /// <summary>
        /// 监听
        /// </summary>
        public static void Listen()
        {
            try
            {
                // 持续不断监听客户端发来的请求
                while (!cts.IsCancellationRequested)
                {
                    clientConnection = socketWatch.Accept();
 
                    // wdy
                    //AddListView(new ListViewModel
                    //{
                    //    Type = "客-》连接",
                    //    Port = clientConnection.RemoteEndPoint.ToString(),
                    //    receive_parameter = "",
                    //    send_parameter = "",
                    //    createtime = DateTime.Now.ToString()
                    //});
 
                    // 创建一个通信线程
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(Received);
                    threadReceive = new Thread(pts);
                    threadReceive.IsBackground = true;
                    threadReceive.Start(clientConnection);
                }
            }
            catch (Exception ex)
            {
                LoggerSocketHelper.ErrorLog($"监听Listen失败:{ex.Message}");
            }
        }
        #endregion
 
        #region 服务器端不停的接收客户端发来的消息
        /// <summary>
        /// 服务器端不停的接收客户端发来的消息
        /// </summary>
        /// <param name="socket"></param>
        public static void Received(object socket)
        {
            try
            {
                //客户端连接服务器成功后,服务器接收客户端发送的消息
                Socket socketSend = socket as Socket;
                while (!cts.IsCancellationRequested)
                {
                    object lockObject = new object();
                    lock (lockObject)
                    {
                        //创建一个内存缓冲区 其大小为1024*1024字节  即3M
                        byte[] buffer = new byte[1024 * 1024 * 3];
                        //实际接收到的有效字节数
                        int len = socketSend.Receive(buffer);
                        if (len == 0)
                        {
                            // wdy
                            //AddListView(new ListViewModel
                            //{
                            //    Type = "客-》断开",
                            //    Port = socketSend.RemoteEndPoint.ToString(),
                            //    receive_parameter = "",
                            //    send_parameter = "",
                            //    createtime = DateTime.Now.ToString()
                            //});
                            break;
                        }
 
                        string msg = Encoding.UTF8.GetString(buffer, 0, len);
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            var msgList = msg.Split(new string[] { CommonParameter.SpecifiedDisplay }, StringSplitOptions.None);
 
                            foreach (var item in msgList)
                            {
                                var receiveData = JsonConvert.DeserializeObject<HxSendBase>(item);
                                if (receiveData != null && !string.IsNullOrWhiteSpace(receiveData.method))
                                {
                                    #region Del
                                    //AddListView(new ListViewModel
                                    //{
                                    //    Type = "接收-》客-》消息",
                                    //    Port = socketSend.RemoteEndPoint.ToString(),
                                    //    receive_parameter = msg,
                                    //    send_parameter = "",
                                    //    createtime = DateTime.Now.ToString()
                                    //});
                                    #endregion
 
                                    //HxClientResponseObject hxClientResponseObject = new HxClientResponseObject();
                                    //hxClientResponseObject.ResponseBase = new HxResponseBase
                                    //{
                                    //    message_id = receiveData.message_id,
                                    //    message_type = receiveData.message_type,
                                    //    method = receiveData.method,
                                    //    equipment_id = receiveData.equipment_id,
                                    //    workflow_id = receiveData.workflow_id,
                                    //    experiment_id = receiveData.experiment_id,
                                    //    data = null,
                                    //    method_status = EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed),
                                    //    timestamp = DateTime.Now.ToString(),
                                    //    error = null,
                                    //};
 
                                    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(receiveData.method)}指令【开始执行】------");
 
                                    #region Del
                                    //switch (EnumManagement.ToEnum<InfoTypeEnum_Enum>(receiveData.method))
                                    //{
                                    //    case InfoTypeEnum_Enum.SendHeartbeatConnect:   //发送心跳连接(接收到客户端发来的消息)
                                    //        #region 回复消息  
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    Task.Run(() =>
                                    //        //    {
                                    //        //        //to do
                                    //        //        LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.SendHeartbeatConnect)}指令【成功】------");
                                    //        //    });
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.SendServiceData:   //客户端向服务端发送数据(接收到客户端发来的消息)
                                    //        #region 回复消息+处理逻辑 
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    Task.Run(() =>
                                    //        //    {
                                    //        //        //to do
                                    //        //        LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.SendServiceData)}指令【成功】------");
                                    //        //    });
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.SuspendExperiment:   //暂停实验(接收到客户端发来的消息)
                                    //        #region 回复消息+暂停实验 
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    //Task.Run(() =>
                                    //        //    //{
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError = new InstructCommonMethodSendModel();
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError.SendData = new HxSendBase();
                                    //        //    //    EventBind.OperMark = new NodeOperationTypeEnum();// ExpOperationTypeEnum.ExpOperationTypeBEnum;
                                    //        //    //    Upt_DicTestState(scfm.SendData.experiment_id, ProcessTypeColorEnum_Equipment.OrangeColor, InfoTypeEnum_Enum.SuspendExperiment, ProcessLogicTypeEnum_Equipment.NoType);
                                    //        //    //    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.SuspendExperiment)}指令【成功】------");
                                    //        //    //});
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.ContinueExperiment:   //继续(跳过)实验
                                    //        #region 回复消息+继续实验 
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    //Task.Run(() =>
                                    //        //    //{
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError = new InstructCommonMethodSendModel();
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError.SendData = new HxSendBase();
                                    //        //    //    EventBind.OperMark = new NodeOperationTypeEnum();// ExpOperationTypeEnum.ExpOperationTypeBEnum;
                                    //        //    //    ErrorStateDB.Continue(scfm.SendData.experiment_id, StatusEnum.StatusCEnum, NodeOperationTypeEnum.Continue);
 
                                    //        //    //    Upt_DicTestState(scfm.SendData.experiment_id, ProcessTypeColorEnum_Equipment.GreenColor, InfoTypeEnum_Enum.ContinueExperiment, ProcessLogicTypeEnum_Equipment.NoType);
                                    //        //    //    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.ContinueExperiment)}指令【成功】------");
                                    //        //    //});
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.SysErrorRetry:   //系统报错后重试
                                    //        #region 系统报错后重试   
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    //Task.Run(() =>
                                    //        //    //{
                                    //        //    //    //新的参数重新赋值 
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(JsonConvert.SerializeObject(scfm.SendData.parameters));
                                    //        //    //    EventBind.OperMark = NodeOperationTypeEnum.Retry;
 
                                    //        //    //    ErrorStateDB.Continue(scfm.SendData.experiment_id, StatusEnum.StatusCEnum, NodeOperationTypeEnum.Retry);
 
                                    //        //    //    LoggerSocketHelper.DebugLog("运行方法【InfoTypeEnum_Enum.SysErrorRetry】重试参数" + JsonConvert.SerializeObject(scfm.SendData.parameters));
 
                                    //        //    //    Upt_DicTestState(scfm.SendData.experiment_id, ProcessTypeColorEnum_Equipment.GreenColor, InfoTypeEnum_Enum.ContinueExperiment, ProcessLogicTypeEnum_Equipment.NoType);
                                    //        //    //    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.SysErrorRetry)}指令【成功】------");
                                    //        //    //});
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.TerminationExperiment:   //终止实验
                                    //        #region 回复消息+终止实验
                                    //        //if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //{
                                    //        //    //Task.Run(() =>
                                    //        //    //{
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError = new InstructCommonMethodSendModel();
                                    //        //    //    ResultHandle.instructCommonMethodSendModelByError.SendData = new HxSendBase();
                                    //        //    //    EventBind.OperMark = new NodeOperationTypeEnum();// ExpOperationTypeEnum.ExpOperationTypeBEnum;
 
                                    //        //    //    ErrorStateDB.Continue(scfm.SendData.experiment_id, StatusEnum.StatusFEnum, NodeOperationTypeEnum.Cancel);
 
                                    //        //    //    Upt_DicTestState(scfm.SendData.experiment_id, ProcessTypeColorEnum_Equipment.BlueColor, InfoTypeEnum_Enum.TerminationExperiment, ProcessLogicTypeEnum_Equipment.NoType);
                                    //        //    //    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.TerminationExperiment)}指令【成功】------");
                                    //        //    //});
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.StartExperiment:   //启动实验(接收到客户端发来的消息)
                                    //        #region 回复消息+启动实验 
                                    //        //int count = dicManualResetEvent.Where(m => m.Key == scfm.SendData.experiment_id).Count();
                                    //        //if (count == 0)
                                    //        //{
                                    //        //    Task.Run(() =>
                                    //        //    {
                                    //        //        dicManualResetEvent.Add(scfm.SendData.experiment_id, new ManualResetEvent(true));
                                    //        //        var resultExp = InstructMethod.ImplementFlow(scfm.SendData.experiment_id);
                                    //        //        if (resultExp)
                                    //        //        {
                                    //        //            LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.StartExperiment)}指令【成功】------");
                                    //        //            ReplyClientMsg(socketSend, hxClientResponseObject);
                                    //        //        }
                                    //        //        else
                                    //        //        {
                                    //        //            LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.StartExperiment)}指令【失败】------");
                                    //        //        }
                                    //        //    });
                                    //        //}
                                    //        //else
                                    //        //{
                                    //        //    Upt_DicTestState(scfm.SendData.experiment_id, ProcessTypeColorEnum_Equipment.GreenColor, InfoTypeEnum_Enum.ContinueExperiment, ProcessLogicTypeEnum_Equipment.NoType);
                                    //        //    LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.StartExperiment)}指令(统计为0)【成功】------");
                                    //        //}
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.DebuggingBySocket:   //客户端Socket调试
                                    //        #region 客户端Socket调试  
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var model = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(scfm.SendData.parameters.ToString());
                                    //        //    var resultInstructCommonMethod = ResultHandle.InstructCommonMethod(model);
                                    //        //    string debuggingMsg = $"{EnumManagement.GetFieldText(InfoTypeEnum_Enum.DebuggingBySocket)}指令";
 
                                    //        //    if (resultInstructCommonMethod != null && resultInstructCommonMethod.status == EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed))
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【成功】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    else
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【失败】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    ReplyClientMsg(socketSend, hxClientResponseObject);
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.DebuggingByModbus:   //客户端Modbus调试
                                    //        #region 客户端Modbus调试  
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var model = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(scfm.SendData.parameters.ToString());
 
                                    //        //    int countDebuggingByModbus = dicManualResetEvent.Where(m => m.Key == scfm.SendData.experiment_id).Count();
                                    //        //    if (countDebuggingByModbus == 0)
                                    //        //    {
                                    //        //        dicManualResetEvent.Add(scfm.SendData.experiment_id, new ManualResetEvent(true));
                                    //        //    }
                                    //        //    var resultInstructCommonMethod = ResultHandle.InstructCommonMethod(model);
                                    //        //    string debuggingMsg = $"{EnumManagement.GetFieldText(InfoTypeEnum_Enum.DebuggingByModbus)}指令";
                                    //        //    if (resultInstructCommonMethod != null && resultInstructCommonMethod.status == EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed))
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【成功】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    else
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【失败】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    ReplyClientMsg(socketSend, hxClientResponseObject);
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.DebuggingBySocketNonstandard:   //客户端SocketNonstandard调试
                                    //        #region 客户端SocketNonstandard调试  
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var model = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(scfm.SendData.parameters.ToString());
                                    //        //    var resultInstructCommonMethod = ResultHandle.InstructCommonMethod(model);
                                    //        //    string debuggingMsg = $"{EnumManagement.GetFieldText(InfoTypeEnum_Enum.DebuggingBySocketNonstandard)}指令";
 
                                    //        //    if (resultInstructCommonMethod != null && resultInstructCommonMethod.status == EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed))
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【成功】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    else
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【失败】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    ReplyClientMsg(socketSend, hxClientResponseObject);
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.DebuggingBySerialPort:   //客户端DebuggingBySerialPort调试
                                    //        #region 客户端DebuggingBySerialPort调试  
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var model = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(scfm.SendData.parameters.ToString());
                                    //        //    var resultInstructCommonMethod = ResultHandle.InstructCommonMethod(model);
                                    //        //    string debuggingMsg = $"{EnumManagement.GetFieldText(InfoTypeEnum_Enum.DebuggingBySerialPort)}指令";
 
                                    //        //    if (resultInstructCommonMethod != null && resultInstructCommonMethod.status == EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed))
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【成功】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    else
                                    //        //    {
                                    //        //        hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(resultInstructCommonMethod.msg) };
                                    //        //        LoggerSocketHelper.DebugLog($"------{debuggingMsg}【失败】,返回内容:{JsonConvert.SerializeObject(resultInstructCommonMethod)}{",发送参数:" + JsonConvert.SerializeObject(scfm)}------");
                                    //        //    }
                                    //        //    ReplyClientMsg(socketSend, hxClientResponseObject);
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.CheckDeviceConnectState:   //检查设备连接状态
                                    //        #region 检查设备连接状态 
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var getCheckDeviceConnectStateModel = EquConnect.GetCheckDeviceConnectState();
                                    //        //    hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(getCheckDeviceConnectStateModel) };
                                    //        //    if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //    {
                                    //        //        LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.CheckDeviceConnectState)}指令【成功】------");
                                    //        //    }
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.EquipmentStatus:   //设备状态(是否忙碌  1空闲、2忙碌)
                                    //        #region 检查设备连接状态  
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var getEquipmentStatus = SocketParameterModel.Dic_EquipmentStatus;
                                    //        //    hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(getEquipmentStatus) };
                                    //        //    if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //    {
                                    //        //        LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.EquipmentStatus)}指令【成功】------");
                                    //        //    }
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.ServiceConnect:   //服务连接
                                    //        #region 服务连接   
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    var getServiceConnect = EquConnect.ConnectService();
                                    //        //    hxClientResponseObject.ResponseBase.dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(getServiceConnect) };
                                    //        //    if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //    {
                                    //        //        LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.ServiceConnect)}指令【成功】------");
                                    //        //    }
                                    //        //});
                                    //        #endregion
                                    //        break;
                                    //    case InfoTypeEnum_Enum.EquipmentPointSyncData:   //设备点位数据同步
                                    //        #region 设备点位数据同步   
                                    //        //Task.Run(() =>
                                    //        //{
                                    //        //    if (ReplyClientMsg(socketSend, hxClientResponseObject))
                                    //        //    {
                                    //        //        #region 执行命令  
                                    //        //        if (!string.IsNullOrWhiteSpace(scfm.SendData.experiment_id))
                                    //        //        {
                                    //        //            var deviceConfigModel = new DeviceConfigBLL().GetInfodById(scfm.SendData.experiment_id);
                                    //        //            if (deviceConfigModel != null)
                                    //        //            {
                                    //        //                //InstructCommonMethodSendModel instructCommonMethodSendModel = HxSocketParameterService.GetInstructCommonMethodSendModel(new InstructCommonMethodSendModel()
                                    //        //                //{
                                    //        //                //    EquipmentType = deviceConfigModel.Type,
                                    //        //                //    Ip = deviceConfigModel.Ip,
                                    //        //                //    Port = Convert.ToInt32(deviceConfigModel.Port),
                                    //        //                //    EquipmentId = deviceConfigModel.EquipmentId,
                                    //        //                //    SendData = new HxSendBase { experiment_id = HxSockServiceExecute.InstrunctionId(), parameters = "{}", method = "TrySyncAreas" },   //这个方法要写死,不然,前端也不知道传哪个。这个驱动接口他们都是写死的。
 
                                    //        //                //});
                                    //        //                //var resultEquipmentPointSyncData = ResultHandle.InstructCommonMethod(instructCommonMethodSendModel);
                                    //        //                //if (resultEquipmentPointSyncData != null && resultEquipmentPointSyncData.status == EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed))
                                    //        //                {
                                    //        //                    var areasList = new Robot_AreasBLL().GetAreasALL();
                                    //        //                    if (areasList != null && areasList.Count > 0)
                                    //        //                    {
                                    //        //                        foreach (var m in areasList)
                                    //        //                        {
                                    //        //                            var deviceconfigPointList = new DeviceConfigPointBLL().GetDeviceconfigPoint(new DeviceconfigPointModelSearchModel { DeviceconfigId = deviceConfigModel.Id, PointName = m.AreaName });
                                    //        //                            if (deviceconfigPointList == null || deviceconfigPointList.Count <= 0)
                                    //        //                            {
                                    //        //                                DeviceconfigPointModel deviceconfigPointModel = new DeviceconfigPointModel();
                                    //        //                                deviceconfigPointModel.Id = Guid.NewGuid().ToString();
                                    //        //                                deviceconfigPointModel.ProjectId = SharedServiceModel.ServiceConfigModel.Id;
                                    //        //                                deviceconfigPointModel.DeviceconfigId = deviceConfigModel.Id;
                                    //        //                                deviceconfigPointModel.Name = m.Description;
                                    //        //                                deviceconfigPointModel.PointName = m.AreaName;
                                    //        //                                deviceconfigPointModel.Remark = "数据同步" + DateTime.Now;
                                    //        //                                deviceconfigPointModel.CreateTime = DateTime.Now;
                                    //        //                                deviceconfigPointModel.CreatName = "系统同步";
                                    //        //                                var addResult = new DeviceConfigPointBLL().Add(deviceconfigPointModel);
                                    //        //                                LoggerSocketHelper.DebugLog($"------{EnumManagement.GetFieldText(InfoTypeEnum_Enum.EquipmentPointSyncData)}指令【成功】------");
                                    //        //                            }
                                    //        //                        }
                                    //        //                    }
                                    //        //                }
                                    //        //            }
                                    //        //        }
                                    //        //        #endregion
                                    //        //    }
                                    //        //});
                                    //        #endregion
                                    //        break;
 
                                    //    default:
                                    //        break;
                                      
                                    //}
                                    #endregion
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerSocketHelper.ErrorLog($"Received 出错:{ex.Message}" + ex);
            }
        }
        #endregion
 
        #region 修改实验状态字典
        /// <summary>
        /// 修改实验状态字典
        /// </summary>
        /// <param name="expId">实验ID</param>
        /// <param name="processType">处理类型颜色枚举(0不处理,1橙色,2蓝色,3绿色,4红色)</param>
        /// <param name="infotypeEnumType">实验状态</param>
        /// <param name="processLogicType">处理类型(0不处理,1处理)</param>
        public static void Upt_DicTestState(string expId, ProcessTypeColorEnum_Equipment processType, InfoTypeEnum_Enum infotypeEnumType, ProcessLogicTypeEnum_Equipment processLogicType)
        {
            LoggerSocketHelper.DebugLog($"========================== 实验ID:{expId}状态更改:{EnumManagement.GetFieldText(infotypeEnumType)}, 处理类型颜色枚举={EnumManagement.GetFieldText(processType)}, 处理类型={EnumManagement.GetFieldText(processLogicType)} ========================== ");
            
            int count = dicManualResetEvent.Where(m => m.Key == expId).Count();
            if (count == 0)
            {
                dicManualResetEvent.Add(expId, new ManualResetEvent(true));
            }
 
            #region 三色灯
            ProcessTypeColorSet(processType);
            #endregion
 
            if (EnumManagement.GetEnumValue(infotypeEnumType) == EnumManagement.GetEnumValue(InfoTypeEnum_Enum.SuspendExperiment) ||
                EnumManagement.GetEnumValue(infotypeEnumType) == EnumManagement.GetEnumValue(InfoTypeEnum_Enum.TerminationExperiment))    //暂停+终止
            {
                if (EnumManagement.GetEnumValue(infotypeEnumType) == EnumManagement.GetEnumValue(InfoTypeEnum_Enum.SuspendExperiment))    //暂停 
                {
                    if (processLogicType == ProcessLogicTypeEnum_Equipment.YesType)
                    {
                        //暂停 业务逻辑(比如蜂鸣器开打,业务逻辑也可以写在三色灯里面)
                    }
                }
                else if (EnumManagement.GetEnumValue(infotypeEnumType) == EnumManagement.GetEnumValue(InfoTypeEnum_Enum.TerminationExperiment))   //终止
                {
                    if (processLogicType == ProcessLogicTypeEnum_Equipment.YesType)
                    {
                        //终止 业务逻辑(比如蜂鸣器开打,业务逻辑也可以写在三色灯里面)
                    }
                }
 
                dicManualResetEvent[expId].Reset();   //堵塞线程
            }
            else if (EnumManagement.GetEnumValue(infotypeEnumType) == EnumManagement.GetEnumValue(InfoTypeEnum_Enum.ContinueExperiment))     //继续
            {
                if (processLogicType == ProcessLogicTypeEnum_Equipment.YesType)
                {
                    //继续 业务逻辑(比如蜂鸣器关闭,业务逻辑也可以写在三色灯里面)
                }
 
                dicManualResetEvent[expId].Set();   //继续线程
            }
        }
 
        /// <summary>
        /// 处理类型颜色枚举
        /// </summary>
        /// <param name="processType">颜色枚举(0不处理,1橙色,2蓝色,3绿色,4红色)</param>
        private static void ProcessTypeColorSet(ProcessTypeColorEnum_Equipment processType)
        {
            //#region 调用底层控制(DEMO)
            //InstructCommonMethodSendModel instructCommonMethodSendModel = HxSocketParameterService.GetInstructCommonMethodSendModel(new InstructCommonMethodSendModel()
            //{
            //    EquipmentType = getDeviceConfigModel.Type.Trim(),
            //    Ip = getDeviceConfigModel.Ip.Trim(),
            //    Port = Convert.ToInt32(getDeviceConfigModel.Port.Trim()),
            //    EquipmentId = getDeviceConfigModel.EquipmentId.Trim(),
            //    VirtualConnectionState = getDeviceConfigModel.VirtualConnectionState,
            //    CommunicateType = getDeviceConfigModel.CommunicateType,
            //    SendData = new HxSendBase { experiment_id = HxSockServiceExecute.InstrunctionId(), parameters = dictionaryList, method = getDeviceConfigMethod.ParameterName },
            //});
            ////var model = JsonConvert.DeserializeObject<InstructCommonMethodSendModel>(scfm.SendData.parameters.ToString());
            //var resultInstructCommonMethod = ResultHandle.InstructCommonMethod(instructCommonMethodSendModel);
            //#endregion
 
            #region 三色灯
            switch (EnumManagement.ToEnum<ProcessTypeColorEnum_Equipment>(processType.ToString()))
            {
                case ProcessTypeColorEnum_Equipment.OrangeColor:
                    // 状态5 暂停 黄色
                    //MethodAction.Instance.StatusLamp(5);
                    //CommonBll.StatusLamp(5, isSimulator);
                    break;
                case ProcessTypeColorEnum_Equipment.BlueColor:
                    // 状态1 链接成功 蓝亮
                    //MethodAction.Instance.StatusLamp(1);
                    break;
                case ProcessTypeColorEnum_Equipment.GreenColor:
                    // 状态4 运行 绿色
                    //MethodAction.Instance.StatusLamp(4);
                    break;
                case ProcessTypeColorEnum_Equipment.RedColor:
                    // 状态6 报错/急停 红闪/蜂鸣5S
                    //MethodAction.Instance.StatusLamp(6);
                    break;
 
                default:
                    break;
            }
            #endregion
        }
        #endregion
 
        #region 发送信息
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="msg">内容</param>
        /// <returns></returns>
        public static bool SendMessage(HxClientResponseObject model)
        {
            if (clientConnection != null && clientConnection.Connected)
            {
                byte[] sendMsg = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model.ResponseBase) + CommonParameter.SpecifiedDisplay);
                var result = clientConnection.Send(sendMsg);
                if (result > 0)
                {
                    // wdy
                    //AddListView(new ListViewModel
                    //{
                    //    Type = "服-》发送信息",
                    //    Port = clientConnection.RemoteEndPoint.ToString(),
                    //    receive_parameter = "",
                    //    send_parameter = JsonConvert.SerializeObject(model),
                    //    createtime = DateTime.Now.ToString()
                    //});
                    LoggerSocketHelper.DebugLog("运行方法【SendMessage】消息送出成功");
                    return true;
                }
                else
                {
                    // wdy
                    //AddListView(new ListViewModel
                    //{
                    //    Type = "服-》发送信息失败",
                    //    Port = clientConnection.RemoteEndPoint.ToString(),
                    //    receive_parameter = "",
                    //    send_parameter = JsonConvert.SerializeObject(model),
                    //    createtime = DateTime.Now.ToString()
                    //});
                    LoggerSocketHelper.DebugLog("运行方法【SendMessage】消息未送出");
                    return false;
                }
            }
            else
            {
                LoggerSocketHelper.DebugLog("运行方法【SendMessage】断开");
                return false;
            }
        }
        #endregion
 
        #region 停止服务端监听
        /// <summary>
        /// 停止服务端监听
        /// </summary>
        /// <returns></returns>
        public static bool BreakConnect()
        {
            if (socketWatch != null)
            {
                // wdy
                //AddListView(new ListViewModel
                //{
                //    Type = "服-》停止监听",
                //    Port = $"{SharedServiceModel.ServiceConfigModel.Ip}:{SharedServiceModel.ServiceConfigModel.Port}",
                //    receive_parameter = "",
                //    send_parameter = "",
                //    createtime = DateTime.Now.ToString()
                //});
 
                cts.Cancel();//终止线程 
                if (clientConnection != null && clientConnection.Connected)
                {
                    clientConnection.Shutdown(SocketShutdown.Both);     // 禁用发送和接收
                    clientConnection.Close();                           // 关闭同客户端的连接
                }
                socketWatch.Close();                                    // 关闭监听套节字
                return true;
            }
            else
            {
                // wdy
                //AddListView(new ListViewModel
                //{
                //    Type = "服-》停止监听",
                //    Port = clientConnection.RemoteEndPoint.ToString(),
                //    receive_parameter = "",
                //    send_parameter = "网络未连接",
                //    createtime = DateTime.Now.ToString()
                //});
            }
            return false;
        }
        #endregion
 
        #region 添加列表数据
        /// <summary>
        /// 添加列表数据  wdy
        /// </summary>
        /// <param name="listView"></param>
        /// <param name="lvm"></param>
        //public static void AddListView(ListViewModel lvm)
        //{
        //    int noCount = listView.Items.Count;
        //    ListViewItem lvi = new ListViewItem((noCount <= 0 ? noCount + 1 : noCount + 1).ToString());
        //    lvi.SubItems.Add(lvm.Type);
        //    lvi.SubItems.Add(lvm.Port);
        //    lvi.SubItems.Add(lvm.receive_parameter);
        //    lvi.SubItems.Add(lvm.send_parameter);
        //    lvi.SubItems.Add(lvm.createtime);
        //    listView.Items.Add(lvi);
 
        //    LoggerSocketHelper.DebugLog("服务端日志,添加显示到列表数据:" + JsonConvert.SerializeObject(lvm));
        //}
        #endregion 
 
        #region 回复客户端信息
        /// <summary>
        /// 回复客户端信息
        /// </summary>
        /// <param name="socketSend">socket</param>
        /// <param name="hxClientResponseObject">返回数据</param>
        /// <returns></returns>
        public static bool ReplyClientMsg(Socket socketSend, HxClientResponseObject hxClientResponseObject)
        {
            #region 回复消息  
            string sendStr = JsonConvert.SerializeObject(hxClientResponseObject.ResponseBase) + CommonParameter.SpecifiedDisplay;
            byte[] sendMsg = Encoding.UTF8.GetBytes(sendStr);
            int result = socketSend.Send(sendMsg);
            if (result > 0)
            {
                // wdy
                //SocketInteriorService.AddListView(new ListViewModel
                //{
                //    Type = "发送-》服-》消息",
                //    Port = socketSend.RemoteEndPoint.ToString(),
                //    receive_parameter = "",
                //    send_parameter = sendStr,
                //    createtime = DateTime.Now.ToString()
                //});
                return true;
            }
            #endregion
 
            return false;
        }
        #endregion
 
        #region 发送前端信息提示 
        /// <summary>
        /// 发送前端信息提示
        /// </summary>
        /// <param name="expId">流程ID</param>
        /// <param name="methodName">方法名称</param>
        /// <param name="methodStatus">方法状态</param>
        /// <param name="msgContent">消息内容</param>
        /// <returns></returns>
        public static bool SendMessagePrompt(string expId, string methodName, StateEnum_Equipment methodStatus, DealWithType_Enum dealwithtype, string msgContent)
        {
            InstructCommonMethodSendModel instructCommonMethodSendModel = new InstructCommonMethodSendModel();
            instructCommonMethodSendModel.SendData = new HxSendBase { experiment_id = expId };
 
            HxClientResponseObject hxClientResponseObject = new HxClientResponseObject();
            hxClientResponseObject.ResponseBase = new HxResponseBase
            {
                message_id = expId,
                message_type = 2,
                method = methodName,
                equipment_id = "",
                workflow_id = "workflow_id_" + expId + "_" + methodName,
                experiment_id = "experiment_id_" + expId,
                dataResult = new DataResult { ResultJson = JsonConvert.SerializeObject(instructCommonMethodSendModel) },
                method_status = EnumManagement.GetEnumValue(methodStatus),// EnumManagement.GetEnumValue(StateEnum.StateEnum_Equipment.Completed),
                timestamp = DateTime.Now.ToString(),
                error = new ErrorResult { error_text = msgContent, dealwithtype = EnumManagement.GetEnumValue(dealwithtype).ToString() },
            };
            var sendData = SocketInteriorService.SendMessage(hxClientResponseObject);
            return sendData;
        }
        #endregion
    }
}