ComnMethod.cs 40.2 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
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HslCommunication;
using HslCommunication.ModBus;
using XingYe_ACS.BaseStruct;
using XingYe_ACS.Business;
using XingYe_ACS.WebApi;

namespace XingYe_ACS.Common
{
    public class ComnMethod
    {
        private static object obj = new object();
        /// <summary>
        /// 校验码验证
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static byte checkCode(byte[] data, int length)
        {
            byte crc = (byte)(data[0] ^ data[1]);
            for (int i = 2; i < length - 1; i++)
            {
                crc = (byte)(crc ^ data[i]);
            }
            return crc;
        }

        /// <summary>
        /// byte变8位bit,转bool数组
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool[] GetBooleanArray(byte b)
        {
            bool[] array = new bool[8];
            for (int i = 0; i < 8; i++)
            {
                array[i] = Convert.ToBoolean((b & 1));
                b = (byte)(b >> 1);
            }
            return array;
        }

        /// <summary>
        /// 获取小车错误
        /// </summary>
        /// <param name="errorList"></param>
        /// <returns></returns>
        public static string GetAgvError(int[] errorList)
        {
            string strErrorMsg = "";
            foreach (int error in errorList)
            {
                if (error == 0) continue;
                Config_ErrMsg config_ErrMsg = App.Config_ErrMsgList.Find(a => a.intErrorNo == error);
                if (config_ErrMsg == null)
                {
                    if (error == 0) continue;
                    strErrorMsg += error + "未知错误信息-";
                    continue;
                }
                //if (config_ErrMsg.intErrorNo == 19)
                //{
                //    strErrorMsg += "@";
                //}
                strErrorMsg += config_ErrMsg.strErrorMsg + "-";
                config_ErrMsg.intCount++;
            }
            return strErrorMsg;
        }

        /// <summary>
        /// 二进制的int数组转字符串
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string GetString(int[] num)
        {
            string str = "";
            if (num.Length != 8) return str;
            for (int i = 7; i >= 0; i--)
            {
                str += num[i];
            }
            return str;
        }

        /// <summary>
        /// 获取流水号
        /// </summary>
        /// <returns></returns>
        public static string GetTaskNo()
        {
            lock (obj)
            {
                DataSet ds = DbHelperSQL.Query("SELECT Tno FROM  T_Base_Number");
                string taskNo = ds.Tables[0].Rows[0].ItemArray[0].ToString();
                //获取当前日期
                string dateNow = DateTime.Now.ToString("yyyyMMdd");
                if (taskNo == null || taskNo.Substring(0, 8) != dateNow)
                {
                    taskNo = DateTime.Now.ToString("yyyyMMdd") + "000001";
                }
                else
                {
                    int index = int.Parse(taskNo.Substring(8, 6)) + 1;
                    taskNo = taskNo.Substring(0, 8) + index.ToString().PadLeft(6, '0');
                }
                string sqlUpdate = string.Format(@"UPDATE  T_Base_Number SET Tno = '{0}';", taskNo);
                int intSqlResult = DbHelperSQL.ExecuteSql(sqlUpdate);
                if (intSqlResult < 1) return null;
                return taskNo;
            }
        }

