MainWindow.xaml.cs 47.5 KB
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
using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Microsoft.Win32;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using RCS.Model.Entity;
using RCS.Model.PLC;
using RCS.WinClient.Common;
using RCS.WinClient.PLC;
using RCS.WinClient.Service;
using RCS.WinClient.TCP;
using RCS.WinClient.Views.Pages;
using RCS.WinClient.WebApi.Client;
using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;


namespace RCS.WinClient.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }



        #region 缩放、滚动相关

        public double Zoom = 0.5;

        private Point? DownPoint;

        private readonly double MaxZoom = 5;

        private readonly double MinZoom = 0.5;

        Point DefaultPoint = new(165, 145);
        double DefaultZoom = 0.5;
        TranslateTransform Transform = new();
        RotateTransform RotateTransform = new();
        TransformGroup TransformGroup = new();
        #endregion
        private Thread thSocket;
        private Thread thTaskOperator;
        private Thread thTaskIot;
        private Thread thDataMaintain;
        private Socket? SvrSocket;
        private Sharp canvasSharp = new Sharp();

        private WinTaskManager winTaskManager;
        private WinTest winTest;
        private WinOrganization winOrganization;
        private WinParameter winParameter;
        private WinHistoryTask winHistoryTask;
        private Task _task;
        //private System.Timers.Timer taskTimer = new System.Timers.Timer();

        //private List<SiemensS7Net> S7NetList = new List<SiemensS7Net>();
        //private List<KeyenceMcNet> keyenceList = new List<KeyenceMcNet>();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //Thread.Sleep(1000 * 20);
            App.Canvas_Monit = Canvas_Monitor;
            App.AppDispatcher = Dispatcher;
            //设置全屏
            Width = SystemParameters.PrimaryScreenWidth;
            Height = SystemParameters.WorkArea.Height;
            Left = (SystemParameters.PrimaryScreenWidth - Width) / 2;
            Top = (SystemParameters.WorkArea.Height - Height) / 2;
            #region 缩放事件
            //缩放事件
            this.Canvas_Monitor.RenderTransformOrigin = new Point(0.5, 0.5);
            Transform = new TranslateTransform(DefaultPoint.X, DefaultPoint.Y);
            //Canvas_Monitor.RenderTransform = Transform;
            //Canvas_Monitor.RenderTransform = RotateTransform;
            //TransformGroup transformGroup = new TransformGroup();
            TransformGroup.Children.Add(Transform);
            TransformGroup.Children.Add(RotateTransform);
            Canvas_Monitor.RenderTransform = TransformGroup;
            Canvas_Monitor.LayoutTransform = new ScaleTransform(0.5, 0.5);
            MouseTool.CallbackErroeHandle += (IntPtr wParam, Mouse_LL_Hook_Data mhd) =>
            {
                System.Diagnostics.Debug.WriteLine($"mouse event:{wParam}, ({mhd.yx & 0xffffffff},{mhd.yx >> 32})");
                if (wParam == MouseTool.WM_LBUTTONUP)
                    DownPoint = null;
            };
            MouseTool.InsertErrorHandle += (int error) =>
            {
                MessageBox.Show($"Failed to install global mouse hook. Error code: {error}");
            };
            #endregion

            //初始化数据库数据
            var result = Init.InitData();
            if (!result.IsSuccess)
            {
                ComnMethod.Message(result.Message);
                App.ExFile.MessageError("Window_Loaded", result.Message);
                //Environment.Exit(0);
            }

            if (App.PointList.Count != 0)
            {
                int[] Area = canvasSharp.MoniterAreaInit();
                Canvas_Monitor.Width = Area[0];
                Canvas_Monitor.Height = Area[1];
                try
                {
                    //设置货架位置
                    canvasSharp.ShelfSet();
                    canvasSharp.AgvPointSet();
                    canvasSharp.PointSet();
                    canvasSharp.TextTostring();
                    canvasSharp.DrawMapLine(App.PointList);
                }
                catch (Exception ex)
                {
                    ComnMethod.Message(ex.ToString());
                }
            }

            DGrid_Agv.ItemsSource = App.AgvList.OrderBy(a => a.AgvNo);

            //开启webapi通讯接口
            thSocket = new Thread(StartWebApi);
            thSocket.IsBackground = true;
            thSocket.Start();

            if (result.IsSuccess)
            {
                #region PLC处理
                if (App.EquipmentList.Count > 0)
                {
                    // 开始执行PLC处理
                    result = EquipmentExecutor.Instance.StartExcute();
                    if (!result.IsSuccess)
                    {
                        ComnMethod.Message(result.Message);
                        App.ExFile.MessageError("Window_Loaded", result.Message);
                        return;
                    }

                    //显示各类设备的PLC交互信号监控
                    thTaskOperator = new Thread(PLCInfo);
                    thTaskOperator.IsBackground = true;
                    thTaskOperator.Start();

                    //用来监听输送线请求入库
                    //thTaskOperator = new Thread(CallContainer);
                    //thTaskOperator.IsBackground = true;
                    //thTaskOperator.Start();
                }
                #endregion

                //和AGV通讯
                thSocket = new Thread(SocketBuild);
                thSocket.IsBackground = true;
                thSocket.Start();

                //任务处理
                thTaskOperator = new Thread(TaskOperator);
                thTaskOperator.IsBackground = true;
                thTaskOperator.Start();

                //异常数据处理

                UpdateManage.UpdateAgvErrorToDB();
                ////数据维护
                //thDataMaintain = new Thread(DataMaintain);
                //thDataMaintain.IsBackground = true;
                //thDataMaintain.Start();

                //任务提交、任务完成、充电
                //TaskTimer();
            }

        }

        #region 任务回传

        ///// <summary>
        ///// 定时器
        ///// </summary>
        //private void TaskTimer()
        //{
        //    //开启一个定时器,定时去执行任务。
        //    taskTimer.Interval = 2000; //间隔时间
        //    taskTimer.Elapsed += AgvTaskFinish;
        //    taskTimer.AutoReset = true;
        //    taskTimer.Enabled = true;
        //}

        ///// <summary>
        ///// 找出【动作完成】且【信号未发送】的子任务,然后向上游系统发送数据,成功后更新子任务状态为【信号已发送】
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void AgvTaskFinish(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    lock (new object())
        //    {
        //        if (stop_Tasktimer)
        //        {
        //            try
        //            {
        //                stop_Tasktimer = false;
        //                BaseDal<Base_SubTask> _sonTask = new BaseDal<Base_SubTask>();
        //                //子任务完成请求wcs确认是否进行下步动作
        //                var taskList = App.TaskList.Where(a =>  a.SubTaskList.Count != 0 && 
        //                                                        a.SubTaskList[0].TaskRequestType < EnumMsg.TaskRequestType.信号发送完成 && 
        //                                                        a.SubTaskList[0].SubTaskState == EnumMsg.SubTaskState.动作完成).ToList();
        //                for (var i = 0; i < taskList.Count(); i++)
        //                {
        //                    var task = taskList[i];
        //                    var agv = App.AgvList.Find(a => a.AgvNo == task.TaskAgvNo);
        //                    var station = App.StationList.Find(a => a.PreBarcode == agv.Barcode);
        //                    var sonTask = taskList[i].SubTaskList[0];
        //                    var agvState = 0;
        //                    if (agv.AgvType == EnumMsg.AgvType.差速)
        //                    {
        //                        if (sonTask.SubTaskType == EnumMsg.AgvTaskType.上升到顶)
        //                        {
        //                            //agvState = 20;
        //                        }
        //                        else if (sonTask.SubTaskType == EnumMsg.AgvTaskType.下降到底)
        //                        {
        //                            agvState = 100;
        //                        }
        //                    }
        //                    else if (agv.AgvType == EnumMsg.AgvType.舵轮)
        //                    {
        //                        agvState = (int)sonTask.TaskRequestType;
        //                    }
        //                    ////如果舵轮车型在不需要的交互的地方,直接完成
        //                    //if ((task.Initial.Contains("存放") && sonTask.SerialNo < 5)
        //                    //    || (task.Target.Contains("存放") && sonTask.SerialNo > 5))
        //                    //{
        //                    //    sonTask.TaskRequestType = EnumMsg.TaskRequestType.信号发送完成;
        //                    //    continue;
        //                    //}

        //                    #region 测试环境注释 任务回传接口
        //                    //向上游系统发送信息【AGV任务回传】
        //                    var returnState = WebApiClient.ToAcsWebApiTaskState(taskList[i], agvState);
        //                    if (!returnState.Success)
        //                    {
        //                        App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{returnState.Msg}\r");
        //                        continue;
        //                    }
        //                    App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{(int)sonTask.TaskRequestType}\r");
        //                    #endregion

        //                    //var curTaskRequestType = (int)sonTask.TaskRequestType + 5;
        //                    var updateresult0 = _sonTask.Update(it => it.SubTaskNo == sonTask.SubTaskNo, 
        //                                                              it => new Base_SubTask()
        //                                                              {
        //                                                                    //TaskRequestType = (EnumMsg.TaskRequestType)curTaskRequestType,
        //                                                                    SubTaskState = EnumMsg.SubTaskState.信号已发送
        //                                                              });
        //                    if (!updateresult0.Success) continue;
        //                    sonTask.SubTaskState = EnumMsg.SubTaskState.信号已发送;
        //                    //sonTask.TaskRequestType = (EnumMsg.TaskRequestType)curTaskRequestType;
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{ex.Message}\n{ex.StackTrace}\r");
        //            }
        //            finally
        //            {
        //                stop_Tasktimer = true;
        //                Thread.Sleep(5000);
        //            }
        //        }
        //    }
        //    #region MyRegion
        //    //try
        //    //{
        //    //    BaseDal<Base_SubTask> _sonTask = new BaseDal<Base_SubTask>();
        //    //    //子任务完成请求wcs确认是否进行下步动作
        //    //    var taskList = App.TaskList.Where(a => a.SubTaskList.Count != 0 && a.SubTaskList[0].SubTaskState ==
        //    //                                               EnumMsg.SubTaskState.动作完成
        //    //                                               && (int)a.SubTaskList[0].TaskRequestType < 101).ToList();
        //    //    for (var i = 0; i < taskList.Count(); i++)
        //    //    {
        //    //        var task = taskList[i];
        //    //        var agv = App.AgvList.Find(a => a.AgvNo == task.TaskAgvNo);
        //    //        var station = App.StationList.Find(a => a.PreBarcode == agv.Barcode);
        //    //        var sonTask = taskList[i].SubTaskList[0];
        //    //        var agvState = 0;
        //    //        if (agv.AgvType == EnumMsg.AgvType.差速)
        //    //        {
        //    //            if (sonTask.SubTaskType == EnumMsg.AgvTaskType.顶升)
        //    //            {
        //    //                //agvState = 20;
        //    //            }
        //    //            else if (sonTask.SubTaskType == EnumMsg.AgvTaskType.下降)
        //    //            {
        //    //                agvState = 100;
        //    //            }
        //    //        }
        //    //        else if (agv.AgvType == EnumMsg.AgvType.舵轮)
        //    //        {
        //    //            agvState = (int)sonTask.TaskRequestType;
        //    //        }
        //    //        //如果舵轮车型在不需要的交互的地方,直接完成
        //    //        if ((task.Initial.Contains("存放") && sonTask.SerialNo < 5)
        //    //            || (task.Target.Contains("存放") && sonTask.SerialNo > 5))
        //    //        {
        //    //            sonTask.TaskRequestType = EnumMsg.TaskRequestType.信号发送完成;
        //    //            continue;
        //    //        }
        //    //        //更新AGV搬运进度
        //    //        var returnState = WebApiClient.ToAcsWebApiTaskState(taskList[i], agvState);
        //    //        if (!returnState.Success)
        //    //        {
        //    //            App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{returnState.Msg}\r");
        //    //            continue;
        //    //        }
        //    //        App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{(int)sonTask.TaskRequestType}\r");

        //    //        var curTaskRequestType = (int)sonTask.TaskRequestType + 5;
        //    //        var updateresult0 = _sonTask.Update(it => it.SubTaskNo == sonTask.SubTaskNo, it => new Base_SubTask()
        //    //        {
        //    //            TaskRequestType = (EnumMsg.TaskRequestType)curTaskRequestType,
        //    //            SubTaskState = EnumMsg.SubTaskState.信号已发送
        //    //        });
        //    //        if (!updateresult0.Success) continue;
        //    //        sonTask.SubTaskState = EnumMsg.SubTaskState.信号已发送;
        //    //        sonTask.TaskRequestType = (EnumMsg.TaskRequestType)curTaskRequestType;
        //    //    }
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    App.ExFile.MessageWebApi("AcsWebApiError", $"接口(AgvTaskFinish),{ex.Message}\n{ex.StackTrace}\r");
        //    //}
        //    #endregion
        //}

        #endregion

        /// <summary>
        /// 开启web通讯接口
        /// </summary>
        private void StartWebApi()
        {
            try
            {
                var builder = WebApplication.CreateBuilder();

                builder.Services.AddControllers();
                builder.Services.AddEndpointsApiExplorer();
                // 添加 CORS 策略
                builder.Services.AddCors(options =>
                {
                    options.AddPolicy("default", policy =>
                    {
                        policy.AllowAnyOrigin()
                              .AllowAnyMethod()
                              .AllowAnyHeader();
                    });
                });
                builder.Services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "RCSAPI", Version = "v1" });

                    // 添加XML注释,如果你想要Swagger UI显示注释  
                    //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    //options.IncludeXmlComments(xmlPath);

                    // 其他设置,比如添加认证、授权、过滤器等  
                });

                var app = builder.Build();

                app.UseCors("default");

                app.Urls.Add(App.AppConfig.RcsWebApi);


                // 启用Swagger中间件生成JSON文件  
                app.UseSwagger();

                // 启用Swagger UI中间件  
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "RCSAPI V1");

                    // 你可以设置默认打开的文档,比如:  
                    c.RoutePrefix = string.Empty; // 设置路由前缀为空,Swagger UI将直接显示在根路径下  
                });

                app.MapControllers();

                app.UseRouting();
                app.UseAuthorization();

                //_ = app.UseEndpoints(endpoints =>
                //{
                //    endpoints.MapControllers();
                //});

                Console.WriteLine("Application started, listening on: " + string.Join(", ", app.Urls));
                app.Run();

                #region 全面的写法,暂时先不用
                //var builder = WebApplication.CreateBuilder();
                //// Add services to the container.
                //builder.Services.AddSingleton(new Appsettings(builder.Configuration));
                //builder.AddSerilog();
                //builder.Services.AddCorsSetup();
                //builder.Services.AddSignalR().AddNewtonsoftJsonProtocol();

                //builder.Services.AddHostedService<HubClientService>();
                //builder.Services.AddHostedService<SoundService>();

                //builder.Services.Configure<KestrelServerOptions>(builder.Configuration.GetSection("Kestrel"));
                //builder.Services.AddControllers();

                //var app = builder.Build();
                //// Configure the HTTP request pipeline.
                ////跨域
                //app.UseCors("Cors");
                //app.UseDefaultFiles();
                //// 启用默认静态资源目录(wwwroot)
                //app.UseStaticFiles();
                //var baseDirec = Path.Combine(AppContext.BaseDirectory, "webfile");
                //if (!Directory.Exists(baseDirec)) Directory.CreateDirectory(baseDirec);
                //app.UseFileServer(new FileServerOptions()
                //{
                //    FileProvider = new PhysicalFileProvider(baseDirec),
                //    RequestPath = new PathString("/webfile"),
                //    EnableDirectoryBrowsing = false
                //});
                //app.UseStatusCodePages();
                //app.UseRouting();

                //app.UseEndpoints(endpoints =>
                //{
                //    endpoints.MapHub<ChatHub>("/hub");
                //    endpoints.MapControllers();
                //});
                //app.Run();
                #endregion

            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("StartWebApi", $"开放接口异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
            }
        }

        /// <summary>
        /// Socket通讯
        /// </summary>
        private void SocketBuild()
        {
            if (SvrSocket != null)
            {
                SvrSocket.Close();
                SvrSocket = null;
            }
            try
            {
                //用指定的端口号和服务器的ip建立一个IPEndPoint对象
                var ip = IPAddress.Parse(App.AppConfig.ServiceIP);
                var ipe = new IPEndPoint(IPAddress.Any, App.AppConfig.ServicePort);
                //创建一个用于监听连接的Socket对象
                SvrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //用socket对象的Bind()方法绑定IPEndPoint;
                SvrSocket.Bind(ipe);
                ManageTcp.ServerListen(App.ServerConactNum, SvrSocket);
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("SocketBuild", $"创建AGV监听线程异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
                Thread.Sleep(1000 * 3);
                thSocket = new Thread(SocketBuild);
                thSocket.IsBackground = true;
                thSocket.Start();
            }
        }

        /// <summary>
        /// 任务处理
        /// </summary>
        private void TaskOperator()
        {
            try
            {

                while (true)
                {
                    //任务分解
                    TaskManage.TaskSplit();
                    //给任务分配AGV
                    TaskManage.AgvGetTask();
                    //解锁充电桩
                    ComnMethod.UnLockStation();
                    //清理点位的AGV锁定
                    ComnMethod.ClearPointOccupy();
                    //清理点位的方向锁
                    ComnMethod.ClearPointDirection();
                    ////为路径卡住,无法分配路线的车增加一条行走子任务,来避让
                    //TaskManage.AvoidSubTask();
                    //分配路径
                    GetPath.AssignePath();

                    ////建立回家、充电任务
                    ChargeManager.AgvCharge();

                    #region 测试任务

                    if (App.RadomTaskConfig.IsStartRadom)
                    {
                        var diff = App.RadomTaskConfig.Concurrency - App.TaskList.Count;
                        for (int i = 0; i < diff; i++)
                        {
                            TaskManage.AddRadomTasks(null, App.RadomTaskConfig.TaskTypes, true);
                        }
                    }
                    //简易版取消充电
                    //Business.TaskManage.ChargeCancle();
                    //调用WCS补空货架
                    //Business.TaskManage.PlatformListen();
                    //建立回库任务
                    //Business.TaskManage.MoveBack();
                    //建立循环行走任务
                    //if (App.StartCycle == 1)
                    //{
                    //    TaskManage.WalkTask();
                    //}
                    //if (App.RotateTask == 1)
                    //{
                    //    Business.TaskManage.RotateTask();
                    //}
                    //if (App.LiftTask == 1)
                    //{
                    //    Business.TaskManage.LiftTask();
                    //}
                    //if (App.PalletTask == 1)
                    //{
                    //    Business.TaskManage.PalletTask();
                    //}

                    #endregion 测试任务

                    //判断心跳
                    ComnMethod.CheckAgvOnline();
                    //发送IOT数据
                    //if (_task == null || _task.Status >= TaskStatus.RanToCompletion)
                    //{
                    //    _task = Task.WhenAll(Task.Run(WebApiClient.UpdateClientStatus), Task.Run(WebApiClient.SendAGVInfoToIot));
                    //}
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("TaskOperator", $"任务处理线程异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
                thTaskOperator = new Thread(TaskOperator);
                thTaskOperator.IsBackground = true;
                thTaskOperator.Start();
            }
        }

        /// <summary>
        /// 数据维护
        /// </summary>
        private void DataMaintain()
        {
            try
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["DataMaintainInterval"], out int dataMaintainInterval))
                {
                    var msg = "配置文件没有设置【数据维护间隔时间】,无法启动数据维护,请设置!";
                    ComnMethod.Message(msg);
                    App.ExFile.MessageError("Window_Loaded", msg);
                    return;
                };
                while (true)
                {
                    UpdateManage.DataMaintain();
                    Thread.Sleep(1000 * 60 * dataMaintainInterval);
                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("DataMaintain", $"数据维护线程异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
                thDataMaintain = new Thread(DataMaintain);
                thDataMaintain.IsBackground = true;
                thDataMaintain.Start();
            }
        }

        #region S7通讯处理

        /// <summary>
        /// 显示设备的PLC交互信号监控
        /// </summary>
        private void PLCInfo()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        #region 更新界面的实体
                        //更新华恒站台交互信号
                        foreach (var huahengStaion in App.HuahengStaionList)
                        {
                            var equipment = App.EquipmentList.FirstOrDefault(t => t.Name == huahengStaion.EquipmentName);
                            if (equipment != null)
                            {
                                huahengStaion.SetProp(equipment.EquipmentProps);
                            }
                        }
                        #endregion

                        #region 信号监控,如果PLC有信号,但是没有车正在执行,就清除RCS信号,同时恢复任务初始状态
                        var equipmentList = App.EquipmentList.Where(t => !t.Name.EndsWith("心跳")).ToList();
                        foreach (var equipment in equipmentList)
                        {
                            //MsgManage.CheckPLC(equipment);
                            MsgManage.ClearRequest(equipment);
                        }
                        #endregion

                        Thread.Sleep(EquipmentExecutor.Instance.Count * EquipmentExecutor.Instance.Delay);
                    }
                    catch (Exception ex)
                    {
                        App.ExFile.MessageError("PLCInfo", $"PLC交互信号监控出现异常: {ex.Message},\n 堆栈:{ex.StackTrace}");
                    }

                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("PLCInfo", $"创建显示设备的PLC交互信号监控线程失败:{ex.Message},\n 堆栈:{ex.StackTrace}");
                thTaskOperator = new Thread(PLCInfo);
                thTaskOperator.IsBackground = true;
                thTaskOperator.Start();
            }
        }

        /// <summary>
        /// 输送线P1002、P1004请求WMS入库
        /// </summary>
        private void CallContainer()
        {
            try
            {
                while (true)
                {
                    //处理站台请求
                    var stations = App.EquipmentList.Where(t => t.Type == EnumPLC.EquipmentType.HuaHengStation.ToString() && t.Name == "P1002");

                    foreach (var equipment in stations)
                    {
                        var pickReady = equipment[EnumPLC.PLCHuaHengProps.PickReady.ToString()];
                        var weight = equipment[EnumPLC.PLCHuaHengProps.Weight.ToString()];
                        var code = equipment[EnumPLC.PLCHuaHengProps.Code.ToString()];
                        if (pickReady?.Value == EnumPLC.PLCBool.True.ToString())
                        {
                            if (weight == null || string.IsNullOrEmpty(weight.Value))
                            {
                                App.ExFile.MessageError("CallContainer", $"输送线{equipment.Name}请求WMS入库出错,输送线的重量为空!");
                                continue;
                            }
                            if (!double.TryParse(weight.Value, out double weightValue))
                            {
                                App.ExFile.MessageError("CallContainer", $"输送线{equipment.Name}请求WMS入库出错,输送线的重量【{weight.Value}】不能转为双精度类型!");
                                continue;
                            }
                            if (weightValue == 0)
                            {
                                App.ExFile.MessageError("CallContainer", $"输送线{equipment.Name}请求WMS入库出错,输送线的重量【{weight.Value}】不能为0!");
                                continue;
                            }
                            if (code == null || string.IsNullOrEmpty(code.Value))
                            {
                                App.ExFile.MessageError("CallContainer", $"输送线{equipment.Name}请求WMS入库出错,输送线的条码为空!");
                                continue;
                            }
                            if (App.TaskList.Any(t => t.TaskPallet == code.Value))
                            {
                                continue;
                            }

                            var returnState = WebApiClient.ToWMSContainerInfo(code.Value, weightValue, 0, equipment.Name);
                            if (!returnState.IsSuccess)
                            {
                                App.ExFile.MessageError("CallContainer", $"输送线{equipment.Name}请求WMS入库出错,调用方法【ToWMSContainerInfo】失败,原因:{returnState.Message}\r");
                            }
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("CallContainer", $"创建输送线请求WMS入库的线程失败:{ex.Message},\n 堆栈:{ex.StackTrace}");
                thTaskOperator = new Thread(CallContainer);
                thTaskOperator.IsBackground = true;
                thTaskOperator.Start();
            }
        }

        #endregion S7通讯处理

        #region 界面操作

        /// <summary>
        /// 关闭程序事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, EventArgs e)
        {
            if (MessageBox.Show("请确认是否退出程序?\n退出后将无法继续全部或部分功能!", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 左键拖框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        /// <summary>
        /// 最小化按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        /// <summary>
        /// 最大化按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMax_Click(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Normal)
            {
                WindowState = WindowState.Maximized;
            }
            else if (WindowState == WindowState.Maximized)
            {
                WindowState = WindowState.Normal;
            }
        }

        /// <summary>
        /// 关闭按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("请确认是否退出程序?\n退出后将无法继续全部或部分功能!", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 菜单栏点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StackPanel_Click(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is not Button btn) return;
            //任务管理
            if (btn.Name == Btn_TaskManager.Name)
            {
                if (winTaskManager == null || winTaskManager.IsVisible == false)
                {
                    winTaskManager ??= new WinTaskManager();
                    winTaskManager.Show();
                }
                else
                {
                    winTaskManager.Activate();
                    winTaskManager.WindowState = WindowState.Normal;
                }
            }
            //手动任务
            else if (btn.Name == Btn_Test.Name)
            {
                if (winTest == null || winTest.IsVisible == false)
                {
                    winTest ??= new WinTest();
                    winTest.Show();
                }
                else
                {
                    winTest.Activate();
                    winTest.WindowState = WindowState.Normal;
                }
            }
            else if (btn.Name == Btn_MachineManager.Name)
            {
                if (winOrganization == null || winOrganization.IsVisible == false)
                {
                    winOrganization ??= new WinOrganization();

                    winOrganization.Show();
                }
                else
                {
                    winOrganization.Activate();
                    winOrganization.WindowState = WindowState.Normal;
                }
            }
            else if (btn.Name == Btn_Parameter.Name)
            {
                if (winParameter == null || winParameter.IsVisible == false)
                {
                    winParameter ??= new WinParameter();
                    winParameter.Show();
                }
                else
                {
                    winParameter.Activate();
                    winParameter.WindowState = WindowState.Normal;
                }
            }
            else if (btn.Name == Btn_History.Name)
            {

                if (winHistoryTask == null || !winHistoryTask.IsVisible)
                {
                    winHistoryTask ??= new WinHistoryTask();
                    winHistoryTask.Show();
                }
                else
                {
                    winHistoryTask.Activate();
                    winHistoryTask.WindowState = WindowState.Normal;
                }
            }
            else if (btn.Name == Btn_LogInfoView.Name)
            {
                if (this.StackMsg.Visibility == Visibility.Collapsed)
                    this.StackMsg.Visibility = Visibility.Visible;
                else
                {

                    this.StackMsg.Visibility = Visibility.Collapsed;
                }
            }

        }

        /// <summary>
        /// 异常信息清除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TBox_EMessage_Clear_Click(object sender, RoutedEventArgs e)
        {
            TBox_EMessage.Clear();
        }

        /// <summary>
        /// 系统异常信息清除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TBox_BussErrMsg_Clear_Click(object sender, RoutedEventArgs e)
        {
            TBox_BussErrMsg.Clear();
        }

        /// <summary>
        /// 关闭DataGrid选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is not DataGrid grid) return;
            var border = FindParent<Border>((DependencyObject)e.OriginalSource);
            if (border?.Name == "Border_AGVDetails") return; //this.Border_AGVDetails.Name
                                                             // if (border?.Name == this.Border_AGVDetails.Name) return;  
            var row = FindParent<DataGridRow>((DependencyObject)e.OriginalSource);
            if (row != null && row.DataContext == grid.SelectedItem)
            {
                grid.SelectedItem = null;
            }
        }
        private T? FindParent<T>(DependencyObject child) where T : DependencyObject
        {
            while (child != null)
            {
                if (child is T parent)
                {
                    return parent;
                }
                child = VisualTreeHelper.GetParent(child);
            }
            return null;
        }

        private void DataGrid_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
        {
            if (e.Row.DataContext is Base_Agv _agv)
                if (e.DetailsElement.Visibility == Visibility.Visible)
                {
                    //  expandedItems.Add(e.Row.DataContext); // 添加到集合中
                }
                else
                {
                    // expandedItems.Remove(e.Row.DataContext); // 从集合中移除
                }

            //// 显示所有展开的行
            //ShowExpandedItems();
        }

        /// <summary>
        /// 界面变换方向
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRotote_Click(object sender, RoutedEventArgs e)
        {
            try
            {


                //  RotateTransform.Angle = (RotateTransform.Angle + 90) % 360;

                if (App.Rotote == 1)
                {
                    App.Rotote = 2;
                }
                else
                {
                    App.Rotote = 1;
                }
                App.Canvas_Monit.Children.Clear();
                App.PointSharp.Clear();
                App.ShelfSharp.Clear();
                App.AgvSharp.Clear();
                //设置货架位置
                canvasSharp.ShelfSet();
                canvasSharp.AgvPointSet();
                canvasSharp.PointSet();
                canvasSharp.TextTostring();
            }
            catch (Exception ex)
            {
                ComnMethod.Message(ex.ToString());
            }
        }
        #endregion 界面操作

        #region 页面缩放

        //滚轮时间
        private void Canvas_Monitor_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var zoom = e.Delta > 0 ? 0.1 : -0.1;
            Zoom += zoom;
            if (Zoom < MinZoom) { Zoom = MinZoom; return; }
            else if (Zoom > MaxZoom) { Zoom = MaxZoom; return; }
            Zoom = Math.Round(Zoom, 1);

            #region 缩放页面

            ScaleTransform scaleTransform = new(Zoom, Zoom);
            Canvas_Monitor.LayoutTransform = scaleTransform;

            var pos = Mouse.GetPosition(Canvas_Monitor);
            var x = -pos.X * zoom;
            var y = -pos.Y * zoom;
            Transform.X += x;
            Transform.Y += y;

            #endregion


        }



        private void MonitorPanel_MouseMove(object sender, MouseEventArgs e)
        {
            e.Handled = true;
            if (DownPoint == null) return;
            var pos = Mouse.GetPosition(Canvas_Top);
            var x = pos.X - ((Point)DownPoint).X;
            var y = pos.Y - ((Point)DownPoint).Y;
            Transform.X += x;
            Transform.Y += y;
            DownPoint = pos;
        }

        private void MonitorPanel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            DownPoint = Mouse.GetPosition(Canvas_Top);

            MouseTool.InsertMouseHook();
        }

        private void MonitorPanel_MouseUp(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            DownPoint = null;
            MouseTool.RemoveMouseHook();
        }
        private void BtnReset_Click(object sender, RoutedEventArgs e)
        {
            Zoom = DefaultZoom;
            Canvas_Monitor!.LayoutTransform = new ScaleTransform(Zoom, Zoom);
            this.Transform.X = DefaultPoint.X;
            this.Transform.Y = DefaultPoint.Y;
            this.RotateTransform.Angle = 0;
            //this.Transform = new TranslateTransform(Canvas_Monitor.RenderTransformOrigin.X, Canvas_Monitor.RenderTransformOrigin.Y);
            // Canvas_Monitor.RenderTransform. = Transform;
            //TransformGroup.
        }

        #endregion

        private void BtnPrint_Click(object sender, RoutedEventArgs e)
        {

            // 创建保存文件对话框
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG Image|*.png",
                Title = "保存图片"
            };
            saveFileDialog.FileName = $"AGV运行地图{DateTime.Now:yyyyMMddhhmmss}.png";
            if (saveFileDialog.ShowDialog() != true) return;
            try
            {
                // 设置高分辨率
                double dpi = 300 / Zoom; // 300 DPI 是打印的标准分辨率
                double scaleFactor = dpi / 96.0; // 96 DPI 是默认 DPI


                var width = Canvas_Monitor.ActualWidth * scaleFactor * Zoom + Math.Abs(Transform.X * scaleFactor);
                var height = Canvas_Monitor.ActualHeight * scaleFactor * Zoom + Math.Abs(Transform.Y * scaleFactor);
                //var width = Canvas_Monitor.ActualWidth * scaleFactor * Zoom +1000;
                //var height = Canvas_Monitor.ActualHeight * scaleFactor * Zoom + 1000;
                // 创建 RenderTargetBitmap,使用更高的宽度和高度
                RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                    (int)width,
                    (int)height,
                    dpi, dpi,
                    PixelFormats.Pbgra32);

                renderBitmap.Render(Canvas_Monitor);
                #region 用于缩放 注释

                //// 创建一个 VisualBrush,用于渲染内容
                //VisualBrush visualBrush = new(Canvas_Monitor);
                //DrawingVisual drawingVisual = new();

                //using (DrawingContext context = drawingVisual.RenderOpen())
                //{
                //    //控制内容在画布中的偏移
                //    //context.PushTransform(new TranslateTransform(-Transform.X,-Transform.Y));
                //    context.PushTransform(new TranslateTransform(-Transform.X,-Transform.Y));
                //    //context.PushTransform(new ScaleTransform(Zoom/Zoom, Zoom / Zoom));
                //    context.PushTransform(new ScaleTransform(Zoom/Zoom, Zoom / Zoom));
                //    context.DrawRectangle(visualBrush, null,
                //             new Rect(new Point(0.5, 0.5),
                //             new Size(width, height)
                //            )
                //        );
                //}
                //renderBitmap.Render(drawingVisual);

                #endregion

                // 保存为 PNG 文件
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                using (FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }

                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                App.ExFile.MessageError("BtnPrint_Click", $"{ex}");
            }

        }

        private void MItem_LoaclAGV_Click(object sender, RoutedEventArgs e)
        {

            if (sender is not MenuItem menuItem) return;
            var menu = menuItem.Parent as ContextMenu;
            if (menu?.PlacementTarget is not DataGrid dataGrid) return;
            if (dataGrid.SelectedItem is not Base_Agv _agv) return;

            var agvElemnet = App.AgvSharp.Find(x => x.Name == _agv.AgvNo);
            if (agvElemnet == null)
            {
                MessageBox.Show($"所选agv{_agv.AgvNo}在界面中不存在");
                return;
            }
            // 获取元素在窗口中的位置
            var pointInWindow = agvElemnet.TransformToAncestor(this).Transform(new Point(0, 0));

            //获取窗口的中心位置
            double centerX = this.Left + (this.Width / 2);
            double centerY = this.Top + (this.Height / 2);

            var moveX = pointInWindow.X - centerX;
            var moveY = pointInWindow.Y - centerY;

            Transform.X -= moveX;
            Transform.Y -= moveY;
        }

        private void DGrid_Agv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }

    public class MakeupFonts : System.Windows.Markup.MarkupExtension
    {
        private string SizeType;

        public MakeupFonts(string fontType)
        { SizeType = fontType; }

        public override object ProvideValue(IServiceProvider Isp)
        {
            double FontSize = 0d;
            switch (SizeType)
            {
                case "Title":
                    FontSize = 20;
                    break;

                case "Normal":
                    FontSize = 12;
                    break;

                case "BottomTitle":
                    FontSize = 20;
                    break;
            }
            return FontSize;
        }
    }

    //定义值转换器
    [ValueConversion(typeof(string), typeof(string))]
    public class AgvBackGroundConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return new SolidColorBrush(Colors.Transparent);

            if ((int)value == 0) return new SolidColorBrush(Colors.Transparent);
            else if ((int)value == 1) return new SolidColorBrush(Colors.Red);
            else if ((int)value == 2) return new SolidColorBrush(Colors.Yellow);
            else if ((int)value == 3) return new SolidColorBrush(Colors.SkyBlue);
            else if ((int)value == 4) return new SolidColorBrush(Colors.LightGreen);
            else if ((int)value == 90) return new SolidColorBrush(Colors.Gray);
            else return new SolidColorBrush(Colors.Red);
            //return Application.res
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}