BlowingDetect360Encoder.cs 39.4 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 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
using AutoMapper;
using FLY.Thick.Blowing;
using FLY.Thick.Blowing.IService;
using FLY.Thick.Blowing360.IService;
using FlyADBase;
using FObjBase;
using FObjBase.Reflect;
using Misc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.Thick.Blowing360.Server
{
    /// <summary>
    /// <para>1.每次收到限位信号(有->没 and 没->有),都会触发 FilmInfoChangedEvent ;时间为上一次限位信号</para>
    /// <para>2.改变辊周长,膜长,都会触发 FilmInfoChangedEvent ;时间为前3次限位信号</para>
    /// <para>3.每次查找FilmInfo, 时间比 当前的限位信号+RenZiJiaPeriod 还要未来,修正 RenZiJiaPeriod,</para>
    /// <para>RenZiJiaPeriod预留10s的余量,避免不断修正</para>
    /// <para>并且触发FilmInfoChangedEvent 时间为上一次限位信号</para>
    /// </summary>
    public class BlowingDetect360Encoder : IBlowingDetect360EncoderService, IBlowingDetectInServer
    {
        #region 输入口定义
        /// <summary>
        /// 旋转架转一圈的定位信号
        /// </summary>
        const int Org_bit = 12;

        /// <summary>
        /// 辊信号 对应输入位
        /// </summary>
        const int Roll_bit = 11;
        #endregion

        #region 参数

        /// <summary>
        /// 人字架 旋转1周总脉冲数
        /// </summary>
        public int PosOfR { get; set; }

        /// <summary>
        /// 复位信号总脉冲数
        /// </summary>
        public int PosOfOrgSign { get; set; }
        /// <summary>
        /// 人字架到测厚仪膜长 单位m
        /// </summary>
        public double FilmLength { get; set; }

        /// <summary>
        /// 辊周长,单位mm
        /// </summary>
        public double RollPerimeter { get; set; }

        #endregion

        #region 状态

        /// <summary>
        /// 当前旋转架旋转角度
        /// </summary>
        public double Angle { get; private set; }


        /// <summary>
        /// 当前方向
        /// </summary>
        public Misc.DIRECTION Direction { get; private set; } = DIRECTION.FORWARD;

        /// <summary>
        /// 累计旋转次数
        /// </summary>
        public virtual int RotationCnt { get; protected set; }

        /// <summary>
        /// 最后一个限位信号 到当前已经消耗的时间
        /// </summary>
        public TimeSpan PastTime { get; private set; }

        /// <summary>
        /// 当前线速度,单位 m/min
        /// </summary>
        public double FilmVelocity { get; private set; }

        /// <summary>
        /// 离开限位 到 撞下一个限位  的 旋转架转动时间, 需要初始值,以后测量出来的
        /// </summary>
        public TimeSpan RenZiJiaPeriod { get; private set; }

        /// <summary>
        /// 缓冲区拥有数据的时间长度,1s更新一次
        /// </summary>
        public TimeSpan BufTotalTime { get; private set; }

        /// <summary>
        /// 缓冲区最新数据时间
        /// </summary>
        public DateTime BufLastTime { get; private set; }

        /// <summary>
        ///旋转架脉冲
        /// </summary>
        public int GlobalPos { get; private set; }
        /// <summary>
        /// 旋转架脉冲速度
        /// </summary>
        public int Speed { get; private set; }
        #endregion



        public event FilmInfoChangedEventHandler FilmInfoChangedEvent;


        public event ClearEventHandler ClearEvent;


        /// <summary>
        /// 原点脉冲
        /// </summary>
        int OrgPos;
        private int OrgPosDiff { get; set; }
        /// <summary>
        /// 复位信号列表更新时间
        /// </summary>
        public DateTime OrgSignListUpdateTime { get; protected set; }

        /// <summary>
        /// 辊信号列表
        /// </summary>
        RList<RollCell> mRollList;

        /// <summary>
        /// 旋转信息列表
        /// </summary>
        RList<RotationData> mRotationList;

        /// <summary>
        /// 辊速度列表
        /// </summary>
        RList<FilmVelocityData> mFilmVelocityList;

        /// <summary>
        /// 与mLimitList 一样!!
        /// 存在的目的用于看看信号是否正常
        /// </summary>
        RList<OrgSignData> mOrgSignList;

        /// <summary>
        /// 脉冲信号列表
        /// </summary>
        RList<RPosData> mPosList;

        /// <summary>
        /// 最后一次接收到辊信号的时间
        /// </summary>
        DateTime lastRollTime;
        DateTime lastOrgSignTime;
        IFlyADClientAdv flyad;


        /// <summary>
        /// 
        /// </summary>
        public BlowingDetect360Encoder()
        {
            RenZiJiaPeriod = TimeSpan.FromMinutes(8);

            RollPerimeter = 314;//mm
            FilmLength = 25;//m

            PosOfR = 50000;
            PosOfOrgSign = 100;
            OrgPos = 0;
            Angle = 0;
            FilmVelocity = 0;//m/min

            mRollList = new RList<RollCell>(100);//100m/min, 周长314mm = 5.3r/s 
            lastRollTime = DateTime.MinValue;

            mFilmVelocityList = new RList<FilmVelocityData>(30*60);//限制最快间隔1s, 保存30min数据
            mRotationList = new RList<RotationData>(5);//5圈数据
            mOrgSignList = new RList<OrgSignData>(10);
            mPosList = new RList<RPosData>(30*60);//限制最快间隔1s, 只保存30min数据
            RotationCnt = 0;
            
            Clear();


            Load();
            CheckParamErr();

            PropertyChanged += new PropertyChangedEventHandler(RenZiJiaAndFilmPositionDetect_PropertyChanged);

        }

        double getAngle(int pos) {
            double angle = 360 * pos / PosOfR;
            while (angle < 0)
                angle += 360;
            while (angle >= 360)
                angle -= 360;

            return angle;
        }



        /// <summary>
        /// 使参数合法
        /// </summary>
        public void CheckParamErr()
        {

            if ((FilmLength < 0) || (FilmLength > 100))
            {
                FilmLength = 25;
            }

            if ((RollPerimeter < 100) || (RollPerimeter > 1000))
            {
                RollPerimeter = 314;
            }
        }

        void RenZiJiaAndFilmPositionDetect_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if ((e.PropertyName == nameof(FilmLength)) ||
                (e.PropertyName == nameof(RollPerimeter)) ||
                (e.PropertyName == nameof(PosOfR))||
                (e.PropertyName == nameof(PosOfOrgSign))
            )
            {

                TouchFilmInfoChanged_lastLimit(2);
            }
        }
        /// <summary>
        /// 触发膜信息修改事件
        /// </summary>
        /// <param name="last_cnt">最后旋转几次</param>
        void TouchFilmInfoChanged_lastLimit(int last_cnt)
        {
            int idx = mRotationList.Count - last_cnt;
            if (idx < 0)
                idx = 0;
            var earlyInquiryTime = mRotationList[idx].EarlyInquiryTime;
            FilmInfoChangedEvent?.Invoke(this, new FilmInfoChangedEventArgs(earlyInquiryTime));
        }

        /// <summary>
        /// 创建完对象后,必须赋值
        /// </summary>
        /// <param name="flyad"></param>
        public void Init(IFlyADClientAdv flyad)
        {
            this.flyad = flyad;
            flyad.IStatusChangedEvent += flyad_IStatusChangedEvent;

            FObjBase.PollModule.Current.Poll_Config(
                FObjBase.PollModule.POLL_CONFIG.ADD, OnPoll, TimeSpan.FromSeconds(1));

            flyad.PropertyChanged += Flyad_PropertyChanged;
        }

        private void Flyad_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(flyad.BeResetTime)) {
                //被复位了,全部清空重新来
                Clear();
            }
        }

        void flyad_IStatusChangedEvent(object sender, FlyADBase.IStatusChangedEventArgs e)
        {
            update_orgSign(e);
            update_rollSign(e);

        }

        void update_orgSign(IStatusChangedEventArgs e)
        {

            bool bchanged = false;//信号更新?
            DateTime sysTime = e.Time;//信号更新发生的时间,这个是AD盒的时间
            DateTime now = DateTime.Now;
            bool status = false;//信号的状态 true开始, false结束

            if (Misc.MyBase.CHECKBIT(e.IChanged, Org_bit - 1))//信号0 发生变化
            {
                bchanged = true;
                if (!Misc.MyBase.CHECKBIT(e.IStatus, Org_bit - 1))
                {
                    status = true;
                }
            }

            if (!bchanged)//没有信号更新
                return;

            OrgSignData sd = new OrgSignData() { Time = now, SysTime = sysTime,  On = status, GlobalPos = e.Position2, Speed = flyad.Speed2 };
            mOrgSignList.RAdd(sd);
            OrgSignListUpdateTime = now;

        }

        void update_rollSign(IStatusChangedEventArgs e)
        {
            //----------------------------------------------------------------------
            //更新辊信号
            if (!Misc.MyBase.CHECKBIT(e.IChanged, Roll_bit - 1))
                return;//没有信号更新

            //信号的状态
            bool status = !Misc.MyBase.CHECKBIT(e.IStatus, Roll_bit - 1);


            DateTime sysTime = e.Time;//信号更新发生的时间
            DateTime dt = DateTime.Now;

            if (status)//1->0 触发!!!
            {
                mRollList.RAdd(
                    new RollCell()
                    {
                        Time = dt,
                        SysTime = sysTime
                    });
            }
        }

        void OnPoll_updatePos() {

            DateTime now = DateTime.Now;
            DateTime sysTime = flyad.Now;
            int globalPos = flyad.Position2;
            int speed = flyad.Speed2;
            if (mPosList.Count() > 0)
            {
                var lastPosData = mPosList.Last();
                if (now - lastPosData.Time < TimeSpan.FromSeconds(1))
                {
                    return;
                }
            }
            mPosList.RAdd(new RPosData() { Time = now, SysTime= sysTime, Speed = speed, GlobalRPos = globalPos });
            GlobalPos = globalPos;
            Speed = speed;

            if (speed > 0)
                Direction = DIRECTION.FORWARD;
            else if (speed < 0)
                Direction = DIRECTION.BACKWARD;
            updateRenZiJiaPeriod();

            updateRotation(now, globalPos);


            updateAngle();
        }
        void updateRenZiJiaPeriod() 
        {
            int sum = 0;
            int cnt = 0;
            for (int i = 0; i < 10; i++) {
                int index = mPosList.Count() - 1 - i;
                if (index < 0)
                    break;
                sum+=mPosList[index].Speed;
                cnt++;
            }
            double speed = Math.Abs(1.0*sum/cnt);
            if (speed > 0)
            {
                double min = PosOfR / (speed * 60.0);
                if (min < 20)
                    RenZiJiaPeriod = TimeSpan.FromMinutes(min);
            }
        }
        /// <summary>
        /// 1秒触发一次
        /// </summary>
        void OnPoll()
        {
            if (!flyad.IsReady || !flyad.IsConnected)
                return;

            //--------------------------------------------------------------------
            //更新脉冲位置
            OnPoll_updatePos();

            //--------------------------------------------------------------------
            //轮询复位信号列表
            OnPoll_updateOrgPos();
            //--------------------------------------------------------------------
            //更新当前线速度
            OnPoll_updateFilmV();

            //更新pasttime
            updatePastTime();
            //--------------------------------------------------------------------
            //缓存区尺寸
            updateBufSize();
        }
        void updatePastTime()
        {
            if (mOrgSignList.Count() > 0)
            {
                var sign = mOrgSignList.Last();
                var time = sign.Time;
                var ts = DateTime.Now - time;
                if (ts.TotalMinutes < 99)
                {
                    PastTime = ts;
                }
            }
            else {
                if (mPosList.Count() > 0) {
                    var time = mPosList.First().Time;
                    var ts = DateTime.Now - time;
                    if (ts.TotalMinutes < 99)
                    {
                        PastTime = ts;
                    }
                }
            }
        }
        void updateBufSize() 
        {
            List<DateTime> times = new List<DateTime>();
            if (mPosList.Count() > 0)
            {
                times.Add(mPosList.First().Time);
                times.Add(mPosList.Last().Time);
            }
            if (mOrgSignList.Count() > 0)
            {
                times.Add(mOrgSignList.First().Time);
                times.Add(mOrgSignList.Last().Time);
            }
            if (mFilmVelocityList.Count() > 0)
            {
                times.Add(mFilmVelocityList.First().Time);
                times.Add(mFilmVelocityList.Last().Time);
            }
            if (times.Count() > 0)
            {
                BufLastTime = times.Max();
                BufTotalTime = times.Max() - times.Min();
            }
            else {
                BufLastTime = DateTime.MinValue;
                BufTotalTime = TimeSpan.Zero;
            }
        }
        /// <summary>
        /// 旋转架速度换算
        /// </summary>
        void updateAngle()
        {
            int globalPos = mPosList.Last().GlobalRPos;

            int pos = globalPos - OrgPos;
            while (pos < 0)
                pos += PosOfR;
            while (pos > PosOfR)
                pos -= PosOfR;
            Angle = getAngle(pos);
        }


        /// <summary>
        /// 计算复位脉冲
        /// </summary>
        void OnPoll_updateOrgPos() 
        {
            if (mOrgSignList.Count() == 0)
                return;

            var orgSign = mOrgSignList.Last();
            if (lastOrgSignTime == orgSign.Time)
                return;

            lastOrgSignTime = orgSign.Time;
            if (orgSign.On == false)
            {
                //下降沿

                //通过速度,判断方向
                int lastOrgPos = OrgPos;
                if (orgSign.Speed > 0)
                {
                    //正方向
                    OrgPos = orgSign.GlobalPos;
                    Direction = DIRECTION.FORWARD;
                    
                }
                else
                {
                    //反方向
                    OrgPos = orgSign.GlobalPos - PosOfOrgSign;
                    Direction = DIRECTION.BACKWARD;
                }
                OrgPosDiff = (OrgPos - lastOrgPos) % PosOfR;
                if (OrgPosDiff > 2 * PosOfR / 360.0)
                    TouchFilmInfoChanged_lastLimit(1);

                addRotation(orgSign.Time, orgSign.GlobalPos);
            }

        }
        void addRotation(DateTime time, int globalPos) 
        {
            if (mRotationList.Count() == 0)
            {
                var rotation = new RotationData();
                rotation.BeginTime = time;
                rotation.EndTime = time;
                rotation.Direction = Direction;
                rotation.GlobalPosMin = globalPos;
                rotation.GlobalPosMax = globalPos;
                rotation.OrgPos = OrgPos;
                rotation.RotationCnt = 0;
                mRotationList.RAdd(rotation);
                RotationCnt = rotation.RotationCnt;
            }
            else {
                var last_rotation = mRotationList.Last();
                if (last_rotation.RotationCnt == 0)
                    last_rotation.OrgPos = OrgPos;

                if ((last_rotation.GlobalPosMax - last_rotation.GlobalPosMin) < PosOfR / 2)
                {
                    //小于1/2圈,它不是完整的,删除之前的
                    var rotation = last_rotation;
                    rotation.EndTime = time;
                    last_rotation.Direction = Direction;
                    last_rotation.GlobalPosMin = globalPos;
                    last_rotation.GlobalPosMax = globalPos;
                    last_rotation.OrgPos = OrgPos;

                }
                else {
                    //之前的结束了
                    last_rotation = new RotationData();
                    last_rotation.BeginTime = time;
                    last_rotation.EndTime = time;
                    last_rotation.Direction = Direction;
                    last_rotation.GlobalPosMin = globalPos;
                    last_rotation.GlobalPosMax = globalPos;
                    last_rotation.OrgPos = OrgPos;
                    last_rotation.RotationCnt = RotationCnt+1;
                    mRotationList.RAdd(last_rotation);
                    RotationCnt = last_rotation.RotationCnt;
                }
            }
        }

        void updateRotation(DateTime time, int globalPos) 
        {
            if (mRotationList.Count() == 0)
            {
                OrgPos = globalPos;//当前的位置是不能确定的
                RotationCnt = 0;


                var rotation = new RotationData();
                rotation.BeginTime = time;
                rotation.EndTime = time;
                rotation.Direction = Direction;
                rotation.GlobalPosMin = globalPos;
                rotation.GlobalPosMax = globalPos;
                rotation.OrgPos = globalPos;
                rotation.RotationCnt = 0;
                mRotationList.RAdd(rotation);

            }
            else
            {
                var rotation = mRotationList.Last();
                if (globalPos < rotation.GlobalPosMin)
                    rotation.GlobalPosMin = globalPos;
                if (globalPos > rotation.GlobalPosMax)
                    rotation.GlobalPosMax = globalPos;
                rotation.EndTime = time;
            }
        }
        /// <summary>
        /// 更新当前线速度
        /// </summary>
        void OnPoll_updateFilmV()
        {

            if (mRollList.Count() < 3)
            {
                //不够数据
                return;
            }

            DateTime now = flyad.Now;// AD盒的systick

            
            if (now - lastRollTime < TimeSpan.FromSeconds(1))//1秒更新一次速度
                return;//间隔太短


            //更新当前速度
            if (lastRollTime != mRollList.Last().Time)
            {
                lastRollTime = mRollList.Last().Time;
                int lastIndex = mRollList.Count() - 1;
                double v = FilmVelocity;
                //计算3秒内均值
                for (int index = mRollList.Count() - 2; index >= 0; index--)
                {
                    DateTime firstTime = mRollList[index].Time;
                    TimeSpan ts = lastRollTime - firstTime;
                    int interval = lastIndex - index;
                    double m = RollPerimeter * interval / 1000.0;
                    v = m / ts.TotalMinutes;
                    if (ts.TotalSeconds >= 3)
                    {
                        //满足要求
                        break;
                    }
                }
                FilmVelocity = Math.Round(v, 2);
            }
            else
            {
                if (now > lastRollTime)
                {
                    TimeSpan ts = now - lastRollTime;
                    double mm = RollPerimeter;
                    double v = mm / ts.TotalMinutes;
                    if (v < FilmVelocity / 4)
                    {
                        //太长时间没有辊信号,应该已经停了
                        //清空列表
                        mRollList.Clear();
                        lastRollTime = DateTime.MinValue;
                        FilmVelocity = 0;
                        
                    }
                }
            }

            updateFilmVelocityList();
        }
        void updateFilmVelocityList() {
            var now = DateTime.Now;
            var sysTime = flyad.Now;
            if (mFilmVelocityList.Count() == 0)
            {
                mFilmVelocityList.RAdd(new FilmVelocityData()
                {
                    Time = now,
                    SysTime = sysTime,
                    FilmVelocity = FilmVelocity,
                    GlobalMm = 0
                });
            }
            else
            {
                var last_filmVelocityData = mFilmVelocityList.Last();
                var filmVelocityData = new FilmVelocityData
                {
                    Time = now,
                    SysTime = sysTime,
                    FilmVelocity = FilmVelocity,
                    GlobalMm = last_filmVelocityData.GlobalMm + (int)(FilmVelocity * (now - last_filmVelocityData.Time).TotalMinutes * 1000)
                };
                mFilmVelocityList.RAdd(filmVelocityData);
            }
        }
        public void Clear()
        {
            mRotationList.Clear();
            mRollList.Clear();
            mPosList.Clear();
            mOrgSignList.Clear();

            FilmVelocity = 0;
            RotationCnt = 0;//复位次数!!!
            Angle = 0;
            OrgPos = 0;
            

            lastRollTime = DateTime.MinValue;
            lastOrgSignTime = DateTime.MinValue;

            BufTotalTime = TimeSpan.Zero;
            BufLastTime = DateTime.MinValue;
            OrgSignListUpdateTime = DateTime.MinValue;

            ClearEvent?.Invoke(this);
        }

        /// <summary>
        /// 获取当前在膜上的测量点,对应于膜泡的角度信息, 当时间点,比LimitList.Last.dt+RenZiJiaPeriod还要后,更新RenZiJiaPeriod
        /// 返回 -1, 当前的时间点在列表以前;
        /// 返回 0, 当前的时间点在列表中;
        /// 返回 1, 当前的时间点在列表的未来;
        /// </summary>
        /// <param name="filmWidth">被压扁后的膜宽度</param>
        /// <param name="filmPosH">探头所在膜的横向位置</param>
        /// <param name="dt">测量的时间点</param>
        /// <returns></returns>
        public int GetFilmInfo(out FilmInfo filminfo, DateTime dt, double filmWidth, double filmPosH)
        {
            double filmlen = FilmLength;

            return GetFilmInfo(out filminfo, dt, filmWidth, filmPosH, filmlen);
        }
        int GetFilmInfo(out FilmInfo filminfo, DateTime dt, double filmWidth, double filmPosH, double filmLen)
        {
            filminfo = null;

            //与0°的偏移
            double a = filmPosH / filmWidth * 180;

            if ((a < 0) || (a > 180))
            {
                return -1;//不在膜的范围内
            }

            if (dt == DateTime.MinValue)
            {
                //TODO, BUG
                return -1;//不在膜的范围内
            }

            int ret = GetAgo(dt, filmLen, out DateTime ago_dt, out double velocity);

            if (ret == 1)
                return ret;//发生在未来不处理!!!

            GetAngle(a, ago_dt, out double angle0, out double angle1, out int rotationCnt, out DIRECTION direction);
            
            var rotation = mRotationList.Find(r => r.RotationCnt == rotationCnt);
            if (rotation != null)
            {
                if(rotation.EarlyInquiryTime!=DateTime.MinValue
                    && rotation.EarlyInquiryTime>dt)
                    rotation.EarlyInquiryTime = dt;
            }
            
            filminfo = new FilmInfo()
            {
                angle1 = angle0,
                angle2 = angle1,
                filmVelocity = velocity,
                direction = direction,
                rotationCnt = rotationCnt,
                inCV = true,
            };
            return ret;
        }

        #region 人字架时间点<-->24m后膜时间点

        /// <summary>
        /// 输入当前时间点,找到 刚出人字架时的时间点, 及那时候的线速度;
        /// 返回 -1, 当前的时间点在列表以前;
        /// 返回 0, 当前的时间点在列表中;
        /// 返回 1, 当前的时间点在列表的未来;
        /// </summary>
        /// <param name="dt">当前时间</param>
        /// <param name="ago_dt">24米真实长度</param>
        /// <returns></returns>
        int GetAgo(DateTime dt, double filmlength, out DateTime ago_dt, out double ago_velocity)
        {
            ago_dt = DateTime.MinValue;
            ago_velocity = 0;

            int index;
            int ret = FilmVelocityList_FindIndex(dt, out index);
            if (ret == 1)
            {
                return ret;
            }
            else if (ret == -1)
            {
                if (mFilmVelocityList[0].FilmVelocity == 0)
                    return 1;

                double min = filmlength / mFilmVelocityList[0].FilmVelocity;
                if (min > 30)
                    return 1;//时间太长,速度基本为0 ,异常

                ago_dt = dt - TimeSpan.FromMinutes(min);
                ago_velocity = mFilmVelocityList[0].FilmVelocity;
                return -1;
            }
            else
            {
                var next_fvd = mFilmVelocityList[index + 1];
                var fvd = mFilmVelocityList[index];
                TimeSpan ts = dt - fvd.Time;
                int globalmm = (int)(ts.TotalMinutes * next_fvd.FilmVelocity * 1000) + fvd.GlobalMm;
                globalmm = globalmm - (int)(filmlength * 1000);

                //向前找

                for (int i = index; i >= 0; i--) 
                {
                    index = i;
                    if (globalmm >= mFilmVelocityList[i].GlobalMm) 
                    {
                        //找到,就是这里
                        break;
                    }
                }

                if (globalmm >= mFilmVelocityList[index].GlobalMm)
                {
                    double min = (mFilmVelocityList[index + 1].GlobalMm - globalmm)/1000.0 / mFilmVelocityList[index + 1].FilmVelocity;
                    ago_dt = mFilmVelocityList[index + 1].Time - TimeSpan.FromMinutes(min);
                    ago_velocity = mFilmVelocityList[index + 1].FilmVelocity;
                    return 0;
                }
                else 
                {
                    if (mFilmVelocityList[index].FilmVelocity == 0)
                    {
                        //永远无法到达
                        ago_dt = mFilmVelocityList[index].Time;
                        ago_velocity = mFilmVelocityList[index].FilmVelocity;
                        return -1;

                    }
                    else {
                        double min = (mFilmVelocityList[index].GlobalMm - globalmm) / 1000.0 / mFilmVelocityList[index].FilmVelocity;
                        ago_dt = mFilmVelocityList[index].Time - TimeSpan.FromMinutes(min);
                        ago_velocity = mFilmVelocityList[index].FilmVelocity;
                        return -1;
                    }
                }
            }
        }

   

        #endregion




        /// <summary>
        /// 时间点查找旋转角度 -180~180
        /// </summary>
        /// <param name="dt">时间</param>
        /// <param name="angle">角度</param>
        /// <param name="direction">旋转的方向</param>
        /// <param name="rotationCnt">旋转的次数</param>
        void GetAngle(DateTime dt, out double angle, out int rotationCnt, out DIRECTION direction)
        {
            angle = Angle;
            rotationCnt = RotationCnt;
            direction = Direction;

            int ret = RotationList_FindIndex(dt, out int r_index);
            int retPos = PosList_FindIndex(dt, out int p_index);
            if (ret == 1 || retPos == 1) {
                //发生在未来
                return;
            }

            if (ret ==-1)
            {
                mRotationList[r_index].BeginTime = dt;
                p_index = -1;
            }

            var posData = mPosList[p_index + 1];
            TimeSpan ts = posData.Time - dt;
            int globalPos = (int)(posData.GlobalRPos - ts.TotalSeconds * posData.Speed);


            angle = getAngle(globalPos - mRotationList[r_index].OrgPos);
            rotationCnt = mRotationList[r_index].RotationCnt;
            direction = mRotationList[r_index].Direction;
        }

        #region RollList 查找


        /// <summary>
        /// dt 这个时间,在是 index 与 index+1 中间发生的
        /// 返回 -1,这个过去的时间;
        /// 返回 0,在列表中;
        /// 返回 1,发生在未来的时间;
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        int FilmVelocityList_FindIndex(DateTime dt, out int index)
        {
            index = 0;
            if (mFilmVelocityList.Count < 2)//没数据,所以是发生在未来的
                return 1;

            for (int i = mFilmVelocityList.Count - 1; i >= 0; i--)
            {
                index = i;
                if (dt >= mFilmVelocityList[i].Time)
                {
                    //找到了
                    if (i == (mFilmVelocityList.Count - 1))//这个是未来的时间点,还没发生!!! 
                        return 1;
                    else
                    {
                        return 0;
                    }
                    
                }
            }

            //这个在过去的时间
            return -1;
        }

        /// <summary>
        /// dt 这个时间,在是 index 与 index+1 中间发生的
        /// 返回 -1,这个过去的时间;
        /// 返回 0,在列表中;
        /// 返回 1,发生在未来的时间;
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        int PosList_FindIndex(DateTime dt, out int index) {

            index = 0;
            if (mPosList.Count <= 1)//没数据,所以是发生在未来的
                return 1;

            for (int i = mPosList.Count - 1; i >= 0; i--)
            {
                if (dt >= mPosList[i].Time)
                {
                    //找到了
                    if (i == (mPosList.Count - 1))//这个是未来的时间点,还没发生!!! 
                    {
                        index = i;
                        return 1;
                    }
                    else
                    {
                        index = i;
                        return 0;
                    }
                }
            }

            //这个在过去的时间
            return -1;
        }
        #endregion

        /// <summary>
        /// 时间对应旋转状态
        /// </summary>
        enum DTSTATUS
        {
            /// <summary>
            /// 发生在未来的均速阶段
            /// </summary>
            Future,
            /// <summary>
            /// 发生在过去的均速阶段
            /// </summary>
            Past,
            /// <summary>
            /// 发生在均速阶段
            /// </summary>
            Normal,
            /// <summary>
            /// 发生在方向切换阶段
            /// </summary>
            Swap,

        }
        enum ListFindIndexResult
        {
            /// <summary>
            /// 发生在未来, index.dt_end ~ 未来, 可能 index都还没有发生
            /// </summary>
            Future,
            /// <summary>
            /// 发生在 index.dt_end ~ (index+1).dt_begin
            /// </summary>
            BetweenCells,
            /// <summary>
            /// 发生在 过去
            /// </summary>
            Past
        }
        /// <summary>
        /// 找到 列表中 (开始时间,结束时间) 小于 dt 的信号点
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        int RotationList_FindIndex(DateTime dt, out int index)
        {
            index = 0;
            if (mRotationList.Count <= 0)//没数据,所以是发生在未来的
                return 1;

            for (int i = mRotationList.Count - 1; i >= 0; i--)
            {
                var rotationData  = mRotationList[i];
                if (dt >= rotationData.BeginTime)
                {
                    //找到了
                    index = i;
                    return 0;
                }
            }

            //这个在过去的时间
            return -1;
        }



        /// <summary>
        /// 获取膜角度
        /// </summary>
        /// <param name="a">与0°的偏移, 0~180</param>
        /// <param name="dt">时间点</param>
        /// <param name="angle0">上面的膜对应的膜角度</param>
        /// <param name="angle1">下面的膜对应的膜角度</param>
        /// <param name="rotationCnt">扫描次数</param>
        bool GetAngle(double a, DateTime dt, out double angle0, out double angle1, out int rotationCnt, out DIRECTION direction)
        {
            angle0 = 0;
            angle1 = 0;
            rotationCnt = 0;
            direction = DIRECTION.FORWARD;
            if (a > 180 || a < 0)
                return false;

            //压扁对面的角度
            double a_other = 360 - a;
            double angle;

            //不修改旋转速度!!!!!!!!!!!!
            GetAngle(dt, out angle, out rotationCnt, out direction);

            a += angle;
            if (a >= 360)
                a -= 360;
            else if (a < 0)
                a += 360;

            a_other += angle;
            if (a_other >= 360)
                a_other -= 360;
            else if (a_other < 0)
                a_other += 360;
            angle0 = a;
            angle1 = a_other;
            return true;
        }



        public void Apply()
        {
            Save();
        }




        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Clear();
        }

        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion


        /// <summary>
        /// 加载历史数据
        /// </summary>
        /// <returns></returns>
        public bool Load()
        {
            if (File.Exists(file_path))
            {
                try
                {
                    string json = File.ReadAllText(file_path);
                    var jsonDb = JsonConvert.DeserializeObject<BlowingDetect360EncoderJsonDb>(json);
                    //BlowingDetect360EncoderJsonDb.Mapper.Map(jsonDb, this);
                    jsonDb.Map(this);
                    return true;
                }
                catch(Exception e)
                {
                    //异常,没有json 解码失败

                }
                return false;
            }
            return false;
        }
        string file_path = "blowingdetect360encoder.json";
        /// <summary>
        /// 保存
        /// </summary>
        public void Save()
        {
            try
            {
                var jsonDb = BlowingDetect360EncoderJsonDb.Mapper.Map<BlowingDetect360EncoderJsonDb>(this);
                string json = JsonConvert.SerializeObject(jsonDb, Formatting.Indented);
                File.WriteAllText(file_path, json);
            }
            catch
            {
                //异常,没有json 编码失败

            }
        }


        /// <summary>
        /// 获取 旋转位置列表
        /// </summary>
        /// <param name="begin">开始时间</param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        [Call(typeof(List<RPosData>))]
        public void GetRPosList(DateTime begin, AsyncCBHandler asyncDelegate, object asyncContext) 
        {
            if (mPosList.Count() == 0)
                asyncDelegate?.Invoke(asyncContext, null);
            else
            {
                int index = mPosList.FindIndex(s => s.Time >= begin);
                if (index == -1)
                    index = 0;
                asyncDelegate?.Invoke(asyncContext, mPosList.Skip(index).ToList());
            }
        }

        /// <summary>
        /// 获取 旋转信号列表
        /// </summary>
        /// <param name="begin">开始时间</param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        [Call(typeof(List<OrgSignData>))]
        public void GetOrgSignList(DateTime begin, AsyncCBHandler asyncDelegate, object asyncContext)
        {
            if (mOrgSignList.Count() == 0)
                asyncDelegate?.Invoke(asyncContext, null);
            else {
                int index = mOrgSignList.FindIndex(s => s.Time >= begin);
                if (index == -1)
                    index = 0;
                asyncDelegate?.Invoke(asyncContext, mOrgSignList.Skip(index).ToList());
            }
        }


        /// <summary>
        /// 获取 线速度列表
        /// </summary>
        /// <param name="begin">开始时间</param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        [Call(typeof(List<FilmVelocityData>))]
        public void GetFilmVelocityList(DateTime begin, AsyncCBHandler asyncDelegate, object asyncContext) 
        {
            int ret = FilmVelocityList_FindIndex(begin, out int index);
            if (ret <= 0)
                asyncDelegate?.Invoke(asyncContext, mFilmVelocityList.Skip(index).ToList());
            else
                asyncDelegate?.Invoke(asyncContext, null);
        }


        /// <summary>
        /// 获取 旋转信号列表
        /// </summary>
        /// <param name="begin">开始时间</param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        [Call(typeof(List<RotationData>))]
        public void GetRotationList(DateTime begin, AsyncCBHandler asyncDelegate, object asyncContext) 
        {
            int ret = RotationList_FindIndex(begin, out int index);
            if (ret <= 0)
                asyncDelegate?.Invoke(asyncContext, mRotationList.Skip(index).ToList());
            else 
                asyncDelegate?.Invoke(asyncContext, null);
            
        }
    }

    public class BlowingDetect360EncoderJsonDb
    {
        public static Mapper Mapper { get; } = new AutoMapper.Mapper(new MapperConfiguration(c => {
            c.CreateMap<BlowingDetect360Encoder, BlowingDetect360EncoderJsonDb>().ReverseMap();
        }));
        public void Map(BlowingDetect360Encoder dest) {
            dest.PosOfR = PosOfR;
            dest.PosOfOrgSign = PosOfOrgSign;
            dest.FilmLength = FilmLength;
            dest.RollPerimeter = RollPerimeter;
        }
        /// <summary>
        /// 人字架 旋转1周总脉冲数
        /// </summary>
        public int PosOfR { get; set; } = 100000;

        /// <summary>
        /// 复位信号总脉冲数
        /// </summary>
        public int PosOfOrgSign { get; set; } = 300;
        /// <summary>
        /// 人字架到测厚仪膜长 单位m
        /// </summary>
        public double FilmLength { get; set; } = 26;

        /// <summary>
        /// 辊周长,单位mm
        /// </summary>
        public double RollPerimeter { get; set; } = 314;
    }
}