AGVManager.cs 39.7 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Common;
using static DeviceLibrary.Agv_Info;

namespace DeviceLibrary
{
    public static class AGVManager
    {

        static log4net.ILog log = log4net.LogManager.GetLogger("AGVManager");
        /// <summary>
        /// 节点信息
        /// </summary>
        public static List<ClientNode> nodeInfo;
        /// <summary>
        /// 小车信息
        /// </summary>
        public static List<Agv_Info> agvInfo;
        public static AgvServer server;
        public static Control control;
        public static WebService web;
        public static UnlockMissionManager unlockManager;
        public static ChargeManager Charge;
        //public static StandbyManager Standby;
        public static List<JobType> jobTypes;
        public static readonly string CONFIG_PATH = AppDomain.CurrentDomain.BaseDirectory + "Config\\";
        #region 任务日志
        static log4net.ILog runLog = log4net.LogManager.GetLogger("RunLog");
        static Dictionary<string, RunInfo> runInfoMap = new Dictionary<string, RunInfo>();

        public static void RunLogInfo(RunInfo info)
        {
            if (runInfoMap == null)
                return;
            if (runInfoMap.Keys.Contains(info.AGVNum))
            {
                if (!runInfoMap[info.AGVNum].Equals(info))
                {
                    runLog.Info(info.ToString());
                }
            }
            else
            {
                runInfoMap.Add(info.AGVNum, info);
                runLog.Info(info.ToString());
            }
        }

        public static void ErrorLogRecord(ErrorInfo errorInfo)
        {
            runLog.Info(errorInfo.ToString());
        }
        #endregion
        /// <summary>
        /// 初始化配置
        /// </summary>
        public static void Init()
        {
            string path;
            string[] line;
            string[] temp;
            bool isuse;
            string rfid = "";

            Charge = new ChargeManager();
            //Standby = new StandbyManager();
            agvInfo = new List<Agv_Info>();
            jobTypes = new List<JobType>();
            jobTypes.Add(new JobForRoomD());
            jobTypes.Add(new ChargeJobType());
            path = CONFIG_PATH + SettingString.FileName_AGV;
            line = File.ReadAllLines(path, Encoding.UTF8);
            for (int i = 1; i < line.Length; i++)
            {
                temp = line[i].Split(',');
                if (temp.Length != 5) continue;
                bool.TryParse(ReadIni(temp[1], SettingString.IsUse), out isuse);
                rfid = ReadIni(temp[1], SettingString.RFID);
                agvInfo.Add(new Agv_Info(temp[0], temp[1], temp[2], temp[3], temp[4], isuse, rfid));
            }

            //任务加载
            MissionSys.Init();

            //节点加载
            nodeInfo = new List<ClientNode>();
            path = CONFIG_PATH + SettingString.FileName_AgvProductionLine;
            line = System.IO.File.ReadAllLines(path, Encoding.GetEncoding("gb2312"));
            for (int i = 1; i < line.Length; i++)
            {
                temp = line[i].Split(',');
                if (temp.Length != 6) continue;
                Boolean.TryParse(ReadIni(temp[1], SettingString.IsUse), out bool isUse);
                Int32.TryParse(ReadIni(temp[1], SettingString.EmptyShelfCnt), out int emptyShelfCnt);
                nodeInfo.Add(new ClientNode(temp[1], temp[2], temp[3], temp[0], temp[4], temp[5], isUse, emptyShelfCnt));
            }
            //读取解绑信息
            AGVManager.ReadUnlockLineInfo();
        }


        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadIni(string section, string key)
        {
            return IniFileHelper.ReadValue(section, key, CONFIG_PATH + SettingString.FileName_tempData);
        }
        /// <summary>
        /// 写入配置
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void WriteIni(string section, string key, string value)
        {
            IniFileHelper.WriteValue(section, key, value, CONFIG_PATH + SettingString.FileName_tempData);
        }

