FlyAd2021Adv.cs 22.2 KB
Newer Older
1
using FObjBase;
2 3
using Misc;
using System;
4
using System.Diagnostics;
5 6
using System.Linq;

7
namespace FlyADBase
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
{
    public partial class FlyAd2021 : IFlyADClientAdv
    {
        #region IFlyADClientAdv property
        /// <summary>
        /// 通过脉冲计算速度,不使用AD盒的输出
        /// </summary>
        [Obsolete("已经无效,必须通过电脑计算速度")]
        public bool IsCalSpeed { get; set; } = true;

        /// <summary>
        /// grid数据平滑
        /// </summary>
        public int GridSmooth { get; set; }

        /// <summary>
        /// 机架总长
        /// </summary>
        public int PosLen { get; set; } = 8900;

        /// <summary>
        /// 使用独立的脉冲最大最小值
        /// </summary>
        public bool HasPosMaxMin { get; set; }

        /// <summary>
        /// 最小脉冲,默认是0
        /// </summary>
        public int PosMin { get; set; } = 0;

        /// <summary>
        /// 最大脉冲,默认于PosLen 一样
        /// </summary>
        public int PosMax { get; set; } = 8900;

        public int GridLen => PosLen / PosOfGrid;
        /// <summary>
        /// Speed1 = Velocity * Speed1Scale
        /// </summary>
        public double Speed1Scale => (double)Ratio02 / Ratio01;

        /// <summary>
        /// 动作完成
        /// </summary>
        public bool IsFinish { get; set; }

        /// <summary>
        /// 机架修正
        /// </summary>
        public CorrectADsHandler CorrectADs { get; set; }

        /// <summary>
        /// ad滞后修正  单位ms
        /// </summary>
        public int ADLag { get; set; }

        //一共有1.AD数据池(由timegrid提供) 1min
        //2.pos数据池(pos推送提供) 1min
        //4.当接收的grid事件数据。它有 (direction, grid_start,grid_len, systick )
        //systick 就是结束的时间点。 当AD数据池出现了这个时间点

        //pos数据池向前找。 pos 在 grid_start*posOfGrid 范围的数据。 
        //找到开始的systick 后,整合3个数据池的数据。
        //5.最后代替 grid 推送出去。
        public TimeGridAdvHelper mTimeGridAdvHelper { get; } = new TimeGridAdvHelper();

        /// <summary>
        /// 动作指令完成,准备推送 timegridadv 事件
        /// </summary>
        public bool IsTimeToPushTimeGridAdv { get; private set; } = false;

        /// <summary>
        /// 以timegrid 为单位,推送数据
        /// </summary>
        public event TimeGridAdv2EventHandler TimeGridAdv2Event;
        #endregion


        DateTime lastUpdateADTime;
        int lastGrid = Misc.MyBase.NULL_VALUE;
        DateTime lastGridTime;
89
        Stopwatch stopwatch_gridTime = new Stopwatch();
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

        SGrid fGrid = new SGrid();
        void advConstructor()
        {
            fGrid.SetSize(PosLen / PosOfGrid);

            mTimeGridAdvHelper.Init();

            this.PropertyChanged += FlyAD7_PropertyChanged1;


            //更新线速度
            PollModule.Current.Poll_Config(PollModule.POLL_CONFIG.ADD,
                () =>
                {
105

106 107 108 109 110 111 112
                    if (calSpeed.Cal(Now, out int speed1, out int speed2))
                    {
                        Speed = speed1;
                        Speed2 = speed2;
                    }

                }, TimeSpan.FromSeconds(1));
113 114 115

            //轮询事件触发
            PollModule.Current.Poll_Config(PollModule.POLL_CONFIG.ADD, OnPoll);
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
        }
        private void FlyAD7_PropertyChanged1(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(DriveStatus))
            {
                switch (DriveStatus)
                {
                    case DRIVE_MAN_STATUS.STOP_MANUAL:
                    case DRIVE_MAN_STATUS.STOP:
                    case DRIVE_MAN_STATUS.LIMIT:
                        IsFinish = true;
                        break;
                    case DRIVE_MAN_STATUS.RUNNING:
                        IsFinish = false;
                        break;
                }
            }
            else if ((e.PropertyName == nameof(PosLen)) ||
                (e.PropertyName == nameof(PosOfGrid)))
            {
                fGrid.SetSize(PosLen / PosOfGrid);
            }
            else if (e.PropertyName == nameof(Marker))
            {
                //if (DriveOrder == DRIVE_MAN_ORDER.SYNC)
                {
                    //同步运行中
                    //检测与哪个指令一致, 
                    //该指令置为 Doing, 前面的全部置为 Finish,并且删除
                    for (int i = 0; i < SyncOrders.Count(); i++)
                    {
                        if (SyncOrders[i].Marker == Marker)
                        {
                            SyncOrders[i].State = SyncOrderState.Doing;

                            for (int j = 0; j < i; j++)
                            {
                                SyncOrders[0].State = SyncOrderState.Finish;
                                SyncOrders.RemoveAt(0);
                            }
                        }
                    }
                }
            }
        }

        void advAfterContected()
        {
            mTimeGridAdvHelper.Clear();
            lastUpdateADTime = DateTime.MinValue;
            lastGrid = Misc.MyBase.NULL_VALUE;
            lastGridTime = DateTime.MinValue;
        }

        #region IFlyADClientAdv function
        /// <summary>
        /// Runto(0), 不同于 Backward
        /// </summary>
        public void RuntoMin()
        {
            if (HasPosMaxMin)
                Runto(PosMin);
            else
                Runto(0);
        }

        /// <summary>
        /// Runto(PosLen), 不同于 Forward
        /// </summary>
        public void RuntoMax()
        {
            if (HasPosMaxMin)
                Runto(PosMax);
            else
                Runto(PosLen);
        }

        /// <summary>
        /// 设置输出
        /// </summary>
        /// <param name="index"></param>
        /// <param name="is1"></param>
        public void SetOutputBit(int index, bool is1)
        {
            if (index > 15)//4)
                return;
            if (index < 0)
                return;
            if (is1)
            {
                SetOutput(
                    (UInt16)Misc.MyBase.BIT(index),
                    (UInt16)Misc.MyBase.BIT(index));
            }
            else
            {
                SetOutput(
                    (UInt16)Misc.MyBase.BIT(index),
                    (UInt16)~Misc.MyBase.BIT(index));
            }
        }

        /// <summary>
        /// 从正反缓存区, 获取grid数据
        /// </summary>
        /// <param name="direction">方向, 只有 正,反</param>
        /// <param name="grid_start">grid 开始位置</param>
        /// <param name="grid_len">grid 长度</param>
        /// <param name="dat">grid 数据</param>
        public void GetGrid(Misc.DIRECTION direction, int grid_start, int grid_len, out int[] dat)
        {
            int index = 0;
            if (direction == Misc.DIRECTION.BACKWARD)
                index = 1;

            dat = new int[grid_len];

            for (int i = 0; i < dat.Length; i++)
            {
                int grid_num = grid_start + i;
                if (grid_num >= fGrid.data[index].Length)
                    break;

                if (GridSmooth > 0)
                {
                    int sum = 0;
                    int cnt = 0;
                    for (int j = 0; j < (GridSmooth * 2 + 1); j++)
                    {
                        int idx = grid_num - GridSmooth + j;
                        if (idx < 0)
                            continue;
                        if (idx >= fGrid.data[index].Length)
                            break;
                        if (Misc.MyBase.ISVALIDATA(fGrid.data[index][idx]))
                        {
                            sum += fGrid.data[index][idx];
                            cnt++;
                        }
                    }
                    if (cnt > 0)
                        dat[i] = sum / cnt;
                    else
                        dat[i] = Misc.MyBase.NULL_VALUE;
                }
                else
                {
                    dat[i] = fGrid.data[index][grid_num];
                }
            }

            CorrectADs?.Invoke(direction, grid_start, dat);
            return;
        }

        /// <summary>
        /// 从正反缓存区, 获取全部grid数据
        /// </summary>
        /// <param name="direction">方向, 只有 正,反</param>
        /// <param name="dat">grid 数据</param>
        public void GetGrid(Misc.DIRECTION direction, out int[] dat)
        {
            GetGrid(direction, 0, fGrid.data[0].Length, out dat);
        }
        #endregion


        void advPushPosAll()
        {
            advPushPos1();
            advPushPos2();
        }

        void advPushPos1()
        {
291 292
            if (mTimeGridAdvHelper.AddPos(Now, Position))
            {
293 294 295 296 297 298 299 300 301 302 303 304 305 306
                PositionChangedEvent?.Invoke(this, new PositionChangedEventArgs() { Time = Now, Position = Position });
            }
        }

        void advPushPos2()
        {
            if (mTimeGridAdvHelper.AddPos2(Now, Position2))
            {
                Position2ChangedEvent?.Invoke(this, new PositionChangedEventArgs() { Time = Now, Position = Position2 });
            }
        }

        void advPushIn()
        {
307 308
            if (isReadyContext.isReadyGetPos)
            {
309 310 311 312 313 314 315 316 317 318 319
                mTimeGridAdvHelper.AddIStatus(Now, IStatus);
            }
            else
            {
                if (mTimeGridAdvHelper.AddIStatus(Now, IStatus, Position, Position2, out UInt16 ichanged))
                {
                    IStatusChangedEvent?.Invoke(this,
                        new IStatusChangedEventArgs(Now, IStatus, ichanged, Position, Position2));
                }
            }
        }
320

321 322 323 324 325 326 327 328 329
        void advPushAd(int ad)
        {
            mTimeGridAdvHelper.AddAD(Now - TimeSpan.FromMilliseconds(ADLag), new int[] { ad });
        }

        void advPushStatus()
        {
            if (mTimeGridAdvHelper.AddDriveStatus(Now, DriveOrder, DriveStatus, Marker))
            {
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
                //状态变了
                if (DriveStatus != DRIVE_MAN_STATUS.RUNNING)
                {
                    //通知 mTimeGridAdvHelper 下次触发 timegridadv
                    IsTimeToPushTimeGridAdv = true;
                }

                DriveStatusChangedEvent?.Invoke(this, new DriveStatusChangedEventArgs()
                {
                    Time = Now,
                    DriveOrder = DriveOrder,
                    DriveStatus = DriveStatus,
                    Marker = Marker
                });
            }
        }

        /// <summary>
        /// ScanMotion 使用。给定按扫描的时间点。 当探头停下来后,获取数据
        /// </summary>
        /// <param name="beginTime"></param>
        /// <returns></returns>
        public TimeGridAdv2EventArgs GetTimeGridAdv2Event(DateTime beginTime)
        {
            //获取ad列表
            var adList = mTimeGridAdvHelper.GetAD(beginTime);
            if (adList.Count() == 0)
                return null;
            DateTime endTime = mTimeGridAdvHelper.NewestTime;

            //获取pos
            var posList = mTimeGridAdvHelper.GetPos(mTimeGridAdvHelper.NewestTime, adList.Count());



            Misc.DIRECTION direction;
            //判断运动方向
            if (posList.Last() > posList.First())
            {
                //正向
                direction = DIRECTION.FORWARD;
            }
            else
            {
                direction = DIRECTION.BACKWARD;
            }


            //机架修正
            if (CorrectADs != null)
            {
                for (int i = 0; i < adList.Count(); i++)
                {
                    adList[i] = CorrectAD(posList[i] / PosOfGrid, adList[i]);
                }
            }

            TimeGridAdv2EventArgs eventArgs = new TimeGridAdv2EventArgs();
            eventArgs.Direction = direction;
            eventArgs.EndTime = endTime;
            eventArgs.AdList = adList;
            eventArgs.PosList = posList;

            return eventArgs;
        }

        void OnPoll()
        {
            if (!IsConnected)
                return;
            if (!IsReady)
                return;

            OnPoll_TimeGrid();
            OnPoll_TimeGridAdv();
            OnPoll_miniGrid();


        }
410
        
411 412 413 414 415 416 417 418 419 420 421 422 423 424
        void OnPoll_TimeGrid()
        {
            if (lastUpdateADTime == DateTime.MinValue)
            {
                lastUpdateADTime = Now;
                return;
            }


            if (Now - lastUpdateADTime < TimeSpan.FromSeconds(0.2))
                return;

            //获取0.2s到现在的数据
            var adList = mTimeGridAdvHelper.GetAD(lastUpdateADTime);
425
            
426
            //算AD均值
427
            
428
            //机架修改处理
429 430 431 432 433 434
            //ad = CorrectAD(Position / PosOfGrid, ad);
            //AD = ad;
            for (int i = 0; i < adList.Count(); i++) {
                adList[i] = CorrectAD(Position / PosOfGrid, adList[i]);
            }
            int ad = (int)(adList.Average());
435 436 437 438 439 440 441 442
            AD = ad;

            //推送timegrid事件
            TimeGridEvent?.Invoke(this,
                new TimeGridEventArgs()
                {
                    Time = lastUpdateADTime,
                    Data = adList.ToArray(),
443
                    Ts = TimeSpan.FromMilliseconds(1)
444 445 446 447 448 449
                });

            lastUpdateADTime = Now;

        }

450

451 452 453 454 455 456 457 458
        void OnPoll_miniGrid()
        {
            int grid = Position / PosOfGrid;

            if (!Misc.MyBase.ISVALIDATA(lastGrid))
            {
                lastGrid = grid;
                lastGridTime = Now;
459
                stopwatch_gridTime.Restart();
460 461 462 463 464 465 466 467 468 469 470 471 472
                return;
            }

            if (lastGrid == grid)
            {
                if (Now - lastGridTime > TimeSpan.FromSeconds(2))
                {
                    //太慢,超过2秒还没走完一个grid
                    //强制缩少数据
                    lastGridTime = Now;
                }
                return;
            }
473 474 475 476 477 478
            if (stopwatch_gridTime.Elapsed < TimeSpan.FromSeconds(0.2)) 
            {
                //太快,控制推送频率
                return;
            }
            stopwatch_gridTime.Restart();
479 480 481 482 483 484 485 486 487 488 489

            //方向
            Misc.DIRECTION direction;
            if (lastGrid < grid)
                direction = Misc.DIRECTION.FORWARD;
            else
                direction = Misc.DIRECTION.BACKWARD;

            //开始位置
            var adList = mTimeGridAdvHelper.GetAD(lastGridTime);
            var posList = mTimeGridAdvHelper.GetPos(Now, adList.Count());
490
            var gridList = TimeGridAdvHelperExt.ToGrid(adList, posList, PosOfGrid, GridLen, out int grid_start, out int grid_end, isMiniGrid: true);
491 492 493 494 495

            if (gridList == null)
                return;

            int index = (direction == Misc.DIRECTION.BACKWARD) ? 1 : 0;
496 497
            
            var grid_data = fGrid.data[index];
498

499
            if (grid_start >= grid_data.Length)
500 501
                return;

502 503
            if (grid_end >= grid_data.Length)
                grid_end = grid_data.Length - 1;
504 505 506

            int len = grid_end - grid_start + 1;

507
            Array.Copy(gridList, 0, grid_data, grid_start, len);
508 509 510 511

            //清空后面的数据
            if (direction == Misc.DIRECTION.BACKWARD)
            {
512
                if (grid_data[0] != Misc.MyBase.NULL_VALUE) 
513
                {
514 515 516 517
                    for (int i = 0; i < grid_start; i++)
                    {
                        fGrid.data[index][i] = Misc.MyBase.NULL_VALUE;
                    }
518 519 520 521
                }
            }
            else
            {
522
                if (grid_data.Last() != Misc.MyBase.NULL_VALUE)
523
                {
524 525 526 527
                    for (int i = (grid_end + 1); i < grid_data.Length; i++)
                    {
                        grid_data[i] = Misc.MyBase.NULL_VALUE;
                    }
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
            var data = gridList.ToArray();
            CorrectADs?.Invoke(direction, grid_start, data);


            //需要推送grid
            MiniGridEvent?.Invoke(this, new MiniGridEventArgs()
            {
                direction = direction,
                grid_start = grid_start,
                posOfGrid = PosOfGrid,
                buf = data,
                marker = Marker
            });

            lastGrid = grid;
            lastGridTime = Now;
        }


        void OnPoll_TimeGridAdv()
        {
            if (!IsTimeToPushTimeGridAdv)
                return;
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
            IsTimeToPushTimeGridAdv = false;

            //触发全部高级版的 timegrid
            bool ret = mTimeGridAdvHelper.GetLastRunningTime(out DateTime beginTime, out DateTime endTime, out int marker, out DRIVE_MAN_ORDER order);
            if (!ret)
                return;

            //获取ad列表
            var adList = mTimeGridAdvHelper.GetAD(beginTime, endTime, out DateTime reponse_endTime);
            int adCnt = adList.Count();
            if (adCnt == 0)
                return;

            //获取pos
            var posList = mTimeGridAdvHelper.GetPos(reponse_endTime, adCnt);

            Misc.DIRECTION direction;
            //判断运动方向
            if (posList.Last() > posList.First())
            {
                //正向
                direction = DIRECTION.FORWARD;
            }
            else
            {
                direction = DIRECTION.BACKWARD;
            }
582 583 584 585 586 587 588 589 590 591 592
            
            //生成grid图
            var gridList = TimeGridAdvHelperExt.ToGrid(adList, posList, PosOfGrid, GridLen);
            //放入对应方向缓存区
            int index = (direction == Misc.DIRECTION.BACKWARD) ? 1 : 0;

            var grid_data = fGrid.data[index];

            int len = Math.Min(gridList.Length, grid_data.Length);
            
            Array.Copy(gridList, 0, fGrid.data[index], 0, len);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612


            //机架修正
            if (CorrectADs != null)
            {
                for (int i = 0; i < adList.Count(); i++)
                {
                    adList[i] = CorrectAD(posList[i] / PosOfGrid, adList[i]);
                }
            }


            TimeGridAdv2Event?.Invoke(this, new TimeGridAdv2EventArgs
            {
                Direction = direction,
                EndTime = reponse_endTime,
                AdList = adList,
                PosList = posList,
                Marker = marker
            });
613

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
            GridEvent?.Invoke(this, new MiniGridEventArgs()
            {
                direction = direction,
                marker = Marker,
                buf = gridList,
                posOfGrid = PosOfGrid,
                grid_start = 0
            });
        }





        int CorrectAD(int grid, int ad)
        {
            int[] d = new int[1];
            d[0] = ad;
632
            CorrectADs?.Invoke(Misc.DIRECTION.FIX, grid, d);
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
            return d[0];
        }
    }

    class CalSpeed
    {
        DateTime last_now;
        DateTime pos1_changed_time;
        DateTime pos2_changed_time;
        DateTime last_pos1_changed_time;
        DateTime last_pos2_changed_time;
        int last_pos1;
        int last_pos2;
        int pos1;
        int pos2;

        public bool Cal(DateTime now, out int speed1, out int speed2)
        {
            speed1 = 0;
            speed2 = 0;
            if (last_now == DateTime.MinValue && now != DateTime.MinValue)
            {
                last_now = now;
                last_pos1_changed_time = pos1_changed_time;
                last_pos2_changed_time = pos2_changed_time;
                last_pos1 = pos1;
                last_pos2 = pos2;
                return false;
            }

            if (now - last_now < TimeSpan.FromSeconds(1))
                return false;

            if (pos1_changed_time != last_pos1_changed_time && last_pos1_changed_time != DateTime.MinValue)
            {
                speed1 = (int)((pos1 - last_pos1) / (pos1_changed_time - last_pos1_changed_time).TotalSeconds);
            }
            else
            {
                //停了
            }

            if (pos2_changed_time != last_pos2_changed_time && last_pos2_changed_time != DateTime.MinValue)
            {
                speed2 = (int)((pos2 - last_pos2) / (pos2_changed_time - last_pos2_changed_time).TotalSeconds);
            }
            else
            {
                //停了
            }

            last_now = now;
            last_pos1_changed_time = pos1_changed_time;
            last_pos2_changed_time = pos2_changed_time;
            last_pos1 = pos1;
            last_pos2 = pos2;

            return true;

        }

        public void SetPos1(DateTime changedTime, int pos)
        {
            pos1_changed_time = changedTime;
            pos1 = pos;
        }
        public void SetPos2(DateTime changedTime, int pos)
        {
            pos2_changed_time = changedTime;
            pos2 = pos;
        }
        public void Reset()
        {
            last_now = DateTime.MinValue;

            pos1_changed_time = DateTime.MinValue;
            pos1 = 0;
            last_pos1_changed_time = DateTime.MinValue;
            last_pos1 = 0;

            pos2_changed_time = DateTime.MinValue;
            pos2 = 0;
            last_pos2_changed_time = DateTime.MinValue;
            last_pos2 = 0;


        }
    }

    /// <summary>
    /// 正反转 grid数据 缓存区
    /// </summary>
    class SGrid
    {
        public const int GRID_MAX_SIZE = 1000;
        int size;
        public int[][] data = new int[2][];//data[0]=forword, data[1]=backward
        public SGrid()
        {
            //清空所有数据
            SetSize(GRID_MAX_SIZE);
        }
        public void SetSize(int size)
        {
            this.size = size;
            data[0] = new int[size];
            data[1] = new int[size];
            Clear();
        }
        public void Clear()
        {
            //清空所有数据
            for (int i = 0; i < size; i++)
            {
                data[0][i] = Misc.MyBase.NULL_VALUE;
                data[1][i] = Misc.MyBase.NULL_VALUE;
            }
        }
    }
}