        /// <summary>
        /// 获取时间差
        /// </summary>
        /// <param name="dateTime">开始时间</param>
        /// <returns></returns>
        public static int DiffTime(DateTime dateTime)
        {
            TimeSpan ts1 = new TimeSpan(dateTime.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts3 = ts2.Subtract(ts1).Duration();
            int num = ts3.Minutes * 60 + ts3.Seconds;
            return num;
        }

        /// <summary>
        /// 获取小车停止原因
        /// </summary>
        /// <param name="oldstr"></param>
        /// <param name="newstr"></param>
        /// <returns></returns>
        public static string GetStopReason(string oldstr, string newstr)
        {
            if (newstr == "") return "";
            if (oldstr.Contains(newstr)) return oldstr;
            if (oldstr == "")
                return newstr;
            return oldstr + ";\n" + newstr;
        }

        /// <summary>
        /// 查找当前点的路径下一点
        /// </summary>
        /// <param name="lastAgv"></param>
        /// <param name="nowPoint"></param>
        /// <returns></returns>
        public static PathPoint GetNextPathPoint(Agv agv, PathPoint pathPoint)
        {
            if (agv.agvTask == null || agv.agvTask.sonTaskList.Count == 0 || agv.agvTask.sonTaskList[0].pathPointList.Count == 0) return null;
            PathPoint nextPoint = agv.agvTask.sonTaskList[0].pathPointList.Find(a => a.point.strBarcode == pathPoint.point.strBarcode);
            if (nextPoint == null) return null;
            PathPoint nextPointNew = agv.agvTask.sonTaskList[0].pathPointList.Find(a => a.intSerialNo == nextPoint.intSerialNo + 1);
            if (nextPointNew == null) return null;
            return nextPointNew;
        }

        /// <summary>
        /// 获取路径点
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public static PathPoint GetPathPoint(Point point)
        {
            PathPoint pathPoint = new PathPoint();
            pathPoint.point = point;
            return pathPoint;
        }

        /// <summary>
        /// 获取最近的AGV
        /// </summary>
        /// <param name="startPoint"></param>
        /// <returns></returns>
        public static Agv GetNearAgv(Point startPoint, FTask task)
        {
            Agv nearAgv = null;
            //获取当前任务群组的所能派遣的小车任务群组
            List<TaskAgvGroup> agvGroup = App.TaskAgvGroupList.FindAll(a => a.taskGroup == task.strTaskGroup);
            //查找所有状态满足的小车
            List<Agv> agvList = App.AgvList.Where(a => a.isEnable && a.isOnline && a.strAgvError == "" && a.agvState == EnumMsg.State.自动空闲 && a.agvTask == null
                    && !a.isCarry && agvGroup.Exists(b => b.agvGroup == a.agvGroup) && a.currentCharge > App.DangerCharge).ToList();
            if (agvList.Count == 0) return nearAgv;
            int intMin = 0;
            foreach (Agv agv in agvList)
            {
                Point point = App.PointList.Find(a => a.strBarcode == agv.strBarcode);
                if (point == null) continue;
                //agv当前点与任务起点不在同一区域
                if (point.AreaType != task.startPoint.AreaType) continue;
                int agvMinNum = GetMinPoint(startPoint.intX, startPoint.intY, point.intX, point.intY);
                if (intMin == 0) intMin = agvMinNum;
                if (agvMinNum <= intMin)
                {
                    nearAgv = agv;
                    intMin = agvMinNum;
                }
            }
            return nearAgv;
        }

        /// <summary>
        /// 计算两点距离
        /// </summary>
        /// <param name="intX1"></param>
        /// <param name="intY1"></param>
        /// <param name="intX2"></param>
        /// <param name="intY2"></param>
        /// <returns></returns>
        public static int GetMinPoint(int intX1, int intY1, int intX2, int intY2)
        {
            int absXpos = Math.Abs(intX1 - intX2);
            int absYpos = Math.Abs(intY1 - intY2);
            return absXpos + absYpos;
        }

        /// <summary>
        /// 记录行驶前后两点距离
        /// </summary>
        /// <param name="oldBarcode">当前码值</param>
        /// <param name="newBarcode">下个码值</param>
        /// <returns></returns>
        public static int GetDistance(string oldBarcode, string newBarcode, string xuniBarcode)
        {
            int distance = 0;
            Point oldPoint = App.PointList.Find(a => a.strBarcode == oldBarcode);
            Point newPoint = App.PointList.Find(a => a.strBarcode == newBarcode);
            if (oldPoint == null || newPoint == null) return distance;
            Point xuniPoint = App.PointList.Find(a => xuniBarcode != "" && a.strBarcode == xuniBarcode);
            if (oldPoint.intX == newPoint.intX)
            {
                //往Y方向行驶距离
                if (newPoint.intY > oldPoint.intY) { distance = oldPoint.YPosLength; } else { distance = oldPoint.YNegLength; }
            }
            else if (oldPoint.intY == newPoint.intY)
            {
                //往X方向行驶距离
                if (newPoint.intX > oldPoint.intX)
                {
                    if (xuniPoint != null)
                    {
                        distance = oldPoint.XPosLength + xuniPoint.XPosLength;
                    }
                    else
                    {
                        distance = oldPoint.XPosLength;
                    }
                }
                else
                {
                    if (xuniPoint != null)
                    {
                        distance = oldPoint.XNegLength + xuniPoint.XNegLength;
                    }
                    else
                    {
                        distance = oldPoint.XNegLength;
                    }
                }
            }
            return distance;
        }

        /// <summary>
        /// 判断心跳是否存在
        /// </summary>
        public static void CheckAgvOnline()
        {
            foreach (Agv agv in App.AgvList.Where(a => a.isEnable))
            {
                agv.HeartStop();
            }

            if (App.offAgv == 1)
            {
                TimeSpan ts1 = new TimeSpan(App.offTime.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts3 = ts2.Subtract(ts1).Duration();
                int num = ts3.Hours * 3600 + ts3.Minutes * 60 + ts3.Seconds;
                if (num > 300) App.offAgv = 0;
            }
        }

        /// <summary>
        /// 获取起点终点
        /// </summary>
        /// <param name="task"></param>
        /// <param name="fromToPoint"></param>
        /// <returns></returns>
        public static Point GetTaskPoint(FTask task, EnumMsg.ConfigToFromPoint fromToPoint)
        {
            Point point = null;
            switch (fromToPoint)
            {
                case EnumMsg.ConfigToFromPoint.小车当前点:
                    point = App.PointList.Find(a => a.strBarcode == App.AgvList.FirstOrDefault(b => b.strAgvNo == task.strTaskAgv).strBarcode);
                    break;
                case EnumMsg.ConfigToFromPoint.任务起点:
                    point = task.startPoint;
                    break;
                case EnumMsg.ConfigToFromPoint.任务终点:
                    point = task.endPoint;
                    break;
                case EnumMsg.ConfigToFromPoint.旋转点:
                    //待添加,查找合适的旋转点
                    //测试旋转点放到站台点
                    //point = App.PointList.Find(a => a.strBarcode == App.StationList.Find(b => b.strStationNo == task.strStationNo).strBarcode);
                    break;
                case EnumMsg.ConfigToFromPoint.起点动作点:
                    point = App.PointList.Find(a => a.strBarcode == task.startPoint.strPreBarcode);
                    break;

                case EnumMsg.ConfigToFromPoint.终点动作点:
                    //叠托区终点 
                    point = App.PointList.Find(a => a.strBarcode == task.endPoint.strPreBarcode);

                    break;
                default:
                    throw new Exception("未找到对应的点依据信息!!");
            }
            return point;
        }

        /// <summary>
        /// 清理无任务小车锁定的方向信息
        /// </summary>
        public static void ClearPointDirection()
        {
            try
            {
                List<PathPoint> pathList = new List<PathPoint>();
                foreach (Agv agv in App.AgvList.Where(a => a.agvTask != null && a.agvTask.sonTaskList.Count != 0))
                {
                    SonTask sonTask = agv.agvTask.sonTaskList[0];
                    if (sonTask.pathPointList.Count == 0) continue;
                    pathList.AddRange(sonTask.pathPointList);
                }
                List<Point> listPointDirectionLock = App.PointList.FindAll(a => a.tmpDirectionList.Count != 0);
                foreach (Point point in listPointDirectionLock)
                {
                    for (int i = 0; i < point.tmpDirectionList.Count; i++)
                    {
                        TmpDirection tmpDirection = point.tmpDirectionList[i];
                        bool isExists = pathList.Exists(a => a.point == point && a.pathDirection == tmpDirection.pathDirection);
                        if (!isExists)
                            point.tmpDirectionList.Remove(tmpDirection);
                    }
                }
            }
            catch (Exception Ex)
            {
                App.ExFile.MessageError("ClearPointDirection", Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        /// <summary>
        /// 设置小车点占用
        /// </summary>
        public static void SetPointOccupy()
        {
            try
            {
                foreach (Agv agv in App.AgvList)
                {

                    List<Point> pointList = App.PointList.FindAll(a => a.strOccupyAgvNo == agv.strAgvNo || a.strBarcode == agv.strBarcode);
                    foreach (Point point in pointList)
                    {
                        if (agv.isEnable && agv.agvTask == null && point.strBarcode == agv.strBarcode)
                        {
                            point.isOccupy = true;
                            point.strOccupyAgvNo = agv.strAgvNo;
                            continue;
                        }
                        point.isOccupy = false;
                        point.strOccupyAgvNo = "";
                    }
                }
            }
            catch (Exception Ex)
            {
                App.ExFile.MessageError("SetPointOccupy", Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        /// <summary>
        /// 解锁充电桩
        /// </summary>
        public static void UnLockStation()
        {
            try
            {
                foreach (Station Cs in App.StationList)
                {
                    if (!Cs.isLocked) continue;
                    //充电任务选中的充电桩
                    Agv chargeAgv = App.AgvList.FirstOrDefault(a => a.strChooseStation == Cs.strStationNo);
                    if (chargeAgv != null) continue;

                    Point point = App.PointList.Find(a => a.strBarcode == Cs.strBarcode);
                    Agv agv = App.AgvList.FirstOrDefault(a => a.strBarcode == point.strBarcode);
                    if (point.lockedAgv == null && agv == null)
                    {
                        Cs.isLocked = false;
                        UpdateManage.UpdateStation(Cs);
                    }
                }
            }
            catch (Exception Ex)
            {
                App.ExFile.MessageError("UnLockStation", Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        /// <summary>
        /// 配送计算方向
        /// </summary>
        /// <returns></returns>
        public static EnumMsg.OriDial getDirection(int ori, int shelfOri, int stationOri)
        {
            int DialDirection = 0;
            if (ori == 0)
            {
                DialDirection = 5;
                return (EnumMsg.OriDial)DialDirection;
            }
            else if (shelfOri - stationOri - ori + 5 != 0)
            {
                DialDirection = shelfOri - stationOri - ori + 5;
                if (DialDirection < 0)
                {
                    DialDirection = DialDirection + 4 + 5;
                    return (EnumMsg.OriDial)DialDirection;
                }
                else if (DialDirection > 3)
                {
                    DialDirection = DialDirection - 4 + 5;
                    return (EnumMsg.OriDial)DialDirection;
                }
                else
                {
                    DialDirection = DialDirection + 5;
                    return (EnumMsg.OriDial)DialDirection;
                }
            }
            return (EnumMsg.OriDial)DialDirection;
        }

        /// <summary>
        /// 获取最近的充电点
        /// </summary>
        /// <param name="agv"></param>
        public static Station GetMinChargeStation(Agv agv)
        {
            try
            {
                int intMin = 0;
                Station minCs = null;
                //获取所有充电点
                List<Point> listPoint = App.PointList.Where(a => a.pointType == EnumMsg.PointType.充电点 && a.lockedAgv == null).ToList();
                if (listPoint.Count == 0) return minCs;
                foreach (Point point in listPoint)
                {
                    Station Cs = App.StationList.FirstOrDefault(a => a.isEnable && !a.isLocked && a.strBarcode == point.strBarcode);
                    if (Cs == null)
                    {
                        continue;
                    }
                    else
                    {
                        Point agvPoint = App.PointList.Find(a => a.strBarcode == agv.strBarcode);
                        if (point == null) continue;
                        int csMinNum = GetMinPoint(agvPoint.intX, agvPoint.intY, point.intX, point.intY);
                        if (intMin == 0) intMin = csMinNum;
                        if (csMinNum <= intMin)
                        {
                            minCs = Cs;
                            intMin = csMinNum;
                        }
                    }
                }
                return minCs;
            }
            catch (Exception Ex)
            {
                throw new Exception("GetMinChargeStation:" + Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        /// <summary>
        /// 获取最近的回家点
        /// </summary>
        /// <param name="agv"></param>
        /// <returns></returns>
        public static Station GetMinHome(Agv agv,int flag)
        {
            try
            {
                int intMin = 0;
                Station minHome = null;
                Point startPoint = App.PointList.Find(a => a.strBarcode == agv.strBarcode);
                if (startPoint == null) return minHome;

                List<Station> listHome = App.StationList.FindAll(a => a.isEnable && !a.isLocked
                                    && (a.strBarcode == "746")).ToList();
                foreach (Station home in listHome)
                {
                    if (startPoint.pointType == EnumMsg.PointType.回家点) continue;
                    if (App.TaskList.FirstOrDefault(a => a.endPoint.strBarcode == home.strBarcode && a.isTaskSubmit) != null) continue;
                    if (App.PointList.Find(a => a.strBarcode == home.strBarcode).lockedAgv != null) continue;
                    if (App.AgvList.ToList().Exists(a => a.strBarcode == home.strBarcode)) continue;
                    if (App.AgvList.FirstOrDefault(a => a.strChooseStation == home.strStationNo) != null) continue;
                    Point homePoint = App.PointList.Find(a => a.strBarcode == home.strBarcode);
                    int csMinNum = GetMinPoint(startPoint.intX, startPoint.intY, homePoint.intX, homePoint.intY);
                    if (intMin == 0) intMin = csMinNum;
                    if (csMinNum <= intMin)
                    {
                        minHome = home;
                        intMin = csMinNum;
                    }
                }
                return minHome;
            }
            catch (Exception Ex)
            {
                throw new Exception("GetMinHome:" + Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        public static Point GetMinHomePoint(Agv agv, int flag) 
        {
            Point minHomePoint = null;
            int intMin = 0;
            var startPoint = App.PointList.Find(a => a.strBarcode == agv.strBarcode);
            var pointList = App.PointList.Where(a => a.isEnable && a.isStop && a.lockedAgv == null).OrderByDescending(b => b.intStopLevel).ToList();
            foreach (Point point in pointList)
            {
                if (minHomePoint != null && minHomePoint.intStopLevel > point.intStopLevel) continue;
                if (startPoint.isStop && !pointList.Exists(a => a.intStopLevel > startPoint.intStopLevel)) continue;
                var taskList = App.TaskList.ToList();
                if (taskList.Count != 0)
                {
                    var result1 = taskList.Exists(a => a.sonTaskList.Count == 0 && a.endPoint == point);
                    if (result1) continue;
                    //获取所有提交的主任务的子任务
                    var result = taskList.Exists(a => a.sonTaskList.Count != 0 && a.sonTaskList.FirstOrDefault(b => b.startPoint == point || b.endPoint == point) != null);
                    if (result) continue;
                }
                int csMinNum = GetMinPoint(startPoint.intX, startPoint.intY, point.intX, point.intY);
                if (intMin == 0) intMin = csMinNum;
                if (csMinNum <= intMin)
                {
                    minHomePoint = point;
                    intMin = csMinNum;
                }
            }
            

            return minHomePoint;
        }
        /// <summary>
        /// 获取最近的电梯
        /// </summary>
        /// <param name="startPoint">起点信息</param>
        /// <returns></returns>
        public static Point GetMinLiftPoint(Point startPoint)
        {
            try
            {
                int intMin = 0;
                Point minPoint = null;
                List<Point> points = App.PointList.Where(a => a.pointType == EnumMsg.PointType.电梯点 && a.AreaType == startPoint.AreaType).ToList();
                foreach (Point point in points)
                {
                    int csMinNum = GetMinPoint(startPoint.intX, startPoint.intY, point.intX, point.intY);
                    if (intMin == 0) intMin = csMinNum;
                    if (csMinNum <= intMin)
                    {
                        minPoint = point;
                        intMin = csMinNum;
                    }
                }
                return minPoint;

            }
            catch (Exception Ex)
            {
                throw new Exception("GetMinLiftPoint:" + Ex.StackTrace);
            }
        }

        public static Point GetMinLiftWaitPoint(Point startPoint)
        {
            try
            {
                int intMin = 0;
                Point minPoint = null;
                var result = App.StationList.FindAll(b => b.stationType == EnumMsg.StationType.外联及大件工位 && b.strBarcode != startPoint.strBarcode);
                List<Point> points = App.PointList.ToList().FindAll(a => result.Exists(b => b.strBarcode == a.strBarcode));
                foreach (Point point in points)
                {
                    int csMinNum = GetMinPoint(startPoint.intX, startPoint.intY, point.intX, point.intY);
                    if (intMin == 0) intMin = csMinNum;
                    if (csMinNum <= intMin)
                    {
                        minPoint = point;
                        intMin = csMinNum;
                    }
                }
                return minPoint;

            }
            catch (Exception Ex)
            {
                throw new Exception("GetMinLiftWaitPoint:" + Ex.StackTrace);
            }
        }

        /// <summary>
        /// Demo获取最近的电梯
        /// </summary>
        /// <param name="startPoint">起点信息</param>
        /// <returns></returns>
        public static Point GetMinLiftDemoPoint(Point startPoint)
        {
            try
            {
                int intMin = 0;
                Point minPoint = null;
                List<Point> points = App.DemoPointList.Where(a => a.pointType == EnumMsg.PointType.电梯点 && a.AreaType == startPoint.AreaType).ToList();
                foreach (Point point in points)
                {
                    int csMinNum = GetMinPoint(startPoint.intX, startPoint.intY, point.intX, point.intY);
                    if (intMin == 0) intMin = csMinNum;
                    if (csMinNum <= intMin)
                    {
                        minPoint = point;
                        intMin = csMinNum;
                    }
                }
                return minPoint;

            }
            catch (Exception Ex)
            {
                throw new Exception("GetMinLiftDemoPoint:" + Ex.StackTrace);
            }
        }

        /// <summary>
        /// 删除主任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static string DeleteTask(FTask task)
        {
            try
            {
                Agv agv = App.AgvList.FirstOrDefault(a => a.strAgvNo == task.strTaskAgv);
                string sqlDelete = string.Format("DELETE FROM  T_SonTask WHERE strTaskNo = '{0}';", task.strTaskNo);
                foreach (SonTask sonTask in task.sonTaskList)
                {
                    sqlDelete += string.Format("DELETE FROM  T_Base_PathPoint WHERE intSonTaskNo = '{0}';", sonTask.intSonTaskNo);
                }
                bool sqlResult = DbHelperSQL.SqlTransOperator(sqlDelete);
                if (!sqlResult) return "子任务数据库清除失败";
                task.strEndTime = DateTime.Now.ToString();
                bool isUpdateFTaskResult = UpdateManage.UpdateFTask(task);
                if (task.strTaskAgv != "") UpdateManage.InsertAgvMilage(task);
                if (!isUpdateFTaskResult) return "主任务数据库清除失败";
                CServiceImpl.ToWebTaskRefresh(task, 99);
                App.AppDispatcher.Invoke(new Action(() =>
                {
                    App.TaskList.Remove(task);
                }));
                if (agv != null && agv.agvTask == task) agv.agvTask = null;
                if (agv != null && agv.strChooseStation != "")
                {
                    UpdateManage.UpdateAgvMsg(agv);
                    Station station = App.StationList.Find(a => a.strStationNo == agv.strChooseStation);
                    station.isLocked = false;
                    UpdateManage.UpdateStation(station);
                    agv.strChooseStation = "";
                }
                return "";
            }
            catch (Exception Ex)
            {
                throw new Exception("DeleteTask:" + Ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        public static List<Point> GetAreaPoint(Point startPoint, Point endPoint)
        {
            try
            {
                Point newStartPoint = App.PointList.Find(a => a.strBarcode == startPoint.strBarcode && a.AreaType == startPoint.AreaType);
                Point newEndPoint = App.PointList.Find(a => a.strBarcode == endPoint.strBarcode && a.AreaType == endPoint.AreaType);
                List<Point> points = new List<Point>();
                if (newStartPoint.AreaType != newEndPoint.AreaType)
                {
                    if (App.PointList.FindAll(a => a.strBarcode == newEndPoint.strBarcode).Count > 1)
                    {
                        newEndPoint = App.PointList.Find(a => a.strBarcode == newEndPoint.strBarcode && a.AreaType == newStartPoint.AreaType);
                    }
                    else
                    {
                        newStartPoint = App.PointList.Find(a => a.strBarcode == newStartPoint.strBarcode && a.AreaType == newEndPoint.AreaType);
                    }
                }
                if (newStartPoint == null || newEndPoint == null) return null;
                if (newStartPoint.pointType == EnumMsg.PointType.电梯点 && newEndPoint.pointType == EnumMsg.PointType.电梯点)
                {
                    newStartPoint = App.PointList.Find(a => a.AreaType == App.StationList.Find(b => b.strBarcode == newStartPoint.strBarcode && b.strStationNo == "2").stationArea && a.strBarcode == startPoint.strBarcode);
                    newEndPoint = App.PointList.Find(a => a.AreaType == App.StationList.Find(b => b.strBarcode == newEndPoint.strBarcode && b.strStationNo == "2").stationArea && a.strBarcode == endPoint.strBarcode);
                }
                points.Add(newStartPoint);
                points.Add(newEndPoint);
                return points;
            }
            catch (Exception Ex)
            {
                throw new Exception("GetAreaPoint:" + Ex.StackTrace);
            }
        }

        public static bool[] ChangeDoor(int flag, int write, string liftNo)
        {
            bool[] bo = new bool[20];
            try
            {
                ModbusTcpNet readModbus = null;
                ModbusTcpNet writeModbus = null;
                //门外检测门开传感器
                if (liftNo == "1")
                {
                    readModbus = new ModbusTcpNet(App.DoorIp1, 502, 0x01);
                    writeModbus = new ModbusTcpNet(App.DoorIp1, 502, 0x06);
                }
                else
                {
                    readModbus = new ModbusTcpNet(App.DoorIp2, 502, 0x01);
                    writeModbus = new ModbusTcpNet(App.DoorIp2, 502, 0x06);
                }
                OperateResult<bool[]> read1 = readModbus.ReadDiscrete("0", 20);

                //电梯外测传感器
                //OperateResult<bool[]> read1 = readModbus.ReadDiscrete("0", 20);
                if (read1.IsSuccess)
                {
                    //门是否高位
                    //bo[1]==true 门处在高位
                    bo[0] = read1.Content[0];
                    //门开
                    bo[1] = read1.Content[16];
                    //门关
                    bo[2] = read1.Content[17];
                }
                else
                {
                    App.ExFile.MessageError("ReadDoor", "风淋门模块读取失败!= =" + read1.ToMessageShowString() + "= =" + read1.Message);
                    return bo = null;
                }
                //开门
                if (flag == 2)
                {
                    writeModbus.WriteCoil("16", true);
                    writeModbus.WriteCoil("17", false);
                }
                //关门
                else if (flag == 3)
                {
                    writeModbus.WriteCoil("16", false);
                    writeModbus.WriteCoil("17", false);
                }
            }
            catch (Exception Ex)
            {

                App.ExFile.MessageError("ReadDoor", Ex.Message.Replace(Environment.NewLine, ""));
                return bo = null;
            }
            return bo;
        }

        #region 电梯控制
        /// <summary>
        /// 问询电梯
        /// </summary>
        /// <returns></returns>
        public static byte[] liftAsk()
        {
            byte[] askDate = new byte[5];
            try
            {
                askDate[0] = 1;
                askDate[1] = 3;
                askDate[2] = 0;
                var result = CRC16(askDate, 3);
                askDate[3] = result[0];
                askDate[4] = result[1];
                return askDate;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 电梯控制
        /// </summary>
        /// <param name="flag">1、AGV叫电梯;2在电梯内选择去往的楼层,并且关门;3开门;4关门</param>
        /// <param name="liftFlood">楼层信息</param>
        /// <returns></returns>
        public static byte[] liftControl(int flag,int liftFlood)
        {
            byte[] date = new byte[9];
            try
            {
                date[0] = 1;
                date[1] = 6;
                date[2] = 4;
                if (flag == 1)
                {
                    date[3] = (byte)(liftFlood == 1 ? 65 : 2);
                    date[4] = 0;
                    date[5] = 0;
                }
                else if (flag == 2)
                {
                    //在电梯内选择去往的楼层
                    date[3] = 0;
                    date[4] = (byte)liftFlood;
                    date[5] = 32;
                }
                else if (flag == 3)
                {
                    //开门持续中
                    date[3] = 0;
                    date[4] = 0;
                    date[5] = 128;
                }
                else if (flag == 4)
                {
                    //关门持续中
                    date[3] = 0;
                    date[4] = 0;
                    date[5] = 32;
                }
                date[6] = 0;
                var result = CRC16(date, 7);
                date[7] = result[0];
                date[8] = result[1];
                return date;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 电梯校验
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] CRC16(byte[] data,int len)
        {
            //int len = data.Length;
            if (len > 0)
            {
                ushort crc = 0xFFFF;
                for (int i = 0; i < len; i++)
                {
                    crc = (ushort)(crc ^ (data[i]));
                    for (int j = 0; j < 8; j++)
                    {
                        crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
                    }
                }
                byte hi = (byte)((crc & 0xFF00) >> 8);  //高位置
                byte lo = (byte)(crc & 0x00FF);         //低位置

                return new byte[] { lo, hi };
            }
            return new byte[] { 0, 0 };
        }
        #endregion
        public static byte BoolArrayToByte(bool[] array)
        {
            byte rarray = new byte();
            for (int i = 0; i < array.Length; i++)
            {
                int num3 = i % 8;
                byte b = 0;
                switch (num3)
                {
                    case 0:
                        b = 1;
                        break;

                    case 1:
                        b = 2;
                        break;

                    case 2:
                        b = 4;
                        break;

                    case 3:
                        b = 8;
                        break;

                    case 4:
                        b = 16;
                        break;

                    case 5:
                        b = 32;
                        break;

                    case 6:
                        b = 64;
                        break;

                    case 7:
                        b = 128;
                        break;
                }
                if (array[i])
                {
                    rarray += b;
                }
            }
            return rarray;
        }

        /// <summary>
        /// byte转bool
        /// </summary>
        /// <param name="InByte"></param>
        /// <returns></returns>
        public static bool[] ByteToBoolArray(byte InByte)
        {
            bool[] array = new bool[8];
            for (int i = 0; i < 8; i++)
            {
                int num = i / 8;
                int num2 = i % 8;
                byte b = 0;
                switch (num2)
                {
                    case 0:
                        b = 1;
                        break;
                    case 1:
                        b = 2;
                        break;
                    case 2:
                        b = 4;
                        break;
                    case 3:
                        b = 8;
                        break;
                    case 4:
                        b = 16;
                        break;
                    case 5:
                        b = 32;
                        break;
                    case 6:
                        b = 64;
                        break;
                    case 7:
                        b = 128;
                        break;
                }
                if ((InByte & b) == b)
                {
                    array[i] = true;
                }
            }
            return array;
        }

        //public static 

        public static byte[] receiveDate(string address)
        {
            try
            {
                //轮询电梯当前状态
                LiftControl liftControl = ManageTcp.SendLift(liftAsk(), address);
                if (liftControl.receiveDate[1] == 83)
                {
                    //广播错误代码
                    return null;
                }
                var result = CRC16(liftControl.receiveDate, liftControl.receiveDate.Length - 2);
                if (result[0] == liftControl.receiveDate[9] && result[1] == liftControl.receiveDate[10]
                    && liftControl.address == address) { return liftControl.receiveDate; }
                else return null;
            }
            catch (Exception Ex)
            {
                throw new Exception("receiveDate:" + Ex.StackTrace);
            }
        }

        #region  获取当前点小车转盘方向
        /// <summary>
        /// 获取当前点小车转盘方向
        /// </summary>
        /// <param name="currentPathPoint"></param>
        /// <param name="agv"></param>
        /// <returns></returns>
        public static int getAgvDial(PathPoint currentPathPoint, Agv agv)
        {
            try
            {
                int agvDial = 0;
                //给定当前点的车头和转盘方向
                if (currentPathPoint.isCorner)
                {
                    //判断车头与行进方向是否相同
                    if (currentPathPoint.pathDirection == agv.agvOri)
                    {
                        //车头与行进方向相同,转盘方向不变
                        agvDial = (int)agv.dialOri;
                    }
                    else if (Math.Abs(currentPathPoint.pathDirection - agv.agvOri) == 1)
                    {
                        //顺时针旋转90°,转盘顺时针90度
                        if (agv.dialOri > EnumMsg.OriType.X正方向)
                        {
                            agvDial = (int)agv.dialOri + 1;
                        }
                        else
                        {
                            agvDial = 4;
                        }
                    }
                    else if (Math.Abs(currentPathPoint.pathDirection - agv.agvOri) == 2)
                    {
                        //顺时针旋转180°,转盘顺时针180°
                        if (agv.dialOri > EnumMsg.OriType.Y正方向)
                        {
                            agvDial = (int)agv.dialOri - 2;
                        }
                        else
                        {
                            agvDial = (int)agv.dialOri + 2;
                        }
                    }
                    else if (Math.Abs(currentPathPoint.pathDirection - agv.agvOri) == 3)
                    {
                        //顺时针旋转270°,转盘顺时针270°
                        if (agv.dialOri < EnumMsg.OriType.Y负方向)
                        {
                            agvDial = (int)agv.dialOri + 1;
                        }
                        else
                        {
                            agvDial = 1;
                        }
                    }
                }
                return agvDial;
            }
            catch (Exception Ex)
            {
                throw new Exception("getAgvDial:" + Ex.Message.Replace(Environment.NewLine, ""));
            }
        }
        #endregion
    }
}