        /// <summary>
        /// 根据线体名获取节点名
        /// </summary>
        /// <param name="lineName"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public static bool GetNodeNameByLineName(string lineName, out string nodeName)
        {
            nodeName = "";
            int id = nodeInfo.FindIndex(s => s.LineName.Equals(lineName));
            if (id > -1)
            {
                nodeName = nodeInfo[id].Name;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 根据节点名获取线体名
        /// </summary>
        /// <param name="nodeName"></param>
        /// <param name="lineName"></param>
        /// <returns></returns>
        public static bool GetLineNameByNodeName(string nodeName, out string lineName)
        {
            lineName = "";
            int id = nodeInfo.FindIndex(s => s.Name.Equals(nodeName));
            if (id > -1)
            {
                lineName = nodeInfo[id].LineName;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 查找节点是否存在以及是否调用
        /// </summary>
        /// <param name="nodeName">节点名称</param>
        /// <returns>-1:不存在/未调用</returns>
        public static int FindNode(string nodeName)
        {
            int idx = nodeInfo.FindIndex(s => s.Name.Equals(nodeName) && s.IsUse);
            return idx;
        }

        /// <summary>
        /// 检查4C目的地是否被占用
        /// </summary>
        /// <param name="agv"></param>
        /// <returns></returns>
        internal static bool CheckRoomCTarget(Agv_Info agv, string nodeName)
        {
            List<Agv_Info> agvs = agvInfo.FindAll(s => !s.IP.Equals(agv.IP) && (s.CurJob is GoEmptyShelfLineJob || s.CurJob is SendFullShelfToLineJob));
            if (agvs.Count.Equals(0))
                return false;
            else if (agvs.Count > 0)
            {
                foreach (Agv_Info item in agvs)
                {
                    if (item.CurJob is GoEmptyShelfLineJob)
                    {
                        if (((GoEmptyShelfLineJob)item.CurJob).EmptyShelfPlace.Equals(nodeName) && item.Place.Equals(nodeName))
                        {
                            log.Debug(item.Name + " 在目的地:" + ((GoEmptyShelfLineJob)item.CurJob).EmptyShelfPlace + " " + agv.Name + "暂不去" + nodeName);
                            return true;
                        }

                    }
                    else if (item.CurJob is SendFullShelfToLineJob)
                    {
                        if (((SendFullShelfToLineJob)item.CurJob).FullShelfPlace.Equals(nodeName) && item.Place.Equals(nodeName))
                        {
                            log.Debug(item.Name + " 在目的地:" + ((SendFullShelfToLineJob)item.CurJob).FullShelfPlace + " " + agv.Name + "暂不去" + nodeName);
                            return true;
                        }

                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 去C车间待机位
        /// </summary>
        /// <param name="agv"></param>
        internal static void MoveToRoomCStandy(Agv_Info agv)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 查看双层线需要料架的状况
        /// </summary>
        /// <param name="agv"></param>
        /// <param name="node"></param>
        public static bool CheckA5A6State(Agv_Info agv, eShelfType shelfType, out string nodeName)
        {
            nodeName = "";
            if (shelfType.Equals(eShelfType.SmallShelf))
            {
                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A5
                            && (s.StateEquals(eNodeStatus.NeedD) || s.StateEquals(eNodeStatus.NeedEnter)) && s.IsUse);
                if (tarIdx > -1)
                {
                    tarIdx = agvInfo.FindIndex(s => !s.IP.Equals(agv.IP) && s.CurJob != null && s.CurJob is EmptyShelfBackJob
                    && ((((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace) != null) && ((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace.Equals(SettingString.A5));
                    if (tarIdx == -1)
                    {
                        nodeName = SettingString.A5;
                        log.Debug(string.Format("{0} {1}需要小料架", agv.Name, SettingString.A5));
                        return true;
                    }

                }

                tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A6 &&
                (s.StateEquals(eNodeStatus.NeedEnter) || s.StateEquals(eNodeStatus.NeedEnterLeave)) && s.IsUse);

                if (tarIdx > -1)
                {
                    tarIdx = agvInfo.FindIndex(s => !s.IP.Equals(agv.IP) && s.CurJob != null && s.CurJob is EmptyShelfBackJob
                                && ((((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace) != null) && ((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace.Equals(SettingString.A6));
                    if (tarIdx == -1)
                    {
                        nodeName = SettingString.A6;
                        log.Debug(string.Format("{0} {1}需要小料架", agv.Name, SettingString.A6));
                        return true;
                    }
                }
            }
            else if (shelfType.Equals(eShelfType.BigShelf))
            {
                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A5
                            && (s.StateEquals(eNodeStatus.NeedC) || s.StateEquals(eNodeStatus.NeedEnter)) && s.IsUse);
                if (tarIdx > -1)
                {
                    //tarIdx = agvInfo.FindIndex(s => !s.IP.Equals(agv.IP) && s.CurJob != null && s.CurJob is EmptyShelfBackJob
                    //        && ((((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace) != null) && ((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace.Equals(SettingString.A5));
                    //if (tarIdx == -1)
                    {
                        nodeName = SettingString.A5;
                        log.Debug(string.Format("{0} {1}需要大料架", agv.Name, SettingString.A5));
                        return true;
                    }

                }

                //tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A6 &&
                //(s.StateEquals(eNodeStatus.NeedEnter) || s.StateEquals(eNodeStatus.NeedEnterLeave)) && s.IsUse);

                //if (tarIdx > -1)
                //{
                //    tarIdx = agvInfo.FindIndex(s => !s.IP.Equals(agv.IP) && s.CurJob != null && s.CurJob is EmptyShelfBackJob
                //               && ((((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace) != null) && ((EmptyShelfBackJob)s.CurJob).EmptyShelfTargetPlace.Equals(SettingString.A6));
                //    if (tarIdx == -1)
                //    {
                //        nodeName = SettingString.A6;
                //        log.Debug(string.Format("{0} {1}需要大料架", agv.Name, SettingString.A6));
                //        return true;
                //    }

                //}
            }

            return false;
        }

        /// <summary>
        /// 查看A5料架的状况,主动拉料架
        /// </summary>
        /// <param name="agv"></param>
        /// <param name="node"></param>
        public static bool CheckA5State(Agv_Info agv, eShelfType shelfType)
        {
            if (shelfType.Equals(eShelfType.SmallShelf))
            {
                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A5 && s.ClientLevel.Equals(ClientLevel.High)
                            && (s.StateEquals(eNodeStatus.NeedD) || s.StateEquals(eNodeStatus.NeedEnter)) && s.IsUse);
                if (tarIdx > -1)
                {
                    log.Debug(string.Format("{0} {1}需要小料架", agv.Name, SettingString.A5));
                    return true;
                }
            }
            else if (shelfType.Equals(eShelfType.BigShelf))
            {
                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A5
                            && (s.StateEquals(eNodeStatus.NeedC) || s.StateEquals(eNodeStatus.NeedEnter)) && s.IsUse);
                if (tarIdx > -1)
                {
                    log.Debug(string.Format("{0} {1}需要大料架", agv.Name, SettingString.A5));
                    return true;
                }

            }

            return false;
        }

        /// <summary>
        /// 查看A6料架的状况
        /// </summary>
        /// <param name="agv"></param>
        /// <param name="node"></param>
        public static bool CheckA6State(Agv_Info agv, eShelfType shelfType)
        {
            if (shelfType.Equals(eShelfType.SmallShelf))
            {

                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A6 &&
                (s.StateEquals(eNodeStatus.NeedEnter) || s.StateEquals(eNodeStatus.NeedEnterLeave)) && s.IsUse);

                if (tarIdx > -1)
                {
                    log.Debug(string.Format("{0} {1}需要小料架", agv.Name, SettingString.A6));
                    return true;
                }
            }
            else if (shelfType.Equals(eShelfType.BigShelf))
            {
                int tarIdx = nodeInfo.FindIndex(s => s.Name == SettingString.A6 &&
               (s.StateEquals(eNodeStatus.NeedEnter) || s.StateEquals(eNodeStatus.NeedEnterLeave)) && s.IsUse);

                if (tarIdx > -1)
                {
                    //nodeName = SettingString.A6;
                    log.Debug(string.Format("{0} {1}需要大料架", agv.Name, SettingString.A6));
                    return true;

                }
            }

            return false;
        }

        //双层线工单信息
        public static string doubleLine_WO = "";
        public static string warnMsg = "";
        /// <summary>
        /// 查找空架任务
        /// </summary>
        /// <param name="curPlace">为空表示待机位</param>
        /// <param name="nodeName">出空料架的节点名</param>
        /// <param name="emptyAGVbACK">agv空车返回,带一个料架</param>
        /// <returns></returns>
        public static bool FindEmptyShelfNode(Agv_Info agv, out string nodeName, bool emptyAGVbACK = false)
        {

            nodeName = "";
            if (!CheckCanExecuteMission(agv))
                return false;

            ///双层线出口检查
            int idx = nodeInfo.FindIndex(s => s.Name.Equals(SettingString.A6)
            && (s.StateEquals(eNodeStatus.NeedEnterLeave) || (s.StateEquals(eNodeStatus.NeedLeave))) && !s.RFID.Equals(""));
            if (idx > -1)
            {
                if (HttpManager.FindFullShelfTarget(nodeInfo[idx].RFID, out HttpManager.BoxDestInfo FullShelfDestInfo))
                {
                    idx = nodeInfo.FindIndex(s => s.Name.Equals(FullShelfDestInfo.location) && s.EmptyShelfCnt > 0);
                    if (idx > -1)
                    {
                        if (FullShelfDestInfo.location.StartsWith(SettingString.RoomC_Name_Prefix) && SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                        {
                            nodeName = FullShelfDestInfo.location;
                            GetLineNameByNodeName(nodeName, out string line);
                            log.Debug("A6出满料架的产线有空料架,优先处理 " + FullShelfDestInfo.ShowInfo(line));
                            return true;
                        }
                        else if (FullShelfDestInfo.location.StartsWith(SettingString.RoomS_Name_Prefix) && !SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                        {
                            nodeName = FullShelfDestInfo.location;
                            GetLineNameByNodeName(nodeName, out string line);
                            log.Debug("A6出满料架的产线有空料架,优先处理 " + FullShelfDestInfo.ShowInfo(line));
                            return true;
                        }

                    }
                }
                else
                {
                    if (FullShelfDestInfo != null)
                    {
                        log.Error("A6的出料信息不正确,请检查:" + FullShelfDestInfo.ShowInfo("ERROR"));
                        //return false;
                    }
                }
            }

            //查询双层线正在出的工单料
            if (HttpManager.FindCurSO(out HttpManager.WOData woData))
            {
                if (GetNodeNameByLineName(woData.line, out string loc))
                {
                    nodeName = loc;
                    doubleLine_WO = woData.ToTxt(loc);
                    log.Debug(doubleLine_WO);
                    idx = nodeInfo.FindIndex(s => s.Name.Equals(loc) && s.EmptyShelfCnt > 0);

                    if (idx > -1)
                    {
                        if (loc.StartsWith(SettingString.RoomC_Name_Prefix) && SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                        {
                            nodeName = loc;
                            //Common.LogInfo("双层线正在出的工单目标产线有空料架,优先处4C-" + loc);
                            return true;
                        }
                        else if (loc.StartsWith(SettingString.RoomS_Name_Prefix) && !SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                        {
                            nodeName = loc;
                            log.Debug("双层线正在出的工单目标产线有空料架,优先处理4D-" + loc);
                            return true;
                        }
                    }

                }
            }

            ///AGV出满料带回一个料架
            if (emptyAGVbACK)
            {
                //双层线是否需要小料架
                if (CheckA5A6State(agv, eShelfType.SmallShelf, out string nodename))
                {

                    //4C车间寻找
                    if (SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        string nearNodeName = CalculateNearNode(agv, SettingString.RoomC_Name_Prefix);
                        if (nearNodeName.Equals(""))
                        {
                            return false;
                        }
                        nodeName = nearNodeName;
                        log.Debug(agv.Name + " 双层线需要小料架,准备去4C-" + nearNodeName);
                        return true;
                    }

                    //4D车间寻找
                    if (!SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        string nearNodeName = CalculateNearNode(agv, SettingString.RoomS_Name_Prefix);
                        if (nearNodeName.Equals(""))
                        {
                            return false;
                        }
                        nodeName = nearNodeName;
                        log.Debug(agv.Name + " 双层线需要小料架,准备去4D-" + nearNodeName);
                        return true;
                    }

                }

            }
            else//主动拉料架
            {
                //双层线是否需要小料架
                if (CheckA5State(agv, eShelfType.SmallShelf))
                {
                    //4C车间备料区寻找
                    if (SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        idx = nodeInfo.FindIndex(s => s.EmptyShelfCnt > 0 && s.Name.Equals(SettingString.RoomCFeederOut) && s.RFID.StartsWith("D") && s.IsUse);
                        if (idx > -1)
                        {
                            nodeName = nodeInfo[idx].Name;
                            log.Debug(agv.Name + " 双层线右侧需要料架,准备去3C-" + nodeName);
                            return true;
                        }
                    }
                    //4D车间备料区寻找
                    if (!SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        idx = nodeInfo.FindIndex(s => s.EmptyShelfCnt > 0 && s.Name.Equals(SettingString.RoomDFeederOut) && !s.RFID.StartsWith("D") && s.IsUse);
                        if (idx > -1)
                        {
                            nodeName = nodeInfo[idx].Name;
                            log.Debug(agv.Name + " 双层线右侧需要料架,准备去3D-" + nodeName);
                            return true;
                        }

                    }
                    //4C车间寻找
                    if (SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        string nearNodeName = CalculateNearNode(agv, SettingString.RoomC_Name_Prefix);
                        if (!nearNodeName.Equals(""))
                        {
                            nodeName = nearNodeName;
                            log.Debug(agv.Name + " 双层线需要小料架,准备去3C-" + nearNodeName);
                            return true;
                        }

                    }

                    //4D车间寻找
                    if (!SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        string nearNodeName = CalculateNearNode(agv, SettingString.RoomS_Name_Prefix);
                        if (!nearNodeName.Equals(""))
                        {
                            nodeName = nearNodeName;
                            log.Debug(agv.Name + " 双层线需要小料架,准备去3D-" + nearNodeName);
                            return true;
                        }

                    }
                }
                else if (CheckA5State(agv, eShelfType.BigShelf))
                {
                    //4C车间备料区寻找
                    if (SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        idx = nodeInfo.FindIndex(s => s.EmptyShelfCnt > 0 && s.Name.Equals(SettingString.RoomCFeederOut) && s.RFID.StartsWith("C") && s.IsUse);
                        if (idx > -1)
                        {
                            nodeName = nodeInfo[idx].Name;
                            log.Debug(agv.Name + " 双层线左侧需要大料架,准备去4C-" + nodeName);
                            return true;
                        }
                    }
                    //4D车间备料区寻找
                    if (!SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        idx = nodeInfo.FindIndex(s => s.EmptyShelfCnt > 0 && s.Name.Equals(SettingString.RoomDFeederOut) && s.RFID.StartsWith("C") && s.IsUse);
                        if (idx > -1)
                        {
                            nodeName = nodeInfo[idx].Name;
                            log.Debug(agv.Name + " 双层线左侧需要大料架,准备去4D-" + nodeName);
                            return true;
                        }

                    }
                }

                if (CheckA6State(agv, eShelfType.BigShelf) || CheckA6State(agv, eShelfType.SmallShelf))
                {
                    //D车间备料区寻找
                    if (!SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        idx = nodeInfo.FindIndex(s => s.EmptyShelfCnt > 0 && s.Name.Equals(SettingString.RoomDFeederOut) && !s.RFID.StartsWith("0") && s.IsUse);
                        if (idx > -1)
                        {
                            nodeName = nodeInfo[idx].Name;
                            log.Debug(agv.Name + " 双层线右侧需要料架,准备去4D-" + nodeName);
                            return true;
                        }

                    }
                }
            }
            return false;

        }

        /// <summary>
        /// 查找出满料架任务
        /// </summary>
        /// <returns></returns>
        public static bool FindFullShelfTask(Agv_Info agv)
        {
            if (!CheckCanExecuteMission(agv))
                return false;
            int idx = nodeInfo.FindIndex(s => s.Name.Equals(SettingString.A6)
                && (s.StateEquals(eNodeStatus.NeedEnterLeave) || (s.StateEquals(eNodeStatus.NeedLeave))) && !s.RFID.Equals(""));
            if (idx > -1)
            {
                if (HttpManager.FindFullShelfTarget(nodeInfo[idx].RFID, out HttpManager.BoxDestInfo FullShelfDestInfo))
                {
                    if (FullShelfDestInfo.location.StartsWith(SettingString.RoomC_Name_Prefix) && SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        int i = agvInfo.FindIndex(s => s.CurJob is GoFullShelfStationJob && !s.IP.Equals(agv.IP));
                        if (i == -1)
                            return true;

                    }
                    else if ((FullShelfDestInfo.location.StartsWith(SettingString.RoomS_Name_Prefix)|| FullShelfDestInfo.location.StartsWith(SettingString.SmallShelf_Prefix)) 
                        && !SettingString.RoomC_AGV_IPs.Contains(agv.IP))
                    {
                        int i = agvInfo.FindIndex(s => s.CurJob is SendFullShelfToLineJob && !s.IP.Equals(agv.IP)
                                && ((SendFullShelfToLineJob)s.CurJob).FullShelfPlace.Equals(FullShelfDestInfo.location));
                        if (i > -1)
                            return false;
                        i = agvInfo.FindIndex(s => s.CurJob is GoFullShelfStationJob && !s.IP.Equals(agv.IP));
                        if (i == -1)
                            return true;
                    }
                }
                else
                {
                    if (FullShelfDestInfo != null)
                    {
                        log.Error("A6的出料信息不正确,请检查:" + FullShelfDestInfo.ShowInfo("ERROR"));
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 查找当前出料工单的产线是否有空料架
        /// </summary>
        /// <param name="agv"></param>
        /// <returns></returns>
        public static bool FindEmptyShelfBeforeSendFullShelf(out string nodeName)
        {
            nodeName = "";
            int idx = nodeInfo.FindIndex(s => s.Name.Equals(SettingString.A6)
            && (s.StateEquals(eNodeStatus.NeedEnterLeave) || (s.StateEquals(eNodeStatus.NeedLeave))) && !s.RFID.Equals("") && s.IsUse);
            if (idx > -1)
            {
                if (HttpManager.FindFullShelfTarget(nodeInfo[idx].RFID, out HttpManager.BoxDestInfo FullShelfDestInfo))
                {
                    idx = nodeInfo.FindIndex(s => s.Name.Equals(FullShelfDestInfo.location) && s.EmptyShelfCnt > 0 && s.IsUse);
                    if (idx > -1)
                    {
                        nodeName = FullShelfDestInfo.location;
                        GetLineNameByNodeName(nodeName, out string line);
                        log.Debug("A6出满料架的产线有空料架,优先处理 " + FullShelfDestInfo.ShowInfo(line));
                        return true;
                    }
                }
                else
                {
                    if (FullShelfDestInfo != null)
                    {
                        log.Error("A6的出料信息不正确,请检查:" + FullShelfDestInfo.ShowInfo("ERROR"));
                    }
                }
            }

            return false;
        }
        /// <summary>
        /// 检查接驳台状态
        /// </summary>
        /// <returns></returns>
        public static bool CheckStationState(ClientNode clientNode, out string rfid)
        {
            rfid = "";
            if (unlockManager.GetUnlockCnt(clientNode.Name) > 0 && !unlockManager.GetUnlockRfids(clientNode.Name).Contains(clientNode.RFID))
            {
                if (clientNode.Name.Equals(SettingString.RoomCFeederOut) || clientNode.Name.Equals(SettingString.RoomDFeederOut))
                {
                    warnMsg = string.Format("佳世达线体[{0}]外侧料架[{1}]未解绑,已解绑料架:{2}", clientNode.AliceName, clientNode.RFID, string.Join(",", unlockManager.GetUnlockRfids(clientNode.Name).ToArray()));
                    log.Debug(warnMsg);
                }
                else
                {
                    string res = HttpManager.GetRFIDs(clientNode.LineName);
                    warnMsg = string.Format("佳世达线体[{0}]外侧料架[{1}]未解绑,已解绑料架:{2}", clientNode.AliceName, clientNode.RFID, string.Join(",", unlockManager.GetUnlockRfids(clientNode.Name).ToArray()));
                    log.Debug(warnMsg);
                }
                return false;
            }
            rfid = clientNode.RFID;
            warnMsg = "";
            return true;
        }

        /// <summary>
        /// 上报接驳台状态
        /// </summary>
        /// <param name="clientNode"></param>
        /// <returns>true:表示正常</returns>
        public static bool UpdateStationState(ClientNode clientNode)
        {

            if (unlockManager.GetUnlockCnt(clientNode.Name) > 0 && !unlockManager.GetUnlockRfids(clientNode.Name).Contains(clientNode.RFID))
            {
                if (clientNode.Name.Equals(SettingString.RoomCFeederOut) || clientNode.Name.Equals(SettingString.RoomDFeederOut))
                {
                    clientNode.WarnMsg = string.Format("佳世达外侧料架[{0}]未解绑,已解绑料架:{1}", clientNode.RFID, string.Join(",", unlockManager.GetUnlockRfids(clientNode.Name).ToArray()));
                    return false;
                }
                else
                {
                    string res = HttpManager.GetRFIDs(clientNode.LineName);
                    clientNode.WarnMsg = string.Format("佳世达外侧料架[{0}]未解绑,已解绑料架:{1}", clientNode.RFID, string.Join(",", unlockManager.GetUnlockRfids(clientNode.Name).ToArray()));
                    return false;
                }
            }
            clientNode.WarnMsg = "";
            return true;
        }
        /// <summary>
        /// 出料前检查接驳台状态
        /// </summary>
        /// <returns></returns>
        public static bool CheckStationState(ClientNode clientNode)
        {
            if (unlockManager.GetUnlockCnt(clientNode.Name) > 0)
            {
                // if (warnMsg.Equals(""))
                {
                    warnMsg = string.Format("接驳台[{1}]有空料架未回收完,无法出满料,请检查接驳台RFID读取情况", clientNode.RFID, clientNode.Name);
                    log.Warn(warnMsg);
                }
                return false;
            }
            return true;
        }
        /// <summary>
        ///  计算当前小车距离最近的任务点(只针对产线)
        /// </summary>
        /// <param name="agv"></param>
        /// <returns>节点名称</returns>
        public static string CalculateNearNode(Agv_Info agv, string RoomProfix)
        {
            double minDis = Double.MaxValue;
            string nodeName = "";
            List<ClientNode> clientNodes = nodeInfo.FindAll(s => s.EmptyShelfCnt > 0 && s.Name.Substring(0, 1).Equals(RoomProfix) && s.IsUse);
            try
            {
                if (clientNodes.Count.Equals(0))
                    return nodeName;
                foreach (var item in clientNodes)
                {
                    double dis = Math.Sqrt(Math.Pow((agv.Position.Point.X - item.Position.X), 2) + Math.Pow((agv.Position.Point.Y - item.Position.Y), 2));
                    log.Debug(string.Format("{0} 距离{1}={2}", agv.Name, item.Name, dis.ToString("f2")));
                    if (dis < minDis)
                    {
                        minDis = dis;
                        nodeName = item.Name;
                    }

                }
                log.Debug(string.Format("{0} 准备运动到产线 {1} 回收空料架", agv.Name, nodeName));
                return nodeName;
            }
            catch (Exception e)
            {
                log.Error("CalculateNearNode " + e.ToString());
            }
            return nodeName;
        }

        /// <summary>
        /// 判断电量是否够执行任务
        /// </summary>
        /// <param name="agv"></param>
        /// <returns></returns>
        public static bool CheckCanExecuteMission(Agv_Info agv)
        {
            if (agv.Battery <= Charge.BatteryMin)
            {
                log.Debug(agv.Name + " 电量小于" + Charge.BatteryMin + "%,不执行任务");
                return false;
            }


            return true;
        }

        /// <summary>
        /// 判断小车是否能接任务
        /// </summary>
        /// <param name="agv"></param>
        /// <returns></returns>
        public static bool CheckAGVStatusNone(Agv_Info agv)
        {
            if (agv.CurJob == null || agv.CurJob is ChargeJob && !agv.IsExistShelf)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 读取料架解绑信息
        /// </summary>
        public static void ReadUnlockLineInfo()
        {
            if (!System.IO.File.Exists(CONFIG_PATH + "UnlockInfo.json"))
            {
                File.Create(CONFIG_PATH + "UnlockInfo.json");
                unlockManager = new UnlockMissionManager(nodeInfo);
                return;
            }
            string s = File.ReadAllText(CONFIG_PATH + "UnlockInfo.json");
            unlockManager = JsonHelper.DeserializeJsonToObject<UnlockMissionManager>(s);
            if (unlockManager == null)
                unlockManager = new UnlockMissionManager(nodeInfo);
            unlockManager.Init();
        }

        public static void GetNodesPosition()
        {
            Agv_Info agv = agvInfo[0];
            foreach (ClientNode clientNode in nodeInfo)
            {
                bool rtn = MiR_API.Get_Node_Pos(agv, clientNode, out MirPosition mirPosition);
                Thread.Sleep(50);
                if (rtn)
                {
                    clientNode.Position.X = mirPosition.Point.X;
                    clientNode.Position.Y = mirPosition.Point.Y;
                    log.Debug(string.Format("软件开启:{0} 获取节点位置({1},{2})", clientNode.Name, clientNode.Position.X, clientNode.Position.Y));
                }
                else
                {
                    log.Error(clientNode.Name + " GetNodesPosition 获取节点位置失败");
                }
            }
        }

        public static bool CheckIsInAirDoor(string nodeName)
        {
            return SettingString.Lines_In_Air_Door.Contains(nodeName);
        }
    }

    public class RunInfo
    {
        /// <summary>
        /// AGV编号
        /// </summary>
        public string AGVNum { get; set; } = "";
        public string DeviceName { get; set; } = "";
        /// <summary>
        /// 任务名称
        /// </summary>
        public string TaskName { get; set; } = "";
        /// <summary>
        /// 目的地
        /// </summary>
        public string TargetPlace { get; set; } = "";
        /// <summary>
        /// 任务步骤
        /// </summary>
        public string TaskStep { get; set; } = "";
        /// <summary>
        /// 任务内容
        /// </summary>
        public string MissionInfo { get; set; } = "";
        /// <summary>
        /// 开始时间
        /// </summary>
        public string DateTime { get; set; } = "";
        /// <summary>
        /// 结束时间
        /// </summary>
        public string EndDateTime { get; set; } = "";
        /// <summary>
        /// 任务运行时长
        /// </summary>
        public string TaskRunTime { get; set; } = "";
        /// <summary>
        /// 类型
        /// </summary>
        public string Type { get; set; } = "Task";

        public RunInfo(string AGVNum, string taskName, string targetPlace, string taskStep, string missionInfo, DateTime startTime)
        {
            //开始时间 2006-01-02 15:04:05
            DateTime = startTime.ToString("yyyy-MM-dd HH:mm:ss");
            EndDateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            this.AGVNum = AGVNum;
            MissionInfo = missionInfo;
            TaskName = taskName;
            TaskRunTime = (System.DateTime.Now - startTime).TotalMinutes.ToString("f2");
            TargetPlace = targetPlace;
            TaskStep = taskStep;
        }
        public RunInfo() { }
        public override bool Equals(object obj)
        {
            if (obj is RunInfo)
            {
                RunInfo info = (RunInfo)obj;
                if (this.MissionInfo.Equals(info.MissionInfo))
                    return true;
                this.MissionInfo = info.MissionInfo;
            }
            return false;
        }
        public override string ToString()
        {
            return JsonHelper.SerializeObject(this);
        }
    }

    public class ErrorInfo
    {
        /// <summary>
        /// AGV编号
        /// </summary>
        public string AGVNum
        {
            get { return agvname; }
            set
            {
                agvname = value.PadLeft(4, '0');
            }
        }
        public string DeviceName { get; set; } = "";
        private string agvname = "";
        /// <summary>
        /// 开始时间
        /// </summary>
        public string DateTime { get; set; } = "";
        /// <summary>
        /// 结束时间
        /// </summary>
        public string EndDateTime { get; set; } = "";
        /// <summary>
        /// 异常信息
        /// </summary>
        public string ErrorMsg { get; set; } = "";
        public string ErrorLastTime { get; set; } = "";
        /// <summary>
        /// 任务名称
        /// </summary>
        public string TaskName { get; set; } = "";
        /// <summary>
        /// AGV的当前任务
        /// </summary>
        public string AGVMissionName { get; set; } = "";

        public string MissionInfo { get; set; } = "";
        /// <summary>
        /// 目的地
        /// </summary>
        public string TargetPlace { get; set; } = "";
        /// <summary>
        /// 类型
        /// </summary>
        public string Type { get; set; } = "Error";
        public ErrorInfo(Agv_Info agv)
        {
            DateTime = agv.errStartTime.ToString("yyyy-MM-dd HH:mm:ss");
            AGVNum = agv.Name;
            EndDateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            ErrorMsg = agv.ErrorMsg;
            ErrorLastTime = (System.DateTime.Now - agv.errStartTime).TotalMinutes.ToString("f2");
            if (agv.CurJob != null)
            {
                TaskName = agv.CurJob.JobName;
                MissionInfo = agv.CurJob.runInfo;
            }
            AGVMissionName = agv.CurTarName;
            TargetPlace = agv.Place;
        }
        public override string ToString()
        {
            return JsonHelper.SerializeObject(this);
        }
    }
    public static class Window_API
    {
        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        [DllImport("user32.dll ", SetLastError = true)]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
        public const int SW_RESTORE = 9;

    }


}